Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / sieve / src / fromSieve / fromSieveTree.ts
blob2b35de5d6b849423b6c1f00165c1f4eb6a08c2ee
1 import invert from 'lodash/invert';
3 import type { FilterCondition, SimpleObject } from '@proton/components/containers/filters/interfaces';
4 import { FilterStatement } from '@proton/components/containers/filters/interfaces';
6 import { LABEL_KEYS, OPERATOR_KEYS } from '../interface';
7 import { extractMainNode, parseComparatorComment, parseIfConditions, parseThenNodes } from './fromSieveTree.helpers';
9 /**
10  * Transforms a tree into a simple representation.
11  */
12 export const fromSieveTree = (tree: any): SimpleObject | undefined => {
13     try {
14         const validated = extractMainNode(tree);
15         const validatedTree = Object.assign(validated.tree, {});
16         const comment = parseComparatorComment(validated.comment);
17         const operator = invert(OPERATOR_KEYS)[validatedTree.If.Type];
19         if (comment && comment.type && operator !== comment.type) {
20             throw new Error('Comment and computed type incompatible');
21         }
23         const conditions = parseIfConditions(
24             validatedTree.If.Tests,
25             comment && comment.comparators
26         ) as FilterCondition[];
28         return {
29             Operator: {
30                 label: operator === 'all' ? LABEL_KEYS.all : LABEL_KEYS.any,
31                 value: operator === 'all' ? FilterStatement.ALL : FilterStatement.ANY,
32             },
33             Conditions: [...conditions],
34             Actions: parseThenNodes(validatedTree.Then),
35         };
36     } catch (e) {
37         return undefined;
38     }