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,408 +0,0 @@
1
- // Thin glue over `tsdav`: RFC 6764 discovery + calendar listing + event
2
- // PUT, each authenticated with the credential. A fresh, stateless call per
3
- // request — same model as the JMAP wrappers in src/jmap.
4
- //
5
- // The transport details (well-known redirect to /dav/cal, principal ->
6
- // calendar-home-set -> calendars) live inside tsdav; we thread the credential
7
- // through, pin every request to the configured origin, and reshape the
8
- // result into our CalendarSummary / DiscoveredAccount types.
9
- import { createAccount, createCalendarObject, DAVNamespace, DAVNamespaceShort, davRequest, deleteCalendarObject, fetchCalendarObjects, fetchCalendarUserAddresses, getDAVAttribute, makeCalendar, updateCalendarObject, } from "tsdav";
10
- import { parseEvents } from "../ical/index.js";
11
- import { authorizationHeader, OriginMismatchError, originPinnedFetch, } from "../jmap/index.js";
12
- class CalDavError extends Error {
13
- status;
14
- constructor(status, message) {
15
- super(message);
16
- this.status = status;
17
- this.name = "CalDavError";
18
- }
19
- }
20
- const DEFAULT_CAL_RE = /\/default\/?$/u;
21
- const MAILTO_RE = /^mailto:/iu;
22
- // A 2xx code in a status line like "HTTP/1.1 200 OK" (padded, so "HTTP/1.1 200" matches too).
23
- const SUCCESS_STATUS_LINE_RE = / 2\d\d /u;
24
- // Same order as the JMAP deadline (src/jmap/timeout.ts): enough for a
25
- // legitimately slow REPORT over a large calendar, short enough that a stalled
26
- // Stalwart becomes a logged error instead of a tool call that never returns.
27
- const CALDAV_TIMEOUT_MS = 30_000;
28
- // tsdav threads `fetchOptions` into every fetch it makes, including the several
29
- // requests a single `createAccount` discovery performs (verified against tsdav
30
- // 2.3.0), so one signal bounds every request it covers. It must be built per
31
- // use — a signal created once at module load would already be expired.
32
- //
33
- // Each exported function below builds exactly one and shares it across the
34
- // tsdav calls it makes, so the deadline bounds the *function*, not each
35
- // round-trip inside it. A tool that calls two of them in sequence (discover,
36
- // then write) therefore has two windows, not one: the deadline turns a stall
37
- // into an error, and is not a per-tool latency budget.
38
- const deadline = () => ({
39
- signal: AbortSignal.timeout(CALDAV_TIMEOUT_MS),
40
- });
41
- const authHeaders = (cfg, credential) => cfg.authHeaders
42
- ? cfg.authHeaders(credential)
43
- : { authorization: authorizationHeader(credential) };
44
- // What every tsdav call is given: the credential, the deadline, and a `fetch`
45
- // that refuses any URL off the configured server's origin. tsdav follows the
46
- // `/.well-known/caldav` redirect and the hrefs of a multistatus wherever they
47
- // point and re-sends its headers there, so the pin is what keeps the
48
- // credential on the user's own server. The three travel together on purpose:
49
- // a call site cannot send the credential without the pin.
50
- const transport = (cfg, credential, fetchOptions = deadline()) => ({
51
- fetch: originPinnedFetch(cfg.serverUrl, "CalDAV"),
52
- fetchOptions,
53
- headers: authHeaders(cfg, credential),
54
- });
55
- // CalDAV collection URLs are canonically trailing-slashed; tsdav resolves
56
- // object URLs via `new URL(filename, url)`, which silently drops the last
57
- // path segment without it. Normalize before comparing or PUTting so the
58
- // membership check and the PUT can't disagree on the same calendar.
59
- export const withTrailingSlash = (url) => url.endsWith("/") ? url : `${url}/`;
60
- const toSummary = (cal) => ({
61
- // Guarded like displayName: a color sent with attributes parses to an object.
62
- ...(typeof cal.calendarColor === "string" && cal.calendarColor
63
- ? { color: cal.calendarColor }
64
- : {}),
65
- displayName: typeof cal.displayName === "string" ? cal.displayName : "",
66
- url: cal.url,
67
- });
68
- // The calendar an unqualified event lands in: Stalwart auto-provisions a
69
- // `.../default/` collection, so prefer that; otherwise the first listed.
70
- export const pickDefaultCalendar = (calendars) => {
71
- const def = calendars.find((c) => DEFAULT_CAL_RE.test(c.url));
72
- return (def ?? calendars[0])?.url ?? null;
73
- };
74
- export const resolveCalendarUrl = (account, requested) => {
75
- const url = requested ?? account.defaultCalendarUrl;
76
- if (!url) {
77
- return { ok: false, reason: "none" };
78
- }
79
- if (requested &&
80
- !account.calendars.some((c) => withTrailingSlash(c.url) === withTrailingSlash(requested))) {
81
- return { ok: false, reason: "not-found" };
82
- }
83
- return { ok: true, url };
84
- };
85
- // The principal's `mailto:` calendar-user-address as a bare email.
86
- // calendar-user-address-set (RFC 6638) can list several hrefs — often
87
- // the principal URL alongside the mailto — so we must pick the mailto
88
- // one specifically; a non-mailto organizer would break iMIP routing.
89
- export const pickOrganizer = (addresses) => {
90
- const mail = addresses.find((a) => MAILTO_RE.test(a));
91
- return mail ? mail.replace(MAILTO_RE, "") : null;
92
- };
93
- // Takes the caller's deadline so a function that discovers *and* then acts is
94
- // bounded once overall, rather than granting each leg a fresh window.
95
- //
96
- // tsdav's discovery tries further root URLs when one fails and reports only
97
- // the last failure ("cannot find principalUrl"), which would bury a refused
98
- // off-origin URL under a message that explains nothing. So the first refusal
99
- // is kept and thrown once discovery returns, whether or not a later candidate
100
- // answered: a server that points its CalDAV endpoints elsewhere is
101
- // misconfigured, and the user should hear that rather than get half an answer.
102
- const loadAccount = async (cfg, token, fetchOptions) => {
103
- const pinned = transport(cfg, token, fetchOptions);
104
- let refused;
105
- const recording = (async (input, init) => {
106
- try {
107
- return await pinned.fetch(input, init);
108
- }
109
- catch (err) {
110
- if (err instanceof OriginMismatchError) {
111
- refused ??= err;
112
- }
113
- throw err;
114
- }
115
- });
116
- let account;
117
- try {
118
- account = await createAccount({
119
- account: { accountType: "caldav", serverUrl: cfg.serverUrl },
120
- ...pinned,
121
- fetch: recording,
122
- loadCollections: true,
123
- });
124
- }
125
- catch (err) {
126
- throw refused ?? err;
127
- }
128
- if (refused) {
129
- throw refused;
130
- }
131
- return account;
132
- };
133
- export const fetchCalendarList = async (cfg, token) => {
134
- const account = await loadAccount(cfg, token, deadline());
135
- return (account.calendars ?? []).map(toSummary);
136
- };
137
- export const discoverAccount = async (cfg, token) => {
138
- const fetchOptions = deadline();
139
- const account = await loadAccount(cfg, token, fetchOptions);
140
- const addresses = await fetchCalendarUserAddresses({
141
- account,
142
- ...transport(cfg, token, fetchOptions),
143
- });
144
- const calendars = (account.calendars ?? []).map(toSummary);
145
- return {
146
- calendars,
147
- defaultCalendarUrl: pickDefaultCalendar(calendars),
148
- organizer: pickOrganizer(addresses),
149
- };
150
- };
151
- // Creates a new CalDAV calendar collection under the principal's
152
- // calendar-home-set via MKCALENDAR, and returns its URL (trailing-slashed,
153
- // ready for create_calendar_event). The collection's path segment is a fresh
154
- // UUID — the human name lives in the `displayname` prop, not the URL — so
155
- // retries or same-named calendars never collide on a path.
156
- export const createCalendar = async (cfg, p) => {
157
- const fetchOptions = deadline();
158
- const account = await loadAccount(cfg, p.token, fetchOptions);
159
- if (!account.homeUrl) {
160
- throw new Error("no calendar-home-set discovered for the principal");
161
- }
162
- // homeUrl comes back absolute from RFC 6764 discovery, so the returned URL is
163
- // directly usable as create_calendar_event's `calendarUrl`.
164
- const url = withTrailingSlash(`${withTrailingSlash(account.homeUrl)}${crypto.randomUUID()}`);
165
- const res = await makeCalendar({
166
- ...transport(cfg, p.token, fetchOptions),
167
- props: {
168
- [`${DAVNamespaceShort.DAV}:displayname`]: { _text: p.name },
169
- ...(p.color
170
- ? {
171
- [`${DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]: {
172
- _text: p.color,
173
- },
174
- }
175
- : {}),
176
- },
177
- url,
178
- });
179
- // An empty response array would otherwise slip past the `find` below and
180
- // report success without confirmation, so treat it as a failure.
181
- if (res.length === 0) {
182
- throw new Error("caldav MKCALENDAR returned no response");
183
- }
184
- const failed = res.find((r) => !r.ok);
185
- if (failed) {
186
- throw new CalDavError(failed.status, `caldav MKCALENDAR returned ${failed.status}`);
187
- }
188
- return url;
189
- };
190
- // Status lines of every propstat in a parsed multistatus. tsdav merges only
191
- // the successful propstats into `props` and marks the response `ok` from the
192
- // 207, so a refused property is otherwise invisible.
193
- const propstatStatuses = (raw) => {
194
- const multistatus = raw?.multistatus;
195
- const responses = [multistatus?.response].flat();
196
- return responses
197
- .flatMap((r) => [r?.propstat].flat())
198
- .filter((p) => p !== undefined)
199
- .map((p) => p.status ?? "no status");
200
- };
201
- // Renames and/or recolors a calendar collection with one PROPPATCH of
202
- // `displayname` and Apple `calendar-color` — the two props createCalendar
203
- // sets on MKCALENDAR.
204
- export const updateCalendar = async (cfg, p) => {
205
- const { headers, ...pinned } = transport(cfg, p.token);
206
- const res = await davRequest({
207
- ...pinned,
208
- init: {
209
- body: {
210
- propertyupdate: {
211
- // tsdav's own prefix map, so the `ca:` on calendar-color is bound.
212
- _attributes: getDAVAttribute([
213
- DAVNamespace.DAV,
214
- DAVNamespace.CALDAV_APPLE,
215
- ]),
216
- set: {
217
- prop: {
218
- ...(p.name === undefined
219
- ? {}
220
- : {
221
- [`${DAVNamespaceShort.DAV}:displayname`]: { _text: p.name },
222
- }),
223
- ...(p.color
224
- ? {
225
- [`${DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]: {
226
- _text: p.color,
227
- },
228
- }
229
- : {}),
230
- },
231
- },
232
- },
233
- },
234
- headers,
235
- method: "PROPPATCH",
236
- namespace: DAVNamespaceShort.DAV,
237
- },
238
- url: p.url,
239
- });
240
- if (res.length === 0) {
241
- throw new Error("caldav PROPPATCH returned no response");
242
- }
243
- const isMultistatus = typeof res[0]?.raw === "object" &&
244
- res[0]?.raw !== null &&
245
- "multistatus" in res[0].raw;
246
- // tsdav takes a response's status from its propstats when every one fails,
247
- // so a refused property also lands here as `!ok`. Leave that to the propstat
248
- // check below, which names every refused status rather than just the first.
249
- const failed = isMultistatus ? undefined : res.find((r) => !r.ok);
250
- if (failed) {
251
- throw new CalDavError(failed.status, `caldav PROPPATCH returned ${failed.status}`);
252
- }
253
- // tsdav hangs the whole parsed document off every response, so read it once.
254
- const statuses = propstatStatuses(res[0]?.raw);
255
- const refused = statuses.filter((status) => !SUCCESS_STATUS_LINE_RE.test(`${status} `));
256
- if (refused.length > 0) {
257
- throw new Error(`caldav PROPPATCH refused a property: ${refused.join(", ")}`);
258
- }
259
- // RFC 4918 §9.2.1 requires a propstat per property, so a multistatus without
260
- // any confirms nothing. A reply that is not a multistatus at all (a bare 2xx)
261
- // is the server saying it applied the change, and passes.
262
- if (isMultistatus && statuses.length === 0) {
263
- throw new Error("caldav PROPPATCH confirmed no property");
264
- }
265
- };
266
- // The name of a freshly created `.ics` resource. RFC 4791 §5.3.2 says the
267
- // resource URL need bear no relationship to the object's properties, and §11
268
- // says the name MUST NOT expose data from inside the object — so it is a bare
269
- // UUID, generated independently of the event UID.
270
- //
271
- // Naming the resource after the UID is what made events created here invisible
272
- // in Apple Calendar: our UIDs carried a domain, and since Stalwart 0.16.19 a
273
- // `@` in a resource name is stored verbatim rather than percent-encoded,
274
- // while clients ask for it percent-encoded.
275
- export const newEventResourceName = () => `${crypto.randomUUID()}.ics`;
276
- export const putEvent = async (cfg, p) => {
277
- const res = await createCalendarObject({
278
- calendar: { url: withTrailingSlash(p.calendarUrl) },
279
- ...transport(cfg, p.token),
280
- filename: newEventResourceName(),
281
- iCalString: p.ical,
282
- });
283
- if (!res.ok) {
284
- throw new CalDavError(res.status, `caldav PUT returned ${res.status}`);
285
- }
286
- };
287
- // tsdav stringifies a missing getetag as the literal "undefined"; treat
288
- // that as no ETag so we never send a bogus `If-Match: undefined`.
289
- const normalizeEtag = (etag) => etag && etag !== "undefined" ? etag : undefined;
290
- // Reshapes a tsdav object into our CalendarObject, dropping anything the
291
- // server returned without calendar data (e.g. a 404'd multiget href).
292
- const toCalendarObject = (obj) => {
293
- if (typeof obj.data !== "string" || obj.data.length === 0) {
294
- return null;
295
- }
296
- const etag = normalizeEtag(obj.etag);
297
- return { data: obj.data, url: obj.url, ...(etag ? { etag } : {}) };
298
- };
299
- // Stalwart answers a calendar-query REPORT over an *empty* collection with a
300
- // 404, which tsdav surfaces as a thrown "Collection query failed: 404". An
301
- // empty calendar is a normal state, not an error, so we map it to an empty
302
- // list (the calendar itself is already validated by resolveCalendarUrl, so a
303
- // 404 here means "no events", not "no such calendar"). The pattern matches
304
- // tsdav's internal error string (observed on tsdav 2.2.2) — re-check the
305
- // message format on tsdav upgrades, or the 404 starts propagating again.
306
- const EMPTY_COLLECTION_RE = /Collection query failed: 404\b/u;
307
- export const isEmptyCollectionError = (err) => err instanceof Error && EMPTY_COLLECTION_RE.test(err.message);
308
- // Lists the event objects in a calendar (optionally bounded by a time
309
- // range) so the agent can discover UIDs to update/delete.
310
- export const fetchEvents = async (cfg, p) => {
311
- let objects;
312
- try {
313
- objects = await fetchCalendarObjects({
314
- calendar: { url: withTrailingSlash(p.calendarUrl) },
315
- ...transport(cfg, p.token),
316
- ...(p.timeRange ? { timeRange: p.timeRange } : {}),
317
- });
318
- }
319
- catch (err) {
320
- if (isEmptyCollectionError(err)) {
321
- return [];
322
- }
323
- throw err;
324
- }
325
- return objects
326
- .map(toCalendarObject)
327
- .filter((o) => o !== null);
328
- };
329
- // Finds the stored object holding a given iCalendar UID among a collection's
330
- // objects. CalDAV resource names are server-assigned and bear no relation to
331
- // the UID — including for events we create ourselves (see
332
- // newEventResourceName) — so we match on the parsed VEVENT UID rather than
333
- // guessing the filename.
334
- export const findEventObject = (objects, uid) => objects.find((o) => parseEvents(o.data).some((e) => e.uid === uid)) ?? null;
335
- // Fetches the single event object carrying `uid`. Lists the collection and
336
- // matches by UID (see findEventObject) so it works regardless of how the
337
- // object was named — including events synced in from other clients. Returns
338
- // null when no object carries the UID, surfaced as a friendly "not found".
339
- export const fetchEvent = async (cfg, p) => {
340
- const objects = await fetchEvents(cfg, {
341
- calendarUrl: p.calendarUrl,
342
- token: p.token,
343
- });
344
- return findEventObject(objects, p.uid);
345
- };
346
- export const updateEvent = async (cfg, p) => {
347
- const res = await updateCalendarObject({
348
- calendarObject: { data: p.ical, etag: p.etag, url: p.url },
349
- ...transport(cfg, p.token),
350
- });
351
- if (!res.ok) {
352
- throw new CalDavError(res.status, `caldav PUT returned ${res.status}`);
353
- }
354
- };
355
- export const deleteEvent = async (cfg, p) => {
356
- const res = await deleteCalendarObject({
357
- calendarObject: { data: "", etag: p.etag, url: p.url },
358
- ...transport(cfg, p.token),
359
- });
360
- if (!res.ok) {
361
- throw new CalDavError(res.status, `caldav DELETE returned ${res.status}`);
362
- }
363
- };
364
- const NO_UID_CONFLICT_RE = /no-uid-conflict/u;
365
- // Re-files one event in another calendar with a WebDAV MOVE (RFC 4918 §9.9).
366
- // Stalwart re-parents the stored event without copying it and without an
367
- // iTIP step: the iCalendar data, and with it the UID, overrides and alarms,
368
- // stays byte-identical and no attendee hears about it. Only the ETag changes.
369
- // `Overwrite: F` means a name collision refuses instead of replacing.
370
- //
371
- // Throws only when the exchange broke off (a timeout, a dropped connection);
372
- // the server may have committed the move by then.
373
- export const moveEvent = async (cfg, p) => {
374
- const { headers, ...pinned } = transport(cfg, p.token);
375
- const [res] = await davRequest({
376
- ...pinned,
377
- init: {
378
- body: null,
379
- headers: {
380
- ...headers,
381
- destination: p.destination,
382
- overwrite: "F",
383
- },
384
- method: "MOVE",
385
- namespace: DAVNamespaceShort.DAV,
386
- },
387
- url: p.url,
388
- });
389
- const status = res?.status ?? 0;
390
- if (status === 201 || status === 204) {
391
- return { kind: "moved" };
392
- }
393
- // The UID precondition carries its element in the body; a name collision
394
- // answers with an empty one. Stalwart 1.0 sends the UID precondition with
395
- // 403 (RFC 4791 §5.3.2.1), 0.16 sent it with 412. davRequest hands back the
396
- // raw text for any non-2xx reply, so `raw` is a string here.
397
- const body = typeof res?.raw === "string" ? res.raw : "";
398
- if ((status === 403 || status === 412) && NO_UID_CONFLICT_RE.test(body)) {
399
- return { kind: "uidConflict" };
400
- }
401
- if (status === 412) {
402
- return { kind: "nameConflict" };
403
- }
404
- if (status === 403) {
405
- return { kind: "forbidden" };
406
- }
407
- return { kind: "failed", status };
408
- };
@@ -1,248 +0,0 @@
1
- // Builds the iMIP invitation (VCALENDAR/VEVENT, METHOD:REQUEST) that we
2
- // PUT to the principal's CalDAV calendar. `ical-generator` owns escaping,
3
- // CRLF line-folding, and date formatting; this module just maps our
4
- // invite shape onto it.
5
- import { getVtimezoneComponent } from "@touch4it/ical-timezones";
6
- import ical, { ICalAlarmType, ICalAttendeeRole, ICalAttendeeStatus, ICalCalendarMethod, ICalEventTransparency, } from "ical-generator";
7
- import { toZonedDate, UTC_TIME_ZONE } from "./timezone.js";
8
- // An `Etc/GMT±N` zone name. The sign is POSIX's, the reverse of the offset:
9
- // `Etc/GMT-13` is UTC+13.
10
- const ETC_GMT_RE = /^Etc\/GMT([+-])(\d{1,2})$/u;
11
- // A fixed-offset VTIMEZONE for an `Etc/GMT±N` zone: one STANDARD component
12
- // whose offset never changes. Returns null for any other name.
13
- const etcGmtVtimezone = (name) => {
14
- const match = ETC_GMT_RE.exec(name);
15
- if (!match) {
16
- return null;
17
- }
18
- const [, posixSign, hours = "0"] = match;
19
- // RFC 5545 §3.3.14 forbids `-0000`, so a zero offset is always `+`.
20
- const sign = posixSign === "+" && Number(hours) > 0 ? "-" : "+";
21
- const tzname = `${sign}${hours.padStart(2, "0")}`;
22
- const offset = `${tzname}00`;
23
- return [
24
- "BEGIN:VTIMEZONE",
25
- `TZID:${name}`,
26
- "BEGIN:STANDARD",
27
- "DTSTART:19700101T000000",
28
- `TZOFFSETFROM:${offset}`,
29
- `TZOFFSETTO:${offset}`,
30
- `TZNAME:${tzname}`,
31
- "END:STANDARD",
32
- "END:VTIMEZONE",
33
- "",
34
- ].join("\n");
35
- };
36
- const TZID_LINE_RE = /^TZID:.*$/mu;
37
- // The VTIMEZONE for a zone the event names, under that same TZID (RFC 5545
38
- // §3.6.5). `Etc/GMT±N` zones are written here: @touch4it/ical-timezones lacks
39
- // Etc/GMT-13 and Etc/GMT-14 and ships the rest with the offset's sign flipped.
40
- // Every other zone takes the library's definition, renamed to the requested
41
- // TZID, because the library defines an alias (Asia/Calcutta) under another
42
- // name (Asia/Kolkata).
43
- export const vtimezoneComponent = (name) => etcGmtVtimezone(name) ??
44
- getVtimezoneComponent(name)?.replace(TZID_LINE_RE, `TZID:${name}`) ??
45
- null;
46
- const RECURRENCE_ID_LINE_RE = /^RECURRENCE-ID(?:;[^:]*)?:.*$/mu;
47
- // The DTSTAMP content line, with whatever params ical-generator attached.
48
- // `buildInvite` always emits exactly one VEVENT, so the `g` flag is belt and
49
- // braces rather than load-bearing; `String.replace` resets `lastIndex`, so
50
- // sharing the regex across calls is safe (`.test`/`.exec` would not be).
51
- //
52
- // It follows that only output passing through here is restamped: a stored
53
- // master's pre-existing floating DTSTAMP is healed by a whole-event rebuild,
54
- // not by an occurrence edit, which splices the master across verbatim.
55
- const DTSTAMP_LINE_RE = /^DTSTAMP(?:;[^:]*)?:.*$/gmu;
56
- // The start of each ATTENDEE content line (before its first param/value
57
- // delimiter); multiline + global so every attendee is matched, folded
58
- // continuation lines (leading space) are not.
59
- const ATTENDEE_LINE_START_RE = /^ATTENDEE(?=[;:])/gmu;
60
- // The value-position `:MAILTO:` scheme, matched across a line fold (CRLF +
61
- // space) between any two of its characters: ical-generator folds at 75
62
- // octets, and a CN on the ATTENDEE pushes the scheme right onto the fold.
63
- const UPPERCASE_MAILTO_RE = new RegExp([...":MAILTO:"].join(String.raw `(?:\r\n )?`), "gu");
64
- // The END:VEVENT line; buildInvite emits exactly one VEVENT, so the first match
65
- // is the only one.
66
- const END_VEVENT_RE = /^END:VEVENT$/mu;
67
- const CRLF = "\r\n";
68
- // RFC 5545 §3.1: content lines SHOULD NOT exceed 75 octets.
69
- const MAX_LINE_OCTETS = 75;
70
- // Folds one unfolded content line at 75 octets (continuations start with a
71
- // space, which counts toward their own limit). Splits on code points so a
72
- // multi-byte character is never cut in half.
73
- export const foldLine = (line) => {
74
- const encoder = new TextEncoder();
75
- const out = [];
76
- let current = "";
77
- let octets = 0;
78
- for (const ch of line) {
79
- const size = encoder.encode(ch).length;
80
- if (octets + size > MAX_LINE_OCTETS) {
81
- out.push(current);
82
- current = " ";
83
- octets = 1;
84
- }
85
- current += ch;
86
- octets += size;
87
- }
88
- out.push(current);
89
- return out.join(CRLF);
90
- };
91
- const ATTENDEE_STATUSES = new Map(Object.values(ICalAttendeeStatus).map((status) => [status, status]));
92
- const ATTENDEE_ROLES = new Map(Object.values(ICalAttendeeRole).map((role) => [role, role]));
93
- const TRANSPARENCY = {
94
- busy: ICalEventTransparency.OPAQUE,
95
- free: ICalEventTransparency.TRANSPARENT,
96
- };
97
- // Returns the serialized VCALENDAR string. METHOD:REQUEST + an ORGANIZER
98
- // + ATTENDEE(RSVP) is what triggers Stalwart's server-side scheduling.
99
- // Without attendees there is nothing to schedule — and RFC 5546 requires at
100
- // least one ATTENDEE on a REQUEST — so a personal event is serialized as a
101
- // plain calendar object with no METHOD at all.
102
- export const buildInvite = (input) => {
103
- // All-day dates are floating: formatting them in UTC turns the UTC-midnight
104
- // instants back into exactly the calendar dates they stand for.
105
- const timeZone = input.allDay
106
- ? UTC_TIME_ZONE
107
- : (input.timeZone ?? UTC_TIME_ZONE);
108
- const cal = ical({
109
- prodId: { company: "Langmail", product: "MCP" },
110
- ...(input.attendees.length > 0
111
- ? { method: ICalCalendarMethod.REQUEST }
112
- : {}),
113
- });
114
- if (timeZone !== UTC_TIME_ZONE) {
115
- cal.timezone({ generator: vtimezoneComponent, name: timeZone });
116
- }
117
- const event = cal.createEvent({
118
- end: toZonedDate(input.end, timeZone),
119
- id: input.uid,
120
- start: toZonedDate(input.start, timeZone),
121
- summary: input.title,
122
- timezone: timeZone,
123
- ...(input.allDay ? { allDay: true } : {}),
124
- ...(input.organizer
125
- ? { organizer: { email: input.organizer, name: input.organizer } }
126
- : {}),
127
- ...(input.description ? { description: input.description } : {}),
128
- ...(input.location ? { location: input.location } : {}),
129
- ...(input.sequence === undefined ? {} : { sequence: input.sequence }),
130
- ...(input.showAs ? { transparency: TRANSPARENCY[input.showAs] } : {}),
131
- });
132
- // A RECURRENCE-ID makes this the override of one instance; an RRULE would
133
- // instead (re-)declare a series, so the two never coexist on one VEVENT.
134
- if (input.recurrenceId) {
135
- event.recurrenceId(toZonedDate(input.recurrenceId, timeZone));
136
- }
137
- else if (input.rrule) {
138
- // Passing the raw RRULE string makes this a recurring series; ical-generator
139
- // emits it as a single `RRULE:` line (adding the prefix itself).
140
- event.repeating(input.rrule);
141
- }
142
- for (const alarm of input.alarms ?? []) {
143
- if ("minutesBefore" in alarm) {
144
- event.createAlarm({
145
- description: input.title,
146
- trigger: alarm.minutesBefore * 60,
147
- type: ICalAlarmType.display,
148
- });
149
- }
150
- }
151
- for (const attendee of input.attendees) {
152
- event.createAttendee(attendeeData(attendee));
153
- }
154
- return rewriteSerialized(cal.toString(), input, timeZone);
155
- };
156
- // An InviteAttendee as ical-generator attendee data, RSVP always requested.
157
- const attendeeData = (attendee) => {
158
- const { email, name, role, status } = typeof attendee === "string" ? { email: attendee } : attendee;
159
- return {
160
- email,
161
- role: ATTENDEE_ROLES.get(role?.toUpperCase() ?? "") ?? ICalAttendeeRole.REQ,
162
- rsvp: true,
163
- status: ATTENDEE_STATUSES.get(status?.toUpperCase() ?? "") ??
164
- ICalAttendeeStatus.NEEDSACTION,
165
- ...(name ? { name } : {}),
166
- };
167
- };
168
- // The fixes ical-generator's output needs on the way out, in order. Each one
169
- // rewrites serialized lines because ical-generator offers no lever for it.
170
- const rewriteSerialized = (generated, input, timeZone) => {
171
- // RFC 5545 §3.8.7.2: DTSTAMP is a UTC DATE-TIME — it has no TZID param and no
172
- // floating form. ical-generator formats it in the event's timezone, so a
173
- // zoned event gets a floating local timestamp whose meaning depends on the
174
- // host clock. Restamp it in UTC. (Rewriting the serialized line is the only
175
- // lever: ical-generator has no per-property timezone.)
176
- let serialized = generated.replace(DTSTAMP_LINE_RE, `DTSTAMP:${formatUtcTimestamp(new Date())}`);
177
- // ical-generator formats RECURRENCE-ID like the override's own DTSTART; it
178
- // must match the *master's* DTSTART instead (zone and value type).
179
- if (input.recurrenceId) {
180
- serialized = serialized.replace(RECURRENCE_ID_LINE_RE, input.recurrenceAllDay
181
- ? `RECURRENCE-ID;VALUE=DATE:${formatUtcDate(input.recurrenceId)}`
182
- : formatRecurrenceId(input.recurrenceId, input.recurrenceTimeZone ?? timeZone));
183
- }
184
- // Suppress iMIP fan-out by stamping SCHEDULE-AGENT=NONE onto each ATTENDEE
185
- // (ical-generator has no attendee-param for it). Inserted right after the
186
- // property name, before ical-generator's own params — order is irrelevant in
187
- // iCalendar. `^ATTENDEE` (multiline) only matches a line's starting physical
188
- // line, so a folded continuation is never touched.
189
- if (input.scheduleAgent === "NONE") {
190
- serialized = serialized.replace(ATTENDEE_LINE_START_RE, "ATTENDEE;SCHEDULE-AGENT=NONE");
191
- }
192
- // ical-generator serializes the ATTENDEE CAL-ADDRESS scheme in uppercase
193
- // (`:MAILTO:`) but the ORGANIZER in lowercase. Stalwart's iMIP scheduler
194
- // only strips a lowercase `mailto:` to derive the SMTP recipient, so the
195
- // uppercase scheme leaks into `RCPT TO:<mailto:…>` and the invite bounces.
196
- // Normalize the value-position scheme to lowercase on every line, folded or
197
- // not (lowercasing the fold's CRLF + space leaves it intact).
198
- serialized = serialized.replace(UPPERCASE_MAILTO_RE, (scheme) => scheme.toLowerCase());
199
- // Stored alarms go in last, after every rewrite above, so they stay exactly
200
- // as another client wrote them (an EMAIL alarm's ATTENDEE must not pick up
201
- // SCHEDULE-AGENT, for one).
202
- const preserved = (input.alarms ?? []).flatMap((alarm) => "lines" in alarm ? alarm.lines : []);
203
- if (preserved.length > 0) {
204
- // A replacer function, not a string: stored text is arbitrary, and a
205
- // replacement string would expand `$'`, `$&` and `$$` inside it.
206
- const block = `${preserved.map(foldLine).join(CRLF)}${CRLF}END:VEVENT`;
207
- serialized = serialized.replace(END_VEVENT_RE, () => block);
208
- }
209
- return serialized;
210
- };
211
- const pad = (value, length = 2) => String(value).padStart(length, "0");
212
- // An instant as an RFC 5545 UTC DATE-TIME value (`YYYYMMDDTHHMMSSZ`).
213
- const formatUtcTimestamp = (instant) => `${pad(instant.getUTCFullYear(), 4)}${pad(instant.getUTCMonth() + 1)}${pad(instant.getUTCDate())}` +
214
- `T${pad(instant.getUTCHours())}${pad(instant.getUTCMinutes())}${pad(instant.getUTCSeconds())}Z`;
215
- // An instant's UTC calendar date as an RFC 5545 DATE value (`YYYYMMDD`).
216
- const formatUtcDate = (instant) => `${pad(instant.getUTCFullYear(), 4)}${pad(instant.getUTCMonth() + 1)}${pad(instant.getUTCDate())}`;
217
- const formatRecurrenceId = (instant, timeZone) => {
218
- if (timeZone === UTC_TIME_ZONE) {
219
- return `RECURRENCE-ID:${formatUtcTimestamp(instant)}`;
220
- }
221
- const zoned = toZonedDate(instant, timeZone);
222
- return (`RECURRENCE-ID;TZID=${timeZone}:` +
223
- `${pad(zoned.getFullYear(), 4)}${pad(zoned.getMonth() + 1)}${pad(zoned.getDate())}` +
224
- `T${pad(zoned.getHours())}${pad(zoned.getMinutes())}${pad(zoned.getSeconds())}`);
225
- };
226
- // Reads the current SEQUENCE off a serialized VEVENT so an edit can bump
227
- // it. A VEVENT without a SEQUENCE line is implicitly 0 (RFC 5545 §3.8.7.4).
228
- const SEQUENCE_RE = /^SEQUENCE:(\d+)/imu;
229
- export const parseSequence = (icalString) => {
230
- const match = SEQUENCE_RE.exec(icalString);
231
- return match?.[1] ? Number(match[1]) : 0;
232
- };
233
- // Highest SEQUENCE across *every* VEVENT in a calendar object. A recurring
234
- // object holds the master plus its per-occurrence overrides, each carrying its
235
- // own SEQUENCE; a fresh (or re-edited) override bumps past this maximum so
236
- // attendees' clients always treat it as the newest revision of that instance.
237
- // No SEQUENCE lines → implicitly 0 (RFC 5545 §3.8.7.4).
238
- const SEQUENCE_ALL_RE = /^SEQUENCE:(\d+)/gimu;
239
- export const maxSequence = (icalString) => {
240
- let max = 0;
241
- for (const match of icalString.matchAll(SEQUENCE_ALL_RE)) {
242
- const value = Number(match[1]);
243
- if (value > max) {
244
- max = value;
245
- }
246
- }
247
- return max;
248
- };