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,57 +0,0 @@
1
- // Keeps web pages away from the listener.
2
- //
3
- // A page open in the user's browser can make that browser send requests to a
4
- // server on the same machine or network. Two checks stop it, as the MCP
5
- // specification asks of HTTP servers:
6
- //
7
- // Origin — a browser names the page a cross-site request comes from. A
8
- // request whose Origin is not this server's own address is refused.
9
- // Clients that are not browsers send no Origin and pass.
10
- // Host — a page can point a hostname of its own at 127.0.0.1 ("DNS
11
- // rebinding") so the browser treats the server as same-origin. Such a
12
- // request still carries the page's hostname in Host. When the listener is
13
- // bound to loopback, only loopback names (and the public URL's) are
14
- // accepted there. A listener bound to another address is reached under
15
- // names this process cannot know (a reverse proxy's, an IP), so Host is
16
- // not checked there.
17
- //
18
- // No CORS headers are sent anywhere, so a browser also refuses to let a page
19
- // read an answer or send the Authorization header across origins.
20
- import { localhostAllowedHostnames, validateHostHeader, validateOriginHeader, } from "@modelcontextprotocol/server";
21
- import { logger } from "../logger.js";
22
- import { isLoopbackHost, urlHostname } from "./hosts.js";
23
- const HTTP_FORBIDDEN = 403;
24
- const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", ""]);
25
- const forbidden = () => new Response(`${JSON.stringify({ error: "forbidden" })}\n`, {
26
- headers: {
27
- "cache-control": "no-store",
28
- "content-type": "application/json",
29
- },
30
- status: HTTP_FORBIDDEN,
31
- });
32
- export const createRequestGuard = (options) => {
33
- const own = new Set(localhostAllowedHostnames());
34
- if (!WILDCARD_HOSTS.has(options.host)) {
35
- own.add(urlHostname(options.host).toLowerCase());
36
- }
37
- if (options.publicUrl !== undefined) {
38
- own.add(new URL(options.publicUrl).hostname.toLowerCase());
39
- }
40
- const allowed = [...own];
41
- const checkHost = isLoopbackHost(options.host);
42
- return (req) => {
43
- const origin = validateOriginHeader(req.headers.get("origin"), allowed);
44
- if (!origin.ok) {
45
- // The reason only: the header is whatever the page chose to be.
46
- logger.warn({ reason: origin.errorCode }, "http request refused");
47
- return forbidden();
48
- }
49
- if (checkHost) {
50
- const host = validateHostHeader(req.headers.get("host"), allowed);
51
- if (!host.ok) {
52
- logger.warn({ reason: host.errorCode }, "http request refused");
53
- return forbidden();
54
- }
55
- }
56
- };
57
- };
@@ -1,10 +0,0 @@
1
- // How a bind address (`MCP_HOST`) is told apart and spelled.
2
- const LOOPBACK_V4_RE = /^127(?:\.\d{1,3}){3}$/u;
3
- const BRACKETS_RE = /^\[|\]$/gu;
4
- /** Whether a bind address is reachable from this machine only. */
5
- export const isLoopbackHost = (host) => {
6
- const bare = host.replace(BRACKETS_RE, "").toLowerCase();
7
- return bare === "localhost" || bare === "::1" || LOOPBACK_V4_RE.test(bare);
8
- };
9
- /** A host the way a URL (and the Host header) spells it: an IPv6 address in brackets. */
10
- export const urlHostname = (host) => host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
@@ -1,170 +0,0 @@
1
- // Serves a fetch-style handler (`Request` in, `Response` out) over `node:http`.
2
- //
3
- // The routes are written against the web-standard `Request` and `Response`,
4
- // which is also what the MCP SDK's HTTP transport speaks. This file is the
5
- // only place that touches Node's own request and response objects.
6
- import { createServer, } from "node:http";
7
- import { Readable } from "node:stream";
8
- import { pipeline } from "node:stream/promises";
9
- import { logger } from "../logger.js";
10
- import { describeError } from "../observability/errors.js";
11
- import { urlHostname } from "./hosts.js";
12
- const HTTP_BAD_REQUEST = 400;
13
- const HTTP_INTERNAL_ERROR = 500;
14
- const DEFAULT_CLOSE_GRACE_MS = 5000;
15
- const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
16
- const toWebRequest = (req, signal) => {
17
- // The URL's host is only a label here: routing reads the path, and the
18
- // guard reads the Host header itself.
19
- const url = new URL(req.url ?? "/", "http://localhost");
20
- const headers = new Headers();
21
- for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
22
- headers.append(req.rawHeaders[i] ?? "", req.rawHeaders[i + 1] ?? "");
23
- }
24
- const method = req.method ?? "GET";
25
- if (BODYLESS_METHODS.has(method)) {
26
- return new Request(url, { headers, method, signal });
27
- }
28
- return new Request(url, {
29
- body: Readable.toWeb(req),
30
- // Node requires this to send a body that is still arriving.
31
- duplex: "half",
32
- headers,
33
- method,
34
- signal,
35
- });
36
- };
37
- const writeResponse = async (response, res) => {
38
- const headers = {};
39
- for (const [name, value] of response.headers) {
40
- if (name !== "set-cookie") {
41
- headers[name] = value;
42
- }
43
- }
44
- const cookies = response.headers.getSetCookie();
45
- if (cookies.length > 0) {
46
- headers["set-cookie"] = cookies;
47
- }
48
- res.writeHead(response.status, headers);
49
- if (response.body === null) {
50
- res.end();
51
- return;
52
- }
53
- // A streamed answer (server-sent events) goes out chunk by chunk; when the
54
- // caller hangs up, the pipeline cancels the body so its source stops.
55
- await pipeline(Readable.fromWeb(response.body), res);
56
- };
57
- const serve = async (fetchHandler, req, res) => {
58
- const hungUp = new AbortController();
59
- res.once("close", () => {
60
- if (!res.writableFinished) {
61
- hungUp.abort();
62
- }
63
- });
64
- let request;
65
- try {
66
- request = toWebRequest(req, hungUp.signal);
67
- }
68
- catch {
69
- // A request line or header Node let through but a Request cannot hold.
70
- res.writeHead(HTTP_BAD_REQUEST).end();
71
- return;
72
- }
73
- try {
74
- await writeResponse(await fetchHandler(request), res);
75
- }
76
- catch (error) {
77
- if (hungUp.signal.aborted) {
78
- return;
79
- }
80
- logger.error(describeError(error), "http unhandled request error");
81
- if (res.headersSent) {
82
- res.destroy();
83
- }
84
- else {
85
- res.writeHead(HTTP_INTERNAL_ERROR).end();
86
- }
87
- }
88
- };
89
- const listen = (server, host, port) => new Promise((resolve, reject) => {
90
- const onError = (error) => {
91
- reject(new Error(error.code === "EADDRINUSE"
92
- ? `cannot listen on ${host}:${port}: the port is already in use. Set MCP_PORT to a free port.`
93
- : `cannot listen on ${host}:${port}: ${error.message}`, { cause: error }));
94
- };
95
- server.once("error", onError);
96
- server.listen(port, host, () => {
97
- server.off("error", onError);
98
- resolve();
99
- });
100
- });
101
- // The connections of a server, and how many requests each is answering.
102
- // `server.closeIdleConnections()` leaves a connection alone that has not sent
103
- // a request yet, and such a connection would hold a shutdown open; this keeps
104
- // count so that `close` can end every connection that is not mid-request.
105
- const trackConnections = (server) => {
106
- const inFlight = new Map();
107
- let keepAlive = true;
108
- server.on("connection", (socket) => {
109
- inFlight.set(socket, 0);
110
- socket.once("close", () => inFlight.delete(socket));
111
- });
112
- server.on("request", (req, res) => {
113
- const { socket } = req;
114
- inFlight.set(socket, (inFlight.get(socket) ?? 0) + 1);
115
- res.once("close", () => {
116
- const left = (inFlight.get(socket) ?? 1) - 1;
117
- if (inFlight.has(socket)) {
118
- inFlight.set(socket, left);
119
- }
120
- if (!keepAlive && left === 0) {
121
- // After the answer's last bytes are flushed.
122
- setImmediate(() => socket.destroy());
123
- }
124
- });
125
- });
126
- return {
127
- closeIdle: () => {
128
- for (const [socket, requests] of inFlight) {
129
- if (requests === 0) {
130
- socket.destroy();
131
- }
132
- }
133
- },
134
- stopKeepingAlive: () => {
135
- keepAlive = false;
136
- },
137
- };
138
- };
139
- /** Binds `host:port` and serves `fetch` on it. Rejects when the address cannot be bound. */
140
- export const startHttpListener = async (options) => {
141
- const server = createServer((req, res) => {
142
- serve(options.fetch, req, res).catch(() => res.destroy());
143
- });
144
- const connections = trackConnections(server);
145
- await listen(server, options.host, options.port);
146
- if (options.keepsProcessAlive === false) {
147
- server.unref();
148
- }
149
- const { port } = server.address();
150
- const graceMs = options.closeGraceMs ?? DEFAULT_CLOSE_GRACE_MS;
151
- const close = () => new Promise((resolve) => {
152
- const cutOff = setTimeout(() => server.closeAllConnections(), graceMs);
153
- server.close(() => {
154
- clearTimeout(cutOff);
155
- resolve();
156
- });
157
- connections.stopKeepingAlive();
158
- connections.closeIdle();
159
- });
160
- let closing;
161
- return {
162
- close: () => {
163
- closing ??= close();
164
- return closing;
165
- },
166
- host: options.host,
167
- origin: `http://${urlHostname(options.host)}:${port}`,
168
- port,
169
- };
170
- };
@@ -1,72 +0,0 @@
1
- // The routes one HTTP listener serves, and the function that dispatches a
2
- // request to them.
3
- //
4
- // A listener is a list of routes; whoever starts it decides which. The HTTP
5
- // transport serves `/mcp` and `/healthz`. Routes that hand out files under an
6
- // unguessable link can be added to the same list, or served by a listener of
7
- // their own that has no `/mcp` at all.
8
- import { logger } from "../logger.js";
9
- import { describeError } from "../observability/errors.js";
10
- const HTTP_NOT_FOUND = 404;
11
- const HTTP_INTERNAL_ERROR = 500;
12
- const matches = (route, pathname) => route.path.endsWith("/")
13
- ? pathname.startsWith(route.path)
14
- : pathname === route.path;
15
- const notFound = () => new Response("not found\n", {
16
- headers: { "content-type": "text/plain" },
17
- status: HTTP_NOT_FOUND,
18
- });
19
- const internalError = () => new Response(`${JSON.stringify({ error: "internal_error" })}\n`, {
20
- headers: {
21
- "cache-control": "no-store",
22
- "content-type": "application/json",
23
- },
24
- status: HTTP_INTERNAL_ERROR,
25
- });
26
- // A failure inside a route must not take the listener down or reach the
27
- // caller as a stack trace: it is logged and answered with a bare 500.
28
- const answer = async (route, req, url) => {
29
- try {
30
- return await route.handle(req, url);
31
- }
32
- catch (error) {
33
- logger.error(describeError(error), "http unhandled request error");
34
- return internalError();
35
- }
36
- };
37
- /** Liveness for a process supervisor or a reverse proxy. It says that the process answers and nothing else. */
38
- export const healthRoute = {
39
- handle: () => new Response("ok\n", { headers: { "content-type": "text/plain" } }),
40
- path: "/healthz",
41
- };
42
- /**
43
- * Builds the request handler for a list of routes. The first route whose path
44
- * matches answers; a path no route serves is a 404.
45
- */
46
- export const createFetchHandler = (routes, options = {}) => {
47
- return async (req) => {
48
- const refused = options.guard?.(req);
49
- if (refused) {
50
- return refused;
51
- }
52
- const url = new URL(req.url);
53
- const route = routes.find((candidate) => matches(candidate, url.pathname));
54
- if (!route) {
55
- return notFound();
56
- }
57
- if (route.logAs === undefined) {
58
- return answer(route, req, url);
59
- }
60
- // Logged on completion, so a rejected request is on record too. Method,
61
- // route name, status and duration carry no address and no credential.
62
- const startedAt = performance.now();
63
- const res = await answer(route, req, url);
64
- logger.info({
65
- durationMs: Math.round(performance.now() - startedAt),
66
- method: req.method,
67
- route: route.logAs,
68
- status: res.status,
69
- }, "mcp request");
70
- return res;
71
- };
72
- };
@@ -1,357 +0,0 @@
1
- // Minimal read-side parser for the VEVENTs we list back to the agent.
2
- // ical-generator only *writes* iCalendar, and pulling in a full parser for
3
- // the handful of fields list_calendar_events surfaces (uid, title, times,
4
- // location) isn't worth it — so this extracts just those, happy-path.
5
- import { parseWallClockInZone } from "./timezone.js";
6
- import { ianaTimeZone } from "./windows-zones.js";
7
- // RFC 5545 folds long lines with CRLF (or LF) + a single space/tab. Undo
8
- // that before parsing so a folded value (e.g. an email) reads as one line.
9
- const unfold = (ical) => ical.replace(/\r?\n[ \t]/gu, "");
10
- // A content line is `NAME(;PARAM=…)*:VALUE`; the name ends at the first
11
- // `;` or `:`, the value is everything after the first `:`.
12
- const NAME_RE = /^([^;:]+)/u;
13
- const TZID_RE = /(?:^|;)TZID=([^;:]+)/iu;
14
- // Line break between content lines (CRLF or bare LF).
15
- const LINE_RE = /\r?\n/u;
16
- // Reverses RFC 5545 TEXT escaping for display (\\ \, \; \n) in a single
17
- // pass, so an escaped backslash (`\\`) isn't re-read as a newline.
18
- const ESCAPE_RE = /\\([\\;,nN])/gu;
19
- const unescapeText = (value) => value.replace(ESCAPE_RE, (_match, ch) => ch === "n" || ch === "N" ? "\n" : ch);
20
- // `20260612T100000Z` / `20260612` → ISO 8601 for display. Anything else
21
- // (already-ISO, or an exotic form) is returned untouched.
22
- const ICAL_DT_RE = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/u;
23
- export const icalDateToIso = (value) => {
24
- const m = ICAL_DT_RE.exec(value);
25
- if (!m) {
26
- return value;
27
- }
28
- const [, y, mo, d, h, mi, s, z] = m;
29
- if (!h) {
30
- return `${y}-${mo}-${d}`;
31
- }
32
- return `${y}-${mo}-${d}T${h}:${mi}:${s}${z ?? ""}`;
33
- };
34
- // Records one content line onto the current VEVENT block. ATTENDEE is
35
- // multi-valued (collected in order); everything else is keyed by name, later
36
- // wins. First-colon split: misplaces the value boundary if a property parameter
37
- // carries a quoted ':' (e.g. CN="Org:Unit"). Of the properties we read, only
38
- // ORGANIZER/ATTENDEE realistically carry such params (SENT-BY, display-name CNs)
39
- // — parseOrganizerEmail / parseAttendee re-anchor on the trailing mailto: URI,
40
- // so the mis-split stays harmless.
41
- const recordProperty = (block, line) => {
42
- const colon = line.indexOf(":");
43
- if (colon === -1) {
44
- return;
45
- }
46
- const name = NAME_RE.exec(line.slice(0, colon))?.[1]?.toUpperCase();
47
- if (!name) {
48
- return;
49
- }
50
- const property = {
51
- params: line.slice(name.length, colon),
52
- value: line.slice(colon + 1),
53
- };
54
- if (name === "ATTENDEE") {
55
- block.attendees.push(property);
56
- }
57
- else if (name === "EXDATE") {
58
- block.exdates.push(property);
59
- }
60
- else {
61
- block.props.set(name, property);
62
- }
63
- };
64
- // Component delimiters. Names are case-insensitive (RFC 5545 §3.1), and some
65
- // producers emit lowercase ones.
66
- const BEGIN_RE = /^BEGIN:/iu;
67
- const END_RE = /^END:/iu;
68
- const BEGIN_VALARM_RE = /^BEGIN:VALARM\s*$/iu;
69
- const BEGIN_VEVENT_RE = /^BEGIN:VEVENT\s*$/iu;
70
- const END_VEVENT_RE = /^END:VEVENT\s*$/iu;
71
- // A sub-component line (BEGIN:/END:/property) inside the current VEVENT. Only
72
- // VALARMs are kept, as raw lines; any other sub-component is skipped.
73
- const scanNestedLine = (state, block, line) => {
74
- if (BEGIN_RE.test(line)) {
75
- if (state.nested === 0 && BEGIN_VALARM_RE.test(line)) {
76
- state.alarm = [];
77
- }
78
- state.alarm?.push(line);
79
- state.nested += 1;
80
- return;
81
- }
82
- if (END_RE.test(line)) {
83
- state.alarm?.push(line);
84
- state.nested = Math.max(0, state.nested - 1);
85
- if (state.nested === 0 && state.alarm) {
86
- block.alarms.push(state.alarm);
87
- state.alarm = null;
88
- }
89
- return;
90
- }
91
- if (line !== "") {
92
- state.alarm?.push(line);
93
- }
94
- };
95
- const scanLine = (state, line) => {
96
- if (BEGIN_VEVENT_RE.test(line)) {
97
- state.current = {
98
- alarms: [],
99
- attendees: [],
100
- exdates: [],
101
- props: new Map(),
102
- };
103
- state.nested = 0;
104
- state.alarm = null;
105
- return;
106
- }
107
- if (END_VEVENT_RE.test(line)) {
108
- if (state.current) {
109
- state.blocks.push(state.current);
110
- }
111
- state.current = null;
112
- return;
113
- }
114
- if (!state.current) {
115
- return;
116
- }
117
- if (state.nested === 0 && !BEGIN_RE.test(line) && !END_RE.test(line)) {
118
- recordProperty(state.current, line);
119
- return;
120
- }
121
- scanNestedLine(state, state.current, line);
122
- };
123
- const eventBlocks = (ical) => {
124
- const state = {
125
- alarm: null,
126
- blocks: [],
127
- current: null,
128
- nested: 0,
129
- };
130
- for (const line of unfold(ical).split(LINE_RE)) {
131
- scanLine(state, line);
132
- }
133
- return state.blocks;
134
- };
135
- // The ACTION and TRIGGER of a raw VALARM, read off its own top-level lines.
136
- const ALARM_PROPERTY_RE = /^(ACTION|TRIGGER)((?:;[^:]*)?):(.*)$/iu;
137
- const parseAlarm = (lines) => {
138
- const alarm = { lines };
139
- for (const line of lines) {
140
- const match = ALARM_PROPERTY_RE.exec(line);
141
- if (!match) {
142
- continue;
143
- }
144
- const [, name = "", params = "", value = ""] = match;
145
- if (name.toUpperCase() === "ACTION") {
146
- alarm.action = value.trim().toUpperCase();
147
- }
148
- else {
149
- alarm.trigger = value.trim();
150
- if (params) {
151
- alarm.triggerParams = params;
152
- }
153
- }
154
- }
155
- return alarm;
156
- };
157
- // Bare organizer email from a first-colon-split ORGANIZER value. The
158
- // cal-address is the mailto: URI at the END of the content line, but params
159
- // can smuggle colons inside quotes past the split (SENT-BY="mailto:…",
160
- // CN="Team: Weekly"), leaving param debris in `value` — so anchor on the last
161
- // mailto: instead of the front. A value we can't reduce to a clean bare
162
- // address (non-mailto cal-address, leftover quotes/colons) is dropped rather
163
- // than risk callers writing garbage back into a rebuilt invite.
164
- // Greedy by design: the real cal-address is the LAST mailto: on the line,
165
- // after any params. The cost is that a param value containing the literal
166
- // text `mailto:` (e.g. CN="Reply to mailto:me@example.com instead") strips
167
- // through that occurrence and yields a wrong address — accepted, since the
168
- // alternative (parsing quoted params properly) is a full RFC 5545 lexer
169
- // for a case no server we talk to emits.
170
- const LAST_MAILTO_RE = /^.*mailto:/isu;
171
- const NOT_BARE_EMAIL_RE = /["\s:;,]/u;
172
- const parseOrganizerEmail = (property) => {
173
- if (!property) {
174
- return;
175
- }
176
- const email = property.value.replace(LAST_MAILTO_RE, "").trim();
177
- return email &&
178
- email !== property.value.trim() &&
179
- !NOT_BARE_EMAIL_RE.test(email)
180
- ? email
181
- : undefined;
182
- };
183
- const propertyTimeZone = (property) => {
184
- const timeZone = TZID_RE.exec(property?.params ?? "")?.[1];
185
- return timeZone ? timeZone.replace(/^"|"$/gu, "") : undefined;
186
- };
187
- // A RECURRENCE-ID value reduced to a UTC ISO instant. The stored value is
188
- // either a UTC date-time, a date-only value, or wall-clock digits qualified by
189
- // a TZID param — all three have to compare equal to the caller's ISO instant,
190
- // so they are resolved here rather than surfaced raw. An unparsable value is
191
- // dropped (the VEVENT then reads as a plain event, which is the safe default).
192
- const parseRecurrenceInstant = (property) => {
193
- if (!property) {
194
- return;
195
- }
196
- const iso = icalDateToIso(property.value.trim());
197
- const timeZone = propertyTimeZone(property);
198
- let at;
199
- try {
200
- at =
201
- timeZone && !iso.endsWith("Z")
202
- ? parseWallClockInZone(iso, timeZone)
203
- : new Date(iso);
204
- }
205
- catch {
206
- return;
207
- }
208
- // Re-wrap as a plain Date: parseWallClockInZone returns a TZDate, whose
209
- // toISOString() keeps the zone offset instead of normalizing to UTC.
210
- return Number.isNaN(at.getTime())
211
- ? undefined
212
- : new Date(at.getTime()).toISOString();
213
- };
214
- // PARTSTAT on an ATTENDEE parameter list, unquoted. The value runs to the next
215
- // `;` (further param) or `:` (start of the value); absent on a freshly built,
216
- // not-yet-answered attendee only when the client omits the NEEDS-ACTION default.
217
- const PARTSTAT_RE = /(?:^|;)PARTSTAT=([^;:]+)/iu;
218
- // ROLE on an ATTENDEE parameter list, same shape as PARTSTAT.
219
- const ROLE_RE = /(?:^|;)ROLE=([^;:]+)/iu;
220
- // CN on an ATTENDEE parameter list: quoted (CN="Fairweather, Robin" — commas,
221
- // semicolons, and colons are legal inside the quotes) or unquoted (CN=Robin,
222
- // value runs to the next `;` or `:`).
223
- const CN_RE = /(?:^|;)CN=(?:"([^"]*)"|([^;:]+))/iu;
224
- // Bare attendee email + CN + PARTSTAT + ROLE from an ATTENDEE line. Same
225
- // trailing-mailto anchoring as parseOrganizerEmail: params can smuggle colons
226
- // past the first-colon split (SENT-BY, CN), so read the address off the last
227
- // mailto:. An ATTENDEE we can't reduce to a clean bare address is dropped
228
- // rather than surfaced as garbage or written back into a rebuilt invite.
229
- const parseAttendee = (property) => {
230
- const email = property.value.replace(LAST_MAILTO_RE, "").trim();
231
- if (!email ||
232
- email === property.value.trim() ||
233
- NOT_BARE_EMAIL_RE.test(email)) {
234
- return;
235
- }
236
- // Params can land in `value` rather than `params` when an earlier quoted
237
- // parameter (e.g. CN="Team: Weekly") pushes a ':' past the first-colon split.
238
- // Reassemble the property (name aside) and search the parameter section — i.e.
239
- // everything before the trailing cal-address — so the mis-split doesn't hide it.
240
- const reassembled = `${property.params}:${property.value}`;
241
- const addressAt = reassembled.toLowerCase().lastIndexOf("mailto:");
242
- const paramSection = addressAt === -1 ? reassembled : reassembled.slice(0, addressAt);
243
- const status = PARTSTAT_RE.exec(paramSection)?.[1]?.replace(/^"|"$/gu, "");
244
- const role = ROLE_RE.exec(paramSection)?.[1]?.replace(/^"|"$/gu, "");
245
- const cnMatch = CN_RE.exec(paramSection);
246
- const name = (cnMatch?.[1] ?? cnMatch?.[2])?.trim();
247
- return {
248
- email,
249
- ...(name ? { name } : {}),
250
- ...(role ? { role } : {}),
251
- ...(status ? { status } : {}),
252
- };
253
- };
254
- // Flattens the EXDATE lines of one VEVENT into ISO values. Each line may carry
255
- // a comma-separated list, and the property may repeat (RFC 5545 §3.8.5.1).
256
- //
257
- // A TZID-qualified date-time (`EXDATE;TZID=Europe/Berlin:20260623T120000`, the
258
- // form foreign clients write) is resolved to a UTC ISO instant, like
259
- // parseRecurrenceInstant does: left floating, `Date.parse` would read it as the
260
- // host's local time and it would never compare equal to an occurrence's
261
- // instant. UTC (`…Z`) and DATE values are surfaced as stored.
262
- const parseExcludedDates = (exdates) => exdates.flatMap((property) => {
263
- const timeZone = propertyTimeZone(property);
264
- return property.value
265
- .split(",")
266
- .map((value) => resolveExcludedValue(icalDateToIso(value.trim()), timeZone))
267
- .filter(Boolean);
268
- });
269
- const resolveExcludedValue = (iso, timeZone) => {
270
- if (!(timeZone && iso.includes("T")) || iso.endsWith("Z")) {
271
- return iso;
272
- }
273
- try {
274
- return new Date(parseWallClockInZone(iso, timeZone).getTime()).toISOString();
275
- }
276
- catch {
277
- return iso;
278
- }
279
- };
280
- // A DATE (not DATE-TIME) property value: `;VALUE=DATE`, or a bare 8-digit value
281
- // from a producer that omits the (technically required) parameter.
282
- const VALUE_DATE_RE = /(?:^|;)VALUE=DATE(?:;|$)/iu;
283
- const DATE_ONLY_VALUE_RE = /^\d{8}$/u;
284
- // TRANSP value → showAs, case-insensitively. Anything else reads as unset.
285
- const SHOW_AS = { OPAQUE: "busy", TRANSPARENT: "free" };
286
- const parseShowAs = (property) => property ? SHOW_AS[property.value.trim().toUpperCase()] : undefined;
287
- const isDateValue = (property) => property !== undefined &&
288
- (VALUE_DATE_RE.test(property.params) ||
289
- DATE_ONLY_VALUE_RE.test(property.value.trim()));
290
- // Parses every VEVENT in a VCALENDAR. Blocks without a UID are skipped —
291
- // an event we can't address with update/delete isn't useful to list.
292
- // The fields a VEVENT only carries sometimes. Split out from parseEvents so the
293
- // conditional-spread block doesn't dominate that function's complexity.
294
- const optionalFields = (block, attendees) => {
295
- const description = block.props.get("DESCRIPTION")?.value;
296
- const location = block.props.get("LOCATION")?.value;
297
- const organizer = parseOrganizerEmail(block.props.get("ORGANIZER"));
298
- // Trim so a server that emits a trailing space (`RRULE:FREQ=WEEKLY `) doesn't
299
- // leak it into the listed `repeats:` value.
300
- const recurrence = block.props.get("RRULE")?.value.trim();
301
- const recurrenceId = parseRecurrenceInstant(block.props.get("RECURRENCE-ID"));
302
- const excludedDates = parseExcludedDates(block.exdates);
303
- const unparsedAttendeeCount = block.attendees.length - attendees.length;
304
- const allDay = isDateValue(block.props.get("DTSTART"));
305
- // A TZID beside a DATE is off-spec and meaningless; surfacing it would let
306
- // consumers re-express a date-only series in that zone.
307
- const storedStartTzid = allDay
308
- ? undefined
309
- : propertyTimeZone(block.props.get("DTSTART"));
310
- const startTzid = storedStartTzid === undefined ? undefined : ianaTimeZone(storedStartTzid);
311
- const showAs = parseShowAs(block.props.get("TRANSP"));
312
- const status = block.props.get("STATUS")?.value.trim().toUpperCase();
313
- const classification = block.props.get("CLASS")?.value.trim().toUpperCase();
314
- const duration = block.props.get("DURATION")?.value.trim();
315
- return {
316
- ...(block.alarms.length > 0
317
- ? { alarms: block.alarms.map(parseAlarm) }
318
- : {}),
319
- ...(allDay ? { allDay: true } : {}),
320
- ...(classification ? { classification } : {}),
321
- ...(description ? { description: unescapeText(description) } : {}),
322
- ...(duration ? { duration } : {}),
323
- ...(excludedDates.length > 0 ? { excludedDates } : {}),
324
- ...(location ? { location: unescapeText(location) } : {}),
325
- ...(organizer ? { organizer } : {}),
326
- ...(recurrence ? { recurrence } : {}),
327
- ...(recurrenceId ? { recurrenceId } : {}),
328
- ...(showAs ? { showAs } : {}),
329
- ...(startTzid ? { startTzid } : {}),
330
- ...(status ? { status } : {}),
331
- ...(storedStartTzid && storedStartTzid !== startTzid
332
- ? { storedStartTzid }
333
- : {}),
334
- ...(unparsedAttendeeCount > 0 ? { unparsedAttendeeCount } : {}),
335
- };
336
- };
337
- export const parseEvents = (ical) => {
338
- const events = [];
339
- for (const block of eventBlocks(ical)) {
340
- const uid = block.props.get("UID");
341
- if (!uid?.value) {
342
- continue;
343
- }
344
- const attendees = block.attendees
345
- .map(parseAttendee)
346
- .filter((a) => a !== undefined);
347
- events.push({
348
- attendees,
349
- end: icalDateToIso(block.props.get("DTEND")?.value ?? ""),
350
- start: icalDateToIso(block.props.get("DTSTART")?.value ?? ""),
351
- title: unescapeText(block.props.get("SUMMARY")?.value ?? ""),
352
- uid: uid.value,
353
- ...optionalFields(block, attendees),
354
- });
355
- }
356
- return events;
357
- };
@@ -1,4 +0,0 @@
1
- // biome-ignore lint/performance/noBarrelFile: package entry point requires re-exports
2
- export { icalDateToIso, parseEvents, } from "./ical-parse.js";
3
- export { DATE_TIME_RE, parseWallClockInZone } from "./timezone.js";
4
- export { ianaTimeZone, WINDOWS_ZONES } from "./windows-zones.js";