@postalsys/email-ai-tools 3.0.4 → 3.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,82 +1,652 @@
1
- import { parseDocument } from 'htmlparser2';
1
+ import { DomHandler, Parser } from 'htmlparser2';
2
2
  import serialize from 'dom-serializer';
3
+ import { compile } from 'css-select';
4
+ import { parse as parseSelector } from 'css-what';
3
5
  import { isTag, isText, isComment, hasChildren, textContent, findAll, findOne, prependChild, removeElement } from 'domutils';
4
6
  import { truncate } from './token-estimate.js';
5
7
  // What the reader never sees must not reach the model either: an email can carry instructions
6
8
  // for an AI in text a mail client does not render, and the summary has to describe the message
7
9
  // as it looks to the person it was sent to. The links are collected before anything is removed,
8
10
  // because the checks run on them must see every link the message carries, hidden or not
11
+ // Elements a browser reads as raw text, or as markup depending on whether scripts run, where the
12
+ // parser here builds elements: a style element inside one is text to a mail client and a sheet
13
+ // here, or the other way round. A sheet in one makes the sheets unreadable (see gatherStyle())
14
+ const RAW_TEXT_IN_BROWSER = new Set(['noframes', 'noembed', 'iframe', 'plaintext', 'noscript', 'xmp', 'textarea', 'title']);
9
15
  // Elements whose content is never rendered as text
10
16
  const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed']);
11
- // Comments and quoted strings inside a style attribute, which carry no declarations
12
- const STYLE_NOISE = /\/\*[\s\S]*?\*\/|"[^"]*"|'[^']*'/g;
13
17
  // Everything here runs synchronously in the process that called it, so how much of a message is
14
18
  // read has to be this library's decision rather than the sender's. The HTML is cut before it is
15
19
  // parsed; the text of a link is cut to what a reader could take in as its destination
16
20
  const MAX_HTML_LENGTH = 1024 * 1024;
17
21
  const MAX_LINK_TEXT_LENGTH = 1024;
18
- // Outlook for Windows shows what a conditional comment wraps; the markers go, the content stays.
19
- // The condition is bounded: an opening marker that never closes used to be scanned to the end
20
- // of the document, once for every marker, which is quadratic
21
- const CONDITIONAL_COMMENT = /<!--\[if [^\]]{0,200}\]>|<!\[endif\]-->/gi;
22
+ // The style sheets of a message are read for the rules that hide text or show it again. How much of
23
+ // them is read, how many such rules are applied and how long a selector may be are bounded, since
24
+ // every rule is tested against every element
25
+ const MAX_STYLE_LENGTH = 128 * 1024;
26
+ const MAX_HIDING_RULES = 100;
27
+ const MAX_SELECTOR_LENGTH = 512;
28
+ // How deep elements may nest before the rest of the document is left out. The parser's work grows
29
+ // with the square of the depth and every walk over the document recurses: a megabyte of nothing but
30
+ // opening tags took the parser and the link scan more than ten seconds, and then overflowed the
31
+ // stack. Real mail nests a few dozen levels, a layout of tables in tables a hundred or two. The
32
+ // HTML to text converter reads no deeper than this either, so nothing it would have shown is lost
33
+ const MAX_NESTING = 500;
34
+ // The work the hiding rules may cost, as tests of a selector against an element, a descendant
35
+ // combinator counting once for every level it may have to climb. Ten million such tests take about
36
+ // half a second; ordinary mail, a few thousand elements and a few dozen rules, stays far below it.
37
+ // Past the budget no rule is applied, and the text stays in front of the model as it did before
38
+ // style sheets were read at all
39
+ const RULE_WORK_BUDGET = 10_000_000;
40
+ // A media query is honored only when it holds for every reader: no narrower than the smallest
41
+ // phone, no wider than any screen. A sheet or a block for some readers only is not read, and when it
42
+ // sets anything the hiding check reads, no sheet is trusted (see sheetRules())
43
+ const ALWAYS_MIN_WIDTH = 320;
44
+ const ALWAYS_MAX_WIDTH = 4000;
45
+ // The start of an Outlook conditional comment's text, "[if mso]>" and the like. The condition is
46
+ // bounded, so a comment that only starts like one is not scanned for its end
47
+ const CONDITIONAL_OPEN = /^\[if [^\]]{0,200}\]>/i;
48
+ // What is left of a downlevel-revealed opener, "<!--[if !mso]><!-->" or "<!--[if !mso]><!-- -->"
49
+ const REVEALED_OPEN_REST = /^<!(?:--\s*)?$/;
50
+ const CONDITIONAL_CLOSE = '<![endif]';
22
51
  // Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
23
52
  // bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
24
53
  // stops them splitting words the model should recognise or reordering text it should read
