langmail-mcp 0.0.0 → 0.2.0

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 (138) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -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/test-client.js +0 -43
  75. package/dist/mcp/tool-logging.js +0 -67
  76. package/dist/observability/errors.js +0 -41
  77. package/dist/rules/apply.js +0 -236
  78. package/dist/rules/rule.js +0 -280
  79. package/dist/rules/store.js +0 -92
  80. package/dist/tools/annotations.js +0 -71
  81. package/dist/tools/archive-emails.js +0 -40
  82. package/dist/tools/calendar-lookup.js +0 -64
  83. package/dist/tools/contact-common.js +0 -146
  84. package/dist/tools/contact-format.js +0 -72
  85. package/dist/tools/contact-write-through.js +0 -37
  86. package/dist/tools/create-calendar-event.js +0 -231
  87. package/dist/tools/create-calendar.js +0 -54
  88. package/dist/tools/create-contact.js +0 -172
  89. package/dist/tools/create-draft.js +0 -369
  90. package/dist/tools/create-mail-rule.js +0 -101
  91. package/dist/tools/delete-calendar-event.js +0 -165
  92. package/dist/tools/delete-contact.js +0 -60
  93. package/dist/tools/delete-draft.js +0 -129
  94. package/dist/tools/delete-mail-rule.js +0 -38
  95. package/dist/tools/download-attachment.js +0 -90
  96. package/dist/tools/download-email.js +0 -112
  97. package/dist/tools/draft-common.js +0 -600
  98. package/dist/tools/email-types.js +0 -58
  99. package/dist/tools/error-detail.js +0 -10
  100. package/dist/tools/file-emails-common.js +0 -75
  101. package/dist/tools/format.js +0 -131
  102. package/dist/tools/forward-message.js +0 -237
  103. package/dist/tools/forward-quote.js +0 -179
  104. package/dist/tools/get-draft.js +0 -61
  105. package/dist/tools/get-email.js +0 -164
  106. package/dist/tools/get-thread.js +0 -67
  107. package/dist/tools/keywords.js +0 -43
  108. package/dist/tools/list-calendar-events.js +0 -180
  109. package/dist/tools/list-calendars.js +0 -44
  110. package/dist/tools/list-drafts.js +0 -134
  111. package/dist/tools/list-mail-rules.js +0 -28
  112. package/dist/tools/list-unsubscribe.js +0 -152
  113. package/dist/tools/list-upcoming-birthdays.js +0 -165
  114. package/dist/tools/mail-rule-common.js +0 -43
  115. package/dist/tools/mail-rule-format.js +0 -79
  116. package/dist/tools/mailbox-lookup.js +0 -13
  117. package/dist/tools/mark-emails.js +0 -78
  118. package/dist/tools/merge-contacts.js +0 -145
  119. package/dist/tools/move-calendar-events.js +0 -340
  120. package/dist/tools/move-emails.js +0 -64
  121. package/dist/tools/one-click-post.js +0 -275
  122. package/dist/tools/preview-email.js +0 -204
  123. package/dist/tools/preview-mail-rule.js +0 -79
  124. package/dist/tools/reply-quote.js +0 -426
  125. package/dist/tools/reply-to-message.js +0 -292
  126. package/dist/tools/respond-to-event.js +0 -110
  127. package/dist/tools/result.js +0 -9
  128. package/dist/tools/search-contacts.js +0 -431
  129. package/dist/tools/search-emails.js +0 -570
  130. package/dist/tools/send-draft.js +0 -308
  131. package/dist/tools/trash-emails.js +0 -36
  132. package/dist/tools/unsubscribe-from-list.js +0 -249
  133. package/dist/tools/update-calendar-event.js +0 -973
  134. package/dist/tools/update-calendar.js +0 -100
  135. package/dist/tools/update-contact.js +0 -382
  136. package/dist/tools/update-draft.js +0 -714
  137. package/dist/tools/update-mail-rule.js +0 -103
  138. package/dist/tools/upload-attachments.js +0 -126
