parser.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. "use strict";
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  14. if (k2 === undefined) k2 = k;
  15. var desc = Object.getOwnPropertyDescriptor(m, k);
  16. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  17. desc = { enumerable: true, get: function() { return m[k]; } };
  18. }
  19. Object.defineProperty(o, k2, desc);
  20. }) : (function(o, m, k, k2) {
  21. if (k2 === undefined) k2 = k;
  22. o[k2] = m[k];
  23. }));
  24. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  25. Object.defineProperty(o, "default", { enumerable: true, value: v });
  26. }) : function(o, v) {
  27. o["default"] = v;
  28. });
  29. var __importStar = (this && this.__importStar) || (function () {
  30. var ownKeys = function(o) {
  31. ownKeys = Object.getOwnPropertyNames || function (o) {
  32. var ar = [];
  33. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  34. return ar;
  35. };
  36. return ownKeys(o);
  37. };
  38. return function (mod) {
  39. if (mod && mod.__esModule) return mod;
  40. var result = {};
  41. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  42. __setModuleDefault(result, mod);
  43. return result;
  44. };
  45. })();
  46. var __read = (this && this.__read) || function (o, n) {
  47. var m = typeof Symbol === "function" && o[Symbol.iterator];
  48. if (!m) return o;
  49. var i = m.call(o), r, ar = [], e;
  50. try {
  51. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  52. }
  53. catch (error) { e = { error: error }; }
  54. finally {
  55. try {
  56. if (r && !r.done && (m = i["return"])) m.call(i);
  57. }
  58. finally { if (e) throw e.error; }
  59. }
  60. return ar;
  61. };
  62. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  63. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  64. if (ar || !(i in from)) {
  65. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  66. ar[i] = from[i];
  67. }
  68. }
  69. return to.concat(ar || Array.prototype.slice.call(from));
  70. };
  71. var __importDefault = (this && this.__importDefault) || function (mod) {
  72. return (mod && mod.__esModule) ? mod : { "default": mod };
  73. };
  74. var _a, _b;
  75. Object.defineProperty(exports, "__esModule", { value: true });
  76. var root_1 = __importDefault(require("./selectors/root"));
  77. var selector_1 = __importDefault(require("./selectors/selector"));
  78. var className_1 = __importDefault(require("./selectors/className"));
  79. var comment_1 = __importDefault(require("./selectors/comment"));
  80. var id_1 = __importDefault(require("./selectors/id"));
  81. var tag_1 = __importDefault(require("./selectors/tag"));
  82. var string_1 = __importDefault(require("./selectors/string"));
  83. var pseudo_1 = __importDefault(require("./selectors/pseudo"));
  84. var attribute_1 = __importStar(require("./selectors/attribute"));
  85. var universal_1 = __importDefault(require("./selectors/universal"));
  86. var combinator_1 = __importDefault(require("./selectors/combinator"));
  87. var nesting_1 = __importDefault(require("./selectors/nesting"));
  88. var sortAscending_1 = __importDefault(require("./sortAscending"));
  89. var tokenize_1 = __importStar(require("./tokenize"));
  90. var tokens = __importStar(require("./tokenTypes"));
  91. var types = __importStar(require("./selectors/types"));
  92. var util_1 = require("./util");
  93. var WHITESPACE_TOKENS = (_a = {},
  94. _a[tokens.space] = true,
  95. _a[tokens.cr] = true,
  96. _a[tokens.feed] = true,
  97. _a[tokens.newline] = true,
  98. _a[tokens.tab] = true,
  99. _a);
  100. var WHITESPACE_EQUIV_TOKENS = __assign(__assign({}, WHITESPACE_TOKENS), (_b = {}, _b[tokens.comment] = true, _b));
  101. function tokenStart(token) {
  102. return {
  103. line: token[tokenize_1.FIELDS.START_LINE],
  104. column: token[tokenize_1.FIELDS.START_COL],
  105. };
  106. }
  107. function tokenEnd(token) {
  108. return {
  109. line: token[tokenize_1.FIELDS.END_LINE],
  110. column: token[tokenize_1.FIELDS.END_COL],
  111. };
  112. }
  113. function getSource(startLine, startColumn, endLine, endColumn) {
  114. return {
  115. start: {
  116. line: startLine,
  117. column: startColumn,
  118. },
  119. end: {
  120. line: endLine,
  121. column: endColumn,
  122. },
  123. };
  124. }
  125. function getTokenSource(token) {
  126. return getSource(token[tokenize_1.FIELDS.START_LINE], token[tokenize_1.FIELDS.START_COL], token[tokenize_1.FIELDS.END_LINE], token[tokenize_1.FIELDS.END_COL]);
  127. }
  128. function getTokenSourceSpan(startToken, endToken) {
  129. if (!startToken) {
  130. return undefined;
  131. }
  132. return getSource(startToken[tokenize_1.FIELDS.START_LINE], startToken[tokenize_1.FIELDS.START_COL], endToken[tokenize_1.FIELDS.END_LINE], endToken[tokenize_1.FIELDS.END_COL]);
  133. }
  134. function unescapeProp(node, prop) {
  135. var value = node[prop];
  136. if (typeof value !== "string") {
  137. return;
  138. }
  139. if (value.indexOf("\\") !== -1) {
  140. (0, util_1.ensureObject)(node, "raws");
  141. node[prop] = (0, util_1.unesc)(value);
  142. if (node.raws[prop] === undefined) {
  143. node.raws[prop] = value;
  144. }
  145. }
  146. return node;
  147. }
  148. function indexesOf(array, item) {
  149. var i = -1;
  150. var indexes = [];
  151. while ((i = array.indexOf(item, i + 1)) !== -1) {
  152. indexes.push(i);
  153. }
  154. return indexes;
  155. }
  156. function uniqs() {
  157. var list = Array.prototype.concat.apply([], arguments);
  158. return list.filter(function (item, i) { return i === list.indexOf(item); });
  159. }
  160. var Parser = /** @class */ (function () {
  161. function Parser(rule, options) {
  162. if (options === void 0) { options = {}; }
  163. this.rule = rule;
  164. this.options = Object.assign({ lossy: false, safe: false }, options);
  165. this.position = 0;
  166. this.nestingDepth = 0;
  167. this.maxNestingDepth = (0, util_1.resolveMaxNestingDepth)(this.options.maxNestingDepth);
  168. this.css = typeof this.rule === "string" ? this.rule : this.rule.selector;
  169. this.tokens = (0, tokenize_1.default)({
  170. css: this.css,
  171. error: this._errorGenerator(),
  172. safe: this.options.safe,
  173. });
  174. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  175. this.root = new root_1.default({ source: rootSource });
  176. this.root.errorGenerator = this._errorGenerator();
  177. var selector = new selector_1.default({
  178. source: { start: { line: 1, column: 1 } },
  179. sourceIndex: 0,
  180. });
  181. this.root.append(selector);
  182. this.current = selector;
  183. this.loop();
  184. }
  185. Parser.prototype._errorGenerator = function () {
  186. var _this = this;
  187. return function (message, errorOptions) {
  188. if (typeof _this.rule === "string") {
  189. return new Error(message);
  190. }
  191. return _this.rule.error(message, errorOptions);
  192. };
  193. };
  194. Parser.prototype.attribute = function () {
  195. var attr = [];
  196. var startingToken = this.currToken;
  197. this.position++;
  198. while (this.position < this.tokens.length &&
  199. this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  200. attr.push(this.currToken);
  201. this.position++;
  202. }
  203. if (!this.currToken) {
  204. // Ran off the end of the token stream: the attribute was never closed.
  205. // Point at the opening bracket, which is where the author needs to look.
  206. return this.expected("closing square bracket", startingToken[tokenize_1.FIELDS.START_POS]);
  207. }
  208. if (this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  209. return this.expected("closing square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  210. }
  211. var len = attr.length;
  212. var node = {
  213. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  214. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  215. };
  216. if (len === 1 && !~[tokens.word].indexOf(attr[0][tokenize_1.FIELDS.TYPE])) {
  217. return this.expected("attribute", attr[0][tokenize_1.FIELDS.START_POS]);
  218. }
  219. var pos = 0;
  220. var spaceBefore = "";
  221. var commentBefore = "";
  222. var lastAdded = null;
  223. var spaceAfterMeaningfulToken = false;
  224. while (pos < len) {
  225. var token = attr[pos];
  226. var content = this.content(token);
  227. var next = attr[pos + 1];
  228. switch (token[tokenize_1.FIELDS.TYPE]) {
  229. case tokens.space:
  230. // if (
  231. // len === 1 ||
  232. // pos === 0 && this.content(next) === '|'
  233. // ) {
  234. // return this.expected('attribute', token[TOKEN.START_POS], content);
  235. // }
  236. spaceAfterMeaningfulToken = true;
  237. if (this.options.lossy) {
  238. break;
  239. }
  240. if (lastAdded) {
  241. (0, util_1.ensureObject)(node, "spaces", lastAdded);
  242. var prevContent = node.spaces[lastAdded].after || "";
  243. node.spaces[lastAdded].after = prevContent + content;
  244. var existingComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || null;
  245. if (existingComment) {
  246. node.raws.spaces[lastAdded].after = existingComment + content;
  247. }
  248. }
  249. else {
  250. spaceBefore = spaceBefore + content;
  251. commentBefore = commentBefore + content;
  252. }
  253. break;
  254. case tokens.asterisk:
  255. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  256. node.operator = content;
  257. lastAdded = "operator";
  258. }
  259. else if ((!node.namespace || (lastAdded === "namespace" && !spaceAfterMeaningfulToken)) &&
  260. next) {
  261. if (spaceBefore) {
  262. (0, util_1.ensureObject)(node, "spaces", "attribute");
  263. node.spaces.attribute.before = spaceBefore;
  264. spaceBefore = "";
  265. }
  266. if (commentBefore) {
  267. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  268. node.raws.spaces.attribute.before = commentBefore;
  269. commentBefore = "";
  270. }
  271. node.namespace = (node.namespace || "") + content;
  272. var rawValue = (0, util_1.getProp)(node, "raws", "namespace") || null;
  273. if (rawValue) {
  274. node.raws.namespace += content;
  275. }
  276. lastAdded = "namespace";
  277. }
  278. spaceAfterMeaningfulToken = false;
  279. break;
  280. case tokens.dollar:
  281. if (lastAdded === "value") {
  282. var oldRawValue = (0, util_1.getProp)(node, "raws", "value");
  283. node.value += "$";
  284. if (oldRawValue) {
  285. node.raws.value = oldRawValue + "$";
  286. }
  287. break;
  288. }
  289. // Falls through
  290. case tokens.caret:
  291. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  292. node.operator = content;
  293. lastAdded = "operator";
  294. }
  295. spaceAfterMeaningfulToken = false;
  296. break;
  297. case tokens.combinator:
  298. if (content === "~" && next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  299. node.operator = content;
  300. lastAdded = "operator";
  301. }
  302. if (content !== "|") {
  303. spaceAfterMeaningfulToken = false;
  304. break;
  305. }
  306. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  307. node.operator = content;
  308. lastAdded = "operator";
  309. }
  310. else if (!node.namespace && !node.attribute) {
  311. node.namespace = true;
  312. }
  313. spaceAfterMeaningfulToken = false;
  314. break;
  315. case tokens.word:
  316. if (next &&
  317. this.content(next) === "|" &&
  318. attr[pos + 2] &&
  319. attr[pos + 2][tokenize_1.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  320. !node.operator &&
  321. !node.namespace) {
  322. node.namespace = content;
  323. lastAdded = "namespace";
  324. }
  325. else if (!node.attribute || (lastAdded === "attribute" && !spaceAfterMeaningfulToken)) {
  326. if (spaceBefore) {
  327. (0, util_1.ensureObject)(node, "spaces", "attribute");
  328. node.spaces.attribute.before = spaceBefore;
  329. spaceBefore = "";
  330. }
  331. if (commentBefore) {
  332. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  333. node.raws.spaces.attribute.before = commentBefore;
  334. commentBefore = "";
  335. }
  336. node.attribute = (node.attribute || "") + content;
  337. var rawValue = (0, util_1.getProp)(node, "raws", "attribute") || null;
  338. if (rawValue) {
  339. node.raws.attribute += content;
  340. }
  341. lastAdded = "attribute";
  342. }
  343. else if ((!node.value && node.value !== "") ||
  344. (lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark))) {
  345. var unescaped_1 = (0, util_1.unesc)(content);
  346. var oldRawValue = (0, util_1.getProp)(node, "raws", "value") || "";
  347. var oldValue = node.value || "";
  348. node.value = oldValue + unescaped_1;
  349. node.quoteMark = null;
  350. if (unescaped_1 !== content || oldRawValue) {
  351. (0, util_1.ensureObject)(node, "raws");
  352. node.raws.value = (oldRawValue || oldValue) + content;
  353. }
  354. lastAdded = "value";
  355. }
  356. else {
  357. var insensitive = content === "i" || content === "I";
  358. if ((node.value || node.value === "") &&
  359. (node.quoteMark || spaceAfterMeaningfulToken)) {
  360. node.insensitive = insensitive;
  361. if (!insensitive || content === "I") {
  362. (0, util_1.ensureObject)(node, "raws");
  363. node.raws.insensitiveFlag = content;
  364. }
  365. lastAdded = "insensitive";
  366. if (spaceBefore) {
  367. (0, util_1.ensureObject)(node, "spaces", "insensitive");
  368. node.spaces.insensitive.before = spaceBefore;
  369. spaceBefore = "";
  370. }
  371. if (commentBefore) {
  372. (0, util_1.ensureObject)(node, "raws", "spaces", "insensitive");
  373. node.raws.spaces.insensitive.before = commentBefore;
  374. commentBefore = "";
  375. }
  376. }
  377. else if (node.value || node.value === "") {
  378. lastAdded = "value";
  379. node.value += content;
  380. if (node.raws.value) {
  381. node.raws.value += content;
  382. }
  383. }
  384. }
  385. spaceAfterMeaningfulToken = false;
  386. break;
  387. case tokens.str:
  388. if (!node.attribute || !node.operator) {
  389. return this.error("Expected an attribute followed by an operator preceding the string.", {
  390. index: token[tokenize_1.FIELDS.START_POS],
  391. });
  392. }
  393. var _a = (0, attribute_1.unescapeValue)(content), unescaped = _a.unescaped, quoteMark = _a.quoteMark;
  394. node.value = unescaped;
  395. node.quoteMark = quoteMark;
  396. lastAdded = "value";
  397. (0, util_1.ensureObject)(node, "raws");
  398. node.raws.value = content;
  399. spaceAfterMeaningfulToken = false;
  400. break;
  401. case tokens.equals:
  402. if (!node.attribute) {
  403. return this.expected("attribute", token[tokenize_1.FIELDS.START_POS], content);
  404. }
  405. if (node.value) {
  406. return this.error('Unexpected "=" found; an operator was already defined.', {
  407. index: token[tokenize_1.FIELDS.START_POS],
  408. });
  409. }
  410. node.operator = node.operator ? node.operator + content : content;
  411. lastAdded = "operator";
  412. spaceAfterMeaningfulToken = false;
  413. break;
  414. case tokens.comment:
  415. if (lastAdded) {
  416. if (spaceAfterMeaningfulToken ||
  417. (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) ||
  418. lastAdded === "insensitive") {
  419. var lastComment = (0, util_1.getProp)(node, "spaces", lastAdded, "after") || "";
  420. var rawLastComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || lastComment;
  421. (0, util_1.ensureObject)(node, "raws", "spaces", lastAdded);
  422. node.raws.spaces[lastAdded].after = rawLastComment + content;
  423. }
  424. else {
  425. var lastValue = node[lastAdded] || "";
  426. var rawLastValue = (0, util_1.getProp)(node, "raws", lastAdded) || lastValue;
  427. (0, util_1.ensureObject)(node, "raws");
  428. node.raws[lastAdded] = rawLastValue + content;
  429. }
  430. }
  431. else {
  432. commentBefore = commentBefore + content;
  433. }
  434. break;
  435. default:
  436. return this.error("Unexpected \"".concat(content, "\" found."), { index: token[tokenize_1.FIELDS.START_POS] });
  437. }
  438. pos++;
  439. }
  440. unescapeProp(node, "attribute");
  441. unescapeProp(node, "namespace");
  442. this.newNode(new attribute_1.default(node));
  443. this.position++;
  444. };
  445. /**
  446. * return a node containing meaningless garbage up to (but not including) the specified token position.
  447. * if the token position is negative, all remaining tokens are consumed.
  448. *
  449. * This returns an array containing a single string node if all whitespace,
  450. * otherwise an array of comment nodes with space before and after.
  451. *
  452. * These tokens are not added to the current selector, the caller can add them or use them to amend
  453. * a previous node's space metadata.
  454. *
  455. * In lossy mode, this returns only comments.
  456. */
  457. Parser.prototype.parseWhitespaceEquivalentTokens = function (stopPosition) {
  458. if (stopPosition < 0) {
  459. stopPosition = this.tokens.length;
  460. }
  461. var startPosition = this.position;
  462. var nodes = [];
  463. var space = "";
  464. var lastComment = undefined;
  465. do {
  466. if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) {
  467. if (!this.options.lossy) {
  468. space += this.content();
  469. }
  470. }
  471. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.comment) {
  472. var spaces = {};
  473. if (space) {
  474. spaces.before = space;
  475. space = "";
  476. }
  477. lastComment = new comment_1.default({
  478. value: this.content(),
  479. source: getTokenSource(this.currToken),
  480. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  481. spaces: spaces,
  482. });
  483. nodes.push(lastComment);
  484. }
  485. } while (++this.position < stopPosition);
  486. if (space) {
  487. if (lastComment) {
  488. lastComment.spaces.after = space;
  489. }
  490. else if (!this.options.lossy) {
  491. var firstToken = this.tokens[startPosition];
  492. var lastToken = this.tokens[this.position - 1];
  493. nodes.push(new string_1.default({
  494. value: "",
  495. source: getSource(firstToken[tokenize_1.FIELDS.START_LINE], firstToken[tokenize_1.FIELDS.START_COL], lastToken[tokenize_1.FIELDS.END_LINE], lastToken[tokenize_1.FIELDS.END_COL]),
  496. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  497. spaces: { before: space, after: "" },
  498. }));
  499. }
  500. }
  501. return nodes;
  502. };
  503. /**
  504. *
  505. * @param {*} nodes
  506. */
  507. Parser.prototype.convertWhitespaceNodesToSpace = function (nodes, requiredSpace) {
  508. var _this = this;
  509. if (requiredSpace === void 0) { requiredSpace = false; }
  510. var space = "";
  511. var rawSpace = "";
  512. nodes.forEach(function (n) {
  513. var spaceBefore = _this.lossySpace(n.spaces.before, requiredSpace);
  514. var rawSpaceBefore = _this.lossySpace(n.rawSpaceBefore, requiredSpace);
  515. space +=
  516. spaceBefore + _this.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  517. rawSpace +=
  518. spaceBefore +
  519. n.value +
  520. _this.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  521. });
  522. if (rawSpace === space) {
  523. rawSpace = undefined;
  524. }
  525. var result = { space: space, rawSpace: rawSpace };
  526. return result;
  527. };
  528. Parser.prototype.isNamedCombinator = function (position) {
  529. if (position === void 0) { position = this.position; }
  530. return (this.tokens[position + 0] &&
  531. this.tokens[position + 0][tokenize_1.FIELDS.TYPE] === tokens.slash &&
  532. this.tokens[position + 1] &&
  533. this.tokens[position + 1][tokenize_1.FIELDS.TYPE] === tokens.word &&
  534. this.tokens[position + 2] &&
  535. this.tokens[position + 2][tokenize_1.FIELDS.TYPE] === tokens.slash);
  536. };
  537. Parser.prototype.namedCombinator = function () {
  538. if (this.isNamedCombinator()) {
  539. var nameRaw = this.content(this.tokens[this.position + 1]);
  540. var name = (0, util_1.unesc)(nameRaw).toLowerCase();
  541. var raws = {};
  542. if (name !== nameRaw) {
  543. raws.value = "/".concat(nameRaw, "/");
  544. }
  545. var node = new combinator_1.default({
  546. value: "/".concat(name, "/"),
  547. source: getSource(this.currToken[tokenize_1.FIELDS.START_LINE], this.currToken[tokenize_1.FIELDS.START_COL], this.tokens[this.position + 2][tokenize_1.FIELDS.END_LINE], this.tokens[this.position + 2][tokenize_1.FIELDS.END_COL]),
  548. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  549. raws: raws,
  550. });
  551. this.position = this.position + 3;
  552. return node;
  553. }
  554. else {
  555. this.unexpected();
  556. }
  557. };
  558. Parser.prototype.combinator = function () {
  559. var _this = this;
  560. if (this.content() === "|") {
  561. return this.namespace();
  562. }
  563. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  564. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  565. if (nextSigTokenPos < 0 ||
  566. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.comma ||
  567. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  568. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  569. if (nodes.length > 0) {
  570. var last = this.current.last;
  571. if (last) {
  572. var _a = this.convertWhitespaceNodesToSpace(nodes), space = _a.space, rawSpace = _a.rawSpace;
  573. if (rawSpace !== undefined) {
  574. last.rawSpaceAfter += rawSpace;
  575. }
  576. last.spaces.after += space;
  577. }
  578. else {
  579. nodes.forEach(function (n) { return _this.newNode(n); });
  580. }
  581. }
  582. return;
  583. }
  584. var firstToken = this.currToken;
  585. var spaceOrDescendantSelectorNodes = undefined;
  586. if (nextSigTokenPos > this.position) {
  587. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  588. }
  589. var node;
  590. if (this.isNamedCombinator()) {
  591. node = this.namedCombinator();
  592. }
  593. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.combinator) {
  594. node = new combinator_1.default({
  595. value: this.content(),
  596. source: getTokenSource(this.currToken),
  597. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  598. });
  599. this.position++;
  600. }
  601. else if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) {
  602. // pass
  603. }
  604. else if (!spaceOrDescendantSelectorNodes) {
  605. this.unexpected();
  606. }
  607. if (node) {
  608. if (spaceOrDescendantSelectorNodes) {
  609. var _b = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), space = _b.space, rawSpace = _b.rawSpace;
  610. node.spaces.before = space;
  611. node.rawSpaceBefore = rawSpace;
  612. }
  613. }
  614. else {
  615. // descendant combinator
  616. var _c = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), space = _c.space, rawSpace = _c.rawSpace;
  617. if (!rawSpace) {
  618. rawSpace = space;
  619. }
  620. var spaces = {};
  621. var raws = { spaces: {} };
  622. if (space.endsWith(" ") && rawSpace.endsWith(" ")) {
  623. spaces.before = space.slice(0, space.length - 1);
  624. raws.spaces.before = rawSpace.slice(0, rawSpace.length - 1);
  625. }
  626. else if (space[0] === " " && rawSpace[0] === " ") {
  627. spaces.after = space.slice(1);
  628. raws.spaces.after = rawSpace.slice(1);
  629. }
  630. else {
  631. raws.value = rawSpace;
  632. }
  633. node = new combinator_1.default({
  634. value: " ",
  635. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  636. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  637. spaces: spaces,
  638. raws: raws,
  639. });
  640. }
  641. if (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.space) {
  642. node.spaces.after = this.optionalSpace(this.content());
  643. this.position++;
  644. }
  645. return this.newNode(node);
  646. };
  647. Parser.prototype.comma = function () {
  648. if (this.position === this.tokens.length - 1) {
  649. this.root.trailingComma = true;
  650. this.position++;
  651. return;
  652. }
  653. this.current._inferEndPosition();
  654. var selector = new selector_1.default({
  655. source: {
  656. start: tokenStart(this.tokens[this.position + 1]),
  657. },
  658. sourceIndex: this.tokens[this.position + 1][tokenize_1.FIELDS.START_POS],
  659. });
  660. this.current.parent.append(selector);
  661. this.current = selector;
  662. this.position++;
  663. };
  664. Parser.prototype.comment = function () {
  665. var current = this.currToken;
  666. this.newNode(new comment_1.default({
  667. value: this.content(),
  668. source: getTokenSource(current),
  669. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  670. }));
  671. this.position++;
  672. };
  673. Parser.prototype.error = function (message, opts) {
  674. throw this.root.error(message, opts);
  675. };
  676. Parser.prototype.missingBackslash = function () {
  677. return this.error("Expected a backslash preceding the semicolon.", {
  678. index: this.currToken[tokenize_1.FIELDS.START_POS],
  679. });
  680. };
  681. Parser.prototype.missingParenthesis = function () {
  682. return this.expected("opening parenthesis", this.currToken[tokenize_1.FIELDS.START_POS]);
  683. };
  684. Parser.prototype.missingSquareBracket = function () {
  685. return this.expected("opening square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  686. };
  687. Parser.prototype.unexpected = function () {
  688. return this.error("Unexpected '".concat(this.content(), "'. Escaping special characters with \\ may help."), this.currToken[tokenize_1.FIELDS.START_POS]);
  689. };
  690. Parser.prototype.unexpectedPipe = function () {
  691. return this.error("Unexpected '|'.", this.currToken[tokenize_1.FIELDS.START_POS]);
  692. };
  693. Parser.prototype.namespace = function () {
  694. var prev = this.prevToken;
  695. // Only treat the previous token as a namespace prefix when it can actually
  696. // be one (a type/word or the universal `*`). A comment, comma, combinator
  697. // or whitespace before `|` means an empty namespace, not a prefix.
  698. var before = prev &&
  699. (prev[tokenize_1.FIELDS.TYPE] === tokens.word ||
  700. prev[tokenize_1.FIELDS.TYPE] === tokens.asterisk ||
  701. prev[tokenize_1.FIELDS.TYPE] === tokens.ampersand)
  702. ? this.content(prev)
  703. : true;
  704. if (!this.nextToken) {
  705. // A trailing `|` with nothing after it. `unexpectedPipe` reports against
  706. // `currToken`, which is the pipe itself and always present here.
  707. return this.unexpectedPipe();
  708. }
  709. if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  710. this.position++;
  711. return this.word(before);
  712. }
  713. else if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.asterisk) {
  714. this.position++;
  715. return this.universal(before);
  716. }
  717. this.unexpectedPipe();
  718. };
  719. Parser.prototype.nesting = function () {
  720. if (this.nextToken) {
  721. var nextContent = this.content(this.nextToken);
  722. if (nextContent === "|") {
  723. this.position++;
  724. return;
  725. }
  726. }
  727. var current = this.currToken;
  728. this.newNode(new nesting_1.default({
  729. value: this.content(),
  730. source: getTokenSource(current),
  731. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  732. }));
  733. this.position++;
  734. };
  735. Parser.prototype.parentheses = function () {
  736. var last = this.current.last;
  737. var unbalanced = 1;
  738. var openingToken = this.currToken;
  739. this.position++;
  740. if (last && last.type === types.PSEUDO) {
  741. var selector = new selector_1.default({
  742. source: { start: tokenStart(this.tokens[this.position]) },
  743. sourceIndex: this.tokens[this.position][tokenize_1.FIELDS.START_POS],
  744. });
  745. var cache = this.current;
  746. last.append(selector);
  747. this.current = selector;
  748. // Track nesting depth so deeply nested pseudo selectors raise a
  749. // catchable error instead of overflowing the call stack. The
  750. // counter is restored in `finally` so the parser is never left in
  751. // an inconsistent state, even on the error path.
  752. this.nestingDepth++;
  753. try {
  754. if (this.nestingDepth > this.maxNestingDepth) {
  755. this.error("Cannot parse selector: nesting depth exceeds the maximum of ".concat(this.maxNestingDepth, "."), { index: this.currToken[tokenize_1.FIELDS.START_POS] });
  756. }
  757. while (this.position < this.tokens.length && unbalanced) {
  758. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  759. unbalanced++;
  760. }
  761. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  762. unbalanced--;
  763. }
  764. if (unbalanced) {
  765. this.parse();
  766. }
  767. else {
  768. this.current.source.end = tokenEnd(this.currToken);
  769. this.current.parent.source.end = tokenEnd(this.currToken);
  770. this.position++;
  771. }
  772. }
  773. }
  774. finally {
  775. this.nestingDepth--;
  776. }
  777. this.current = cache;
  778. }
  779. else {
  780. // I think this case should be an error. It's used to implement a basic parse of media queries
  781. // but I don't think it's a good idea.
  782. var parenStart = this.currToken;
  783. var parenValue = "(";
  784. var parenEnd = void 0;
  785. while (this.position < this.tokens.length && unbalanced) {
  786. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  787. unbalanced++;
  788. }
  789. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  790. unbalanced--;
  791. }
  792. parenEnd = this.currToken;
  793. parenValue += this.parseParenthesisToken(this.currToken);
  794. this.position++;
  795. }
  796. if (last) {
  797. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  798. }
  799. else {
  800. this.newNode(new string_1.default({
  801. value: parenValue,
  802. source: getSource(parenStart[tokenize_1.FIELDS.START_LINE], parenStart[tokenize_1.FIELDS.START_COL], parenEnd[tokenize_1.FIELDS.END_LINE], parenEnd[tokenize_1.FIELDS.END_COL]),
  803. sourceIndex: parenStart[tokenize_1.FIELDS.START_POS],
  804. }));
  805. }
  806. }
  807. if (unbalanced) {
  808. // `currToken` is undefined when the token stream ran out before the
  809. // parenthesis was closed; fall back to the opening one.
  810. return this.expected("closing parenthesis", (this.currToken || openingToken)[tokenize_1.FIELDS.START_POS]);
  811. }
  812. };
  813. Parser.prototype.pseudo = function () {
  814. var _this = this;
  815. var pseudoStr = "";
  816. var startingToken = this.currToken;
  817. while (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.colon) {
  818. pseudoStr += this.content();
  819. this.position++;
  820. }
  821. if (!this.currToken) {
  822. return this.expected(["pseudo-class", "pseudo-element"], this.position - 1);
  823. }
  824. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  825. this.splitWord(false, function (first, length) {
  826. pseudoStr += first;
  827. _this.newNode(new pseudo_1.default({
  828. value: pseudoStr,
  829. source: getTokenSourceSpan(startingToken, _this.currToken),
  830. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  831. }));
  832. if (length > 1 && _this.nextToken && _this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  833. _this.error("Misplaced parenthesis.", {
  834. index: _this.nextToken[tokenize_1.FIELDS.START_POS],
  835. });
  836. }
  837. });
  838. }
  839. else {
  840. return this.expected(["pseudo-class", "pseudo-element"], this.currToken[tokenize_1.FIELDS.START_POS]);
  841. }
  842. };
  843. Parser.prototype.space = function () {
  844. var content = this.content();
  845. // Handle space before and after the selector
  846. if (this.position === 0 ||
  847. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  848. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis ||
  849. this.current.nodes.every(function (node) { return node.type === "comment"; })) {
  850. this.spaces = this.optionalSpace(content);
  851. this.position++;
  852. }
  853. else if (this.position === this.tokens.length - 1 ||
  854. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  855. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  856. this.current.last.spaces.after = this.optionalSpace(content);
  857. this.position++;
  858. }
  859. else {
  860. this.combinator();
  861. }
  862. };
  863. Parser.prototype.string = function () {
  864. var current = this.currToken;
  865. this.newNode(new string_1.default({
  866. value: this.content(),
  867. source: getTokenSource(current),
  868. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  869. }));
  870. this.position++;
  871. };
  872. Parser.prototype.universal = function (namespace) {
  873. var nextToken = this.nextToken;
  874. if (nextToken && this.content(nextToken) === "|") {
  875. this.position++;
  876. return this.namespace();
  877. }
  878. var current = this.currToken;
  879. this.newNode(new universal_1.default({
  880. value: this.content(),
  881. source: getTokenSource(current),
  882. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  883. }), namespace);
  884. this.position++;
  885. };
  886. Parser.prototype.splitWord = function (namespace, firstCallback) {
  887. var _this = this;
  888. var nextToken = this.nextToken;
  889. var word = this.content();
  890. while (nextToken &&
  891. ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[tokenize_1.FIELDS.TYPE])) {
  892. this.position++;
  893. var current = this.content();
  894. word += current;
  895. if (current.lastIndexOf("\\") === current.length - 1) {
  896. var next = this.nextToken;
  897. if (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) {
  898. word += this.requiredSpace(this.content(next));
  899. this.position++;
  900. }
  901. }
  902. nextToken = this.nextToken;
  903. }
  904. var hasClass = indexesOf(word, ".").filter(function (i) {
  905. // Allow escaped dot within class name
  906. var escapedDot = word[i - 1] === "\\";
  907. // Allow decimal numbers percent in @keyframes
  908. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  909. return !escapedDot && !isKeyframesPercent;
  910. });
  911. var hasId = indexesOf(word, "#").filter(function (i) { return word[i - 1] !== "\\"; });
  912. // Eliminate Sass interpolations from the list of id indexes
  913. var interpolations = indexesOf(word, "#{");
  914. if (interpolations.length) {
  915. hasId = hasId.filter(function (hashIndex) { return !~interpolations.indexOf(hashIndex); });
  916. }
  917. var indices = (0, sortAscending_1.default)(uniqs(__spreadArray(__spreadArray([0], __read(hasClass), false), __read(hasId), false)));
  918. indices.forEach(function (ind, i) {
  919. var index = indices[i + 1] || word.length;
  920. var value = word.slice(ind, index);
  921. if (i === 0 && firstCallback) {
  922. return firstCallback.call(_this, value, indices.length);
  923. }
  924. var node;
  925. var current = _this.currToken;
  926. var sourceIndex = current[tokenize_1.FIELDS.START_POS] + indices[i];
  927. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  928. if (~hasClass.indexOf(ind)) {
  929. var classNameOpts = {
  930. value: value.slice(1),
  931. source: source,
  932. sourceIndex: sourceIndex,
  933. };
  934. node = new className_1.default(unescapeProp(classNameOpts, "value"));
  935. }
  936. else if (~hasId.indexOf(ind)) {
  937. var idOpts = {
  938. value: value.slice(1),
  939. source: source,
  940. sourceIndex: sourceIndex,
  941. };
  942. node = new id_1.default(unescapeProp(idOpts, "value"));
  943. }
  944. else {
  945. var tagOpts = {
  946. value: value,
  947. source: source,
  948. sourceIndex: sourceIndex,
  949. };
  950. unescapeProp(tagOpts, "value");
  951. node = new tag_1.default(tagOpts);
  952. }
  953. _this.newNode(node, namespace);
  954. // Ensure that the namespace is used only once
  955. namespace = null;
  956. });
  957. this.position++;
  958. };
  959. Parser.prototype.word = function (namespace) {
  960. var nextToken = this.nextToken;
  961. if (nextToken && this.content(nextToken) === "|") {
  962. this.position++;
  963. return this.namespace();
  964. }
  965. return this.splitWord(namespace);
  966. };
  967. Parser.prototype.loop = function () {
  968. while (this.position < this.tokens.length) {
  969. this.parse(true);
  970. }
  971. this.current._inferEndPosition();
  972. return this.root;
  973. };
  974. Parser.prototype.parse = function (throwOnParenthesis) {
  975. switch (this.currToken[tokenize_1.FIELDS.TYPE]) {
  976. case tokens.space:
  977. this.space();
  978. break;
  979. case tokens.comment:
  980. this.comment();
  981. break;
  982. case tokens.openParenthesis:
  983. this.parentheses();
  984. break;
  985. case tokens.closeParenthesis:
  986. if (throwOnParenthesis) {
  987. this.missingParenthesis();
  988. }
  989. break;
  990. case tokens.openSquare:
  991. this.attribute();
  992. break;
  993. case tokens.dollar:
  994. case tokens.caret:
  995. case tokens.equals:
  996. case tokens.word:
  997. this.word();
  998. break;
  999. case tokens.colon:
  1000. this.pseudo();
  1001. break;
  1002. case tokens.comma:
  1003. this.comma();
  1004. break;
  1005. case tokens.asterisk:
  1006. this.universal();
  1007. break;
  1008. case tokens.ampersand:
  1009. this.nesting();
  1010. break;
  1011. case tokens.slash:
  1012. case tokens.combinator:
  1013. this.combinator();
  1014. break;
  1015. case tokens.str:
  1016. this.string();
  1017. break;
  1018. // These cases throw; no break needed.
  1019. case tokens.closeSquare:
  1020. this.missingSquareBracket();
  1021. case tokens.semicolon:
  1022. this.missingBackslash();
  1023. default:
  1024. this.unexpected();
  1025. }
  1026. };
  1027. /**
  1028. * Helpers
  1029. */
  1030. Parser.prototype.expected = function (description, index, found) {
  1031. if (Array.isArray(description)) {
  1032. var last = description.pop();
  1033. description = "".concat(description.join(", "), " or ").concat(last);
  1034. }
  1035. var an = /^[aeiou]/.test(description[0]) ? "an" : "a";
  1036. if (!found) {
  1037. return this.error("Expected ".concat(an, " ").concat(description, "."), { index: index });
  1038. }
  1039. return this.error("Expected ".concat(an, " ").concat(description, ", found \"").concat(found, "\" instead."), { index: index });
  1040. };
  1041. Parser.prototype.requiredSpace = function (space) {
  1042. return this.options.lossy ? " " : space;
  1043. };
  1044. Parser.prototype.optionalSpace = function (space) {
  1045. return this.options.lossy ? "" : space;
  1046. };
  1047. Parser.prototype.lossySpace = function (space, required) {
  1048. if (this.options.lossy) {
  1049. return required ? " " : "";
  1050. }
  1051. else {
  1052. return space;
  1053. }
  1054. };
  1055. Parser.prototype.parseParenthesisToken = function (token) {
  1056. var content = this.content(token);
  1057. if (token[tokenize_1.FIELDS.TYPE] === tokens.space) {
  1058. return this.requiredSpace(content);
  1059. }
  1060. else {
  1061. return content;
  1062. }
  1063. };
  1064. Parser.prototype.newNode = function (node, namespace) {
  1065. if (namespace) {
  1066. if (/^ +$/.test(namespace)) {
  1067. if (!this.options.lossy) {
  1068. this.spaces = (this.spaces || "") + namespace;
  1069. }
  1070. namespace = true;
  1071. }
  1072. node.namespace = namespace;
  1073. unescapeProp(node, "namespace");
  1074. }
  1075. if (this.spaces) {
  1076. node.spaces.before = this.spaces;
  1077. this.spaces = "";
  1078. }
  1079. return this.current.append(node);
  1080. };
  1081. Parser.prototype.content = function (token) {
  1082. if (token === void 0) { token = this.currToken; }
  1083. return this.css.slice(token[tokenize_1.FIELDS.START_POS], token[tokenize_1.FIELDS.END_POS]);
  1084. };
  1085. Object.defineProperty(Parser.prototype, "currToken", {
  1086. get: function () {
  1087. return this.tokens[this.position];
  1088. },
  1089. enumerable: false,
  1090. configurable: true
  1091. });
  1092. Object.defineProperty(Parser.prototype, "nextToken", {
  1093. get: function () {
  1094. return this.tokens[this.position + 1];
  1095. },
  1096. enumerable: false,
  1097. configurable: true
  1098. });
  1099. Object.defineProperty(Parser.prototype, "prevToken", {
  1100. get: function () {
  1101. return this.tokens[this.position - 1];
  1102. },
  1103. enumerable: false,
  1104. configurable: true
  1105. });
  1106. /**
  1107. * returns the index of the next non-whitespace, non-comment token.
  1108. * returns -1 if no meaningful token is found.
  1109. */
  1110. Parser.prototype.locateNextMeaningfulToken = function (startPosition) {
  1111. if (startPosition === void 0) { startPosition = this.position + 1; }
  1112. var searchPosition = startPosition;
  1113. while (searchPosition < this.tokens.length) {
  1114. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][tokenize_1.FIELDS.TYPE]]) {
  1115. searchPosition++;
  1116. continue;
  1117. }
  1118. else {
  1119. return searchPosition;
  1120. }
  1121. }
  1122. return -1;
  1123. };
  1124. return Parser;
  1125. }());
  1126. exports.default = Parser;
  1127. //# sourceMappingURL=parser.js.map