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,668 +0,0 @@
1
- // Typed JMAP wrappers for the Email, Thread, and Mailbox capabilities —
2
- // the read surface (query/get/thread/mailbox lookup) plus the write and
3
- // changes surface (Email/set patches, Email/changes, Mailbox/get by role)
4
- // a JMAP client that files and labels mail needs.
5
- import { buildEmailSetPatch } from "./patch.js";
6
- import { jmapCall as call, methodResponse } from "./request.js";
7
- import { JmapError } from "./session.js";
8
- // Every JMAP request must declare the core capability alongside any it uses
9
- // (RFC 8620 §3.3); Stalwart 0.16.10+ enforces this, rejecting requests whose
10
- // `using` omits a required capability. Mirrors auth's StalwartAdminClient.
11
- const USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
12
- // Lightweight properties for search + thread listings. `keywords` is included
13
- // so callers can surface a message's labels; `threadId` lets a hit expand.
14
- const EMAIL_PROPERTIES = [
15
- "id",
16
- "subject",
17
- "from",
18
- "receivedAt",
19
- "preview",
20
- "mailboxIds",
21
- "keywords",
22
- "threadId",
23
- // Cheap boolean so list views can flag hits worth opening for their files.
24
- "hasAttachment",
25
- "attachments",
26
- ];
27
- // Richer properties for get_email and the poller's analysis input:
28
- // recipients, the text body parts, the RFC 5322 Message-ID list, the
29
- // raw-message blob handle (blobId/size) for langmail preprocessing, and
30
- // mailboxIds so the poller can tell sent mail by its Sent membership.
31
- const EMAIL_DETAIL_PROPERTIES = [
32
- "id",
33
- "blobId",
34
- "size",
35
- "subject",
36
- "from",
37
- "to",
38
- "cc",
39
- "receivedAt",
40
- "mailboxIds",
41
- "keywords",
42
- "messageId",
43
- "textBody",
44
- // Part metadata only (no values fetched here) — the blobId handle lets a
45
- // caller download the full HTML part without a truncation cap.
46
- "htmlBody",
47
- "bodyValues",
48
- "threadId",
49
- "attachments",
50
- "hasAttachment",
51
- ];
52
- // Body-part properties requested alongside the detail fetch: enough to list
53
- // attachments (name/type/size), classify cid-inline parts, and hand back the
54
- // blobId retrieval handle — explicit so parts come back minimal.
55
- const EMAIL_BODY_PROPERTIES = [
56
- "partId",
57
- "blobId",
58
- "name",
59
- "type",
60
- "size",
61
- "disposition",
62
- "cid",
63
- ];
64
- // OR a set of conditions, collapsing a single element to its flat form —
65
- // JMAP treats a bare condition and a one-element operator identically, but
66
- // the flat form keeps the wire minimal.
67
- const orNode = (conds) => conds.length === 1 ? conds[0] : { conditions: conds, operator: "OR" };
68
- // Compose the JMAP filter: text terms OR'd among themselves (or as
69
- // `textMatch` says), keyword
70
- // conditions OR'd among themselves, then both AND'd with the scalar
71
- // conditions (date/from/mailbox/keyword states). A single overall condition is passed
72
- // through flat, like the OR nodes.
73
- // None of: a message holding every one of `terms`.
74
- const notAllOf = (terms) => ({
75
- conditions: [
76
- { conditions: terms.map((t) => ({ text: t })), operator: "AND" },
77
- ],
78
- operator: "NOT",
79
- });
80
- const textConditions = (text, match) => {
81
- const each = text.map((t) => ({ text: t }));
82
- const any = orNode(each);
83
- if (!any) {
84
- return [];
85
- }
86
- if (match === "all") {
87
- return each;
88
- }
89
- if (match === "someButNotAll") {
90
- return [any, notAllOf(text)];
91
- }
92
- return [any];
93
- };
94
- const buildFilter = (f) => {
95
- const conditions = f.text
96
- ? textConditions(f.text, f.textMatch)
97
- : [];
98
- if (f.withoutAllOf && f.withoutAllOf.length > 0) {
99
- conditions.push(notAllOf(f.withoutAllOf));
100
- }
101
- if (f.after) {
102
- conditions.push({ after: f.after });
103
- }
104
- if (f.before) {
105
- conditions.push({ before: f.before });
106
- }
107
- if (f.from) {
108
- conditions.push({ from: f.from });
109
- }
110
- if (f.mailboxId) {
111
- conditions.push({ inMailbox: f.mailboxId });
112
- }
113
- if (f.keywords && f.keywords.length > 0) {
114
- const node = orNode(f.keywords.map((k) => ({ hasKeyword: k })));
115
- if (node) {
116
- conditions.push(node);
117
- }
118
- }
119
- for (const [keyword, present] of Object.entries(f.keywordStates ?? {})) {
120
- conditions.push(present ? { hasKeyword: keyword } : { notKeyword: keyword });
121
- }
122
- const [only] = conditions;
123
- if (conditions.length === 1 && only) {
124
- return only;
125
- }
126
- return { conditions, operator: "AND" };
127
- };
128
- // Email/query with a caller-built filter tree — for callers whose condition
129
- // logic (AND/OR composition) outgrows the flat `EmailQueryFilters` bag.
130
- export const emailQueryFilter = async (p) => {
131
- const resp = await call(p, {
132
- methodCalls: [
133
- [
134
- "Email/query",
135
- {
136
- accountId: p.accountId,
137
- calculateTotal: false,
138
- ...(p.collapseThreads ? { collapseThreads: true } : {}),
139
- filter: p.filter,
140
- limit: p.limit,
141
- sort: [{ isAscending: false, property: "receivedAt" }],
142
- },
143
- "0",
144
- ],
145
- ],
146
- using: USING,
147
- });
148
- const out = methodResponse(resp, "Email/query", "0");
149
- return out.ids ?? [];
150
- };
151
- // One Email/query per term, batched into a single JMAP request. JMAP has no
152
- // relevance sort, so a caller that wants match-count ranking ("messages
153
- // hitting more terms first") needs to know which terms matched which
154
- // messages — an OR query collapses that information. Each per-term filter
155
- // ANDs the term with the scalar filters; each list is newest-first.
156
- export const emailQueryPerTerm = async (p) => {
157
- const resp = await call(p, {
158
- methodCalls: p.terms.map((term, i) => [
159
- "Email/query",
160
- {
161
- accountId: p.accountId,
162
- calculateTotal: false,
163
- filter: buildFilter({ ...p.filters, text: [term] }),
164
- limit: p.limit,
165
- sort: [{ isAscending: false, property: "receivedAt" }],
166
- },
167
- String(i),
168
- ]),
169
- using: USING,
170
- });
171
- return p.terms.map((_, i) => methodResponse(resp, "Email/query", String(i)).ids ??
172
- []);
173
- };
174
- export const emailQuery = async (p) => {
175
- const resp = await call(p, {
176
- methodCalls: [
177
- [
178
- "Email/query",
179
- {
180
- accountId: p.accountId,
181
- // Stalwart FTS full totals are expensive on a big mailbox; callers
182
- // that need one ask `emailQueryTotal` once a page comes back full.
183
- calculateTotal: false,
184
- filter: buildFilter(p.filters),
185
- limit: p.limit,
186
- // Newest-first: "last N months" questions need recency, and the
187
- // default mailbox order is meaningless for a date-scoped query.
188
- sort: [{ isAscending: false, property: "receivedAt" }],
189
- },
190
- "0",
191
- ],
192
- ],
193
- using: USING,
194
- });
195
- const out = methodResponse(resp, "Email/query", "0");
196
- return out.ids ?? [];
197
- };
198
- // How many messages match the filters in total, regardless of any page limit.
199
- // Text terms are OR'd exactly as in `emailQuery`, so a multi-term search's
200
- // total counts the union of its per-term hits. Totals cost a full FTS count on
201
- // Stalwart, so callers ask only when a page came back full.
202
- export const emailQueryTotal = async (p) => {
203
- const resp = await call(p, {
204
- methodCalls: [
205
- [
206
- "Email/query",
207
- {
208
- accountId: p.accountId,
209
- calculateTotal: true,
210
- filter: buildFilter(p.filters),
211
- // `limit: 0` is spec-legal (RFC 8620 §5.5 types it UnsignedInt) but
212
- // servers disagree on whether it means "none" or "no limit"; ask for
213
- // one id and discard it. Only `total` is wanted here.
214
- limit: 1,
215
- },
216
- "0",
217
- ],
218
- ],
219
- using: USING,
220
- });
221
- const out = methodResponse(resp, "Email/query", "0");
222
- if (out.total === undefined) {
223
- throw new Error("Email/query returned no total despite calculateTotal");
224
- }
225
- return out.total;
226
- };
227
- export const emailGet = async (p) => {
228
- if (p.ids.length === 0) {
229
- return [];
230
- }
231
- const resp = await call(p, {
232
- methodCalls: [
233
- [
234
- "Email/get",
235
- {
236
- accountId: p.accountId,
237
- bodyProperties: [...EMAIL_BODY_PROPERTIES],
238
- ids: p.ids,
239
- properties: [...EMAIL_PROPERTIES],
240
- },
241
- "0",
242
- ],
243
- ],
244
- using: USING,
245
- });
246
- const out = methodResponse(resp, "Email/get", "0");
247
- return out.list ?? [];
248
- };
249
- // --- Email/get (headers only) ----------------------------------------------
250
- // What contact collection reads off a message: addressing headers, keywords
251
- // (skip-filter), mailboxIds (Sent detection), receivedAt. No bodies — the
252
- // backfill pages thousands of messages and must stay cheap.
253
- const EMAIL_HEADER_PROPERTIES = [
254
- "id",
255
- "from",
256
- "to",
257
- "cc",
258
- "receivedAt",
259
- "keywords",
260
- "mailboxIds",
261
- ];
262
- export const emailGetHeaders = async (p) => {
263
- if (p.ids.length === 0) {
264
- return [];
265
- }
266
- const resp = await call(p, {
267
- methodCalls: [
268
- [
269
- "Email/get",
270
- {
271
- accountId: p.accountId,
272
- ids: p.ids,
273
- properties: [...EMAIL_HEADER_PROPERTIES],
274
- },
275
- "0",
276
- ],
277
- ],
278
- using: USING,
279
- });
280
- const out = methodResponse(resp, "Email/get", "0");
281
- return out.list ?? [];
282
- };
283
- export const emailGetDetail = async (p) => {
284
- if (p.ids.length === 0) {
285
- return [];
286
- }
287
- const resp = await call(p, {
288
- methodCalls: [
289
- [
290
- "Email/get",
291
- {
292
- accountId: p.accountId,
293
- bodyProperties: [...EMAIL_BODY_PROPERTIES],
294
- // Populate bodyValues for the text parts, capped so a huge message
295
- // can't blow the token budget (Stalwart truncates at this size).
296
- fetchTextBodyValues: true,
297
- ids: p.ids,
298
- maxBodyValueBytes: p.maxBodyValueBytes,
299
- properties: [...EMAIL_DETAIL_PROPERTIES],
300
- },
301
- "0",
302
- ],
303
- ],
304
- using: USING,
305
- });
306
- const out = methodResponse(resp, "Email/get", "0");
307
- return out.list ?? [];
308
- };
309
- // --- Email/get (unsubscribe headers) -------------------------------------
310
- // The list headers in the forms RFC 8621 §4.1.2 defines: List-Unsubscribe
311
- // Raw (folding kept, the caller parses `<uri>` entries itself), the Post and
312
- // Delivered-To headers as unfolded text. The text body is fetched so a
313
- // message without the header can still point at its footer link.
314
- const EMAIL_UNSUBSCRIBE_PROPERTIES = [
315
- "id",
316
- "mailboxIds",
317
- "keywords",
318
- "to",
319
- "textBody",
320
- "bodyValues",
321
- "header:List-Unsubscribe",
322
- "header:List-Unsubscribe-Post:asText",
323
- "header:Delivered-To:asText:all",
324
- ];
325
- export const emailGetUnsubscribe = async (p) => {
326
- const resp = await call(p, {
327
- methodCalls: [
328
- [
329
- "Email/get",
330
- {
331
- accountId: p.accountId,
332
- bodyProperties: ["partId", "type"],
333
- fetchTextBodyValues: true,
334
- ids: [p.id],
335
- maxBodyValueBytes: p.maxBodyValueBytes,
336
- properties: [...EMAIL_UNSUBSCRIBE_PROPERTIES],
337
- },
338
- "0",
339
- ],
340
- ],
341
- using: USING,
342
- });
343
- const out = methodResponse(resp, "Email/get", "0");
344
- return out.list?.[0] ?? null;
345
- };
346
- // Patch keywords and/or mailbox membership on a single email via an Email/set
347
- // `update` with a JSON-pointer PatchObject, leaving every other keyword and
348
- // mailbox untouched — this is what lets sync's mirror and the agent's writes
349
- // compose without clobbering each other. Throws JmapError if
350
- // Stalwart reports the id under `notUpdated` (or omits it from `updated`).
351
- export const emailSet = async (p) => {
352
- const resp = await call(p, {
353
- methodCalls: [
354
- [
355
- "Email/set",
356
- {
357
- accountId: p.accountId,
358
- update: { [p.id]: buildEmailSetPatch(p.changes) },
359
- },
360
- "0",
361
- ],
362
- ],
363
- using: USING,
364
- });
365
- const out = methodResponse(resp, "Email/set", "0");
366
- if (out.updated && p.id in out.updated) {
367
- return;
368
- }
369
- const reason = out.notUpdated?.[p.id];
370
- throw new JmapError(200, `Email/set did not update ${p.id}: ${reason?.type ?? "unknown"}`);
371
- };
372
- // Apply the same PatchObject to many emails in a single Email/set. Partial
373
- // failure is data, not an exception: the caller (rule backfill) reports
374
- // modified/failed counts instead of aborting on the first bad id.
375
- export const emailSetMany = async (p) => {
376
- if (p.ids.length === 0) {
377
- return { notUpdated: [], updated: [] };
378
- }
379
- const patch = buildEmailSetPatch(p.changes);
380
- const resp = await call(p, {
381
- methodCalls: [
382
- [
383
- "Email/set",
384
- {
385
- accountId: p.accountId,
386
- update: Object.fromEntries(p.ids.map((id) => [id, patch])),
387
- },
388
- "0",
389
- ],
390
- ],
391
- using: USING,
392
- });
393
- return setManyOutcome(p.ids, methodResponse(resp, "Email/set", "0"));
394
- };
395
- // Fold an Email/set response over the ids we asked for: every id is reported
396
- // exactly once, as updated or as refused with the server's SetError type.
397
- const setManyOutcome = (ids, out) => {
398
- const updated = new Set(Object.keys(out.updated ?? {}));
399
- return {
400
- notUpdated: ids
401
- .filter((id) => !updated.has(id))
402
- .map((id) => ({ id, type: out.notUpdated?.[id]?.type ?? "unknown" })),
403
- updated: ids.filter((id) => updated.has(id)),
404
- };
405
- };
406
- // Replace every email's mailbox membership with exactly one mailbox — a
407
- // "move" in the sense every JMAP client means it. Sends the whole
408
- // `mailboxIds` property rather than a `mailboxIds/<id>` pointer patch: the
409
- // patch form (`emailSetMany`) can only add or drop the mailboxes it names,
410
- // so it cannot express "and remove it from everywhere else". Same
411
- // partial-failure contract as emailSetMany.
412
- export const emailSetMailboxes = async (p) => {
413
- if (p.ids.length === 0) {
414
- return { notUpdated: [], updated: [] };
415
- }
416
- const resp = await call(p, {
417
- methodCalls: [
418
- [
419
- "Email/set",
420
- {
421
- accountId: p.accountId,
422
- update: Object.fromEntries(p.ids.map((id) => [id, { mailboxIds: { [p.mailboxId]: true } }])),
423
- },
424
- "0",
425
- ],
426
- ],
427
- using: USING,
428
- });
429
- return setManyOutcome(p.ids, methodResponse(resp, "Email/set", "0"));
430
- };
431
- // The account's current Email state string (RFC 8621 §5), fetched via an
432
- // empty Email/get. The poller seeds a fresh cursor from this so only mail
433
- // arriving after the seed gets analyzed — no historical backfill.
434
- export const emailState = async (p) => {
435
- const resp = await call(p, {
436
- methodCalls: [["Email/get", { accountId: p.accountId, ids: [] }, "0"]],
437
- using: USING,
438
- });
439
- const out = methodResponse(resp, "Email/get", "0");
440
- if (!out.state) {
441
- throw new JmapError(200, "Email/get returned no state");
442
- }
443
- return out.state;
444
- };
445
- // The delta of email ids created/updated/destroyed since `sinceState`
446
- // (RFC 8621 §5.2). The poller persists `newState` as its cursor and only
447
- // advances it once the batch is processed — a failed batch replays.
448
- export const emailChanges = async (p) => {
449
- const resp = await call(p, {
450
- methodCalls: [
451
- [
452
- "Email/changes",
453
- {
454
- accountId: p.accountId,
455
- ...(p.maxChanges === undefined ? {} : { maxChanges: p.maxChanges }),
456
- sinceState: p.sinceState,
457
- },
458
- "0",
459
- ],
460
- ],
461
- using: USING,
462
- });
463
- const out = methodResponse(resp, "Email/changes", "0");
464
- return {
465
- created: out.created ?? [],
466
- destroyed: out.destroyed ?? [],
467
- hasMoreChanges: out.hasMoreChanges ?? false,
468
- newState: out.newState ?? p.sinceState,
469
- oldState: out.oldState ?? p.sinceState,
470
- updated: out.updated ?? [],
471
- };
472
- };
473
- // Resolve every message id in the same thread as `emailId`, oldest-first
474
- // (RFC 8621 §3 requires Thread.emailIds sorted by receivedAt ascending).
475
- // One round-trip: Email/get the threadId, then Thread/get via a result ref.
476
- export const threadEmailIds = async (p) => {
477
- const resp = await call(p, {
478
- methodCalls: [
479
- [
480
- "Email/get",
481
- { accountId: p.accountId, ids: [p.emailId], properties: ["threadId"] },
482
- "0",
483
- ],
484
- [
485
- "Thread/get",
486
- {
487
- "#ids": {
488
- name: "Email/get",
489
- path: "/list/*/threadId",
490
- resultOf: "0",
491
- },
492
- accountId: p.accountId,
493
- },
494
- "1",
495
- ],
496
- ],
497
- using: USING,
498
- });
499
- const out = methodResponse(resp, "Thread/get", "1");
500
- const [thread] = out.list ?? [];
501
- return thread?.emailIds ?? [];
502
- };
503
- // Expand a set of message ids to every message in their threads (deduped,
504
- // input-thread order). One round-trip via a Thread/get back-reference — the
505
- // bulk sibling of `threadEmailIds`, for the rules backfill's
506
- // "matching conversations" mode.
507
- export const threadsExpandEmailIds = async (p) => {
508
- if (p.emailIds.length === 0) {
509
- return [];
510
- }
511
- const resp = await call(p, {
512
- methodCalls: [
513
- [
514
- "Email/get",
515
- { accountId: p.accountId, ids: p.emailIds, properties: ["threadId"] },
516
- "0",
517
- ],
518
- [
519
- "Thread/get",
520
- {
521
- "#ids": {
522
- name: "Email/get",
523
- path: "/list/*/threadId",
524
- resultOf: "0",
525
- },
526
- accountId: p.accountId,
527
- },
528
- "1",
529
- ],
530
- ],
531
- using: USING,
532
- });
533
- const out = methodResponse(resp, "Thread/get", "1");
534
- const ids = new Set();
535
- for (const thread of out.list ?? []) {
536
- for (const id of thread.emailIds) {
537
- ids.add(id);
538
- }
539
- }
540
- return [...ids];
541
- };
542
- // --- Mailbox/get ---------------------------------------------------------
543
- // One round-trip that hydrates every mailbox's id + name + role. Stalwart's
544
- // mailbox count is small, so listing all and matching in memory is cheaper
545
- // than the name/role-filtered Mailbox/query JMAP doesn't directly support.
546
- const fetchMailboxes = async (p) => {
547
- const resp = await call(p, {
548
- methodCalls: [
549
- ["Mailbox/query", { accountId: p.accountId }, "0"],
550
- [
551
- "Mailbox/get",
552
- {
553
- "#ids": { name: "Mailbox/query", path: "/ids", resultOf: "0" },
554
- accountId: p.accountId,
555
- properties: ["id", "name", "role"],
556
- },
557
- "1",
558
- ],
559
- ],
560
- using: USING,
561
- });
562
- const got = methodResponse(resp, "Mailbox/get", "1");
563
- return got.list ?? [];
564
- };
565
- export const mailboxIdByName = async (p) => {
566
- const wanted = p.name.toLowerCase();
567
- const hit = (await fetchMailboxes(p)).find((m) => m.name.toLowerCase() === wanted);
568
- return hit?.id ?? null;
569
- };
570
- // Resolve a mailbox by its special-use role — the stable way to find the
571
- // inbox, independent of the localized display name.
572
- export const mailboxIdByRole = async (p) => {
573
- const wanted = p.role.toLowerCase();
574
- const hit = (await fetchMailboxes(p)).find((m) => m.role?.toLowerCase() === wanted);
575
- return hit?.id ?? null;
576
- };
577
- // The RFC 8621 special-use role behind each *place* name the product speaks.
578
- //
579
- // A place is addressed by name everywhere a human or an agent types one
580
- // ("Sent", "Archive"), but the mailbox actually holding that mail is whatever
581
- // carries the role — and its display name is the server's to choose. A stock
582
- // Stalwart account names its sent mailbox **"Sent Items"**, so a name-only
583
- // lookup for "Sent" misses the very folder sent mail is filed into.
584
- // That miss reads to the caller as "sent mail was never synced".
585
- //
586
- // Keys are lowercase; synonyms map onto the same role so the obvious spelling
587
- // works ("Spam" → junk, "Bin" → trash).
588
- const ROLE_BY_PLACE_NAME = {
589
- archive: "archive",
590
- bin: "trash",
591
- drafts: "drafts",
592
- inbox: "inbox",
593
- junk: "junk",
594
- sent: "sent",
595
- spam: "junk",
596
- trash: "trash",
597
- };
598
- // The special-use role a place name refers to, or `undefined` for a name that
599
- // isn't a place (an ordinary user folder, resolvable by name only).
600
- export const roleForPlaceName = (name) => ROLE_BY_PLACE_NAME[name.trim().toLowerCase()];
601
- // Resolve a caller-supplied folder name to a mailbox id: for a *place* name the
602
- // mailbox carrying that role, else (and as the fallback) an exact, case-folded
603
- // name match. One round-trip serves both lookups.
604
- //
605
- // Role wins for the eight place names because the role *is* what identifies a
606
- // place. Name-first
607
- // would be shadowable: a stray role-less folder literally named "Sent" (the
608
- // mail-rules `resolveMailboxByName` used to create exactly that) would swallow
609
- // the lookup and return zero hits instead of the account's real sent mail —
610
- // reproducing the very symptom this resolver exists to fix, and silently.
611
- //
612
- // Name remains the fallback, so an ordinary user folder resolves as it always
613
- // did, and a place name still works on a server that has no mailbox carrying
614
- // that role but does have one named for it.
615
- export const mailboxIdByNameOrRole = async (p) => {
616
- const mailboxes = await fetchMailboxes(p);
617
- const role = roleForPlaceName(p.name);
618
- const byRole = role
619
- ? mailboxes.find((m) => m.role?.toLowerCase() === role)
620
- : undefined;
621
- if (byRole) {
622
- return byRole.id;
623
- }
624
- const wanted = p.name.trim().toLowerCase();
625
- return mailboxes.find((m) => m.name.toLowerCase() === wanted)?.id ?? null;
626
- };
627
- // Every folder name in the account. Used to turn a failed mailbox lookup into
628
- // an actionable error rather than a dead end.
629
- export const mailboxNames = async (p) => (await fetchMailboxes(p)).map((m) => m.name);
630
- // Resolve several special-use roles from one mailbox listing — the archive
631
- // move needs both inbox and archive, and one round-trip beats two.
632
- export const mailboxIdsByRoles = async (p) => {
633
- const mailboxes = await fetchMailboxes(p);
634
- return Object.fromEntries(p.roles.map((role) => {
635
- const wanted = role.toLowerCase();
636
- return [
637
- role,
638
- mailboxes.find((m) => m.role?.toLowerCase() === wanted)?.id ?? null,
639
- ];
640
- }));
641
- };
642
- // Create a mailbox (optionally with a special-use role) and return its id.
643
- export const mailboxCreate = async (p) => {
644
- const resp = await call(p, {
645
- methodCalls: [
646
- [
647
- "Mailbox/set",
648
- {
649
- accountId: p.accountId,
650
- create: {
651
- m0: {
652
- name: p.name,
653
- ...(p.role === undefined ? {} : { role: p.role }),
654
- },
655
- },
656
- },
657
- "0",
658
- ],
659
- ],
660
- using: USING,
661
- });
662
- const out = methodResponse(resp, "Mailbox/set", "0");
663
- const id = out.created?.m0?.id;
664
- if (!id) {
665
- throw new JmapError(200, `Mailbox/set did not create ${p.name}: ${out.notCreated?.m0?.type ?? "unknown"}`);
666
- }
667
- return id;
668
- };
@@ -1,12 +0,0 @@
1
- // biome-ignore lint/performance/noBarrelFile: package entry point requires re-exports
2
- export { blobDownload, blobDownloadUrl, blobUpload, } from "./blob.js";
3
- export { addressBookCreate, addressBookList, ContactUidTakenError, contactCardCreate, contactCardDestroy, contactCardGet, contactCardMerge, contactCardPage, contactCardQuery, contactCardUpdate, } from "./contacts.js";
4
- export { DRAFT_FORWARD_OF_KEYWORD_PREFIX, DRAFT_ID_KEYWORD_PREFIX, DRAFT_KEYWORD, DRAFT_REPLY_TO_KEYWORD_PREFIX, draftCreate, draftDestroy, draftIdResolve, draftList, emailComposeGet, threadMessageFind, } from "./drafts.js";
5
- export { emailChanges, emailGet, emailGetDetail, emailGetHeaders, emailGetUnsubscribe, emailQuery, emailQueryFilter, emailQueryPerTerm, emailQueryTotal, emailSet, emailSetMailboxes, emailSetMany, emailState, mailboxCreate, mailboxIdByName, mailboxIdByNameOrRole, mailboxIdByRole, mailboxIdsByRoles, mailboxNames, roleForPlaceName, threadEmailIds, threadsExpandEmailIds, } from "./email.js";
6
- export { LABEL_KEYWORD_PREFIX, TYPE_KEYWORD_PREFIX, toLabelKeyword, toTypeKeyword, } from "./keywords.js";
7
- export { makeJmapLive } from "./live.js";
8
- export { jmapFetch, OriginMismatchError, originPinnedFetch, } from "./origin.js";
9
- export { accountIdForContacts, accountIdForMail, accountIdForSieve, accountIdForSubmission, authorizationHeader, fetchSession, JmapError, } from "./session.js";
10
- export { sieveScriptCreate, sieveScriptList, sieveScriptUpdate, } from "./sieve.js";
11
- export { emailSubmissionCreate, identityGet, } from "./submission.js";
12
- export { jmapTimeoutSignal } from "./timeout.js";