@@ -1,313 +0,0 @@
1
- // Recurrence (RRULE) input for the calendar event tools. The agent can
2
- // express a repeating series two ways: a raw iCalendar RRULE string (most
3
- // flexible — Claude knows RFC 5545 well) or a small structured object
4
- // (friendlier to fill in field-by-field). Both normalize to a single RRULE
5
- // string that ical-generator serializes onto the VEVENT (see ical.ts).
6
- import { TZDate } from "@date-fns/tz";
7
- // rrule ships CommonJS that Node cannot read named exports from, so the
8
- // package is imported whole and `rrulestr` is taken off it.
9
- import rrulePackage from "rrule";
10
- import { z } from "zod";
11
- import { parseWallClockInZone } from "../ical/index.js";
12
- import { dateOnlyToInstant, isDateOnly, isValidTimeZone, toWallClockIso, } from "./timezone.js";
13
- const { rrulestr } = rrulePackage;
14
- // RFC 5545 FREQ values we expose. Lowercase in the structured form for the
15
- // model's convenience; uppercased when emitted into the RRULE.
16
- const RECURRENCE_FREQUENCIES = [
17
- "daily",
18
- "weekly",
19
- "monthly",
20
- "yearly",
21
- ];
22
- // RFC 5545 BYDAY weekday codes.
23
- const RECURRENCE_WEEKDAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
24
- // A raw RRULE, e.g. `FREQ=WEEKLY;BYDAY=TH`. We accept (and strip) a leading
25
- // `RRULE:` so a model that includes the property name still works, and we
26
- // require a `FREQ=` so obvious garbage is rejected before it reaches CalDAV.
27
- // The value must be a single line: `event.repeating(string)` splices a
28
- // multi-line value in verbatim, so a CRLF would inject extra VEVENT content
29
- // lines (a second SUMMARY, an ATTENDEE, …). Forbid line breaks to close that.
30
- const rawRruleSchema = z
31
- .string()
32
- .trim()
33
- .min(1)
34
- .max(1000)
35
- .regex(/^(?:RRULE:)?FREQ=[^\r\n]*$/iu, 'recurrence must be a single-line iCalendar RRULE starting with FREQ=, e.g. "FREQ=WEEKLY;BYDAY=TH"');
36
- // Structured recurrence — a friendlier shape than a raw RRULE.
37
- const structuredRecurrenceSchema = z
38
- .object({
39
- byDay: z
40
- .array(z.enum(RECURRENCE_WEEKDAYS))
41
- .min(1)
42
- .max(7)
43
- .optional()
44
- .describe("Weekdays (RFC 5545 codes MO–SU)."),
45
- count: z
46
- .number()
47
- .int()
48
- .min(1)
49
- .max(1000)
50
- .optional()
51
- .describe("Total occurrences; not with `until`."),
52
- frequency: z.enum(RECURRENCE_FREQUENCIES).describe("How often it repeats."),
53
- interval: z
54
- .number()
55
- .int()
56
- .min(1)
57
- .max(1000)
58
- .optional()
59
- .describe("Every N periods; defaults to 1."),
60
- until: z
61
- .union([z.iso.date(), z.iso.datetime({ offset: true })])
62
- .optional()
63
- .describe("Last day (YYYY-MM-DD) or instant of the series; not with `count`."),
64
- })
65
- .refine((r) => !(r.until !== undefined && r.count !== undefined), {
66
- message: "Provide at most one of `until` or `count`, not both.",
67
- });
68
- // Either form. Listed raw-string-first so a plain RRULE doesn't get coerced
69
- // toward the object branch.
70
- export const recurrenceSchema = z.union([
71
- rawRruleSchema,
72
- structuredRecurrenceSchema,
73
- ]);
74
- // Human-facing description of the recurrence *shape*, attached to the
75
- // `recurrence` field on both calendar event tools (each prefixes its own
76
- // per-tool sentence). Kept here so create/update stay in sync — and kept short,
77
- // because this string is part of what tool search ranks on.
78
- export const recurrenceDescription = 'Either a raw RFC 5545 RRULE ("FREQ=WEEKLY;BYDAY=TH", "FREQ=DAILY;COUNT=10") or ' +
79
- "{frequency, interval?, byDay?, until?|count?}. Use at most one of until/count; " +
80
- "The object’s `until` is ISO (2026-12-31 or 2026-12-31T00:00:00Z); a raw UNTIL is compact " +
81
- "(20261231 or 20261231T000000Z). Either is converted to match the event (a date on an all-day series). " +
82
- "A raw rule is only lightly validated, so a malformed one fails later at the server.";
83
- // ISO `2026-12-31T00:00:00.000Z` → iCalendar `20261231T000000Z`: drop the
84
- // date/time separators, then the milliseconds.
85
- const ISO_SEPARATORS_RE = /[-:]/gu;
86
- const ISO_MILLIS_RE = /\.\d{3}Z$/u;
87
- const EVENT_TIME_ZONE_SUFFIX_RE = / ([A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)$/u;
88
- // A leading `RRULE:` property name on a raw rule, which ical-generator re-adds.
89
- const RRULE_PREFIX_RE = /^RRULE:/iu;
90
- // RFC 5545 wants a UTC date-time (`YYYYMMDDTHHMMSSZ`) for non-floating values —
91
- // an RRULE UNTIL, an EXDATE. Our events are UTC, so normalize the ISO instant.
92
- export const toIcalUtc = (iso) => new Date(iso)
93
- .toISOString()
94
- .replace(ISO_SEPARATORS_RE, "")
95
- .replace(ISO_MILLIS_RE, "Z");
96
- const toIcalFloating = (iso) => iso.replace(EVENT_TIME_ZONE_SUFFIX_RE, "").replace(ISO_SEPARATORS_RE, "");
97
- // Normalizes either input form to a raw RRULE string *without* the `RRULE:`
98
- // prefix — ical-generator re-adds it on serialization.
99
- export const toRRule = (recurrence) => {
100
- if (typeof recurrence === "string") {
101
- return recurrence.trim().replace(RRULE_PREFIX_RE, "");
102
- }
103
- const parts = [`FREQ=${recurrence.frequency.toUpperCase()}`];
104
- if (recurrence.interval !== undefined) {
105
- parts.push(`INTERVAL=${recurrence.interval}`);
106
- }
107
- if (recurrence.byDay) {
108
- parts.push(`BYDAY=${recurrence.byDay.join(",")}`);
109
- }
110
- if (recurrence.count !== undefined) {
111
- parts.push(`COUNT=${recurrence.count}`);
112
- }
113
- if (recurrence.until !== undefined) {
114
- // A date stays a date here; alignUntil re-types it to match the event.
115
- parts.push(`UNTIL=${DATE_ONLY_ISO_RE.test(recurrence.until) ? recurrence.until.replaceAll("-", "") : toIcalUtc(recurrence.until)}`);
116
- }
117
- return parts.join(";");
118
- };
119
- const DATE_ONLY_ISO_RE = /^\d{4}-\d{2}-\d{2}$/u;
120
- const UNTIL_RE = /(^|;)UNTIL=([^;]*)/iu;
121
- const ICAL_DATE_RE = /^(\d{4})(\d{2})(\d{2})$/u;
122
- const ICAL_UTC_DATE_TIME_RE = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/iu;
123
- const ICAL_FLOATING_DATE_TIME_RE = /^(\d{8})T\d{6}$/u;
124
- // The UNTIL value re-typed for the event it bounds, or undefined to keep it.
125
- const alignedUntil = (value, allDay, timeZone) => {
126
- const date = ICAL_DATE_RE.exec(value);
127
- const utc = ICAL_UTC_DATE_TIME_RE.exec(value);
128
- if (allDay) {
129
- if (utc) {
130
- const [, y, mo, d, h, mi, s] = utc;
131
- const instant = new Date(`${y}-${mo}-${d}T${h}:${mi}:${s}Z`);
132
- return toWallClockIso(instant, timeZone).slice(0, 10).replaceAll("-", "");
133
- }
134
- return ICAL_FLOATING_DATE_TIME_RE.exec(value)?.[1];
135
- }
136
- if (date) {
137
- // "Until Dec 31" on a timed series includes that whole day.
138
- const [, y, mo, d] = date;
139
- return toIcalUtc(parseWallClockInZone(`${y}-${mo}-${d}T23:59:59`, timeZone).toISOString());
140
- }
141
- };
142
- // RFC 5545 §3.3.10: UNTIL must have the same value type as DTSTART — a DATE on
143
- // an all-day series, a UTC DATE-TIME on a timed (zoned or UTC) one. Rules
144
- // arrive in either form (a structured date, a raw rule, a rule preserved from
145
- // storage across a timed↔all-day switch), so every rule is aligned right
146
- // before it is written. A date-time becomes its calendar date in `timeZone`; a
147
- // date on a timed series becomes the end of that day in `timeZone`.
148
- export const alignUntil = (rrule, allDay, timeZone) => {
149
- const match = UNTIL_RE.exec(rrule);
150
- const aligned = match?.[2]
151
- ? alignedUntil(match[2].trim(), allDay, timeZone)
152
- : undefined;
153
- return aligned === undefined
154
- ? rrule
155
- : rrule.replace(UNTIL_RE, `$1UNTIL=${aligned}`);
156
- };
157
- // BYDAY on a raw rule, and the parts of a rule that make a naive weekday check
158
- // unsafe: with BYSETPOS or BYMONTHDAY the listed weekdays are a filter within a
159
- // larger pattern rather than the days the series lands on.
160
- const BYDAY_RE = /(?:^|;)BYDAY=([^;]+)/iu;
161
- const COMPLEX_RULE_RE = /(?:^|;)(?:BYSETPOS|BYMONTHDAY|BYYEARDAY|BYWEEKNO)=/iu;
162
- // Strips an RFC 5545 ordinal prefix (`2TU`, `-1FR`) down to the weekday code.
163
- const BYDAY_ORDINAL_RE = /^[+-]?\d*/u;
164
- const WEEKDAY_CODES = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
165
- // True when moving a series to `start` would contradict the repeat rule it is
166
- // keeping — e.g. `FREQ=WEEKLY;BYDAY=TU` with a Friday start, which RFC 5545
167
- // reads as "that Friday, plus every Tuesday" rather than "every Friday". The
168
- // caller has to re-rule the series explicitly instead. Only the unambiguous
169
- // weekday case is judged; rules whose BYDAY is a filter within a larger pattern
170
- // are left alone rather than risk refusing a legitimate edit.
171
- export const startContradictsRule = (rrule, start, timeZone) => {
172
- if (COMPLEX_RULE_RE.test(rrule)) {
173
- return false;
174
- }
175
- const byDay = BYDAY_RE.exec(rrule)?.[1];
176
- if (!byDay) {
177
- return false;
178
- }
179
- const days = byDay
180
- .split(",")
181
- .map((d) => d.trim().replace(BYDAY_ORDINAL_RE, "").toUpperCase());
182
- const weekday = WEEKDAY_CODES[TZDate.tz(timeZone, start).getDay()];
183
- return weekday !== undefined && days.length > 0 && !days.includes(weekday);
184
- };
185
- // A zoned series is expanded on its floating wall clock (see isSeriesOccurrence),
186
- // but RFC 5545 §3.3.10 writes its UNTIL in UTC. Comparing that UTC value against
187
- // wall clock read as UTC would drop the last occurrence east of UTC, and
188
- // re-expressing it as wall clock is ambiguous in a DST fall-back hour. So a UTC
189
- // UNTIL is split off the rule and checked against the true instant instead.
190
- // A producer that writes local digits with a `Z` is read as the instant it
191
- // claims to be (west of UTC it loses its last occurrence); restoring a
192
- // wall-clock reading would bring back the fall-back mis-ordering.
193
- const splitUtcUntil = (rrule) => {
194
- const match = UNTIL_RE.exec(rrule);
195
- const utc = ICAL_UTC_DATE_TIME_RE.exec(match?.[2]?.trim() ?? "");
196
- if (!utc) {
197
- return { rule: rrule };
198
- }
199
- const [, y, mo, d, h, mi, s] = utc;
200
- const until = new Date(`${y}-${mo}-${d}T${h}:${mi}:${s}Z`);
201
- // A digit-shaped but impossible value (month 13, hour 25) stays in the rule
202
- // for rrule to reject, rather than being stripped into an unbounded series.
203
- if (Number.isNaN(until.getTime()) ||
204
- toIcalUtc(until.toISOString()) !== `${y}${mo}${d}T${h}${mi}${s}Z`) {
205
- return { rule: rrule };
206
- }
207
- const rule = rrule.replace(UNTIL_RE, "").replace(LEADING_SEPARATOR_RE, "");
208
- return { rule, until };
209
- };
210
- const LEADING_SEPARATOR_RE = /^;/u;
211
- const NONZERO_FRACTION_RE = /\.\d*[1-9]/u;
212
- // The zone a series' RRULE expands in, for isSeriesOccurrence: the master's
213
- // DTSTART TZID (the parser drops one written beside an all-day DATE, and maps a
214
- // Windows zone name to its IANA zone). A TZID that is neither, such as a vendor
215
- // zone name defined only by the object's VTIMEZONE, can't be expanded at all. It is refused by name, echoing the
216
- // caller's `recurrenceId`, rather than surfacing as an opaque rule error — and
217
- // never matched as if its wall clock were UTC.
218
- export const seriesTimeZone = (master, recurrenceId) => {
219
- const zone = master.startTzid;
220
- if (zone && !isValidTimeZone(zone)) {
221
- return {
222
- error: `This series' time zone (${zone}) is not a recognized IANA zone, so recurrenceId ${recurrenceId} cannot be matched to an occurrence.`,
223
- ok: false,
224
- };
225
- }
226
- return { ok: true, value: zone };
227
- };
228
- // True when `recurrenceId` (an ISO 8601 instant) is the original start of an
229
- // occurrence the series generates — i.e. expanding `rrule` from `masterStart`
230
- // lands exactly on it. update_calendar_event uses this to reject an occurrence
231
- // override that would otherwise dangle off the series: RFC 5545 §3.8.4.4
232
- // requires a RECURRENCE-ID to name a real instance of the master's RRULE.
233
- //
234
- // Membership is tested with a single-instant `between(t, t, inclusive)` rather
235
- // than expanding the whole (possibly unbounded) series. A UTC series is matched
236
- // on instants. A zoned series (`timeZone`, the master's DTSTART TZID) is
237
- // expanded on its floating wall clock and `recurrenceId` is reduced to wall
238
- // clock in that zone, so DST shifts the UTC instant but not the match. Both DST
239
- // edges stay imperfect: an occurrence inside the spring-forward gap has no
240
- // instant that reduces to its wall clock and cannot be named, and one inside the
241
- // fall-back hour is matched by both instants of that repeated wall clock (the
242
- // EXDATE or RECURRENCE-ID written for it is equally ambiguous).
243
- export const isSeriesOccurrence = (masterStart, rrule, recurrenceId, timeZone) => {
244
- if (!timeZone) {
245
- const at = new Date(recurrenceId);
246
- return (rrulestr(`DTSTART:${toIcalUtc(masterStart)}\nRRULE:${rrule}`).between(at, at, true).length > 0);
247
- }
248
- // The wall-clock reduction below keeps whole seconds only, so a sub-second
249
- // instant would otherwise match the occurrence it merely falls near. Read the
250
- // fraction from the text: a Date keeps milliseconds only.
251
- if (NONZERO_FRACTION_RE.test(recurrenceId)) {
252
- return false;
253
- }
254
- const instant = new Date(recurrenceId);
255
- const { rule, until } = splitUtcUntil(rrule);
256
- if (until && instant.getTime() > until.getTime()) {
257
- return false;
258
- }
259
- const at = new Date(`${toWallClockIso(instant, timeZone)}Z`);
260
- return (rrulestr(`DTSTART:${toIcalFloating(masterStart)}\nRRULE:${rule}`).between(at, at, true).length > 0);
261
- };
262
- // A day either side of the wall-clock bounds a zoned expansion reads: more than
263
- // any zone's offset change, so a DST shift can't push an occurrence out of the
264
- // expanded range before the instant filter decides on it.
265
- const WALL_CLOCK_MARGIN_MS = 86_400_000;
266
- // The original starts of the occurrences `rrule` generates from `masterStart`
267
- // within [from, to], as instants — list_calendar_events' agenda. Read the same
268
- // two ways as isSeriesOccurrence: a UTC (or all-day) series expands on
269
- // instants, a zoned one on its floating wall clock, each result resolved back to
270
- // the instant that wall clock names in `timeZone`. At most `limit` are returned.
271
- export const seriesOccurrences = (masterStart, rrule, from, to, limit, timeZone) => {
272
- // Stops the walk after `limit` occurrences rather than expanding the range.
273
- const underLimit = (_at, index) => index < limit;
274
- if (!timeZone) {
275
- return rrulestr(`DTSTART:${toIcalUtc(masterStart)}\nRRULE:${rrule}`).between(from, to, true, underLimit);
276
- }
277
- const { rule, until } = splitUtcUntil(rrule);
278
- const wallFrom = new Date(Date.parse(`${toWallClockIso(from, timeZone)}Z`) - WALL_CLOCK_MARGIN_MS);
279
- const wallTo = new Date(Date.parse(`${toWallClockIso(to, timeZone)}Z`) + WALL_CLOCK_MARGIN_MS);
280
- return rrulestr(`DTSTART:${toIcalFloating(masterStart)}\nRRULE:${rule}`)
281
- .between(wallFrom, wallTo, true, underLimit)
282
- .map((wall) => new Date(parseWallClockInZone(wall.toISOString().slice(0, 19), timeZone).getTime()))
283
- .filter((at) => at >= from && at <= to && !(until && at > until));
284
- };
285
- // The occurrence a caller's `recurrenceId` names, as an ISO instant, for the
286
- // series `master` heads. An all-day series' occurrences start at a date, so it
287
- // takes the date (`2026-06-23`), resolved to its UTC midnight — the instant the
288
- // parser and the splice give a DATE RECURRENCE-ID or EXDATE. A timed series
289
- // takes the occurrence's original start date-time. The wrong kind is refused
290
- // in both directions rather than coerced: a date-time's calendar day depends
291
- // on its offset, so truncating one could name the neighbouring occurrence.
292
- export const resolveRecurrenceId = (recurrenceId, master) => {
293
- const dateOnly = isDateOnly(recurrenceId);
294
- if (master?.allDay) {
295
- return dateOnly
296
- ? { ok: true, value: dateOnlyToInstant(recurrenceId).toISOString() }
297
- : {
298
- // Name the UTC day of the instant and say so: whether that or the
299
- // leading digits is the day the caller meant depends on how they
300
- // computed the value, so the hint must not pass a guess off as fact.
301
- error: "This series is all-day; pass recurrenceId as the occurrence’s date (YYYY-MM-DD). The instant you " +
302
- `passed falls on ${new Date(recurrenceId).toISOString().slice(0, 10)} in UTC.`,
303
- ok: false,
304
- };
305
- }
306
- if (dateOnly && master?.recurrence !== undefined) {
307
- return {
308
- error: `This series is not all-day; pass recurrenceId as the occurrence’s original start date-time (e.g. ${recurrenceId}T10:00:00Z).`,
309
- ok: false,
310
- };
311
- }
312
- return { ok: true, value: recurrenceId };
313
- };
@@ -1,107 +0,0 @@
1
- // Pure iCalendar mutation for RSVP: set the authenticated user's own
2
- // ATTENDEE PARTSTAT on a stored VEVENT, leaving every other byte untouched
3
- // so the PUT back to CalDAV is a minimal diff.
4
- //
5
- // This is the meat behind respond_to_event. Keeping it pure (string in,
6
- // string out) makes the edge cases — line folding, case-insensitive
7
- // matching, insert-vs-replace — unit-testable without a live server.
8
- // Splits on a line break (CRLF, bare CR, or LF) while capturing the break,
9
- // so we can rejoin every unedited line byte-for-byte.
10
- const NL_SPLIT_RE = /(\r\n|\r|\n)/u;
11
- // RFC 5545 §3.1: a folded continuation line begins with a single space/tab.
12
- const CONT_RE = /^[ \t]/u;
13
- const MAILTO_RE = /^mailto:/iu;
14
- // A PARTSTAT parameter on a content line's parameter list. The value runs to
15
- // the next `;` (further param) or `:` (start of the property value).
16
- const PARTSTAT_PARAM_RE = /;PARTSTAT=[^;:]*/iu;
17
- const toPhysicalLines = (ical) => {
18
- // split() with a capturing group yields [text, sep, text, sep, ..., text].
19
- const tokens = ical.split(NL_SPLIT_RE);
20
- const lines = [];
21
- for (let i = 0; i < tokens.length; i += 2) {
22
- lines.push({ sep: tokens[i + 1] ?? "", text: tokens[i] ?? "" });
23
- }
24
- return lines;
25
- };
26
- const groupLogicalLines = (lines) => {
27
- const groups = [];
28
- for (let i = 0; i < lines.length; i += 1) {
29
- const last = groups.at(-1);
30
- if (last && CONT_RE.test(lines[i]?.text ?? "")) {
31
- last.end = i;
32
- }
33
- else {
34
- groups.push({ end: i, start: i });
35
- }
36
- }
37
- return groups;
38
- };
39
- // Reconstructs the logical line, dropping the single leading whitespace each
40
- // continuation contributed (the inverse of RFC 5545 folding).
41
- const unfold = (lines, group) => {
42
- let s = lines[group.start]?.text ?? "";
43
- for (let i = group.start + 1; i <= group.end; i += 1) {
44
- s += (lines[i]?.text ?? "").slice(1);
45
- }
46
- return s;
47
- };
48
- // True when `logical` is the ATTENDEE line for `email`, matching the `mailto:`
49
- // scheme and the address case-insensitively (RFC 5545 calendar-user-addresses
50
- // are case-insensitive; clients vary on casing).
51
- const isAttendeeFor = (logical, email) => {
52
- // First-colon split to separate NAME+params from the value. A param value
53
- // quoting a literal ':' (e.g. CN="Org:Unit") would misplace this boundary
54
- // and the line would silently miss — the same happy-path caveat ical-parse.ts
55
- // documents, and out of scope for this workshop tool.
56
- const colon = logical.indexOf(":");
57
- if (colon === -1) {
58
- return false;
59
- }
60
- // The property name ends at the first `;` (params) or the value colon.
61
- const name = (logical.slice(0, colon).split(";")[0] ?? "")
62
- .trim()
63
- .toUpperCase();
64
- if (name !== "ATTENDEE") {
65
- return false;
66
- }
67
- const value = logical.slice(colon + 1).trim();
68
- if (!MAILTO_RE.test(value)) {
69
- return false;
70
- }
71
- return value.replace(MAILTO_RE, "").toLowerCase() === email.toLowerCase();
72
- };
73
- // Replaces an existing PARTSTAT param on the matched line, or inserts one at
74
- // the end of the parameter list when absent. The property value (`:mailto:…`)
75
- // is preserved exactly; only the parameter section changes.
76
- const withPartstat = (logical, partstat) => {
77
- const colon = logical.indexOf(":");
78
- const head = logical.slice(0, colon);
79
- const value = logical.slice(colon);
80
- if (PARTSTAT_PARAM_RE.test(head)) {
81
- return head.replace(PARTSTAT_PARAM_RE, `;PARTSTAT=${partstat}`) + value;
82
- }
83
- return `${head};PARTSTAT=${partstat}${value}`;
84
- };
85
- export const setAttendeePartstat = (ical, attendeeEmail, partstat) => {
86
- const lines = toPhysicalLines(ical);
87
- const groups = groupLogicalLines(lines);
88
- const match = groups.find((g) => isAttendeeFor(unfold(lines, g), attendeeEmail));
89
- if (!match) {
90
- return { ok: false, reason: "not-an-attendee" };
91
- }
92
- // Re-emit the matched line unfolded. Re-folding is intentionally skipped:
93
- // both Radicale and Stalwart accept over-length lines and there is no fold
94
- // helper on the write path — see the design doc.
95
- const edited = withPartstat(unfold(lines, match), partstat);
96
- const out = [];
97
- for (let i = 0; i < lines.length; i += 1) {
98
- if (i === match.start) {
99
- out.push(edited, lines[match.end]?.sep ?? "");
100
- i = match.end;
101
- continue;
102
- }
103
- const line = lines[i];
104
- out.push(line?.text ?? "", line?.sep ?? "");
105
- }
106
- return { ical: out.join(""), ok: true };
107
- };
@@ -1,22 +0,0 @@
1
- // Outbound-scheduling audit trail shared by the calendar write tools.
2
- import { hashEmail, logger } from "../logger.js";
3
- // Audit line for the accepted PUT: the iMIP fan-out it triggers is otherwise
4
- // unobservable (Stalwart archives nothing outbound), so record enough to answer
5
- // "was a message due, to whom, at which revision" after the fact. Emitted only
6
- // after the PUT succeeds — a rejected PUT hands nothing to Stalwart and must
7
- // not leave an audit line claiming otherwise. Attendee addresses are logged as
8
- // hashes: no email addresses in logs.
9
- export const logSchedulingHandover = (handover) => {
10
- logger.info({
11
- attendeeHashes: handover.attendees.map(hashEmail),
12
- bytes: Buffer.byteLength(handover.ical),
13
- removedAttendeeHashes: handover.removedAttendees.map(hashEmail),
14
- scheduleAgent: handover.scheduleAgent ?? "SERVER",
15
- sequence: handover.sequence,
16
- tool: handover.tool,
17
- // Calendar UIDs are commonly email-shaped, so they need the same
18
- // log-safe deterministic hashing as addresses.
19
- uidHash: hashEmail(handover.uid),
20
- ...(handover.recurrenceId ? { recurrenceId: handover.recurrenceId } : {}),
21
- }, "event PUT to CalDAV; iMIP fan-out delegated to Stalwart");
22
- };
@@ -1,103 +0,0 @@
1
- import { TZDate } from "@date-fns/tz";
2
- import { z } from "zod";
3
- // The wall-clock parser lives in src/ical, where the VEVENT parser consumes
4
- // it. This module keeps the zod input schemas that validate tool arguments,
5
- // which src/ical stays free of.
6
- import { DATE_TIME_RE, ianaTimeZone, parseWallClockInZone, } from "../ical/index.js";
7
- const OFFSET_RE = /(?:Z|[+-]\d{2}:\d{2})$/iu;
8
- export const UTC_TIME_ZONE = "UTC";
9
- export const isValidTimeZone = (timeZone) => {
10
- if (timeZone === UTC_TIME_ZONE) {
11
- return true;
12
- }
13
- if (Intl.supportedValuesOf("timeZone").includes(timeZone)) {
14
- return true;
15
- }
16
- try {
17
- new Intl.DateTimeFormat("en-US", { timeZone }).format(new Date());
18
- return true;
19
- }
20
- catch {
21
- return false;
22
- }
23
- };
24
- export const timeZoneSchema = z.string().refine(isValidTimeZone, {
25
- message: "timeZone must be a valid IANA timezone, e.g. Europe/Berlin",
26
- });
27
- // DATE_TIME_RE narrows z.iso.datetime to what parseWallClockInZone reads: zod
28
- // alone also takes minute precision (`10:00`) and any number of fractional
29
- // digits, which would pass validation and then throw in resolveEventTimes.
30
- const dateTimeWithOptionalOffsetSchema = z.iso
31
- .datetime({ offset: true, local: true })
32
- .regex(DATE_TIME_RE);
33
- // An event's start or end: a date-time for a timed event, or a bare date
34
- // (`2026-10-03`) for an all-day one. The value type *is* the all-day signal,
35
- // exactly as in RFC 5545 (`DTSTART;VALUE=DATE`) — see resolveEventTimes.
36
- // The union's own message is what a caller sees: zod's default for a failed
37
- // union is a bare "Invalid input", which does not say what to send instead.
38
- export const eventTimeSchema = z.union([z.iso.date(), dateTimeWithOptionalOffsetSchema], {
39
- error: "Expected a date (2026-10-03) for an all-day event, or a date-time with seconds (2026-10-03T10:00:00, " +
40
- "optionally with up to three fractional digits and Z or an offset like +02:00).",
41
- });
42
- const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/u;
43
- // True for a bare ISO date (`2026-10-03`) — an all-day value.
44
- export const isDateOnly = (value) => value !== undefined && DATE_ONLY_RE.test(value);
45
- // All-day dates travel through the date-time pipeline as UTC midnights: day
46
- // arithmetic on them is exact (no DST), and buildInvite formats them back in
47
- // UTC, recovering the very same calendar date.
48
- export const dateOnlyToInstant = (date) => new Date(`${date}T00:00:00Z`);
49
- export const instantToDateOnly = (instant) => instant.toISOString().slice(0, 10);
50
- const DAY_MS = 86_400_000;
51
- // Resolves a caller's start/end pair. Both must be dates (all-day) or both
52
- // date-times (timed); an all-day `end` is exclusive (RFC 5545 §3.6.1), so a
53
- // one-day event on Oct 3 ends on Oct 4 — the likeliest slip, `end == start`,
54
- // is refused with the value to use instead.
55
- export const resolveEventTimes = (start, end, timeZone, explicitTimeZone) => {
56
- const allDay = isDateOnly(start);
57
- if (allDay !== isDateOnly(end)) {
58
- return {
59
- error: "Pass `start` and `end` both as dates (YYYY-MM-DD) for an all-day event, or both as date-times for a timed one.",
60
- ok: false,
61
- };
62
- }
63
- if (allDay) {
64
- const startAt = dateOnlyToInstant(start);
65
- const endAt = dateOnlyToInstant(end);
66
- if (endAt <= startAt) {
67
- return { error: allDayEndError(start), ok: false };
68
- }
69
- return { ok: true, value: { allDay, end: endAt, start: startAt } };
70
- }
71
- const startAt = resolveInputDateTime(start, timeZone, explicitTimeZone);
72
- const endAt = resolveInputDateTime(end, timeZone, explicitTimeZone);
73
- if (endAt <= startAt) {
74
- return { error: "Event end must be after its start.", ok: false };
75
- }
76
- return { ok: true, value: { allDay, end: endAt, start: startAt } };
77
- };
78
- // The refusal for an all-day end on or before its start, naming the value a
79
- // single-day event needs.
80
- export const allDayEndError = (start) => `An all-day event's \`end\` is exclusive — the day after its last day. For a single day on ${start}, ` +
81
- `pass end ${instantToDateOnly(new Date(dateOnlyToInstant(start).getTime() + DAY_MS))}.`;
82
- const hasExplicitOffset = (value) => OFFSET_RE.test(value);
83
- // A Windows zone name, as a stored TZID may carry one, reads as its IANA zone
84
- // here and in toWallClockIso, like parseWallClockInZone.
85
- export const toZonedDate = (instant, timeZone) => timeZone === UTC_TIME_ZONE
86
- ? instant
87
- : TZDate.tz(ianaTimeZone(timeZone), instant);
88
- // An instant re-expressed as a naive wall-clock ISO string in `timeZone` (no
89
- // offset suffix) — the inverse of parseWallClockInZone. Used wherever a stored
90
- // instant has to re-enter the wall-clock pipeline, e.g. an occurrence's original
91
- // start standing in for an omitted `start` on an update.
92
- export const toWallClockIso = (instant, timeZone) => {
93
- const zoned = TZDate.tz(ianaTimeZone(timeZone), instant);
94
- const pad = (value) => String(value).padStart(2, "0");
95
- return (`${zoned.getFullYear()}-${pad(zoned.getMonth() + 1)}-${pad(zoned.getDate())}` +
96
- `T${pad(zoned.getHours())}:${pad(zoned.getMinutes())}:${pad(zoned.getSeconds())}`);
97
- };
98
- export const resolveInputDateTime = (value, timeZone, explicitTimeZone) => {
99
- if (explicitTimeZone || !hasExplicitOffset(value)) {
100
- return parseWallClockInZone(value, timeZone);
101
- }
102
- return new Date(value);
103
- };
@@ -1,5 +0,0 @@
1
- // Minimal CalDAV shapes used by the calendar tools.
2
- //
3
- // Like src/jmap/types.ts, this declares only what the tools read or send —
4
- // the tsdav DAVCalendar/DAVAccount types stay behind caldav/client.ts.
5
- export {};