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