25
54
  const INVISIBLE_CHARS = /[\u00ad\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/g;
26
- // Only what reliably hides text. Zero sizes of boxes and negative positions depend on other
27
- // properties to hide anything, so they are left alone rather than dropping text the reader sees
28
- function isHiddenStyle(input) {
29
- const style = String(input ?? '').replace(STYLE_NOISE, ' ');
30
- if (!style.trim()) {
55
+ // Where a comment or a quoted string that starts at `i` ends, or `i` when neither starts there. One
56
+ // that never closes runs to the end of the text, so a scan never restarts from every opening marker
57
+ function skipNoise(text, i) {
58
+ if (text[i] === '/' && text[i + 1] === '*') {
59
+ const end = text.indexOf('*/', i + 2);
60
+ return end < 0 ? text.length : end + 2;
61
+ }
62
+ const quote = text[i];
63
+ if (quote !== '"' && quote !== "'") {
64
+ return i;
65
+ }
66
+ for (let j = i + 1; j < text.length; j++) {
67
+ if (text[j] === '\\') {
68
+ j++;
69
+ }
70
+ else if (text[j] === quote) {
71
+ return j + 1;
72
+ }
73
+ }
74
+ return text.length;
75
+ }
76
+ // The text with each comment, and each quoted string unless `keepStrings`, replaced by a space, in
77
+ // one pass. A declaration carries no strings worth reading, a selector does
78
+ function withoutNoise(input, keepStrings) {
79
+ let output = '';
80
+ let from = 0;
81
+ for (let i = 0; i < input.length;) {
82
+ const end = skipNoise(input, i);
83
+ if (end === i) {
84
+ i++;
85
+ }
86
+ else if (keepStrings && input[i] !== '/') {
87
+ i = end;
88
+ }
89
+ else {
90
+ output += `${input.substring(from, i)} `;
91
+ i = from = end;
92
+ }
93
+ }
94
+ return output + input.substring(from);
95
+ }
96
+ function declarations(input) {
97
+ const list = [];
98
+ for (const declaration of withoutNoise(input, false).split(';')) {
99
+ const match = /^\s*([a-z-]+)\s*:\s*([^!]*)(!\s*important)?/i.exec(declaration);
100
+ if (match) {
101
+ list.push([match[1].toLowerCase(), match[2].trim().toLowerCase(), !!match[3]]);
102
+ }
103
+ }
104
+ return list;
105
+ }
106
+ // The properties the hiding check reads. A style sheet rule that sets none of them cannot hide an
107
+ // element or show one again, so it is not matched at all
108
+ // Vertical padding, which a box of no height still shows (see isCollapsed())
109
+ const PADDING_PROPERTIES = ['padding', 'padding-top', 'padding-bottom', 'padding-block', 'padding-block-start', 'padding-block-end'];
110
+ const HIDING_PROPERTIES = new Set([
111
+ 'display',
112
+ 'visibility',
113
+ 'opacity',
114
+ 'font-size',
115
+ 'text-indent',
116
+ 'height',
117
+ 'max-height',
118
+ 'min-height',
119
+ 'overflow',
120
+ 'overflow-y',
121
+ ...PADDING_PROPERTIES
122
+ ]);
123
+ // The same properties found in raw style text, for style that is not read rule by rule
124
+ const HIDING_IN_TEXT = new RegExp(`(?:^|[{;\\s"'])(?:${[...HIDING_PROPERTIES].join('|')})\\s*:`, 'i');
125
+ // Whether style text nothing here reads rule by rule sets what the hiding check reads. A backslash
126
+ // counts too: CSS allows escapes in a property name, which no check here decodes
127
+ const mentionsHiding = (text) => text.includes('\\') || HIDING_IN_TEXT.test(text);
128
+ // The hiding properties an element inside can set again: they are inherited, so text inside an
129
+ // element that is hidden by one of them shows when something inside it sets the property itself
130
+ const INHERITED_HIDING = new Set(['visibility', 'font-size', 'text-indent']);
131
+ // Elements a height of zero does not collapse: inline elements ignore height, and a table and its
132
+ // rows and cells grow to fit what they hold
133
+ const UNCOLLAPSIBLE_TAGS = new Set([
134
+ 'a',
135
+ 'abbr',
136
+ 'b',
137
+ 'bdi',
138
+ 'bdo',
139
+ 'big',
140
+ 'cite',
141
+ 'code',
142
+ 'dfn',
143
+ 'em',
144
+ 'font',
145
+ 'i',
146
+ 'kbd',
147
+ 'label',
148
+ 'mark',
149
+ 'q',
150
+ 's',
151
+ 'samp',
152
+ 'small',
153
+ 'span',
154
+ 'strike',
155
+ 'strong',
156
+ 'sub',
157
+ 'sup',
158
+ 'time',
159
+ 'tt',
160
+ 'u',
161
+ 'var',
162
+ 'table',
163
+ 'thead',
164
+ 'tbody',
165
+ 'tfoot',
166
+ 'tr',
167
+ 'td',
168
+ 'th',
169
+ 'caption'
170
+ ]);
171
+ const BLOCK_DISPLAYS = new Set(['block', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'list-item', 'flow-root']);
172
+ const isClipped = (value) => value === 'hidden' || value === 'clip';
173
+ // A length of zero that holds whatever the box sits in. A percentage is resolved against the parent
174
+ // and becomes auto when the parent's height is, which is the usual case
175
+ const isAbsoluteZero = (value) => /^0(?:\.0*)?(?:px|pt|pc|em|rem|ex|ch|cm|mm|in|q|vh|vw|vmin|vmax)?$/.test(value || '');
176
+ /**
177
+ * Whether a box of no height clips everything in it: the preheader trick. Only where it holds for
178
+ * every reader, so a block-level box, an absolute zero, nothing that sets a minimum height again, no
179
+ * vertical padding (overflow clips at the padding edge, so text shows in the padding) and a clipped
180
+ * overflow
181
+ */
182
+ function isCollapsed(style, element) {
183
+ const display = style.get('display');
184
+ const blockLevel = display ? BLOCK_DISPLAYS.has(display) : !UNCOLLAPSIBLE_TAGS.has(element.name);
185
+ if (!blockLevel || !(isAbsoluteZero(style.get('height')) || isAbsoluteZero(style.get('max-height')))) {
31
186
  return false;
32
187
  }
33
- for (const declaration of style.split(';')) {
34
- const match = /^\s*([a-z-]+)\s*:\s*([^!]*)/i.exec(declaration);
35
- if (!match) {
36
- continue;
188
+ if (style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) {
189
+ return false;
190
+ }
191
+ for (const property of PADDING_PROPERTIES) {
192
+ if (style.has(property) && !style.get(property).split(/\s+/).every(isAbsoluteZero)) {
193
+ return false;
37
194
  }
38
- const property = match[1].toLowerCase();
39
- const value = match[2].trim().toLowerCase();
40
- const number = parseFloat(value);
41
- switch (property) {
42
- case 'display':
43
- if (value === 'none') {
44
- return true;
45
- }
46
- break;
47
- case 'visibility':
48
- if (value === 'hidden' || value === 'collapse') {
49
- return true;
50
- }
51
- break;
52
- case 'opacity':
53
- if (Number.isFinite(number) && number < 0.1) {
54
- return true;
55
- }
56
- break;
57
- case 'font-size':
58
- // zero in any unit, or below one pixel
59
- if (Number.isFinite(number) && (number === 0 || (number < 1 && /^[\d.]+(?:px|pt)?$/.test(value)))) {
60
- return true;
61
- }
62
- break;
63
- case 'text-indent':
64
- if (Number.isFinite(number) && number <= -1000) {
65
- return true;
66
- }
67
- break;
68
- }
69
- }
70
- return false;
71
- }
72
- function isHiddenElement(node) {
73
- const attribs = node.attribs || {};
74
- const style = attribs.style || '';
75
- // the hidden attribute is a user agent rule, which an author display value overrides
76
- if ('hidden' in attribs && !/display\s*:\s*(?!none)/i.test(style.replace(STYLE_NOISE, ' '))) {
195
+ }
196
+ return isClipped(style.get('overflow')) || isClipped(style.get('overflow-y'));
197
+ }
198
+ /**
199
+ * How an element is hidden by what applies to it, the last value for a property winning (see
200
+ * appliedDeclarations() for the order). "final" when nothing inside it can show text again: no
201
+ * display, the hidden attribute, an opacity a child's own can only lower further, a collapsed box.
202
+ * "inherited" when it is hidden by visibility, a font size below a pixel or a far negative text
203
+ * indent, which an element inside can set again. Only what reliably hides text for every reader
204
+ * counts: negative positions and colors depend on other properties, so they are left alone rather
205
+ * than dropping text the reader sees
206
+ */
207
+ function hiding(applied, element) {
208
+ const hiddenAttribute = 'hidden' in element.attribs;
209
+ if (!applied.length) {
210
+ // most elements: no rule matched and no style attribute
211
+ return hiddenAttribute ? 'final' : '';
212
+ }
213
+ const style = new Map(applied.map(([property, value]) => [property, value]));
214
+ const value = (property) => style.get(property) || '';
215
+ const number = (property) => parseFloat(value(property));
216
+ if (value('display') === 'none' ||
217
+ // the hidden attribute is a user agent rule, which an author display value overrides
218
+ (hiddenAttribute && !style.has('display')) ||
219
+ number('opacity') < 0.1 ||
220
+ isCollapsed(style, element)) {
221
+ return 'final';
222
+ }
223
+ // zero in any unit, or below one pixel
224
+ const fontSize = number('font-size');
225
+ if (value('visibility') === 'hidden' ||
226
+ value('visibility') === 'collapse' ||
227
+ fontSize === 0 ||
228
+ (fontSize < 1 && /^[\d.]+(?:px|pt)?$/.test(value('font-size'))) ||
229
+ number('text-indent') <= -1000) {
230
+ return 'inherited';
231
+ }
232
+ return '';
233
+ }
234
+ // Whether one condition of a media query holds for every reader
235
+ function alwaysTrueCondition(condition) {
236
+ if (condition === 'all' || condition === 'screen') {
77
237
  return true;
78
238
  }
79
- return isHiddenStyle(style);
239
+ const match = /^\(\s*(min|max)-(?:device-)?width\s*:\s*([\d.]+)(px)?\s*\)$/.exec(condition);
240
+ if (!match) {
241
+ return false;
242
+ }
243
+ const width = Number(match[2]);
244
+ if (!match[3] && width !== 0) {
245
+ return false;
246
+ }
247
+ return match[1] === 'min' ? width <= ALWAYS_MIN_WIDTH : width >= ALWAYS_MAX_WIDTH;
248
+ }
249
+ // A media query list that holds whoever reads the message: "screen", "all and (min-width: 0)" and
250
+ // the like
251
+ function isUnconditionalQuery(queries) {
252
+ return queries
253
+ .toLowerCase()
254
+ .split(',')
255
+ .some(query => query
256
+ .trim()
257
+ .replace(/^only\s+/, '')
258
+ .split(/\s+and\s+/)
259
+ .every(condition => alwaysTrueCondition(condition.trim())));
260
+ }
261
+ // Where the block opening at `start` closes, nested blocks, comments and strings skipped
262
+ function blockEnd(css, start) {
263
+ let depth = 0;
264
+ for (let i = start; i < css.length;) {
265
+ const end = skipNoise(css, i);
266
+ if (end !== i) {
267
+ i = end;
268
+ continue;
269
+ }
270
+ if (css[i] === '{') {
271
+ depth++;
272
+ }
273
+ else if (css[i] === '}' && --depth === 0) {
274
+ return i;
275
+ }
276
+ i++;
277
+ }
278
+ return css.length;
279
+ }
280
+ /**
281
+ * What the style sheets say about hiding, or null when they cannot be read faithfully. Every rule a
282
+ * mail client would apply has to be read for a rule that hides to be trusted: a rule left unread
283
+ * may be the one that shows the element again, and then text every reader sees would be taken from
284
+ * the model. So when any rule that sets something the check reads is left unread (inside a
285
+ * conditional or unknown at-rule, behind an @import, past the rule cap, with an escaped property
286
+ * name) the sheets count for nothing and only the style attributes do, as before sheets were read
287
+ *
288
+ * @returns The rules in sheet order, each with only the declarations the check reads
289
+ */
290
+ function sheetRules(css) {
291
+ if (css.includes('\\')) {
292
+ // an escape in a property name or a selector is one no check here decodes
293
+ return null;
294
+ }
295
+ const rules = [];
296
+ let start = 0;
297
+ for (let i = 0; i < css.length;) {
298
+ const end = skipNoise(css, i);
299
+ if (end !== i) {
300
+ i = end;
301
+ continue;
302
+ }
303
+ const char = css[i];
304
+ if (char === ';' || char === '}') {
305
+ // the end of a statement, or of a media block that was entered. A sheet another one
306
+ // imports holds rules nothing here reads
307
+ if (/^\s*@import\b/i.test(css.substring(start, i))) {
308
+ return null;
309
+ }
310
+ start = ++i;
311
+ continue;
312
+ }
313
+ if (char !== '{') {
314
+ i++;
315
+ continue;
316
+ }
317
+ const prelude = withoutNoise(css.substring(start, i), true).trim();
318
+ const media = /^@media\s+(.+)$/i.exec(prelude);
319
+ if (media && isUnconditionalQuery(media[1])) {
320
+ // entered, so that its rules are read next
321
+ i = start = i + 1;
322
+ continue;
323
+ }
324
+ const close = blockEnd(css, i);
325
+ const block = css.substring(i + 1, close);
326
+ i = start = close + 1;
327
+ if (prelude.startsWith('@')) {
328
+ // any other at-rule is not read, so it must not set what the check reads
329
+ if (mentionsHiding(block)) {
330
+ return null;
331
+ }
332
+ continue;
333
+ }
334
+ const found = declarations(block).filter(([property]) => HIDING_PROPERTIES.has(property));
335
+ if (prelude && found.length) {
336
+ if (rules.length >= MAX_HIDING_RULES) {
337
+ return null;
338
+ }
339
+ rules.push({ selector: prelude, declarations: found });
340
+ }
341
+ }
342
+ return rules;
343
+ }
344
+ // The selector tokens a rule may use. A pseudo-class or a pseudo-element is left out: the structural
345
+ // pseudo-classes (:nth-child() and the like) are matched by counting siblings, which is quadratic in
346
+ // a long list of them, and :has() recurses as deep as the document goes. The sibling combinators
347
+ // scan the siblings before an element for every element tested, so they are left out too
348
+ const MATCHABLE_TOKENS = new Set(['tag', 'universal', 'attribute', 'descendant', 'child']);
349
+ const isRoot = (token) => !!token && token.type === 'tag' && (token.name === 'html' || token.name === 'body');
350
+ /**
351
+ * The selector as the matcher reads it, or null for one it cannot match as a mail client does: the
352
+ * same parse decides what is allowed, what it costs and what is compiled, so the three cannot
353
+ * disagree. "html > ..." and "body > ..." are refused too: the parser builds neither around a
354
+ * fragment, so what is a child of the root there cannot be told
355
+ */
356
+ function matchableSelector(selector) {
357
+ if (selector.length > MAX_SELECTOR_LENGTH) {
358
+ return null;
359
+ }
360
+ let parsed;
361
+ try {
362
+ parsed = parseSelector(selector);
363
+ }
364
+ catch {
365
+ return null;
366
+ }
367
+ const matchable = (part) => part.every(token => MATCHABLE_TOKENS.has(token.type)) && !part.some((token, i) => isRoot(token) && part[i + 1]?.type === 'child');
368
+ return parsed.every(matchable) ? parsed : null;
369
+ }
370
+ /**
371
+ * What testing one part of a selector list against one element may cost, in tests: the depth of
372
+ * the document for every descendant combinator in it, since each one climbs the ancestors of the
373
+ * element. The child combinator climbs one level and costs nothing more
374
+ */
375
+ function selectorCost(part, maxDepth) {
376
+ return maxDepth ** part.filter(token => token.type === 'descendant').length;
377
+ }
378
+ /**
379
+ * The specificity of one part of a selector list, as one number that sorts the way the three
380
+ * counts do: ids, then classes and attributes, then types. No part a hiding rule may use comes
381
+ * near a thousand of any of them, the selector length limit sees to that
382
+ */
383
+ function specificity(part) {
384
+ let value = 0;
385
+ for (const token of part) {
386
+ if (token.type === 'attribute') {
387
+ // "#p" is an id selector, "[id=p]" an attribute selector that weighs like a class: the
388
+ // parser gives both the same token and marks only the shorthand with quirks-mode case
389
+ value += token.name === 'id' && token.action === 'equals' && token.ignoreCase === 'quirks' ? 1_000_000 : 1000;
390
+ }
391
+ else if (token.type === 'tag') {
392
+ value += 1;
393
+ }
394
+ }
395
+ return value;
396
+ }
397
+ /**
398
+ * A part without a leading "html" or "body" before a descendant combinator. A browser builds both
399
+ * around any fragment, the parser builds only what the message wrote, so "body p" would match
400
+ * nothing in a message without a body element where a mail client matches every paragraph. Before
401
+ * a descendant combinator the two match the same elements anywhere in the document
402
+ */
403
+ function withoutImpliedRoot(part) {
404
+ let start = 0;
405
+ while (start + 2 < part.length && isRoot(part[start]) && part[start + 1].type === 'descendant') {
406
+ start += 2;
407
+ }
408
+ return start ? part.slice(start) : part;
409
+ }
410
+ /**
411
+ * Compiles the rules of the message's own style sheets that the hiding check reads, one entry for
412
+ * each part of a selector list since each part has a specificity of its own, in the order the
413
+ * cascade weighs them. This is the one place that decides whether the sheets can be trusted, and
414
+ * they are not, so no rule is returned at all, whenever a rule a mail client would apply is left
415
+ * unread: leaving out one rule could leave out the one that shows text again, and then text every
416
+ * reader sees would be taken from the model. Each early return below is one way that happens
417
+ */
418
+ function hidingRules(parsed) {
419
+ // the document was cut short, by the length or the nesting limit, so a sheet may follow unread
420
+ if (parsed.truncated) {
421
+ return [];
422
+ }
423
+ // a linked sheet, or an escaped property name in a style attribute
424
+ if (parsed.unreadableStyle) {
425
+ return [];
426
+ }
427
+ // a sheet one client applies and another does not: in a conditional comment, or for some media
428
+ if (parsed.conditionalStyle.some(mentionsHiding)) {
429
+ return [];
430
+ }
431
+ // more style than is read
432
+ if (parsed.css.length > MAX_STYLE_LENGTH) {
433
+ return [];
434
+ }
435
+ // an at-rule, an @import, an escape or more rules than are read (see sheetRules())
436
+ const read = sheetRules(parsed.css);
437
+ if (!read) {
438
+ return [];
439
+ }
440
+ const rules = [];
441
+ let work = 0;
442
+ for (const [order, { selector, declarations }] of read.entries()) {
443
+ // a selector that cannot be matched as a mail client matches it
444
+ const matchable = matchableSelector(selector);
445
+ if (!matchable) {
446
+ return [];
447
+ }
448
+ // or more work than matching is allowed
449
+ work += parsed.elements * matchable.reduce((sum, part) => sum + selectorCost(part, parsed.maxDepth), 0);
450
+ if (work > RULE_WORK_BUDGET) {
451
+ return [];
452
+ }
453
+ for (const part of matchable) {
454
+ // weighed as written, matched without the root the parser did not build
455
+ rules.push({ test: compile([withoutImpliedRoot(part)]), declarations, specificity: specificity(part), order });
456
+ }
457
+ }
458
+ return rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
459
+ }
460
+ // Builds the document as the parser reads it and stops reading once an element opens deeper than
461
+ // MAX_NESTING: the parser stack, and with it the cost of every element that follows, stays bounded.
462
+ // What was read until then is kept, the rest is left out the way text past the length limit is.
463
+ // The count follows the parser's own events, which close the elements it closes on its own too. The
464
+ // handler also gathers what the hiding rules need to know, so that takes no walk of its own
465
+ class NestingLimitHandler extends DomHandler {
466
+ constructor() {
467
+ super(...arguments);
468
+ this.elements = 0;
469
+ this.maxDepth = 0;
470
+ this.sheets = [];
471
+ /** The style elements for some readers only (a media attribute that does not hold for all) */
472
+ this.conditionalSheets = [];
473
+ /** Something applies styles that cannot be read here */
474
+ this.unreadableStyle = false;
475
+ /** The parser stopped before the end of the document */
476
+ this.stopped = false;
477
+ }
478
+ onparserinit(parser) {
479
+ super.onparserinit(parser);
480
+ this.reader = parser;
481
+ }
482
+ onopentag(name, attribs) {
483
+ super.onopentag(name, attribs);
484
+ // the stack starts with the document itself
485
+ const depth = this.tagStack.length - 1;
486
+ this.elements++;
487
+ this.maxDepth = Math.max(this.maxDepth, depth);
488
+ this.gatherStyle(name, attribs);
489
+ if (depth > MAX_NESTING) {
490
+ this.stopped = true;
491
+ this.reader.pause();
492
+ }
493
+ }
494
+ // A browser ends a comment at "--!>" and a CDATA section, which HTML has not, at the first ">",
495
+ // where the parser here reads on to "-->" and "]]>": a style element between the two ends is a
496
+ // sheet to a mail client and comment text here
497
+ oncomment(data) {
498
+ super.oncomment(data);
499
+ if (data.includes('--!>') || (data.startsWith('[CDATA[') && data.includes('>'))) {
500
+ this.unreadableStyle = true;
501
+ }
502
+ }
503
+ gatherStyle(name, attribs) {
504
+ // an escaped property name in a style attribute is one no check here decodes
505
+ if (attribs.style && attribs.style.includes('\\')) {
506
+ this.unreadableStyle = true;
507
+ }
508
+ if (name === 'link' && /\bstylesheet\b/i.test(attribs.rel || '')) {
509
+ // a sheet loaded from elsewhere holds rules nothing here reads
510
+ this.unreadableStyle = true;
511
+ }
512
+ if (name === 'plaintext') {
513
+ // a browser reads everything after it as text, sheets included
514
+ this.unreadableStyle = true;
515
+ }
516
+ if (name === 'svg' || name === 'math') {
517
+ // a browser parses foreign content by other rules than the parser here: a style element
518
+ // in MathML is no sheet, one in SVG decodes entities and comments, and title or script
519
+ // in SVG hold markup rather than text
520
+ this.unreadableStyle = true;
521
+ }
522
+ if (name !== 'style' || (attribs.type && attribs.type.trim().toLowerCase() !== 'text/css')) {
523
+ // a browser applies no sheet of another type
524
+ return;
525
+ }
526
+ const sheet = this.tagStack[this.tagStack.length - 1];
527
+ const ancestors = this.tagStack.slice(1, -1);
528
+ if (ancestors.some(element => element.name === 'template')) {
529
+ // never rendered, so never applied
530
+ return;
531
+ }
532
+ if (ancestors.some(element => RAW_TEXT_IN_BROWSER.has(element.name))) {
533
+ this.unreadableStyle = true;
534
+ return;
535
+ }
536
+ if (attribs.media && !isUnconditionalQuery(attribs.media)) {
537
+ // applied to some readers only, which counts once its text is known (hidingRules())
538
+ this.conditionalSheets.push(sheet);
539
+ return;
540
+ }
541
+ this.sheets.push(sheet);
542
+ }
543
+ }
544
+ /**
545
+ * Where each comment ends, found the way a browser finds it: at the first "-->" or "--!>", with
546
+ * "<!-->" and "<!--->" empty comments and one that never ends running to the end. The two endings
547
+ * are searched for once each and reused while they lie ahead, so the scan stays linear however many
548
+ * comments there are
549
+ */
550
+ class CommentScanner {
551
+ constructor(html) {
552
+ this.html = html;
553
+ }
554
+ next(token, cached, from) {
555
+ return cached !== undefined && (cached < 0 || cached >= from) ? cached : this.html.indexOf(token, from);
556
+ }
557
+ /** The comment opening at `start` ("<!--"): where its text starts and ends, and where it ends */
558
+ comment(start) {
559
+ const dataStart = start + 4;
560
+ for (const empty of ['>', '->']) {
561
+ if (this.html.startsWith(empty, dataStart)) {
562
+ return { dataStart, dataEnd: dataStart, end: dataStart + empty.length };
563
+ }
564
+ }
565
+ const dash = (this.dash = this.next('-->', this.dash, dataStart));
566
+ const bang = (this.bang = this.next('--!>', this.bang, dataStart));
567
+ if (bang >= 0 && (dash < 0 || bang < dash)) {
568
+ return { dataStart, dataEnd: bang, end: bang + 4 };
569
+ }
570
+ if (dash >= 0) {
571
+ return { dataStart, dataEnd: dash, end: dash + 3 };
572
+ }
573
+ return { dataStart, dataEnd: this.html.length, end: this.html.length };
574
+ }
575
+ }
576
+ /**
577
+ * Reads Outlook's conditional comments as the clients that show the message do, and collects the
578
+ * parts only some of them apply:
579
+ * - "<!--[if mso]>...<![endif]-->" is one comment to every client but Outlook for Windows, which
580
+ * shows what it wraps. That content is kept, as it always was, so Outlook-only text is read too
581
+ * - "<!--[if !mso]><!-->...<!--<![endif]-->" is two comments around content every client but
582
+ * Outlook shows. The two comments stay comments and the content stays where it is
583
+ * - every other comment is left for the parser, ended where a browser ends it
584
+ * Removing the markers piece by piece used to leave a bare "<!--" behind the revealed closer, which
585
+ * the parser read as a comment running over the rest of the message: the pattern email builders
586
+ * write in every message, and all of it past the first such section was left out
587
+ *
588
+ * @returns The HTML, and the text of each conditional section that holds a style element: Outlook
589
+ * applies such a sheet and the other clients do not, or the other way round
590
+ */
591
+ function stripConditionalComments(html) {
592
+ const scanner = new CommentScanner(html);
593
+ const styled = [];
594
+ const collect = (section) => {
595
+ if (/<style[\s>]/i.test(section)) {
596
+ styled.push(section);
597
+ }
598
+ };
599
+ let output = '';
600
+ let from = 0;
601
+ let revealed = -1;
602
+ for (let start = html.indexOf('<!--'); start >= 0; start = html.indexOf('<!--', from)) {
603
+ const { dataStart, dataEnd, end } = scanner.comment(start);
604
+ const data = html.substring(dataStart, dataEnd);
605
+ const open = CONDITIONAL_OPEN.exec(data);
606
+ const rest = open ? data.substring(open[0].length) : '';
607
+ if (open && rest.toLowerCase().endsWith(CONDITIONAL_CLOSE)) {
608
+ // Outlook-only content, kept without its markers
609
+ const content = rest.substring(0, rest.length - CONDITIONAL_CLOSE.length);
610
+ collect(content);
611
+ output += html.substring(from, start) + content;
612
+ }
613
+ else {
614
+ if (open && REVEALED_OPEN_REST.test(rest)) {
615
+ revealed = end;
616
+ }
617
+ else if (data.toLowerCase() === CONDITIONAL_CLOSE && revealed >= 0) {
618
+ collect(html.substring(revealed, start));
619
+ revealed = -1;
620
+ }
621
+ else if (open && end === html.length) {
622
+ // one that never closes is a comment to the end everywhere but in Outlook
623
+ collect(rest);
624
+ }
625
+ // a comment to every client, written so the parser ends it where a browser does: the
626
+ // parser here reads on past "--!>" to the next "-->"
627
+ output += `${html.substring(from, start)}<!--${data}-->`;
628
+ }
629
+ from = end;
630
+ }
631
+ if (revealed >= 0) {
632
+ collect(html.substring(revealed));
633
+ }
634
+ return { html: output + html.substring(from), styled };
635
+ }
636
+ function parseDocument(html) {
637
+ const source = truncate(html, MAX_HTML_LENGTH);
638
+ const { html: markup, styled } = stripConditionalComments(source);
639
+ const handler = new NestingLimitHandler();
640
+ new Parser(handler).end(markup);
641
+ return {
642
+ document: handler.root,
643
+ elements: handler.elements,
644
+ maxDepth: handler.maxDepth,
645
+ css: handler.sheets.map(sheet => textContent(sheet)).join('\n'),
646
+ conditionalStyle: styled.concat(handler.conditionalSheets.map(sheet => textContent(sheet))),
647
+ unreadableStyle: handler.unreadableStyle,
648
+ truncated: handler.stopped || source.length !== String(html ?? '').length
649
+ };
80
650
  }
81
651
  function hasText(node) {
82
652
  if (isText(node)) {
@@ -84,7 +654,87 @@ function hasText(node) {
84
654
  }
85
655
  return hasChildren(node) && node.children.some(hasText);
86
656
  }
87
- function stripHidden(node, stats) {
657
+ /**
658
+ * The declarations that apply to an element, in the order of the cascade, so the last one for a
659
+ * property is the one that holds: the matching rules by specificity and then by their place in the
660
+ * sheet, then the style attribute, then the "!important" declarations of the rules in the same
661
+ * order, then those of the style attribute. Weighing them any other way would let a sender show
662
+ * text to every reader that the summary leaves out
663
+ *
664
+ * @param rules - In cascade order, as hidingRules() returns them
665
+ */
666
+ function appliedDeclarations(element, rules) {
667
+ const matched = [];
668
+ for (const rule of rules) {
669
+ if (rule.test(element)) {
670
+ matched.push(...rule.declarations);
671
+ }
672
+ }
673
+ // only what the check reads, so an element styled for color and fonts alone has nothing to weigh
674
+ const inline = element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
675
+ if (!matched.length && !inline.some(declaration => declaration[2])) {
676
+ return inline;
677
+ }
678
+ const normal = [];
679
+ const important = [];
680
+ for (const declaration of [...matched, ...inline]) {
681
+ (declaration[2] ? important : normal).push(declaration);
682
+ }
683
+ // the rules come before the attribute in both, so this is the cascade order
684
+ return normal.concat(important);
685
+ }
686
+ /**
687
+ * The walk over the document: what it counts, the rules it tests each element against, and what it
688
+ * learned about each element, so no element is tested twice
689
+ */
690
+ class Walk {
691
+ constructor(rules) {
692
+ this.hiddenElements = 0;
693
+ this.invisibleCharacters = 0;
694
+ this.appliedCache = new Map();
695
+ this.setsInheritedCache = new Map();
696
+ this.rules = rules;
697
+ }
698
+ // Kept only for an element whose declarations were read ahead of the walk, by setsInherited(),
699
+ // and dropped when the walk reaches it, since no element is reached twice
700
+ applied(element, keep) {
701
+ const cached = this.appliedCache.get(element);
702
+ if (cached) {
703
+ if (!keep) {
704
+ this.appliedCache.delete(element);
705
+ }
706
+ return cached;
707
+ }
708
+ const applied = appliedDeclarations(element, this.rules);
709
+ if (keep) {
710
+ this.appliedCache.set(element, applied);
711
+ }
712
+ return applied;
713
+ }
714
+ // Whether the element or anything inside it sets an inherited hiding property itself
715
+ setsInherited(element) {
716
+ let sets = this.setsInheritedCache.get(element);
717
+ if (sets === undefined) {
718
+ sets = this.applied(element, true).some(([property]) => INHERITED_HIDING.has(property)) || this.insideSetsInherited(element);
719
+ this.setsInheritedCache.set(element, sets);
720
+ }
721
+ return sets;
722
+ }
723
+ // Whether anything inside the element sets an inherited hiding property, so text in it may show
724
+ insideSetsInherited(element) {
725
+ return element.children.some(child => isTag(child) && this.setsInherited(child));
726
+ }
727
+ isHidden(element) {
728
+ const hidden = hiding(this.applied(element, false), element);
729
+ // an element hidden only by an inherited property is kept when something inside it sets the
730
+ // property again: what is left of its own text then reaches the model, rather than text a
731
+ // reader sees being taken from it
732
+ return hidden === 'final' || (hidden === 'inherited' && !this.insideSetsInherited(element));
733
+ }
734
+ }
735
+ // Each element is tested as the walk reaches it, so nothing under an element that was removed is
736
+ // ever tested
737
+ function stripHidden(node, walk) {
88
738
  if (!hasChildren(node)) {
89
739
  return;
90
740
  }
@@ -95,7 +745,7 @@ function stripHidden(node, stats) {
95
745
  if (isText(child)) {
96
746
  // before the conversion, which would turn a zero-width space into a plain one
97
747
  const cleaned = child.data.replace(INVISIBLE_CHARS, '');
98
- stats.invisibleCharacters += child.data.length - cleaned.length;
748
+ walk.invisibleCharacters += child.data.length - cleaned.length;
99
749
  child.data = cleaned;
100
750
  return true;
101
751
  }
@@ -105,17 +755,17 @@ function stripHidden(node, stats) {
105
755
  if (HIDDEN_TAGS.has(child.name)) {
106
756
  return false;
107
757
  }
108
- if (isHiddenElement(child)) {
758
+ if (walk.isHidden(child)) {
109
759
  // a layout element with no text in it is not hidden content, only a spacer
110
760
  if (hasText(child)) {
111
- stats.hiddenElements++;
761
+ walk.hiddenElements++;
112
762
  }
113
763
  return false;
114
764
  }
115
765
  return true;
116
766
  });
117
767
  for (const child of node.children) {
118
- stripHidden(child, stats);
768
+ stripHidden(child, walk);
119
769
  }
120
770
  }
121
771
  // What the reader takes as the link: its text, and the alt and title of an image standing in
@@ -153,20 +803,21 @@ function surfaceHead(document) {
153
803
  * reader sees it, for the model
154
804
  */
155
805
  function visibleHtml(html) {
156
- const document = parseDocument(truncate(html, MAX_HTML_LENGTH).replace(CONDITIONAL_COMMENT, ''));
806
+ const parsed = parseDocument(html);
807
+ const { document } = parsed;
157
808
  const links = collectLinks(document);
158
- const stats = { hiddenElements: 0, invisibleCharacters: 0 };
159
- stripHidden(document, stats);
809
+ // the rules are read before the style elements go with everything else that is not rendered
810
+ const walk = new Walk(hidingRules(parsed));
811
+ stripHidden(document, walk);
160
812
  surfaceHead(document);
161
- return { links, hiddenElements: stats.hiddenElements, invisibleCharacters: stats.invisibleCharacters, html: () => serialize(document) };
813
+ return { links, hiddenElements: walk.hiddenElements, invisibleCharacters: walk.invisibleCharacters, html: () => serialize(document) };
162
814
  }
163
815
  /**
164
816
  * Removes the characters that take no space on screen
165
- *
166
817
  */
167
818
  function visibleText(input) {
168
819
  const text = String(input ?? '');
169
820
  const matches = text.match(INVISIBLE_CHARS);
170
821
  return { text: matches ? text.replace(INVISIBLE_CHARS, '') : text, invisibleCharacters: matches ? matches.length : 0 };
171
822
  }
172
- export { visibleHtml, visibleText, INVISIBLE_CHARS, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH };
823
+ export { visibleHtml, visibleText, INVISIBLE_CHARS, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH, MAX_NESTING };