langmail-mcp 0.1.0 → 0.2.1

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.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-ad2666h8.js +12696 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +94 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,426 +0,0 @@
1
- // Quote the message being answered below a reply, the way a mail client does.
2
- //
3
- // A reply in an ongoing conversation is expected to carry the history: the new
4
- // text first, then an attribution line ("On …, Name <address> wrote:") and the
5
- // original body — `>`-prefixed in the plain-text part, inside a
6
- // `<blockquote type="cite">` below the attribution in the HTML part (what clients
7
- // collapse as quoted history). The
8
- // original's own quoted history comes along unchanged, so the thread keeps
9
- // nesting the way the recipient's client expects.
10
- //
11
- // Each part of the reply quotes into its own form: a text-only reply gets a text
12
- // quote, an html-only reply an HTML quote. When the original lacks the matching
13
- // part, the other one is converted — escaped text into HTML, or HTML flattened
14
- // to text — so a reply never loses the quote just because the two messages
15
- // chose different bodies.
16
- import sanitizeHtml from "sanitize-html";
17
- import { DATA_IMAGE_RE } from "../email-render/sanitize.js";
18
- import { draftFromRecord, MAX_DRAFT_BODY_VALUE_BYTES, } from "./draft-common.js";
19
- const ESCAPES = {
20
- '"': "&quot;",
21
- "&": "&amp;",
22
- "<": "&lt;",
23
- ">": "&gt;",
24
- };
25
- export const escapeHtml = (text) => text.replace(/[&<>"]/gu, (c) => ESCAPES[c] ?? c);
26
- // Pinned to UTC: the tools have no notion of the user's timezone, and a wrong
27
- // local offset is worse than an explicit "UTC".
28
- const ATTRIBUTION_DATE = new Intl.DateTimeFormat("en-GB", {
29
- day: "numeric",
30
- hour: "2-digit",
31
- hour12: false,
32
- minute: "2-digit",
33
- month: "short",
34
- timeZone: "UTC",
35
- weekday: "short",
36
- year: "numeric",
37
- });
38
- export const formatAttributionDate = (iso) => {
39
- const date = new Date(iso);
40
- if (Number.isNaN(date.getTime())) {
41
- return null;
42
- }
43
- const parts = Object.fromEntries(ATTRIBUTION_DATE.formatToParts(date).map((part) => [part.type, part.value]));
44
- return `${parts.weekday}, ${parts.day} ${parts.month} ${parts.year} at ${parts.hour}:${parts.minute} UTC`;
45
- };
46
- // "On Mon, 5 Oct 2026 at 12:00 UTC, Nadia Bram <nadia@example.org> wrote:"
47
- export const attributionLine = (original) => {
48
- const sender = original.from?.[0];
49
- const named = sender?.name
50
- ? `${sender.name} <${sender.email}>`
51
- : sender?.email;
52
- const who = named ?? "The sender";
53
- // The Date header the sender stamped, not when it reached this mailbox —
54
- // delayed or imported mail can be hours or years apart.
55
- const stamp = original.sentAt ?? original.receivedAt;
56
- const when = stamp ? formatAttributionDate(stamp) : null;
57
- return when ? `On ${when}, ${who} wrote:` : `${who} wrote:`;
58
- };
59
- const LINE_BREAK_RE = /\r?\n/u;
60
- const LINE_BREAKS_RE = /\r?\n/gu;
61
- // Block-level boundaries become line breaks before the tags are dropped, so a
62
- // flattened HTML body keeps its paragraphs instead of running together.
63
- const BLANK_RUN_RE = /\n{3,}/gu;
64
- // `<p>`, `<li>` and `<tr>` break on their opening, since their closing tags are
65
- // optional; `<br>` with any attributes.
66
- // The containers' mandatory closings break too, so text after a table or list
67
- // does not join its last line.
68
- // These run on the raw, sender-controlled body before anything is cut to size,
69
- // so an attribute run is bounded and stops at the next `<`: unbounded, a body
70
- // of unterminated tags (`<p <p <p …`) backtracks quadratically and stalls the
71
- // server for minutes. The cost is that a tag with a literal `<` in an
72
- // attribute, or more than 1000 characters of them, yields no break — a joined
73
- // line in the text alternative, never wrong markup.
74
- // `<div>` breaks on its opening, so the first line of an Apple Mail or Gmail
75
- // body does not join the next; its closing breaks only when no block follows,
76
- // so sibling divs are not double-spaced. `<dt>`/`<dd>` like `<li>`.
77
- const BLOCK_BREAK_RE = /<br\b[^<>]{0,1000}>|<(?:p|li|tr|div|dt|dd)(?:\s[^<>]{0,1000})?>|<\/div>(?!\s*<(?:p|li|tr|div|table|ul|ol|dl)\b)|<\/(?:table|thead|tbody|ul|ol|dl|h[1-6]|blockquote)>/giu;
78
- // Table cells are separated by a space, so a row reads `Qty Price`, not `QtyPrice`.
79
- // Openings too: `</td>` is optional in HTML, and plenty of mail omits it.
80
- const CELL_BREAK_RE = /<\/?t[dh](?:\s[^<>]{0,1000})?>/giu;
81
- const ENTITY_RE = /&(?:amp|lt|gt|quot|#39|nbsp);/gu;
82
- const ENTITIES = {
83
- "&#39;": "'",
84
- "&amp;": "&",
85
- "&gt;": ">",
86
- "&lt;": "<",
87
- "&nbsp;": " ",
88
- "&quot;": '"',
89
- };
90
- const LINE_SPACE_RE = /[ \t]+/gu;
91
- // Elements whose content is never message text. `noscript` is deliberately not
92
- // here: it is the discard path GHSA-x3q4-9hxx-gx8m broke, and as an ordinary
93
- // disallowed tag its content is sanitized like any other text.
94
- const NON_TEXT_TAGS = ["script", "style", "textarea", "title", "head"];
95
- export const htmlToText = (html) => sanitizeHtml(html.replace(BLOCK_BREAK_RE, "\n").replace(CELL_BREAK_RE, " "), {
96
- allowedAttributes: {},
97
- allowedTags: [],
98
- nonTextTags: NON_TEXT_TAGS,
99
- })
100
- .replace(ENTITY_RE, (entity) => ENTITIES[entity] ?? entity)
101
- .split(LINE_BREAK_RE)
102
- .map((line) => line.replace(LINE_SPACE_RE, " ").trim())
103
- .join("\n")
104
- .replace(BLANK_RUN_RE, "\n\n")
105
- .trim();
106
- // The original's HTML as it can sit inside the reply's blockquote. The reply is
107
- // the user's own message going out under their name, so this is an allowlist,
108
- // not a denylist: presentational markup and inline styles survive, while
109
- // anything active — scripts, forms, frames — and any <style> sheet, which is not
110
- // scoped to the blockquote and could restyle or hide the user's own text above
111
- // it, is dropped. <html>/<body> are unwrapped and <head> discarded by the
112
- // parser, never located by pattern: a `<body>` inside a script or comment must
113
- // not decide where the message starts.
114
- const PRESENTATION_ATTRIBUTES = [
115
- "align",
116
- "valign",
117
- "bgcolor",
118
- "width",
119
- "height",
120
- "border",
121
- "dir",
122
- "style",
123
- ];
124
- // Inline styles are an allowlist too: the presentational properties email
125
- // layout leans on, with values that cannot lift quoted content out of the
126
- // blockquote or shrink it to nothing. Everything else — `position`, any
127
- // `transform`/`translate`, negative or large margins, `text-indent`,
128
- // `visibility`, `display:none`, and any property spelled with a CSS escape —
129
- // is dropped by sanitize-html's style filter, which keeps only what is named
130
- // here, with keywords and units matched case-insensitively, as CSS reads them.
131
- // This is layout integrity of the user's own outbound mail, not a security
132
- // boundary: a sender can still colour text white, but cannot paint over the
133
- // reply above.
134
- // No function that fetches — `url(`, `image-set(` / `-webkit-image-set(` (which
135
- // take a bare, scheme-relative string), `src(` — so quoted styles cannot make
136
- // the recipient's client load anything the image rules would not see. No IE
137
- // `expression(` either.
138
- const SAFE_VALUE = /^(?!.*(?:url|src|image-set|expression)\s*\()[#\w\s.,%'"()/+-]*$/iu;
139
- // Margins and padding: non-negative and small. Large vertical padding on an
140
- // inline element paints outside its line box without moving it, so an
141
- // unbounded value is the overlay again. Each unit is bounded by its size, so
142
- // every ceiling lands near 100–200px: 99px/pt, 9em/rem, 9ex/mm, 9% (of the
143
- // width), and 2in/cm — enough for Word's MsoNormal `0in` and `.5in` indents.
144
- const SMALL_LENGTH = String.raw `(?:0|auto|(?:\d{1,2}(?:\.\d+)?|\.\d+)(?:px|pt)|(?:\d(?:\.\d+)?|\.\d+)(?:em|rem|ex|mm|%)|(?:[01](?:\.\d+)?|2(?:\.0+)?|\.\d+)(?:in|cm))`;
145
- const SMALL_BOX = new RegExp(String.raw `^${SMALL_LENGTH}(?:\s+${SMALL_LENGTH}){0,3}$`, "iu");
146
- const POSITIVE = String.raw `(?:0*[1-9]\d*(?:\.\d+)?|0*\.\d*[1-9]\d*)`;
147
- const POSITIVE_NUMBER = new RegExp(`^${POSITIVE}$`, "u");
148
- // Sizes need a unit: unitless lengths are invalid CSS outside line-height.
149
- const POSITIVE_LENGTH = new RegExp(`^(?:auto|${POSITIVE}(?:px|pt|em|rem|ex|in|cm|mm|%))$`, "iu");
150
- const DISPLAY = /^(?:block|inline|inline-block|table|table-row|table-cell|list-item)$/iu;
151
- // Keywords only: a length raises or lowers an inline box by that much, which
152
- // is the overlay again by another route.
153
- const VERTICAL_ALIGN = /^(?:baseline|sub|super|top|text-top|middle|bottom|text-bottom)$/iu;
154
- const QUOTABLE_STYLES = Object.fromEntries([
155
- ["vertical-align", [VERTICAL_ALIGN]],
156
- // Keywords that keep the element on the page; `none` is not one of them.
157
- ["display", [DISPLAY]],
158
- // A zero line box lets glyphs paint over whatever sits above it.
159
- ["line-height", [/^normal$/iu, POSITIVE_LENGTH, POSITIVE_NUMBER]],
160
- ...[
161
- "background",
162
- "background-color",
163
- "border",
164
- "border-bottom",
165
- "border-collapse",
166
- "border-color",
167
- "border-left",
168
- "border-radius",
169
- "border-right",
170
- "border-spacing",
171
- "border-style",
172
- "border-top",
173
- "border-width",
174
- "color",
175
- "font-family",
176
- "font-style",
177
- "font-weight",
178
- "list-style-type",
179
- "text-align",
180
- "text-decoration",
181
- "white-space",
182
- ].map((property) => [property, [SAFE_VALUE]]),
183
- ...[
184
- "margin",
185
- "margin-bottom",
186
- "margin-left",
187
- "margin-right",
188
- "margin-top",
189
- "padding",
190
- "padding-bottom",
191
- "padding-left",
192
- "padding-right",
193
- "padding-top",
194
- ].map((property) => [property, [SMALL_BOX]]),
195
- ...[
196
- "font-size",
197
- "height",
198
- "max-width",
199
- "min-height",
200
- "min-width",
201
- "width",
202
- ].map((property) => [property, [POSITIVE_LENGTH]]),
203
- ]);
204
- // Compared after the same normalization sanitize-html's scheme filter applies —
205
- // it drops control characters and spaces before reading the scheme — so a
206
- // `da<tab>ta:` src cannot pass as "not a data URI" here and as `data:` there.
207
- // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what the scheme filter drops
208
- const SCHEME_NOISE_RE = /[\u0000-\u0020]+/gu;
209
- const WEB_SCHEME_RE = /^https?:/iu;
210
- const LINK_SCHEME_RE = /^(?:https?|mailto|tel):/iu;
211
- // sanitize-html lets a URL with no scheme through (`/pixel`, `logo.png`,
212
- // `//host/x`); in a reply those resolve against the recipient's webmail. Only
213
- // absolute web URLs and raster data images are quoted.
214
- // A forward carries the original's inline parts along, so there a `cid:` src
215
- // still names something the recipient receives.
216
- const CID_SCHEME_RE = /^cid:/iu;
217
- const quotableImageSrc = (src, keepCid) => {
218
- const normalized = src?.replace(SCHEME_NOISE_RE, "") ?? "";
219
- return (WEB_SCHEME_RE.test(normalized) ||
220
- DATA_IMAGE_RE.test(normalized) ||
221
- (keepCid && CID_SCHEME_RE.test(normalized)));
222
- };
223
- const quotableHref = (href) => LINK_SCHEME_RE.test(href.replace(SCHEME_NOISE_RE, ""));
224
- // sanitize-html matches style properties case-sensitively, so `COLOR:red` from a
225
- // Word export would be dropped; property names are lowercased first.
226
- const STYLE_PROPERTY_RE = /(^|;)\s*([-\w]+)\s*:/gu;
227
- const lowercaseStyleProperties = (style) => style.replace(STYLE_PROPERTY_RE, (_, sep, property) => `${sep}${property.toLowerCase()}:`);
228
- const quotableAttributes = (attribs) => {
229
- const { href, style, ...rest } = attribs;
230
- return {
231
- ...rest,
232
- ...(href !== undefined && quotableHref(href) ? { href } : {}),
233
- ...(style === undefined ? {} : { style: lowercaseStyleProperties(style) }),
234
- };
235
- };
236
- // `keepCid` is for a forward, which attaches the inline parts the `cid:` srcs
237
- // point at; a reply does not, so there they would render as broken images.
238
- export const quotableHtml = (body, opts = {}) => sanitizeHtml(body, {
239
- allowedAttributes: {
240
- "*": PRESENTATION_ATTRIBUTES,
241
- a: ["href", "title"],
242
- // So a quote of a quote keeps the marker clients collapse history on.
243
- blockquote: ["type"],
244
- img: ["src", "alt", "title", "width", "height"],
245
- td: ["colspan", "rowspan", ...PRESENTATION_ATTRIBUTES],
246
- th: ["colspan", "rowspan", ...PRESENTATION_ATTRIBUTES],
247
- },
248
- allowedSchemes: ["http", "https", "mailto", "tel"],
249
- allowedSchemesByTag: {
250
- img: ["http", "https", "data", ...(opts.keepCid ? ["cid"] : [])],
251
- },
252
- allowedStyles: { "*": QUOTABLE_STYLES },
253
- allowedTags: [
254
- ...sanitizeHtml.defaults.allowedTags,
255
- "img",
256
- "font",
257
- "center",
258
- "span",
259
- ],
260
- // In a reply an inline image of the original is not carried over as an
261
- // attachment, so its `cid:` src is refused by the scheme list above — and
262
- // an <img> with nothing left to show is dropped rather than rendered as a
263
- // broken box. A `data:` image must be a raster one: SVG can carry markup
264
- // (see email-render/sanitize.ts).
265
- exclusiveFilter: (frame) => frame.tag === "img" &&
266
- !quotableImageSrc(frame.attribs.src, opts.keepCid === true),
267
- nonTextTags: NON_TEXT_TAGS,
268
- transformTags: {
269
- "*": (tagName, attribs) => ({
270
- attribs: quotableAttributes(attribs),
271
- tagName,
272
- }),
273
- },
274
- }).trim();
275
- export const textAsHtml = (text) => escapeHtml(text).replace(LINE_BREAKS_RE, "<br>");
276
- const quoteText = (text) => text
277
- .trimEnd()
278
- .split(LINE_BREAK_RE)
279
- .map((line) => line === "" || line.startsWith(">") ? `>${line}` : `> ${line}`)
280
- .join("\n");
281
- // How much of the original a quote carries, per body part — so a reply to a
282
- // long newsletter stays a reply.
283
- export const MAX_QUOTE_CHARS = 50_000;
284
- // The longest body part that is guaranteed to read back whole: update_draft
285
- // reads at MAX_DRAFT_BODY_VALUE_BYTES octets, a character costs at most four,
286
- // so 100_000 characters always fit. A staged reply's part — the caller's text
287
- // plus the quote — is kept inside this, or update_draft would find it
288
- // truncated and refuse to edit the draft at all.
289
- export const MAX_REPLY_PART_CHARS = MAX_DRAFT_BODY_VALUE_BYTES / 4;
290
- // Room for the shortened note and the markup around the quote; the attribution
291
- // is measured, since it carries the sender's display name.
292
- const QUOTE_FRAME_CHARS = 1000;
293
- const SHORTENED_NOTE = "[… quoted message shortened]";
294
- // Render as much of `value` as fits in `budget` characters once rendered.
295
- // Rendering grows the text unevenly (`> ` prefixes, HTML escaping), so the cut
296
- // is found by shrinking until the output fits rather than computed up front.
297
- export const fitted = (value, render, budget,
298
- // How much of `value` is ever rendered. A reply's quote stops at
299
- // MAX_QUOTE_CHARS; a forward carries as much as the part budget allows.
300
- cap = MAX_QUOTE_CHARS) => {
301
- let limit = Math.min(value.length, cap);
302
- for (;;) {
303
- const rendered = render(value.slice(0, limit));
304
- if (rendered.length <= budget || limit === 0) {
305
- return { rendered, shortened: limit < value.length };
306
- }
307
- limit = Math.max(0, Math.floor((limit * budget) / rendered.length) - 1);
308
- }
309
- };
310
- // Whether a reply quotes the original when the caller did not say. It does,
311
- // unless explicit recipients name someone the original was never addressed
312
- // to: quoting then forwards the whole message to a new person, which is a
313
- // decision the user makes (`quoteOriginal: true`), not a default. The user's
314
- // own addresses are never outsiders — a self-bcc is not a forward.
315
- export const quoteWithheldFrom = (original, recipients, selfAddresses) => {
316
- const roster = new Set([
317
- ...(original.from ?? []),
318
- ...(original.replyTo ?? []),
319
- ...(original.to ?? []),
320
- ...(original.cc ?? []),
321
- // Present on the user's own sent mail: those people already have it.
322
- ...(original.bcc ?? []),
323
- ]
324
- .map((address) => address.email)
325
- .concat(selfAddresses)
326
- .map((email) => email.toLowerCase()));
327
- const named = [
328
- ...(recipients.to ?? []),
329
- ...(recipients.cc ?? []),
330
- ...(recipients.bcc ?? []),
331
- ];
332
- return (named.find((address) => !roster.has(address.email.toLowerCase()))?.email ??
333
- null);
334
- };
335
- // The line a result carries when the default withheld the quote, so the agent
336
- // learns it at the moment it matters rather than only from the description.
337
- export const quoteWithheldNote = (outsider) => `The original was not quoted: ${outsider} was not on it, and quoting would forward it to them. ` +
338
- "Pass `quoteOriginal: true` if the user wants it included.";
339
- // Whether the body value of one media type came back cut off at the read
340
- // budget — per part, so a complete text part is not marked shortened because
341
- // its HTML alternative was long.
342
- export const partTruncated = (record, parts, mediaType) => (parts ?? []).some((part) => part.type === mediaType &&
343
- part.partId &&
344
- record.bodyValues?.[part.partId]?.isTruncated === true);
345
- const quoteTextPart = (own, q) => {
346
- const trimmed = own.trimEnd();
347
- const attribution = quoteText(q.attribution);
348
- const budget = MAX_REPLY_PART_CHARS -
349
- trimmed.length -
350
- attribution.length -
351
- QUOTE_FRAME_CHARS;
352
- // A reply that already fills the part budget goes out unquoted, as written.
353
- if (budget <= 0) {
354
- return own;
355
- }
356
- const quoted = fitted(q.text ?? htmlToText(q.html ?? ""), quoteText, budget);
357
- const truncated = q.text === undefined ? q.htmlTruncated : q.textTruncated;
358
- const note = quoted.shortened || truncated ? `\n>\n> ${SHORTENED_NOTE}` : "";
359
- return `${trimmed}\n\n${attribution}\n>\n${quoted.rendered}${note}\n`;
360
- };
361
- const quoteHtmlPart = (own, q) => {
362
- const attribution = escapeHtml(q.attribution);
363
- const budget = MAX_REPLY_PART_CHARS - own.length - attribution.length - QUOTE_FRAME_CHARS;
364
- if (budget <= 0) {
365
- return own;
366
- }
367
- // Sanitized before it is cut, so markup the sanitizer discards (a long <head>,
368
- // an embedded style sheet) cannot spend the budget; re-sanitizing each cut
369
- // closes whatever tags the cut left open.
370
- const quoted = q.html === undefined
371
- ? fitted(q.text ?? "", textAsHtml, budget)
372
- : fitted(quotableHtml(q.html), quotableHtml, budget);
373
- const truncated = q.html === undefined ? q.textTruncated : q.htmlTruncated;
374
- const note = quoted.shortened || truncated ? `<p>${escapeHtml(SHORTENED_NOTE)}</p>` : "";
375
- return (`${own}\n<br>\n<div>${attribution}</div>\n` +
376
- `<blockquote type="cite" style="margin:0 0 0 0.8ex;border-left:1px solid #ccc;padding-left:1ex">${quoted.rendered}${note}</blockquote>\n`);
377
- };
378
- export const nonBlank = (value) => value !== undefined && value.trim() !== "" ? value : undefined;
379
- // The reply body with the original quoted below it. Returns the body unchanged
380
- // when the original has nothing to quote (no body part came back). A read cut
381
- // off at the body budget is quoted as far as it goes, and says so.
382
- export const withQuotedOriginal = (body, original) => {
383
- const parts = draftFromRecord(original);
384
- const source = {
385
- attribution: attributionLine(original),
386
- html: nonBlank(parts.html),
387
- htmlTruncated: partTruncated(original, original.htmlBody, "text/html"),
388
- text: nonBlank(parts.text),
389
- textTruncated: partTruncated(original, original.textBody, "text/plain"),
390
- };
391
- if (source.text === undefined && source.html === undefined) {
392
- return body;
393
- }
394
- return {
395
- ...(body.text === undefined
396
- ? {}
397
- : { text: quoteTextPart(body.text, source) }),
398
- ...(body.html === undefined
399
- ? {}
400
- : { html: quoteHtmlPart(body.html, source) }),
401
- };
402
- };
403
- // Whether a body already quotes `original` — by its attribution line, which is
404
- // how update_draft tells a reply that carries the quote from a bare one, and a
405
- // caller who passed the whole body (quote included) from one who passed only
406
- // the new part.
407
- export const carriesQuoteOf = (body, original) => {
408
- const attribution = attributionLine(original);
409
- return Boolean(body.text?.includes(attribution) ||
410
- body.html?.includes(escapeHtml(attribution)));
411
- };
412
- // The quoting decision both reply paths make: the caller's `quoteOriginal`
413
- // when given, the recipient rule otherwise. Returns the body to stage and,
414
- // when the default withheld the quote, the note the result should carry.
415
- export const quoteReply = (body, p) => {
416
- if (p.quoteOriginal === false) {
417
- return { body, note: null };
418
- }
419
- if (p.quoteOriginal === undefined) {
420
- const outsider = quoteWithheldFrom(p.original, p.recipients, p.selfAddresses);
421
- if (outsider) {
422
- return { body, note: quoteWithheldNote(outsider) };
423
- }
424
- }
425
- return { body: withQuotedOriginal(body, p.original), note: null };
426
- };