tokenizeSearch.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import {escapeDoubleQuotes} from 'app/utils';
  2. export enum TokenType {
  3. OP,
  4. TAG,
  5. QUERY,
  6. }
  7. export type Token = {
  8. type: TokenType;
  9. value: string;
  10. key?: string;
  11. };
  12. function isOp(t: Token) {
  13. return t.type === TokenType.OP;
  14. }
  15. function isBooleanOp(value: string) {
  16. return ['OR', 'AND'].includes(value.toUpperCase());
  17. }
  18. function isParen(token: Token, character: '(' | ')') {
  19. return (
  20. token !== undefined &&
  21. isOp(token) &&
  22. ['(', ')'].includes(token.value) &&
  23. token.value === character
  24. );
  25. }
  26. export class QueryResults {
  27. tagValues: Record<string, string[]>;
  28. tokens: Token[];
  29. constructor(strTokens: string[]) {
  30. this.tokens = [];
  31. this.tagValues = {};
  32. for (let token of strTokens) {
  33. let tokenState = TokenType.QUERY;
  34. if (isBooleanOp(token)) {
  35. this.addOp(token.toUpperCase());
  36. continue;
  37. }
  38. if (token.startsWith('(')) {
  39. const parenMatch = token.match(/^\(+/g);
  40. if (parenMatch) {
  41. parenMatch[0].split('').map(paren => this.addOp(paren));
  42. token = token.replace(/^\(+/g, '');
  43. }
  44. }
  45. // Traverse the token and determine if it is a tag
  46. // condition or bare words.
  47. for (let i = 0, len = token.length; i < len; i++) {
  48. const char = token[i];
  49. if (i === 0 && (char === '"' || char === ':')) {
  50. break;
  51. }
  52. // We may have entered a tag condition
  53. if (char === ':') {
  54. const nextChar = token[i + 1] || '';
  55. if ([':', ' '].includes(nextChar)) {
  56. tokenState = TokenType.QUERY;
  57. } else {
  58. tokenState = TokenType.TAG;
  59. }
  60. break;
  61. }
  62. }
  63. let trailingParen = '';
  64. if (token.endsWith(')') && !token.includes('(')) {
  65. const parenMatch = token.match(/\)+$/g);
  66. if (parenMatch) {
  67. trailingParen = parenMatch[0];
  68. token = token.replace(/\)+$/g, '');
  69. }
  70. }
  71. if (tokenState === TokenType.QUERY && token.length) {
  72. this.addQuery(token);
  73. } else if (tokenState === TokenType.TAG) {
  74. this.addStringTag(token);
  75. }
  76. if (trailingParen !== '') {
  77. trailingParen.split('').map(paren => this.addOp(paren));
  78. }
  79. }
  80. }
  81. formatString() {
  82. const formattedTokens: string[] = [];
  83. for (const token of this.tokens) {
  84. switch (token.type) {
  85. case TokenType.TAG:
  86. if (token.value === '' || token.value === null) {
  87. formattedTokens.push(`${token.key}:""`);
  88. } else if (/[\s\(\)\\"]/g.test(token.value)) {
  89. formattedTokens.push(`${token.key}:"${escapeDoubleQuotes(token.value)}"`);
  90. } else {
  91. formattedTokens.push(`${token.key}:${token.value}`);
  92. }
  93. break;
  94. case TokenType.QUERY:
  95. if (/[\s\(\)\\"]/g.test(token.value)) {
  96. formattedTokens.push(`"${escapeDoubleQuotes(token.value)}"`);
  97. } else {
  98. formattedTokens.push(token.value);
  99. }
  100. break;
  101. default:
  102. formattedTokens.push(token.value);
  103. }
  104. }
  105. return formattedTokens.join(' ').trim();
  106. }
  107. addStringTag(value: string) {
  108. const [key, tag] = formatTag(value);
  109. this.addTagValues(key, [tag]);
  110. return this;
  111. }
  112. addTagValues(tag: string, tagValues: string[]) {
  113. for (const t of tagValues) {
  114. this.tagValues[tag] = Array.isArray(this.tagValues[tag])
  115. ? [...this.tagValues[tag], t]
  116. : [t];
  117. const token: Token = {type: TokenType.TAG, key: tag, value: t};
  118. this.tokens.push(token);
  119. }
  120. return this;
  121. }
  122. setTagValues(tag: string, tagValues: string[]) {
  123. this.removeTag(tag);
  124. this.addTagValues(tag, tagValues);
  125. return this;
  126. }
  127. getTagValues(tag: string) {
  128. return this.tagValues[tag] ?? [];
  129. }
  130. getTagKeys() {
  131. return Object.keys(this.tagValues);
  132. }
  133. hasTag(tag: string): boolean {
  134. const tags = this.getTagValues(tag);
  135. return !!(tags && tags.length);
  136. }
  137. removeTag(key: string) {
  138. this.tokens = this.tokens.filter(token => token.key !== key);
  139. delete this.tagValues[key];
  140. // Now the really complicated part: removing parens that only have one element in them.
  141. // Since parens are themselves tokens, this gets tricky. In summary, loop through the
  142. // tokens until we find the innermost open paren. Then forward search through the rest of the tokens
  143. // to see if that open paren corresponds to a closed paren with one or fewer items inside.
  144. // If it does, delete those parens, and loop again until there are no more parens to delete.
  145. let parensToDelete: number[] = [];
  146. const cleanParens = (_, idx: number) => !parensToDelete.includes(idx);
  147. do {
  148. if (parensToDelete.length) {
  149. this.tokens = this.tokens.filter(cleanParens);
  150. }
  151. parensToDelete = [];
  152. for (let i = 0; i < this.tokens.length; i++) {
  153. const token = this.tokens[i];
  154. if (!isOp(token) || token.value !== '(') {
  155. continue;
  156. }
  157. let alreadySeen = false;
  158. for (let j = i + 1; j < this.tokens.length; j++) {
  159. const nextToken = this.tokens[j];
  160. if (isOp(nextToken) && nextToken.value === '(') {
  161. // Continue down to the nested parens. We can skip i forward since we know
  162. // everything between i and j is NOT an open paren.
  163. i = j - 1;
  164. break;
  165. } else if (!isOp(nextToken)) {
  166. if (alreadySeen) {
  167. // This has more than one term, no need to delete
  168. break;
  169. }
  170. alreadySeen = true;
  171. } else if (isOp(nextToken) && nextToken.value === ')') {
  172. // We found another paren with zero or one terms inside. Delete the pair.
  173. parensToDelete = [i, j];
  174. break;
  175. }
  176. }
  177. if (parensToDelete.length > 0) {
  178. break;
  179. }
  180. }
  181. } while (parensToDelete.length > 0);
  182. // Now that all erroneous parens are removed we need to remove dangling OR/AND operators.
  183. // I originally removed all the dangling properties in a single loop, but that meant that
  184. // cases like `a OR OR b` would remove both operators, when only one should be removed. So
  185. // instead, we loop until we find an operator to remove, then go back to the start and loop
  186. // again.
  187. let toRemove = -1;
  188. do {
  189. if (toRemove >= 0) {
  190. this.tokens.splice(toRemove, 1);
  191. toRemove = -1;
  192. }
  193. for (let i = 0; i < this.tokens.length; i++) {
  194. const token = this.tokens[i];
  195. const prev = this.tokens[i - 1];
  196. const next = this.tokens[i + 1];
  197. if (isOp(token) && isBooleanOp(token.value)) {
  198. if (prev === undefined || isOp(prev) || next === undefined || isOp(next)) {
  199. // Want to avoid removing `(term) OR (term)`
  200. if (isParen(prev, ')') && isParen(next, '(')) {
  201. continue;
  202. }
  203. toRemove = i;
  204. break;
  205. }
  206. }
  207. }
  208. } while (toRemove >= 0);
  209. return this;
  210. }
  211. removeTagValue(key: string, value: string) {
  212. const values = this.getTagValues(key);
  213. if (Array.isArray(values) && values.length) {
  214. this.setTagValues(
  215. key,
  216. values.filter(item => item !== value)
  217. );
  218. }
  219. }
  220. addQuery(value: string) {
  221. const token: Token = {type: TokenType.QUERY, value: formatQuery(value)};
  222. this.tokens.push(token);
  223. return this;
  224. }
  225. addOp(value: string) {
  226. const token: Token = {type: TokenType.OP, value};
  227. this.tokens.push(token);
  228. return this;
  229. }
  230. get query(): string[] {
  231. return this.tokens.filter(t => t.type === TokenType.QUERY).map(t => t.value);
  232. }
  233. set query(values: string[]) {
  234. this.tokens = this.tokens.filter(t => t.type !== TokenType.QUERY);
  235. for (const v of values) {
  236. this.addQuery(v);
  237. }
  238. }
  239. copy() {
  240. const q = new QueryResults([]);
  241. q.tagValues = {...this.tagValues};
  242. q.tokens = [...this.tokens];
  243. return q;
  244. }
  245. isEmpty() {
  246. return this.tokens.length === 0;
  247. }
  248. }
  249. /**
  250. * Tokenize a search into a QueryResult
  251. *
  252. *
  253. * Should stay in sync with src.sentry.search.utils:tokenize_query
  254. */
  255. export function tokenizeSearch(query: string) {
  256. const tokens = splitSearchIntoTokens(query);
  257. return new QueryResults(tokens);
  258. }
  259. /**
  260. * Splits search strings into tokens for parsing by tokenizeSearch.
  261. *
  262. * Should stay in sync with src.sentry.search.utils:split_query_into_tokens
  263. */
  264. function splitSearchIntoTokens(query: string) {
  265. const queryChars = Array.from(query);
  266. const tokens: string[] = [];
  267. let token = '';
  268. let endOfPrevWord = '';
  269. let quoteType = '';
  270. let quoteEnclosed = false;
  271. for (let idx = 0; idx < queryChars.length; idx++) {
  272. const char = queryChars[idx];
  273. const nextChar = queryChars.length - 1 > idx ? queryChars[idx + 1] : null;
  274. token += char;
  275. if (nextChar !== null && !isSpace(char) && isSpace(nextChar)) {
  276. endOfPrevWord = char;
  277. }
  278. if (isSpace(char) && !quoteEnclosed && endOfPrevWord !== ':' && !isSpace(token)) {
  279. tokens.push(token.trim());
  280. token = '';
  281. }
  282. if (["'", '"'].includes(char) && (!quoteEnclosed || quoteType === char)) {
  283. quoteEnclosed = !quoteEnclosed;
  284. if (quoteEnclosed) {
  285. quoteType = char;
  286. }
  287. }
  288. if (quoteEnclosed && char === '\\' && nextChar === quoteType) {
  289. token += nextChar;
  290. idx++;
  291. }
  292. }
  293. const trimmedToken = token.trim();
  294. if (trimmedToken !== '') {
  295. tokens.push(trimmedToken);
  296. }
  297. return tokens;
  298. }
  299. /**
  300. * Checks if the string is only spaces
  301. */
  302. function isSpace(s: string) {
  303. return s.trim() === '';
  304. }
  305. /**
  306. * Splits tags on ':' and removes enclosing quotes if present, and returns both
  307. * sides of the split as strings.
  308. */
  309. function formatTag(tag: string) {
  310. const idx = tag.indexOf(':');
  311. const key = removeSurroundingQuotes(tag.slice(0, idx));
  312. const value = removeSurroundingQuotes(tag.slice(idx + 1));
  313. return [key, value];
  314. }
  315. function removeSurroundingQuotes(text: string) {
  316. const length = text.length;
  317. if (length <= 1) {
  318. return text;
  319. }
  320. let left = 0;
  321. for (; left <= length / 2; left++) {
  322. if (text.charAt(left) !== '"') {
  323. break;
  324. }
  325. }
  326. let right = length - 1;
  327. for (; right >= length / 2; right--) {
  328. if (text.charAt(right) !== '"' || text.charAt(right - 1) === '\\') {
  329. break;
  330. }
  331. }
  332. return text.slice(left, right + 1);
  333. }
  334. /**
  335. * Strips enclosing quotes and parens from a query, if present.
  336. */
  337. function formatQuery(query: string) {
  338. return query.replace(/^["\(]+|["\)]+$/g, '');
  339. }