Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

node-event-generator.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /**
  2. * @fileoverview The event generator for AST nodes.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const esquery = require("esquery");
  10. //------------------------------------------------------------------------------
  11. // Typedefs
  12. //------------------------------------------------------------------------------
  13. /**
  14. * An object describing an AST selector
  15. * @typedef {Object} ASTSelector
  16. * @property {string} rawSelector The string that was parsed into this selector
  17. * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering
  18. * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
  19. * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match,
  20. * or `null` if all node types could cause a match
  21. * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector
  22. * @property {number} identifierCount The total number of identifier queries in this selector
  23. */
  24. //------------------------------------------------------------------------------
  25. // Helpers
  26. //------------------------------------------------------------------------------
  27. /**
  28. * Computes the union of one or more arrays
  29. * @param {...any[]} arrays One or more arrays to union
  30. * @returns {any[]} The union of the input arrays
  31. */
  32. function union(...arrays) {
  33. // TODO(stephenwade): Replace this with arrays.flat() when we drop support for Node v10
  34. return [...new Set([].concat(...arrays))];
  35. }
  36. /**
  37. * Computes the intersection of one or more arrays
  38. * @param {...any[]} arrays One or more arrays to intersect
  39. * @returns {any[]} The intersection of the input arrays
  40. */
  41. function intersection(...arrays) {
  42. if (arrays.length === 0) {
  43. return [];
  44. }
  45. let result = [...new Set(arrays[0])];
  46. for (const array of arrays.slice(1)) {
  47. result = result.filter(x => array.includes(x));
  48. }
  49. return result;
  50. }
  51. /**
  52. * Gets the possible types of a selector
  53. * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector
  54. * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it
  55. */
  56. function getPossibleTypes(parsedSelector) {
  57. switch (parsedSelector.type) {
  58. case "identifier":
  59. return [parsedSelector.value];
  60. case "matches": {
  61. const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
  62. if (typesForComponents.every(Boolean)) {
  63. return union(...typesForComponents);
  64. }
  65. return null;
  66. }
  67. case "compound": {
  68. const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent);
  69. // If all of the components could match any type, then the compound could also match any type.
  70. if (!typesForComponents.length) {
  71. return null;
  72. }
  73. /*
  74. * If at least one of the components could only match a particular type, the compound could only match
  75. * the intersection of those types.
  76. */
  77. return intersection(...typesForComponents);
  78. }
  79. case "child":
  80. case "descendant":
  81. case "sibling":
  82. case "adjacent":
  83. return getPossibleTypes(parsedSelector.right);
  84. default:
  85. return null;
  86. }
  87. }
  88. /**
  89. * Counts the number of class, pseudo-class, and attribute queries in this selector
  90. * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
  91. * @returns {number} The number of class, pseudo-class, and attribute queries in this selector
  92. */
  93. function countClassAttributes(parsedSelector) {
  94. switch (parsedSelector.type) {
  95. case "child":
  96. case "descendant":
  97. case "sibling":
  98. case "adjacent":
  99. return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
  100. case "compound":
  101. case "not":
  102. case "matches":
  103. return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
  104. case "attribute":
  105. case "field":
  106. case "nth-child":
  107. case "nth-last-child":
  108. return 1;
  109. default:
  110. return 0;
  111. }
  112. }
  113. /**
  114. * Counts the number of identifier queries in this selector
  115. * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
  116. * @returns {number} The number of identifier queries
  117. */
  118. function countIdentifiers(parsedSelector) {
  119. switch (parsedSelector.type) {
  120. case "child":
  121. case "descendant":
  122. case "sibling":
  123. case "adjacent":
  124. return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
  125. case "compound":
  126. case "not":
  127. case "matches":
  128. return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
  129. case "identifier":
  130. return 1;
  131. default:
  132. return 0;
  133. }
  134. }
  135. /**
  136. * Compares the specificity of two selector objects, with CSS-like rules.
  137. * @param {ASTSelector} selectorA An AST selector descriptor
  138. * @param {ASTSelector} selectorB Another AST selector descriptor
  139. * @returns {number}
  140. * a value less than 0 if selectorA is less specific than selectorB
  141. * a value greater than 0 if selectorA is more specific than selectorB
  142. * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
  143. * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically
  144. */
  145. function compareSpecificity(selectorA, selectorB) {
  146. return selectorA.attributeCount - selectorB.attributeCount ||
  147. selectorA.identifierCount - selectorB.identifierCount ||
  148. (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
  149. }
  150. /**
  151. * Parses a raw selector string, and throws a useful error if parsing fails.
  152. * @param {string} rawSelector A raw AST selector
  153. * @returns {Object} An object (from esquery) describing the matching behavior of this selector
  154. * @throws {Error} An error if the selector is invalid
  155. */
  156. function tryParseSelector(rawSelector) {
  157. try {
  158. return esquery.parse(rawSelector.replace(/:exit$/u, ""));
  159. } catch (err) {
  160. if (err.location && err.location.start && typeof err.location.start.offset === "number") {
  161. throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`);
  162. }
  163. throw err;
  164. }
  165. }
  166. const selectorCache = new Map();
  167. /**
  168. * Parses a raw selector string, and returns the parsed selector along with specificity and type information.
  169. * @param {string} rawSelector A raw AST selector
  170. * @returns {ASTSelector} A selector descriptor
  171. */
  172. function parseSelector(rawSelector) {
  173. if (selectorCache.has(rawSelector)) {
  174. return selectorCache.get(rawSelector);
  175. }
  176. const parsedSelector = tryParseSelector(rawSelector);
  177. const result = {
  178. rawSelector,
  179. isExit: rawSelector.endsWith(":exit"),
  180. parsedSelector,
  181. listenerTypes: getPossibleTypes(parsedSelector),
  182. attributeCount: countClassAttributes(parsedSelector),
  183. identifierCount: countIdentifiers(parsedSelector)
  184. };
  185. selectorCache.set(rawSelector, result);
  186. return result;
  187. }
  188. //------------------------------------------------------------------------------
  189. // Public Interface
  190. //------------------------------------------------------------------------------
  191. /**
  192. * The event generator for AST nodes.
  193. * This implements below interface.
  194. *
  195. * ```ts
  196. * interface EventGenerator {
  197. * emitter: SafeEmitter;
  198. * enterNode(node: ASTNode): void;
  199. * leaveNode(node: ASTNode): void;
  200. * }
  201. * ```
  202. */
  203. class NodeEventGenerator {
  204. // eslint-disable-next-line jsdoc/require-description
  205. /**
  206. * @param {SafeEmitter} emitter
  207. * An SafeEmitter which is the destination of events. This emitter must already
  208. * have registered listeners for all of the events that it needs to listen for.
  209. * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.)
  210. * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes.
  211. * @returns {NodeEventGenerator} new instance
  212. */
  213. constructor(emitter, esqueryOptions) {
  214. this.emitter = emitter;
  215. this.esqueryOptions = esqueryOptions;
  216. this.currentAncestry = [];
  217. this.enterSelectorsByNodeType = new Map();
  218. this.exitSelectorsByNodeType = new Map();
  219. this.anyTypeEnterSelectors = [];
  220. this.anyTypeExitSelectors = [];
  221. emitter.eventNames().forEach(rawSelector => {
  222. const selector = parseSelector(rawSelector);
  223. if (selector.listenerTypes) {
  224. const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
  225. selector.listenerTypes.forEach(nodeType => {
  226. if (!typeMap.has(nodeType)) {
  227. typeMap.set(nodeType, []);
  228. }
  229. typeMap.get(nodeType).push(selector);
  230. });
  231. return;
  232. }
  233. const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
  234. selectors.push(selector);
  235. });
  236. this.anyTypeEnterSelectors.sort(compareSpecificity);
  237. this.anyTypeExitSelectors.sort(compareSpecificity);
  238. this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  239. this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity));
  240. }
  241. /**
  242. * Checks a selector against a node, and emits it if it matches
  243. * @param {ASTNode} node The node to check
  244. * @param {ASTSelector} selector An AST selector descriptor
  245. * @returns {void}
  246. */
  247. applySelector(node, selector) {
  248. if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) {
  249. this.emitter.emit(selector.rawSelector, node);
  250. }
  251. }
  252. /**
  253. * Applies all appropriate selectors to a node, in specificity order
  254. * @param {ASTNode} node The node to check
  255. * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
  256. * @returns {void}
  257. */
  258. applySelectors(node, isExit) {
  259. const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
  260. const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
  261. /*
  262. * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
  263. * Iterate through each of them, applying selectors in the right order.
  264. */
  265. let selectorsByTypeIndex = 0;
  266. let anyTypeSelectorsIndex = 0;
  267. while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
  268. if (
  269. selectorsByTypeIndex >= selectorsByNodeType.length ||
  270. anyTypeSelectorsIndex < anyTypeSelectors.length &&
  271. compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0
  272. ) {
  273. this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
  274. } else {
  275. this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
  276. }
  277. }
  278. }
  279. /**
  280. * Emits an event of entering AST node.
  281. * @param {ASTNode} node A node which was entered.
  282. * @returns {void}
  283. */
  284. enterNode(node) {
  285. if (node.parent) {
  286. this.currentAncestry.unshift(node.parent);
  287. }
  288. this.applySelectors(node, false);
  289. }
  290. /**
  291. * Emits an event of leaving AST node.
  292. * @param {ASTNode} node A node which was left.
  293. * @returns {void}
  294. */
  295. leaveNode(node) {
  296. this.applySelectors(node, true);
  297. this.currentAncestry.shift();
  298. }
  299. }
  300. module.exports = NodeEventGenerator;