tokenizeSearch.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import {escapeDoubleQuotes} from 'app/utils';
  2. export enum TokenType {
  3. OPERATOR,
  4. FILTER,
  5. FREE_TEXT,
  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.OPERATOR;
  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. // TODO(epurkhiser): This is legacy from before the existence of
  27. // searchSyntax/parser. We should absolutely replace the internals of this API
  28. // with `parseSearch`.
  29. export class QueryResults {
  30. tokens: Token[];
  31. constructor(strTokens: string[]) {
  32. this.tokens = [];
  33. for (let token of strTokens) {
  34. let tokenState = TokenType.FREE_TEXT;
  35. if (isBooleanOp(token)) {
  36. this.addOp(token.toUpperCase());
  37. continue;
  38. }
  39. if (token.startsWith('(')) {
  40. const parenMatch = token.match(/^\(+/g);
  41. if (parenMatch) {
  42. parenMatch[0].split('').map(paren => this.addOp(paren));
  43. token = token.replace(/^\(+/g, '');
  44. }
  45. }
  46. // Traverse the token and check if it's a filter condition or free text
  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 filter condition
  53. if (char === ':') {
  54. const nextChar = token[i + 1] || '';
  55. if ([':', ' '].includes(nextChar)) {
  56. tokenState = TokenType.FREE_TEXT;
  57. } else {
  58. tokenState = TokenType.FILTER;
  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.FREE_TEXT && token.length) {
  72. this.addFreeText(token);
  73. } else if (tokenState === TokenType.FILTER) {
  74. this.addStringFilter(token, false);
  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.FILTER:
  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.FREE_TEXT:
  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. addStringFilter(filter: string, shouldEscape = true) {
  108. const [key, value] = parseFilter(filter);
  109. this.addFilterValues(key, [value], shouldEscape);
  110. return this;
  111. }
  112. addFilterValues(key: string, values: string[], shouldEscape = true) {
  113. for (const value of values) {
  114. // Filter values that we insert through the UI can contain special characters
  115. // that need to escaped. User entered filters should not be escaped.
  116. const escaped = shouldEscape ? escapeFilterValue(value) : value;
  117. const token: Token = {type: TokenType.FILTER, key, value: escaped};
  118. this.tokens.push(token);
  119. }
  120. return this;
  121. }
  122. setFilterValues(key: string, values: string[], shouldEscape = true) {
  123. this.removeFilter(key);
  124. this.addFilterValues(key, values, shouldEscape);
  125. return this;
  126. }
  127. get filters() {
  128. type Filters = Record<string, string[]>;
  129. const reducer = (acc: Filters, token: Token) => ({
  130. ...acc,
  131. [token.key!]: [...(acc[token.key!] ?? []), token.value],
  132. });
  133. return this.tokens
  134. .filter(t => t.type === TokenType.FILTER)
  135. .reduce<Filters>(reducer, {});
  136. }
  137. getFilterValues(key: string) {
  138. return this.filters[key] ?? [];
  139. }
  140. getFilterKeys() {
  141. return Object.keys(this.filters);
  142. }
  143. hasFilter(key: string): boolean {
  144. return this.getFilterValues(key).length > 0;
  145. }
  146. removeFilter(key: string) {
  147. this.tokens = this.tokens.filter(token => token.key !== key);
  148. // Now the really complicated part: removing parens that only have one element in them.
  149. // Since parens are themselves tokens, this gets tricky. In summary, loop through the
  150. // tokens until we find the innermost open paren. Then forward search through the rest of the tokens
  151. // to see if that open paren corresponds to a closed paren with one or fewer items inside.
  152. // If it does, delete those parens, and loop again until there are no more parens to delete.
  153. let parensToDelete: number[] = [];
  154. const cleanParens = (_, idx: number) => !parensToDelete.includes(idx);
  155. do {
  156. if (parensToDelete.length) {
  157. this.tokens = this.tokens.filter(cleanParens);
  158. }
  159. parensToDelete = [];
  160. for (let i = 0; i < this.tokens.length; i++) {
  161. const token = this.tokens[i];
  162. if (!isOp(token) || token.value !== '(') {
  163. continue;
  164. }
  165. let alreadySeen = false;
  166. for (let j = i + 1; j < this.tokens.length; j++) {
  167. const nextToken = this.tokens[j];
  168. if (isOp(nextToken) && nextToken.value === '(') {
  169. // Continue down to the nested parens. We can skip i forward since we know
  170. // everything between i and j is NOT an open paren.
  171. i = j - 1;
  172. break;
  173. } else if (!isOp(nextToken)) {
  174. if (alreadySeen) {
  175. // This has more than one term, no need to delete
  176. break;
  177. }
  178. alreadySeen = true;
  179. } else if (isOp(nextToken) && nextToken.value === ')') {
  180. // We found another paren with zero or one terms inside. Delete the pair.
  181. parensToDelete = [i, j];
  182. break;
  183. }
  184. }
  185. if (parensToDelete.length > 0) {
  186. break;
  187. }
  188. }
  189. } while (parensToDelete.length > 0);
  190. // Now that all erroneous parens are removed we need to remove dangling OR/AND operators.
  191. // I originally removed all the dangling properties in a single loop, but that meant that
  192. // cases like `a OR OR b` would remove both operators, when only one should be removed. So
  193. // instead, we loop until we find an operator to remove, then go back to the start and loop
  194. // again.
  195. let toRemove = -1;
  196. do {
  197. if (toRemove >= 0) {
  198. this.tokens.splice(toRemove, 1);
  199. toRemove = -1;
  200. }
  201. for (let i = 0; i < this.tokens.length; i++) {
  202. const token = this.tokens[i];
  203. const prev = this.tokens[i - 1];
  204. const next = this.tokens[i + 1];
  205. if (isOp(token) && isBooleanOp(token.value)) {
  206. if (prev === undefined || isOp(prev) || next === undefined || isOp(next)) {
  207. // Want to avoid removing `(term) OR (term)`
  208. if (isParen(prev, ')') && isParen(next, '(')) {
  209. continue;
  210. }
  211. toRemove = i;
  212. break;
  213. }
  214. }
  215. }
  216. } while (toRemove >= 0);
  217. return this;
  218. }
  219. removeFilterValue(key: string, value: string) {
  220. const values = this.getFilterValues(key);
  221. if (Array.isArray(values) && values.length) {
  222. this.setFilterValues(
  223. key,
  224. values.filter(item => item !== value)
  225. );
  226. }
  227. }
  228. addFreeText(value: string) {
  229. const token: Token = {type: TokenType.FREE_TEXT, value: formatQuery(value)};
  230. this.tokens.push(token);
  231. return this;
  232. }
  233. addOp(value: string) {
  234. const token: Token = {type: TokenType.OPERATOR, value};
  235. this.tokens.push(token);
  236. return this;
  237. }
  238. get freeText(): string[] {
  239. return this.tokens.filter(t => t.type === TokenType.FREE_TEXT).map(t => t.value);
  240. }
  241. set freeText(values: string[]) {
  242. this.tokens = this.tokens.filter(t => t.type !== TokenType.FREE_TEXT);
  243. for (const v of values) {
  244. this.addFreeText(v);
  245. }
  246. }
  247. copy() {
  248. const q = new QueryResults([]);
  249. q.tokens = [...this.tokens];
  250. return q;
  251. }
  252. isEmpty() {
  253. return this.tokens.length === 0;
  254. }
  255. }
  256. /**
  257. * Tokenize a search into a QueryResult
  258. *
  259. * Should stay in sync with src.sentry.search.utils:tokenize_query
  260. */
  261. export function tokenizeSearch(query: string) {
  262. const tokens = splitSearchIntoTokens(query);
  263. return new QueryResults(tokens);
  264. }
  265. /**
  266. * Splits search strings into tokens for parsing by tokenizeSearch.
  267. *
  268. * Should stay in sync with src.sentry.search.utils:split_query_into_tokens
  269. */
  270. function splitSearchIntoTokens(query: string) {
  271. const queryChars = Array.from(query);
  272. const tokens: string[] = [];
  273. let token = '';
  274. let endOfPrevWord = '';
  275. let quoteType = '';
  276. let quoteEnclosed = false;
  277. for (let idx = 0; idx < queryChars.length; idx++) {
  278. const char = queryChars[idx];
  279. const nextChar = queryChars.length - 1 > idx ? queryChars[idx + 1] : null;
  280. token += char;
  281. if (nextChar !== null && !isSpace(char) && isSpace(nextChar)) {
  282. endOfPrevWord = char;
  283. }
  284. if (isSpace(char) && !quoteEnclosed && endOfPrevWord !== ':' && !isSpace(token)) {
  285. tokens.push(token.trim());
  286. token = '';
  287. }
  288. if (["'", '"'].includes(char) && (!quoteEnclosed || quoteType === char)) {
  289. quoteEnclosed = !quoteEnclosed;
  290. if (quoteEnclosed) {
  291. quoteType = char;
  292. }
  293. }
  294. if (quoteEnclosed && char === '\\' && nextChar === quoteType) {
  295. token += nextChar;
  296. idx++;
  297. }
  298. }
  299. const trimmedToken = token.trim();
  300. if (trimmedToken !== '') {
  301. tokens.push(trimmedToken);
  302. }
  303. return tokens;
  304. }
  305. /**
  306. * Checks if the string is only spaces
  307. */
  308. function isSpace(s: string) {
  309. return s.trim() === '';
  310. }
  311. /**
  312. * Splits a filter on ':' and removes enclosing quotes if present, and returns
  313. * both sides of the split as strings.
  314. */
  315. function parseFilter(filter: string) {
  316. const idx = filter.indexOf(':');
  317. const key = removeSurroundingQuotes(filter.slice(0, idx));
  318. const value = removeSurroundingQuotes(filter.slice(idx + 1));
  319. return [key, value];
  320. }
  321. function removeSurroundingQuotes(text: string) {
  322. const length = text.length;
  323. if (length <= 1) {
  324. return text;
  325. }
  326. let left = 0;
  327. for (; left <= length / 2; left++) {
  328. if (text.charAt(left) !== '"') {
  329. break;
  330. }
  331. }
  332. let right = length - 1;
  333. for (; right >= length / 2; right--) {
  334. if (text.charAt(right) !== '"' || text.charAt(right - 1) === '\\') {
  335. break;
  336. }
  337. }
  338. return text.slice(left, right + 1);
  339. }
  340. /**
  341. * Strips enclosing quotes and parens from a query, if present.
  342. */
  343. function formatQuery(query: string) {
  344. return query.replace(/^["\(]+|["\)]+$/g, '');
  345. }
  346. /**
  347. * Some characters have special meaning in a filter value. So when they are
  348. * directly added as a value, we have to escape them to mean the literal.
  349. */
  350. export function escapeFilterValue(value: string) {
  351. // TODO(txiao): The types here are definitely wrong.
  352. // Need to dig deeper to see where exactly it's wrong.
  353. //
  354. // astericks (*) is used for wildcard searches
  355. return typeof value === 'string' ? value.replace(/([\*])/g, '\\$1') : value;
  356. }