-
Notifications
You must be signed in to change notification settings - Fork 136
/
ExpensiMark.ts
1494 lines (1327 loc) · 68.7 KB
/
ExpensiMark.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'worklet';
import Str from './str';
import * as Constants from './CONST';
import * as UrlPatterns from './Url';
import Logger from './Logger';
import * as Utils from './utils';
type Extras = {
reportIDToName?: Record<string, string>;
accountIDToName?: Record<string, string>;
cacheVideoAttributes?: (vidSource: string, attrs: string) => void;
videoAttributeCache?: Record<string, string>;
};
const EXTRAS_DEFAULT = {};
type ReplacementFn = (extras: Extras, ...matches: string[]) => string;
type Replacement = ReplacementFn | string;
type ProcessFn = (textToProcess: string, replacement: Replacement, shouldKeepRawInput: boolean) => string;
type CommonRule = {
name: string;
replacement: Replacement;
rawInputReplacement?: Replacement;
pre?: (input: string) => string;
post?: (input: string) => string;
};
type RuleWithRegex = CommonRule & {
regex: RegExp;
};
type RuleWithProcess = CommonRule & {
process: ProcessFn;
};
type Rule = RuleWithRegex | RuleWithProcess;
type ReplaceOptions = {
extras?: Extras;
filterRules?: string[];
disabledRules?: string[];
shouldEscapeText?: boolean;
shouldKeepRawInput?: boolean;
};
type TruncateOptions = {
ellipsis?: string;
truncateLastWord?: boolean;
slop?: number;
removeImageTag?: boolean;
};
const MARKDOWN_LINK_REGEX = new RegExp(`\\[([^\\][]*(?:\\[[^\\][]*][^\\][]*)*)]\\(${UrlPatterns.MARKDOWN_URL_REGEX}\\)(?![^<]*(<\\/pre>|<\\/code>))`, 'gi');
const MARKDOWN_IMAGE_REGEX = new RegExp(`\\!(?:\\[([^\\][]*(?:\\[[^\\][]*][^\\][]*)*)])?\\(${UrlPatterns.MARKDOWN_URL_REGEX}\\)(?![^<]*(<\\/pre>|<\\/code>))`, 'gi');
const MARKDOWN_VIDEO_REGEX = new RegExp(
`\\!(?:\\[([^\\][]*(?:\\[[^\\][]*][^\\][]*)*)])?\\(((${UrlPatterns.MARKDOWN_URL_REGEX})\\.(?:${Constants.CONST.VIDEO_EXTENSIONS.join('|')}))\\)(?![^<]*(<\\/pre>|<\\/code>))`,
'gi',
);
const SLACK_SPAN_NEW_LINE_TAG = '<span class="c-mrkdwn__br" data-stringify-type="paragraph-break" style="box-sizing: inherit; display: block; height: unset;"></span>';
export default class ExpensiMark {
static Log = new Logger({
serverLoggingCallback: () => undefined,
// eslint-disable-next-line no-console
clientLoggingCallback: (message) => console.warn(message),
isDebug: true,
});
/**
* Set the logger to use for logging inside of the ExpensiMark class
* @param logger - The logger object to use
*/
static setLogger(logger: Logger) {
ExpensiMark.Log = logger;
}
/** Rules to apply to the text */
rules: Rule[];
/**
* The list of regex replacements to do on a HTML comment for converting it to markdown.
* Order of rules is important
*/
htmlToMarkdownRules: RuleWithRegex[];
/**
* The list of rules to covert the HTML to text.
* Order of rules is important
*/
htmlToTextRules: RuleWithRegex[];
/**
* The list of rules that we have to exclude in shouldKeepWhitespaceRules list.
*/
whitespaceRulesToDisable = ['newline', 'replacepre', 'replacebr', 'replaceh1br'];
/**
* The list of rules that have to be applied when shouldKeepWhitespace flag is true.
*/
filterRules: (rule: Rule) => boolean;
/**
* Filters rules to determine which should keep whitespace.
*/
shouldKeepWhitespaceRules: Rule[];
/**
* maxQuoteDepth is the maximum depth of nested quotes that we want to support.
*/
maxQuoteDepth: number;
/**
* currentQuoteDepth is the current depth of nested quotes that we are processing.
*/
currentQuoteDepth: number;
constructor() {
/**
* The list of regex replacements to do on a comment. Check the link regex is first so links are processed
* before other delimiters
*/
this.rules = [
// Apply the emoji first avoid applying any other formatting rules inside of it
{
name: 'emoji',
regex: Constants.CONST.REG_EXP.EMOJI_RULE,
replacement: (_extras, match) => `<emoji>${match}</emoji>`,
},
/**
* Apply the code-fence to avoid replacing anything inside of it that we're not supposed to
* (aka any rule with the '(?![^<]*<\/pre>)' avoidance in it
*/
{
name: 'codeFence',
// ` is a backtick symbol we are matching on three of them before then after a new line character
regex: /(```.*?(\r\n|\n))((?:\s*?(?!(?:\r\n|\n)?```(?!`))[\S])+\s*?(?:\r\n|\n))(```)/g,
// We're using a function here to perform an additional replace on the content
// inside the backticks because Android is not able to use <pre> tags and does
// not respect whitespace characters at all like HTML does. We do not want to mess
// with the new lines here since they need to be converted into <br>. And we don't
// want to do this anywhere else since that would break HTML.
// will create styling issues so use  
replacement: (_extras, _match, _g1, _g2, textWithinFences) => {
const group = textWithinFences.replace(/(?:(?![\n\r])\s)/g, ' ');
return `<pre>${group}</pre>`;
},
rawInputReplacement: (_extras, _match, _g1, newLineCharacter, textWithinFences) => {
const group = textWithinFences.replace(/(?:(?![\n\r])\s)/g, ' ').replace(/<emoji>|<\/emoji>/g, '');
return `<pre>${newLineCharacter}${group}</pre>`;
},
},
/**
* Converts markdown style video to video tags e.g. ![Expensify](https://www.expensify.com/attachment.mp4)
* We need to convert before image rules since they will not try to create a image tag from an existing video URL
* Extras arg could contain the attribute cache for the video tag which is cached during the html-to-markdown conversion
*/
{
name: 'video',
regex: MARKDOWN_VIDEO_REGEX,
/**
* @param extras - The extras object
* @param videoName - The first capture group - video name
* @param videoSource - The second capture group - video URL
* @return Returns the HTML video tag
*/
replacement: (extras, _match, videoName, videoSource) => {
const extraAttrs = extras && extras.videoAttributeCache && extras.videoAttributeCache[videoSource];
return `<video data-expensify-source="${Str.sanitizeURL(videoSource)}" ${extraAttrs || ''}>${videoName ? `${videoName}` : ''}</video>`;
},
rawInputReplacement: (extras, _match, videoName, videoSource) => {
const extraAttrs = extras && extras.videoAttributeCache && extras.videoAttributeCache[videoSource];
return `<video data-expensify-source="${Str.sanitizeURL(videoSource)}" data-raw-href="${videoSource}" data-link-variant="${typeof videoName === 'string' ? 'labeled' : 'auto'}" ${extraAttrs || ''}>${videoName ? `${videoName}` : ''}</video>`;
},
},
/**
* Apply inline code-block to avoid applying any other formatting rules inside of it,
* like we do for the multi-line code-blocks
*/
{
name: 'inlineCodeBlock',
// Use the url escaped version of a backtick (`) symbol. Mobile platforms do not support lookbehinds,
// so capture the first and third group and place them in the replacement.
// but we should not replace backtick symbols if they include <pre> tags between them.
// At least one non-whitespace character or a specific whitespace character (" " and "\u00A0")
// must be present inside the backticks.
regex: /(\B|_|)`((?:`)*(?!`).*?[\S| |\u00A0]+?.*?(?<!`)(?:`)*)`(\B|_|)(?!`|[^<]*<\/pre>|[^<]*<\/video>)/gm,
replacement: (_extras, _match, g1, g2, g3) => {
const g2Value = g2.trim() === '' ? g2.replaceAll(' ', ' ') : g2;
return `${g1}<code>${g2Value}</code>${g3}`;
},
},
/**
* Converts markdown style links to anchor tags e.g. [Expensify](concierge@expensify.com)
* We need to convert before the auto email link rule and the manual link rule since it will not try to
* create a link from an existing anchor tag.
*/
{
name: 'email',
process: (textToProcess, replacement, shouldKeepRawInput) => {
const regex = new RegExp(`(?!\\[\\s*\\])\\[([^[\\]]*)]\\((mailto:)?${Constants.CONST.REG_EXP.MARKDOWN_EMAIL}\\)`, 'gim');
return this.modifyTextForEmailLinks(regex, textToProcess, replacement as ReplacementFn, shouldKeepRawInput);
},
replacement: (_extras, match, g1, g2) => {
if (!g1.trim()) {
return match;
}
const label = g1.trim();
const href = `mailto:${g2}`;
const formattedLabel = label === href ? g2 : label;
return `<a href="${href}">${formattedLabel}</a>`;
},
rawInputReplacement: (_extras, match, g1, g2, g3) => {
if (!g1.trim()) {
return match;
}
const dataRawHref = g2 ? g2 + g3 : g3;
const href = `mailto:${g3}`;
return `<a href="${href}" data-raw-href="${dataRawHref}" data-link-variant="labeled">${g1}</a>`;
},
},
{
name: 'heading1',
process: (textToProcess, replacement, shouldKeepRawInput = false) => {
const regexp = shouldKeepRawInput ? /^# ( *(?! )(?:(?!<pre>|<video>|\n|\r\n).)+)/gm : /^# +(?! )((?:(?!<pre>|<video>|\n|\r\n).)+)/gm;
return this.replaceTextWithExtras(textToProcess, regexp, EXTRAS_DEFAULT, replacement);
},
replacement: '<h1>$1</h1>',
},
/**
* Converts markdown style images to image tags e.g. ![Expensify](https://www.expensify.com/attachment.png)
* We need to convert before linking rules since they will not try to create a link from an existing img
* tag.
* Additional sanitization is done to the alt attribute to prevent parsing it further to html by later
* rules.
*/
{
name: 'image',
regex: MARKDOWN_IMAGE_REGEX,
replacement: (_extras, _match, g1, g2) => `<img src="${Str.sanitizeURL(g2)}"${g1 ? ` alt="${this.escapeAttributeContent(g1)}"` : ''} />`,
rawInputReplacement: (_extras, _match, g1, g2) =>
`<img src="${Str.sanitizeURL(g2)}"${g1 ? ` alt="${this.escapeAttributeContent(g1)}"` : ''} data-raw-href="${g2}" data-link-variant="${typeof g1 === 'string' ? 'labeled' : 'auto'}" />`,
},
/**
* Converts markdown style links to anchor tags e.g. [Expensify](https://www.expensify.com)
* We need to convert before the autolink rule since it will not try to create a link
* from an existing anchor tag.
*/
{
name: 'link',
process: (textToProcess, replacement) => this.modifyTextForUrlLinks(MARKDOWN_LINK_REGEX, textToProcess, replacement as ReplacementFn),
replacement: (_extras, match, g1, g2) => {
if (!g1.trim()) {
return match;
}
return `<a href="${Str.sanitizeURL(g2)}" target="_blank" rel="noreferrer noopener">${g1.trim()}</a>`;
},
rawInputReplacement: (_extras, match, g1, g2) => {
if (!g1.trim()) {
return match;
}
return `<a href="${Str.sanitizeURL(g2)}" data-raw-href="${g2}" data-link-variant="labeled" target="_blank" rel="noreferrer noopener">${g1}</a>`;
},
},
/**
* Apply the hereMention first because the string @here is still a valid mention for the userMention regex.
* This ensures that the hereMention is always considered first, even if it is followed by a valid
* userMention.
*
* Also, apply the mention rule after email/link to prevent mention appears in an email/link.
*/
{
name: 'hereMentions',
regex: /([a-zA-Z0-9.!$%&+/=?^`{|}_-]?)(@here)([.!$%&+/=?^`{|}_-]?)(?=\b)(?!([\w'#%+-]*@(?:[a-z\d-]+\.)+[a-z]{2,}(?:\s|$|@here))|((?:(?!<a).)+)?<\/a>|[^<]*(<\/pre>|<\/code>))/gm,
replacement: (_extras, match, g1, g2, g3) => {
if (!Str.isValidMention(match)) {
return match;
}
return `${g1}<mention-here>${g2}</mention-here>${g3}`;
},
},
/**
* A room mention is a string that starts with the '#' symbol and is followed by a valid room name.
*
* Note: We are allowing mentions in a format of #room-name The room name can contain any
* combination of letters and hyphens
*/
{
name: 'reportMentions',
regex: /(?<![^ \n*~_])(#[\p{Ll}0-9-]{1,99})(?![^<]*(?:<\/pre>|<\/code>|<\/a>))/gimu,
replacement: '<mention-report>$1</mention-report>',
},
/**
* This regex matches a valid user mention in a string.
* A user mention is a string that starts with the '@' symbol and is followed by a valid user's primary
* login
*
* Note: currently we are only allowing mentions in a format of @+19728974297 (E.164 format phone number)
* and @username@example.com The username can contain any combination of alphanumeric letters, numbers, and
* underscores
*/
{
name: 'userMentions',
regex: new RegExp(
`(@here|[a-zA-Z0-9.!$%&+=?^\`{|}-]?)(@${Constants.CONST.REG_EXP.EMAIL_PART}|@${Constants.CONST.REG_EXP.PHONE_PART})(?!((?:(?!<a).)+)?<\\/a>|[^<]*(<\\/pre>|<\\/code>))`,
'gim',
),
replacement: (_extras, match, g1, g2) => {
const phoneNumberRegex = new RegExp(`^${Constants.CONST.REG_EXP.PHONE_PART}$`);
const mention = g2.slice(1);
const mentionWithoutSMSDomain = Str.removeSMSDomain(mention);
if (!Str.isValidMention(match) || (phoneNumberRegex.test(mentionWithoutSMSDomain) && !Str.isValidPhoneNumber(mentionWithoutSMSDomain))) {
return match;
}
const phoneRegex = new RegExp(`^@${Constants.CONST.REG_EXP.PHONE_PART}$`);
return `${g1}<mention-user>${g2}${phoneRegex.test(g2) ? `@${Constants.CONST.SMS.DOMAIN}` : ''}</mention-user>`;
},
rawInputReplacement: (_extras, match, g1, g2) => {
const phoneNumberRegex = new RegExp(`^${Constants.CONST.REG_EXP.PHONE_PART}$`);
const mention = g2.slice(1);
const mentionWithoutSMSDomain = Str.removeSMSDomain(mention);
if (!Str.isValidMention(match) || (phoneNumberRegex.test(mentionWithoutSMSDomain) && !Str.isValidPhoneNumber(mentionWithoutSMSDomain))) {
return match;
}
return `${g1}<mention-user>${g2}</mention-user>`;
},
},
{
name: 'hereMentionAfterUserMentions',
regex: /(<\/mention-user>)(@here)(?=\b)/gm,
replacement: '$1<mention-here>$2</mention-here>',
},
/**
* Automatically link urls. Runs last of our linkers since we want anything manual to link before this,
* and we do not want to break emails.
*/
{
name: 'autolink',
process: (textToProcess, replacement) => {
const regex = new RegExp(`(?![^<]*>|[^<>]*<\\/(?!h1>))([_*~]*?)${UrlPatterns.MARKDOWN_URL_REGEX}\\1(?!((?:(?!<a).)+)?<\\/a>|[^<]*(<\\/pre>|<\\/code>))`, 'gi');
return this.modifyTextForUrlLinks(regex, textToProcess, replacement as ReplacementFn);
},
replacement: (_extras, _match, g1, g2) => {
const href = Str.sanitizeURL(g2);
return `${g1}<a href="${href}" target="_blank" rel="noreferrer noopener">${g2}</a>${g1}`;
},
rawInputReplacement: (_extras, _match, g1, g2) => {
const href = Str.sanitizeURL(g2);
return `${g1}<a href="${href}" data-raw-href="${g2}" data-link-variant="auto" target="_blank" rel="noreferrer noopener">${g2}</a>${g1}`;
},
},
{
name: 'quote',
// We also want to capture a blank line before or after the quote so that we do not add extra spaces.
// block quotes naturally appear on their own line. Blockquotes should not appear in code fences or
// inline code blocks. A single prepending space should be stripped if it exists
process: (textToProcess, replacement, shouldKeepRawInput = false) => {
const regex = /^(?:>)+ +(?! )(?![^<]*(?:<\/pre>|<\/code>|<\/video>))([^\v\n\r]+)/gm;
if (shouldKeepRawInput) {
const rawInputRegex = /^(?:>)+ +(?! )(?![^<]*(?:<\/pre>|<\/code>|<\/video>))([^\v\n\r]*)/gm;
return this.replaceTextWithExtras(textToProcess, rawInputRegex, EXTRAS_DEFAULT, replacement);
}
return this.modifyTextForQuote(regex, textToProcess, replacement as ReplacementFn);
},
replacement: (_extras, g1) => {
// We want to enable 2 options of nested heading inside the blockquote: "># heading" and "> # heading".
// To do this we need to parse body of the quote without first space
const handleMatch = (match: string) => match;
const textToReplace = g1.replace(/^>( )?/gm, handleMatch);
const filterRules = ['heading1'];
// if we don't reach the max quote depth we allow the recursive call to process possible quote
if (this.currentQuoteDepth < this.maxQuoteDepth - 1) {
filterRules.push('quote');
this.currentQuoteDepth++;
}
const replacedText = this.replace(textToReplace, {
filterRules,
shouldEscapeText: false,
shouldKeepRawInput: false,
});
this.currentQuoteDepth = 0;
return `<blockquote>${replacedText}</blockquote>`;
},
rawInputReplacement: (_extras, g1) => {
// We want to enable 2 options of nested heading inside the blockquote: "># heading" and "> # heading".
// To do this we need to parse body of the quote without first space
let isStartingWithSpace = false;
const handleMatch = (_match: string, g2: string) => {
isStartingWithSpace = !!g2;
return '';
};
const textToReplace = g1.replace(/^>( )?/gm, handleMatch);
const filterRules = ['heading1'];
// if we don't reach the max quote depth we allow the recursive call to process possible quote
if (this.currentQuoteDepth < this.maxQuoteDepth - 1 || isStartingWithSpace) {
filterRules.push('quote');
this.currentQuoteDepth++;
}
const replacedText = this.replace(textToReplace, {
filterRules,
shouldEscapeText: false,
shouldKeepRawInput: true,
});
this.currentQuoteDepth = 0;
return `<blockquote>${isStartingWithSpace ? ' ' : ''}${replacedText}</blockquote>`;
},
},
/**
* Use \b in this case because it will match on words, letters,
* and _: https://www.rexegg.com/regex-boundaries.html#wordboundary
* Use [\s\S]* instead of .* to match newline
*/
{
name: 'italic',
regex: /(<(pre|code|a|mention-user|video)[^>]*>(.*?)<\/\2>)|((\b_+|\b)_((?![\s_])[\s\S]*?[^\s_](?<!\s))_(?![^\W_])(?![^<]*>)(?![^<]*(<\/pre>|<\/code>|<\/a>|<\/mention-user>|<\/video>)))/g,
replacement: (_extras, match, html, tag, content, text, extraLeadingUnderscores, textWithinUnderscores) => {
// Skip any <pre>, <code>, <a>, <mention-user>, <video> tag contents
if (html) {
return html;
}
// If any tags are included inside underscores, ignore it. ie. _abc <pre>pre tag</pre> abc_
if (textWithinUnderscores.includes('</pre>') || this.containsNonPairTag(textWithinUnderscores)) {
return match;
}
if (String(textWithinUnderscores).match(`^${Constants.CONST.REG_EXP.MARKDOWN_EMAIL}`)) {
return `<em>${extraLeadingUnderscores}${textWithinUnderscores}</em>`;
}
return `${extraLeadingUnderscores}<em>${textWithinUnderscores}</em>`;
},
},
/**
* Automatically links emails that are not in a link. Runs before the autolinker as it will not link an
* email that is in a link
* Prevent emails from starting with [~_*]. Such emails should not be supported.
*/
{
name: 'autoEmail',
regex: new RegExp(`([^\\w'#%+-]|^)${Constants.CONST.REG_EXP.MARKDOWN_EMAIL}(?!((?:(?!<a).)+)?<\\/a>|[^<>]*<\\/(?!em|h1|blockquote))`, 'gim'),
replacement: '$1<a href="mailto:$2">$2</a>',
rawInputReplacement: '$1<a href="mailto:$2" data-raw-href="$2" data-link-variant="auto">$2</a>',
},
{
// Use \B in this case because \b doesn't match * or ~.
// \B will match everything that \b doesn't, so it works
// for * and ~: https://www.rexegg.com/regex-boundaries.html#notb
name: 'bold',
regex: /(?<!<[^>]*)(\b_|\B)\*(?![^<]*(?:<\/pre>|<\/code>|<\/a>|<\/video>))((?![\s*])[\s\S]*?[^\s*](?<!\s))\*\B(?![^<]*>)(?![^<]*(<\/pre>|<\/code>|<\/a>|<\/video>))/g,
replacement: (_extras, match, g1, g2) => {
if (g1.includes('_')) {
return `${g1}<strong>${g2}</strong>`;
}
return g2.includes('</pre>') || this.containsNonPairTag(g2) ? match : `<strong>${g2}</strong>`;
},
},
{
name: 'strikethrough',
regex: /(?<!<[^>]*)\B~((?![\s~])[\s\S]*?[^\s~](?<!\s))~\B(?![^<]*>)(?![^<]*(<\/pre>|<\/code>|<\/a>|<\/video>))/g,
replacement: (_extras, match, g1) => (g1.includes('</pre>') || this.containsNonPairTag(g1) ? match : `<del>${g1}</del>`),
},
{
name: 'newline',
regex: /\r?\n/g,
replacement: '<br />',
},
{
// We're removing <br /> because when </pre> and <br /> occur together, an extra line is added.
name: 'replacepre',
regex: /<\/pre>\s*<br\s*[/]?>/gi,
replacement: '</pre>',
},
{
// We're removing <br /> because when <h1> and <br /> occur together, an extra line is added.
name: 'replaceh1br',
regex: /<\/h1><br\s*[/]?>/gi,
replacement: '</h1>',
},
];
/**
* The list of regex replacements to do on a HTML comment for converting it to markdown.
* Order of rules is important
*/
this.htmlToMarkdownRules = [
// Used to Exclude tags
{
name: 'replacepre',
regex: /<\/pre>(.)/gi,
replacement: '</pre><br />$1',
},
{
name: 'exclude',
regex: new RegExp(['<(script|style)(?:"[^"]*"|\'[^\']*\'|[^\'">])*>([\\s\\S]*?)<\\/\\1>', '(?![^<]*(<\\/pre>|<\\/code>))(\n|\r\n)?'].join(''), 'gim'),
replacement: '',
},
{
name: 'nested',
regex: /<(pre)(?:"[^"]*"|'[^']*'|[^'">])*><(div|code)(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/\2><\/pre>/gi,
replacement: '<pre>$3</pre>',
},
{
name: 'newline',
// Replaces open and closing <br><br/> tags with a single <br/>
// Slack uses special <span> tag for empty lines instead of <br> tag
pre: (inputString) =>
inputString
.replace('<br></br>', '<br/>')
.replace('<br><br/>', '<br/>')
.replace(/(<tr.*?<\/tr>)/g, '$1<br/>')
.replace('<br/></tbody>', '')
.replace(SLACK_SPAN_NEW_LINE_TAG + SLACK_SPAN_NEW_LINE_TAG, '<br/><br/><br/>')
.replace(SLACK_SPAN_NEW_LINE_TAG, '<br/><br/>'),
// Include the immediately followed newline as `<br>\n` should be equal to one \n.
regex: /<br(?:"[^"]*"|'[^']*'|[^'"><])*>\n?/gi,
replacement: '\n',
},
{
name: 'heading1',
regex: /[^\S\r\n]*<(h1)(?:"[^"]*"|'[^']*'|[^'">])*>(.*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: '<h1># $2</h1>',
},
{
name: 'listItem',
regex: /\s*<(li)(?:"[^"]*"|'[^']*'|[^'">])*>(.*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))\s*/gi,
replacement: '<li> $2</li>',
},
// Use [\s\S]* instead of .* to match newline
{
name: 'italic',
regex: /<(em|i)\b(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: '_$2_',
},
{
name: 'bold',
regex: /<(b|strong)\b(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: (extras, match, tagName, innerContent) => {
// To check if style attribute contains bold font-weight
const isBoldFromStyle = (style: string | null) => {
return style ? style.replace(/\s/g, '').includes('font-weight:bold;') || style.replace(/\s/g, '').includes('font-weight:700;') : false;
};
const updateSpacesAndWrapWithAsterisksIfBold = (content: string, isBold: boolean) => {
const trimmedContent = content.trim();
const leadingSpace = content.startsWith(' ') ? ' ' : '';
const trailingSpace = content.endsWith(' ') ? ' ' : '';
return isBold ? `${leadingSpace}*${trimmedContent}*${trailingSpace}` : content;
};
// Determine if the outer tag is bold
const fontWeightRegex = /style="([^"]*?\bfont-weight:\s*(\d+|bold|normal)[^"]*?)"/;
const styleAttributeMatch = match.match(fontWeightRegex);
const isFontWeightBold = isBoldFromStyle(styleAttributeMatch ? styleAttributeMatch[1] : null);
const isBold = styleAttributeMatch ? isFontWeightBold : tagName === 'b' || tagName === 'strong';
// Process nested spans with potential bold style
const processedInnerContent = innerContent.replace(/<span(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/span>/gi, (nestedMatch, nestedContent) => {
const nestedStyleMatch = nestedMatch.match(fontWeightRegex);
const isNestedBold = isBoldFromStyle(nestedStyleMatch ? nestedStyleMatch[1] : null);
return updateSpacesAndWrapWithAsterisksIfBold(nestedContent, isNestedBold);
});
return updateSpacesAndWrapWithAsterisksIfBold(processedInnerContent, isBold);
},
},
{
name: 'strikethrough',
regex: /<(del|s)(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: '~$2~',
},
{
name: 'quote',
regex: /<(blockquote|q)(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: (_extras, _match, _g1, g2) => {
// We remove the line break before heading inside quote to avoid adding extra line
let resultString: string[] | string = g2
.replace(/\n?(<h1># )/g, '$1')
.replace(/(<h1>|<\/h1>)+/g, '\n')
.trim()
.split('\n');
// Wrap each string in the array with <blockquote> and </blockquote>
resultString = resultString.map((line) => {
return `<blockquote>${line}</blockquote>`;
});
resultString = resultString
.map((text) => {
let modifiedText = text;
let depth;
do {
depth = (modifiedText.match(/<blockquote>/gi) || []).length;
modifiedText = modifiedText.replace(/<blockquote>/gi, '');
modifiedText = modifiedText.replace(/<\/blockquote>/gi, '');
} while (/<blockquote>/i.test(modifiedText));
return `${'>'.repeat(depth)} ${modifiedText}`;
})
.join('\n');
// We want to keep <blockquote> tag here and let method replaceBlockElementWithNewLine to handle the line break later
return `<blockquote>${resultString}</blockquote>`;
},
},
{
name: 'inlineCodeBlock',
regex: /<(code)(?:"[^"]*"|'[^']*'|[^'">])*>(.*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: '`$2`',
},
{
name: 'codeFence',
regex: /<(pre)(?:"[^"]*"|'[^']*'|[^'">])*>([\s\S]*?)(\n?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: (_extras, _match, _g1, g2) => `\`\`\`\n${g2}\n\`\`\``,
},
{
name: 'anchor',
regex: /<(a)[^><]*href\s*=\s*(['"])(.*?)\2(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi,
replacement: (_extras, _match, _g1, _g2, g3, g4) => {
const email = g3.startsWith('mailto:') ? g3.slice(7) : '';
if (email === g4) {
return email;
}
return `[${g4}](${email || g3})`;
},
},
{
name: 'image',
regex: /<img[^><]*src\s*=\s*(['"])(.*?)\1(?:[^><]*alt\s*=\s*(['"])(.*?)\3)?[^><]*>*(?![^<][\s\S]*?(<\/pre>|<\/code>))/gi,
replacement: (_extras, _match, _g1, g2, _g3, g4) => {
if (g4) {
return `![${g4}](${g2})`;
}
return `!(${g2})`;
},
},
{
name: 'video',
regex: /<video[^><]*data-expensify-source\s*=\s*(['"])(\S*?)\1(.*?)>([^><]*)<\/video>*(?![^<][\s\S]*?(<\/pre>|<\/code>))/gi,
/**
* @param extras - The extras object
* @param match The full match
* @param _g1 The first capture group
* @param videoSource - the second capture group - video source (video URL)
* @param videoAttrs - the third capture group - video attributes (data-expensify-width, data-expensify-height, etc...)
* @param videoName - the fourth capture group will be the video file name (the text between opening and closing video tags)
* @returns The markdown video tag
*/
replacement: (extras, _match, _g1, videoSource, videoAttrs, videoName) => {
if (videoAttrs && extras && extras.cacheVideoAttributes && typeof extras.cacheVideoAttributes === 'function') {
extras.cacheVideoAttributes(videoSource, videoAttrs);
}
if (videoName) {
return `![${videoName}](${videoSource})`;
}
return `!(${videoSource})`;
},
},
{
name: 'reportMentions',
regex: /<mention-report reportID="(\d+)"(?: *\/>|><\/mention-report>)/gi,
replacement: (extras, _match, g1, _offset, _string) => {
const reportToNameMap = extras.reportIDToName;
if (!reportToNameMap || !reportToNameMap[g1]) {
ExpensiMark.Log.alert('[ExpensiMark] Missing report name', {reportID: g1});
return '#Hidden';
}
return reportToNameMap[g1];
},
},
{
name: 'userMention',
regex: /(?:<mention-user accountID="(\d+)"(?: *\/>|><\/mention-user>))|(?:<mention-user>(.*?)<\/mention-user>)/gi,
replacement: (extras, _match, g1, g2, _offset, _string) => {
if (g1) {
const accountToNameMap = extras.accountIDToName;
if (!accountToNameMap || !accountToNameMap[g1]) {
ExpensiMark.Log.alert('[ExpensiMark] Missing account name', {accountID: g1});
return '@Hidden';
}
return `@${Str.removeSMSDomain(extras.accountIDToName?.[g1] ?? '')}`;
}
return Str.removeSMSDomain(g2);
},
},
];
/**
* The list of rules to covert the HTML to text.
* Order of rules is important
*/
this.htmlToTextRules = [
{
name: 'breakline',
regex: /<br[^>]*>/gi,
replacement: '\n',
},
{
name: 'blockquoteWrapHeadingOpen',
regex: /<blockquote><h1>/gi,
replacement: '<blockquote>',
},
{
name: 'blockquoteWrapHeadingClose',
regex: /<\/h1><\/blockquote>/gi,
replacement: '</blockquote>',
},
{
name: 'blockElementOpen',
regex: /(.|\s)<(blockquote|h1|pre)>/gi,
replacement: '$1\n',
},
{
name: 'blockElementClose',
regex: /<\/(blockquote|h1|pre)>(.|\s)/gm,
replacement: '\n$2',
},
{
name: 'removeStyle',
regex: /<style>.*?<\/style>/gi,
replacement: '',
},
{
name: 'image',
regex: /<img[^><]*src\s*=\s*(['"])(.*?)\1(?:[^><]*alt\s*=\s*(['"])(.*?)\3)?[^><]*>*(?![^<][\s\S]*?(<\/pre>|<\/code>))/gi,
replacement: '[Attachment]',
},
{
name: 'reportMentions',
regex: /<mention-report reportID="(\d+)" *\/>/gi,
replacement: (extras, _match, g1, _offset, _string) => {
const reportToNameMap = extras.reportIDToName;
if (!reportToNameMap || !reportToNameMap[g1]) {
ExpensiMark.Log.alert('[ExpensiMark] Missing report name', {reportID: g1});
return '#Hidden';
}
return reportToNameMap[g1];
},
},
{
name: 'userMention',
regex: /<mention-user accountID="(\d+)" *\/>/gi,
replacement: (extras, _match, g1, _offset, _string) => {
const accountToNameMap = extras.accountIDToName;
if (!accountToNameMap || !accountToNameMap[g1]) {
ExpensiMark.Log.alert('[ExpensiMark] Missing account name', {accountID: g1});
return '@Hidden';
}
return `@${Str.removeSMSDomain(extras.accountIDToName?.[g1] ?? '')}`;
},
},
{
name: 'stripTag',
regex: /(<([^>]+)>)/gi,
replacement: '',
},
];
/**
* The list of rules that we have to exclude in shouldKeepWhitespaceRules list.
*/
this.whitespaceRulesToDisable = ['newline', 'replacepre', 'replacebr', 'replaceh1br'];
/**
* The list of rules that have to be applied when shouldKeepWhitespace flag is true.
* @param rule - The rule to check.
* @returns true if the rule should be applied, otherwise false.
*/
this.filterRules = (rule: Rule) => !this.whitespaceRulesToDisable.includes(rule.name);
/**
* Filters rules to determine which should keep whitespace.
* @returns The filtered rules.
*/
this.shouldKeepWhitespaceRules = this.rules.filter(this.filterRules);
/**
* maxQuoteDepth is the maximum depth of nested quotes that we want to support.
*/
this.maxQuoteDepth = 3;
/**
* currentQuoteDepth is the current depth of nested quotes that we are processing.
*/
this.currentQuoteDepth = 0;
}
/**
* Retrieves the HTML ruleset based on the provided filter rules, disabled rules, and shouldKeepRawInput flag.
* @param filterRules - An array of rule names to filter the ruleset.
* @param disabledRules - An array of rule names to disable in the ruleset.
* @param shouldKeepRawInput - A boolean flag indicating whether to keep raw input.
*/
getHtmlRuleset(filterRules: string[], disabledRules: string[], shouldKeepRawInput: boolean) {
let rules = this.rules;
const hasRuleName = (rule: Rule) => filterRules.includes(rule.name);
const hasDisabledRuleName = (rule: Rule) => !disabledRules.includes(rule.name);
if (shouldKeepRawInput) {
rules = this.shouldKeepWhitespaceRules;
}
if (filterRules.length > 0) {
rules = this.rules.filter(hasRuleName);
}
if (disabledRules.length > 0) {
rules = rules.filter(hasDisabledRuleName);
}
return rules;
}
/**
* Replaces markdown with html elements
*
* @param text - Text to parse as markdown
* @param [options] - Options to customize the markdown parser
* @param [options.filterRules=[]] - An array of name of rules as defined in this class.
* If not provided, all available rules will be applied.
* @param [options.shouldEscapeText=true] - Whether or not the text should be escaped
* @param [options.disabledRules=[]] - An array of name of rules as defined in this class.
* If not provided, all available rules will be applied. If provided, the rules in the array will be skipped.
*/
replace(text: string, {filterRules = [], shouldEscapeText = true, shouldKeepRawInput = false, disabledRules = [], extras = EXTRAS_DEFAULT}: ReplaceOptions = {}): string {
// This ensures that any html the user puts into the comment field shows as raw html
let replacedText = shouldEscapeText ? Utils.escapeText(text) : text;
const rules = this.getHtmlRuleset(filterRules, disabledRules, shouldKeepRawInput);
const processRule = (rule: Rule) => {
// Pre-process text before applying regex
if (rule.pre) {
replacedText = rule.pre(replacedText);
}
const replacement = shouldKeepRawInput && rule.rawInputReplacement ? rule.rawInputReplacement : rule.replacement;
if ('process' in rule) {
replacedText = rule.process(replacedText, replacement, shouldKeepRawInput);
} else {
replacedText = this.replaceTextWithExtras(replacedText, rule.regex, extras, replacement);
}
// Post-process text after applying regex
if (rule.post) {
replacedText = rule.post(replacedText);
}
};
try {
rules.forEach(processRule);
} catch (e) {
ExpensiMark.Log.alert('Error replacing text with html in ExpensiMark.replace', {error: e});
// We want to return text without applying rules if exception occurs during replacing
return shouldEscapeText ? Utils.escapeText(text) : text;
}
return replacedText;
}
/**
* Checks matched URLs for validity and replace valid links with html elements
*/
modifyTextForUrlLinks(regex: RegExp, textToCheck: string, replacement: ReplacementFn): string {
let match = regex.exec(textToCheck);
let replacedText = '';
let startIndex = 0;
while (match !== null) {
// We end the link at the last closing parenthesis that matches an opening parenthesis because unmatched closing parentheses are unlikely to be in the url
// and can be part of markdown for example
let unmatchedOpenParentheses = 0;
let url = match[2];
for (let i = 0; i < url.length; i++) {
if (url[i] === '(') {
unmatchedOpenParentheses++;
} else if (url[i] === ')') {
// Unmatched closing parenthesis
if (unmatchedOpenParentheses <= 0) {
const numberOfCharsToRemove = url.length - i;
match[0] = match[0].substr(0, match[0].length - numberOfCharsToRemove);
url = url.substr(0, url.length - numberOfCharsToRemove);
break;
}
unmatchedOpenParentheses--;
}
}
// Because we are removing ) parenthesis, some special characters that shouldn't be in the href are in the href
// For example google.com/toto.) is accepted by the regular expression above and we remove the ) parenthesis, so the link becomes google.com/toto. which is not a valid link
// In that case we should also remove the "."
// Those characters should only be remove from the url if this url doesn't have a parameter or a fragment
if (!url.includes('?') && !url.includes('#')) {
let numberOfCharsToRemove = 0;
for (let i = url.length - 1; i >= 0; i--) {
if (Constants.CONST.SPECIAL_CHARS_TO_REMOVE.includes(url[i])) {
numberOfCharsToRemove++;
} else {
break;
}
}
if (numberOfCharsToRemove) {
match[0] = match[0].substring(0, match[0].length - numberOfCharsToRemove);
url = url.substring(0, url.length - numberOfCharsToRemove);
}
}
replacedText = replacedText.concat(textToCheck.substr(startIndex, match.index - startIndex));
// We want to avoid matching domains in email addresses so we don't render them as URLs,
// but we need to check if there are valid URLs after the email address and render them accordingly,
// e.g. test@expensify.com/https://www.test.com
let isDoneMatching = false;
let shouldApplyAutoLinkAgain = true;
// If we find a URL with a leading @ sign, we need look for other domains in the rest of the string
if (match.index !== 0 && textToCheck[match.index - 1] === '@') {
const domainRegex = /^(([a-z-0-9]+\.)+[a-z]{2,})(\S*)/i;
const domainMatch = domainRegex.exec(url);
// If we find another domain in the remainder of the string, we apply the auto link rule again and set a flag to avoid re-doing below.
if (domainMatch !== null && domainMatch[3] !== '') {
replacedText = replacedText.concat(domainMatch[1] + this.replace(domainMatch[3], {filterRules: ['autolink']}));
shouldApplyAutoLinkAgain = false;
} else {
// Otherwise, we're done applying rules
isDoneMatching = true;
}
}
// We don't want to apply link rule if match[1] contains the code block inside the [] of the markdown e.g. [```example```](https://example.com)
// or if match[1] is multiline text preceeded by markdown heading, e.g., # [example\nexample\nexample](https://example.com)
if (isDoneMatching || match[1].includes('</pre>') || match[1].includes('</h1>')) {
replacedText = replacedText.concat(textToCheck.substr(match.index, match[0].length));
} else if (shouldApplyAutoLinkAgain) {
const urlRegex = new RegExp(`^${UrlPatterns.LOOSE_URL_REGEX}$|^${UrlPatterns.URL_REGEX}$`, 'i');
// `match[1]` contains the text inside the [] of the markdown e.g. [example](https://example.com)
// At the entry of function this.replace, text is already escaped due to the rules that precede the link
// rule (eg, codeFence, inlineCodeBlock, email), so we don't need to escape the text again here.
// If the text `match[1]` exactly matches a URL, we skip translating the filterRules
// So that special characters such as ['_', '*', '~'] are preserved in the text.
const linkText = urlRegex.test(match[1])
? match[1]
: this.replace(match[1], {
filterRules: ['bold', 'strikethrough', 'italic'],
shouldEscapeText: false,
});
replacedText = replacedText.concat(replacement(EXTRAS_DEFAULT, match[0], linkText, url));
}
startIndex = match.index + match[0].length;
// Now we move to the next match that the js regex found in the text
match = regex.exec(textToCheck);
}
if (startIndex < textToCheck.length) {
replacedText = replacedText.concat(textToCheck.substr(startIndex));
}
return replacedText;
}
/**
* Checks matched Emails for validity and replace valid links with html elements
*/
modifyTextForEmailLinks(regex: RegExp, textToCheck: string, replacement: ReplacementFn, shouldKeepRawInput: boolean): string {