@zerodot/gmail 0.0.0-stage → 1.0.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.
- package/LICENSE +661 -0
- package/README.md +56 -2
- package/dist/index.cjs +1539 -0
- package/gmail.svg +1 -0
- package/package.json +49 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1539 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
let node_crypto = require("node:crypto");
|
|
4
|
+
let _zerodot_node_sdk = require("@zerodot/node-sdk");
|
|
5
|
+
// src/api.ts
|
|
6
|
+
const GMAIL_OAUTH2_CREDENTIAL = "gmail.oauth2";
|
|
7
|
+
const GMAIL_SERVICE_ACCOUNT_CREDENTIAL = "gmail.service_account";
|
|
8
|
+
const GMAIL_API = "https://gmail.googleapis.com/gmail/v1/users";
|
|
9
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
10
|
+
/** Full access. Only this scope can delete a message for good. */
|
|
11
|
+
const GMAIL_SCOPE = "https://mail.google.com/";
|
|
12
|
+
/** A token is fetched again this long before it ends. */
|
|
13
|
+
const REFRESH_WINDOW_MS = 6e4;
|
|
14
|
+
const TOKEN_LIFETIME_S = 3600;
|
|
15
|
+
const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
16
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
/** The fields of a JSON key file. Throws with a short message when the text is not a key. */
|
|
18
|
+
function parseServiceAccountKey(json) {
|
|
19
|
+
let value;
|
|
20
|
+
try {
|
|
21
|
+
value = JSON.parse(json);
|
|
22
|
+
} catch {
|
|
23
|
+
throw new Error("The service account key is not valid JSON");
|
|
24
|
+
}
|
|
25
|
+
if (!isObject(value)) throw new Error("The service account key must be a JSON object");
|
|
26
|
+
const email = text(value.client_email);
|
|
27
|
+
const key = text(value.private_key);
|
|
28
|
+
if (!email || !key) throw new Error("The service account key needs \"client_email\" and \"private_key\"");
|
|
29
|
+
return {
|
|
30
|
+
client_email: email,
|
|
31
|
+
private_key: key,
|
|
32
|
+
private_key_id: text(value.private_key_id)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const base64url = (value) => Buffer.from(value).toString("base64url");
|
|
36
|
+
/**
|
|
37
|
+
* A signed JWT (RS256) that asks Google for an access token. `subject` is the user that the
|
|
38
|
+
* service account acts as (domain-wide delegation). `now` is in milliseconds.
|
|
39
|
+
*/
|
|
40
|
+
function signJwt(key, now, subject, scope = GMAIL_SCOPE) {
|
|
41
|
+
const iat = Math.floor(now / 1e3);
|
|
42
|
+
const header = {
|
|
43
|
+
alg: "RS256",
|
|
44
|
+
typ: "JWT",
|
|
45
|
+
...key.private_key_id && { kid: key.private_key_id }
|
|
46
|
+
};
|
|
47
|
+
const claims = {
|
|
48
|
+
iss: key.client_email,
|
|
49
|
+
sub: subject,
|
|
50
|
+
scope,
|
|
51
|
+
aud: TOKEN_URL,
|
|
52
|
+
iat,
|
|
53
|
+
exp: iat + TOKEN_LIFETIME_S
|
|
54
|
+
};
|
|
55
|
+
const unsigned = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`;
|
|
56
|
+
let signature;
|
|
57
|
+
try {
|
|
58
|
+
signature = (0, node_crypto.createSign)("RSA-SHA256").update(unsigned).sign(key.private_key);
|
|
59
|
+
} catch {
|
|
60
|
+
throw new Error("The private key of the service account is not valid");
|
|
61
|
+
}
|
|
62
|
+
return `${unsigned}.${base64url(signature)}`;
|
|
63
|
+
}
|
|
64
|
+
const tokenCache = /* @__PURE__ */ new Map();
|
|
65
|
+
/** The cache key never has the private key itself. */
|
|
66
|
+
const cacheKey = (key, subject) => `${key.client_email}\n${subject}\n${(0, node_crypto.createHash)("sha256").update(key.private_key).digest("hex")}`;
|
|
67
|
+
/** An access token for a service account that acts as `subject`. It is cached until near its end. */
|
|
68
|
+
async function serviceAccountToken(key, subject, options = {}) {
|
|
69
|
+
const now = options.now ?? Date.now;
|
|
70
|
+
const id = cacheKey(key, subject);
|
|
71
|
+
const cached = tokenCache.get(id);
|
|
72
|
+
if (cached && cached.expiresAt - now() > REFRESH_WINDOW_MS) return cached.token;
|
|
73
|
+
const signals = [AbortSignal.timeout(options.timeoutMs ?? 1e4)];
|
|
74
|
+
if (options.signal) signals.push(options.signal);
|
|
75
|
+
const response = await fetch(TOKEN_URL, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
78
|
+
body: new URLSearchParams({
|
|
79
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
80
|
+
assertion: signJwt(key, now(), subject)
|
|
81
|
+
}).toString(),
|
|
82
|
+
signal: AbortSignal.any(signals)
|
|
83
|
+
});
|
|
84
|
+
const answer = await response.json().catch(() => null);
|
|
85
|
+
const body = isObject(answer) ? answer : {};
|
|
86
|
+
const token = text(body.access_token);
|
|
87
|
+
if (!response.ok || !token) {
|
|
88
|
+
const reason = text(body.error_description) ?? text(body.error) ?? "no answer";
|
|
89
|
+
throw new Error(`Google did not give an access token (${response.status}): ${reason}`);
|
|
90
|
+
}
|
|
91
|
+
const seconds = typeof body.expires_in === "number" ? body.expires_in : TOKEN_LIFETIME_S;
|
|
92
|
+
tokenCache.set(id, {
|
|
93
|
+
token,
|
|
94
|
+
expiresAt: now() + seconds * 1e3
|
|
95
|
+
});
|
|
96
|
+
return token;
|
|
97
|
+
}
|
|
98
|
+
/** The access token of a credential: OAuth2 (the server refreshes it) or a service account. */
|
|
99
|
+
async function gmailToken(credential, options) {
|
|
100
|
+
if (credential?.type === "gmail.oauth2") {
|
|
101
|
+
const token = text(credential.data.accessToken);
|
|
102
|
+
if (!token) throw new Error("The Gmail credential is not connected to an account yet");
|
|
103
|
+
return token;
|
|
104
|
+
}
|
|
105
|
+
if (credential?.type === "gmail.service_account") {
|
|
106
|
+
const json = text(credential.data.serviceAccountKey);
|
|
107
|
+
if (!json) throw new Error("The credential has no \"serviceAccountKey\"");
|
|
108
|
+
const subject = text(credential.data.impersonatedUser);
|
|
109
|
+
if (!subject) throw new Error("The credential has no \"impersonatedUser\"");
|
|
110
|
+
return await serviceAccountToken(parseServiceAccountKey(json), subject, options);
|
|
111
|
+
}
|
|
112
|
+
throw new Error("The node needs a Gmail credential");
|
|
113
|
+
}
|
|
114
|
+
const HINTS = {
|
|
115
|
+
400: " Check the values of the node.",
|
|
116
|
+
401: " Connect the credential again.",
|
|
117
|
+
403: " Turn on the Gmail API in the Google Cloud project, and check the access of the account.",
|
|
118
|
+
404: " Check the ID.",
|
|
119
|
+
429: " Google limits the number of requests per minute. Try again later."
|
|
120
|
+
};
|
|
121
|
+
/** A clear error from a Google answer: `{ error: { code, message, status } }`. */
|
|
122
|
+
function gmailError(status, answer, action) {
|
|
123
|
+
const error = isObject(answer) && isObject(answer.error) ? answer.error : {};
|
|
124
|
+
const message = text(error.message) ?? "no message";
|
|
125
|
+
const code = text(error.status);
|
|
126
|
+
const hint = HINTS[status] ?? "";
|
|
127
|
+
return /* @__PURE__ */ new Error(`Gmail could not ${action} (${status}${code ? ` ${code}` : ""}): ${message}.${hint}`);
|
|
128
|
+
}
|
|
129
|
+
function urlOf(request) {
|
|
130
|
+
const url = new URL(`${GMAIL_API}/me${request.path}`);
|
|
131
|
+
for (const [key, value] of Object.entries(request.query ?? {})) for (const entry of Array.isArray(value) ? value : [value]) if (entry !== void 0 && entry !== "") url.searchParams.append(key, entry);
|
|
132
|
+
return url.toString();
|
|
133
|
+
}
|
|
134
|
+
/** One call. The error text never has the token. A 204 answer gives `{}`. */
|
|
135
|
+
async function callGmail(token, request, options) {
|
|
136
|
+
const response = await fetch(urlOf(request), {
|
|
137
|
+
method: request.method,
|
|
138
|
+
headers: {
|
|
139
|
+
authorization: `Bearer ${token}`,
|
|
140
|
+
accept: "application/json",
|
|
141
|
+
...request.body ? { "content-type": "application/json" } : {}
|
|
142
|
+
},
|
|
143
|
+
body: request.body ? JSON.stringify(request.body) : void 0,
|
|
144
|
+
redirect: "error",
|
|
145
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
|
|
146
|
+
});
|
|
147
|
+
const answer = await response.json().catch(() => null);
|
|
148
|
+
if (!response.ok) throw gmailError(response.status, answer, request.action);
|
|
149
|
+
return answer ?? {};
|
|
150
|
+
}
|
|
151
|
+
// src/icon.ts
|
|
152
|
+
const GMAIL_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../gmail.svg");
|
|
153
|
+
// src/credential.ts
|
|
154
|
+
const TIMEOUT_MS = 1e4;
|
|
155
|
+
/** Google sign-in. `access_type=offline` and `prompt=consent` give a refresh token. */
|
|
156
|
+
const GOOGLE_OAUTH2 = {
|
|
157
|
+
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
158
|
+
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
159
|
+
scopes: [GMAIL_SCOPE],
|
|
160
|
+
authQuery: {
|
|
161
|
+
access_type: "offline",
|
|
162
|
+
prompt: "consent"
|
|
163
|
+
},
|
|
164
|
+
authentication: "body",
|
|
165
|
+
pkce: true
|
|
166
|
+
};
|
|
167
|
+
/** Fields that only the server writes, after the user connects the account. */
|
|
168
|
+
const OAUTH2_TOKEN_FIELDS = [
|
|
169
|
+
"accessToken",
|
|
170
|
+
"refreshToken",
|
|
171
|
+
"expiresAt",
|
|
172
|
+
"tokenType",
|
|
173
|
+
"grantedScope"
|
|
174
|
+
];
|
|
175
|
+
const isKey = (json) => {
|
|
176
|
+
try {
|
|
177
|
+
parseServiceAccountKey(json);
|
|
178
|
+
return true;
|
|
179
|
+
} catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
/** Gets a token, then reads the profile of the mailbox. A 401 or a 403 throws with the text of Google. */
|
|
184
|
+
async function check(credential) {
|
|
185
|
+
const options = {
|
|
186
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
187
|
+
timeoutMs: TIMEOUT_MS
|
|
188
|
+
};
|
|
189
|
+
await callGmail(await gmailToken(credential, options), {
|
|
190
|
+
method: "GET",
|
|
191
|
+
path: "/profile",
|
|
192
|
+
action: "check the credential"
|
|
193
|
+
}, options);
|
|
194
|
+
}
|
|
195
|
+
const gmailOAuth2Credential = {
|
|
196
|
+
type: GMAIL_OAUTH2_CREDENTIAL,
|
|
197
|
+
label: "Gmail OAuth2",
|
|
198
|
+
fields: zod.z.object({
|
|
199
|
+
clientId: zod.z.string().min(1).meta({ placeholder: "…apps.googleusercontent.com" }),
|
|
200
|
+
clientSecret: zod.z.string().min(1),
|
|
201
|
+
accessToken: zod.z.string().min(1).optional(),
|
|
202
|
+
refreshToken: zod.z.string().min(1).optional(),
|
|
203
|
+
/** ISO 8601 time. */
|
|
204
|
+
expiresAt: zod.z.iso.datetime().optional(),
|
|
205
|
+
tokenType: zod.z.string().min(1).optional(),
|
|
206
|
+
grantedScope: zod.z.string().optional()
|
|
207
|
+
}),
|
|
208
|
+
secretFields: [
|
|
209
|
+
"clientSecret",
|
|
210
|
+
"accessToken",
|
|
211
|
+
"refreshToken"
|
|
212
|
+
],
|
|
213
|
+
serverFields: [...OAUTH2_TOKEN_FIELDS],
|
|
214
|
+
oauth2: GOOGLE_OAUTH2,
|
|
215
|
+
icon: "Mail",
|
|
216
|
+
iconUrl: GMAIL_ICON,
|
|
217
|
+
test: check
|
|
218
|
+
};
|
|
219
|
+
const gmailServiceAccountCredential = {
|
|
220
|
+
type: GMAIL_SERVICE_ACCOUNT_CREDENTIAL,
|
|
221
|
+
label: "Gmail service account",
|
|
222
|
+
fields: zod.z.object({
|
|
223
|
+
/** The JSON key file of the service account, as text. */
|
|
224
|
+
serviceAccountKey: zod.z.string().min(1).refine(isKey, "Paste the JSON key file. It needs \"client_email\" and \"private_key\"").meta({ placeholder: "{ \"type\": \"service_account\", \"client_email\": \"…\", … }" }),
|
|
225
|
+
/** The user that the service account acts as. Domain-wide delegation must be on. */
|
|
226
|
+
impersonatedUser: zod.z.string().min(1).meta({ placeholder: "user@example.com" })
|
|
227
|
+
}),
|
|
228
|
+
secretFields: ["serviceAccountKey"],
|
|
229
|
+
icon: "Mail",
|
|
230
|
+
iconUrl: GMAIL_ICON,
|
|
231
|
+
test: check
|
|
232
|
+
};
|
|
233
|
+
// src/config.ts
|
|
234
|
+
const RESOURCES = [
|
|
235
|
+
"message",
|
|
236
|
+
"draft",
|
|
237
|
+
"label",
|
|
238
|
+
"thread"
|
|
239
|
+
];
|
|
240
|
+
const OPERATIONS_OF = {
|
|
241
|
+
message: [
|
|
242
|
+
"send",
|
|
243
|
+
"reply",
|
|
244
|
+
"get",
|
|
245
|
+
"getMany",
|
|
246
|
+
"markAsRead",
|
|
247
|
+
"markAsUnread",
|
|
248
|
+
"trash",
|
|
249
|
+
"untrash",
|
|
250
|
+
"delete",
|
|
251
|
+
"addLabels",
|
|
252
|
+
"removeLabels"
|
|
253
|
+
],
|
|
254
|
+
draft: [
|
|
255
|
+
"create",
|
|
256
|
+
"get",
|
|
257
|
+
"getMany",
|
|
258
|
+
"delete"
|
|
259
|
+
],
|
|
260
|
+
label: [
|
|
261
|
+
"create",
|
|
262
|
+
"get",
|
|
263
|
+
"getMany",
|
|
264
|
+
"delete"
|
|
265
|
+
],
|
|
266
|
+
thread: [
|
|
267
|
+
"get",
|
|
268
|
+
"getMany",
|
|
269
|
+
"trash",
|
|
270
|
+
"untrash",
|
|
271
|
+
"delete",
|
|
272
|
+
"addLabels",
|
|
273
|
+
"removeLabels"
|
|
274
|
+
]
|
|
275
|
+
};
|
|
276
|
+
const ALL_OPERATIONS = [...new Set(Object.values(OPERATIONS_OF).flat())];
|
|
277
|
+
const AUTHENTICATION = ["oAuth2", "serviceAccount"];
|
|
278
|
+
/** Show a field only for these operations of one resource. */
|
|
279
|
+
const on = (resource, ...operations) => ({
|
|
280
|
+
resource: [resource],
|
|
281
|
+
operation: operations
|
|
282
|
+
});
|
|
283
|
+
const when = (...rules) => ({ showWhen: rules });
|
|
284
|
+
const option = (title) => ({
|
|
285
|
+
option: true,
|
|
286
|
+
title
|
|
287
|
+
});
|
|
288
|
+
const MESSAGE_ID_OPERATIONS = [
|
|
289
|
+
"reply",
|
|
290
|
+
"get",
|
|
291
|
+
"markAsRead",
|
|
292
|
+
"markAsUnread",
|
|
293
|
+
"trash",
|
|
294
|
+
"untrash",
|
|
295
|
+
"delete",
|
|
296
|
+
"addLabels",
|
|
297
|
+
"removeLabels"
|
|
298
|
+
];
|
|
299
|
+
const THREAD_ID_OPERATIONS = [
|
|
300
|
+
"get",
|
|
301
|
+
"trash",
|
|
302
|
+
"untrash",
|
|
303
|
+
"delete",
|
|
304
|
+
"addLabels",
|
|
305
|
+
"removeLabels"
|
|
306
|
+
];
|
|
307
|
+
const COMPOSE = [on("message", "send"), on("draft", "create")];
|
|
308
|
+
const BODY = [on("message", "send", "reply"), on("draft", "create")];
|
|
309
|
+
const LISTS = [on("message", "getMany"), on("thread", "getMany")];
|
|
310
|
+
const PARSED = [
|
|
311
|
+
on("message", "get", "getMany"),
|
|
312
|
+
on("draft", "get", "getMany"),
|
|
313
|
+
on("thread", "get")
|
|
314
|
+
];
|
|
315
|
+
const gmailConfig = zod.z.object({
|
|
316
|
+
authentication: zod.z.enum(AUTHENTICATION).default("oAuth2").meta({
|
|
317
|
+
title: "Authentication",
|
|
318
|
+
labels: {
|
|
319
|
+
oAuth2: "OAuth2",
|
|
320
|
+
serviceAccount: "Service Account"
|
|
321
|
+
},
|
|
322
|
+
hints: {
|
|
323
|
+
oAuth2: "Sign in with a Google account",
|
|
324
|
+
serviceAccount: "Use the JSON key of a service account with domain-wide delegation"
|
|
325
|
+
}
|
|
326
|
+
}),
|
|
327
|
+
resource: zod.z.enum(RESOURCES).default("message").meta({
|
|
328
|
+
labels: {
|
|
329
|
+
message: "Message",
|
|
330
|
+
draft: "Draft",
|
|
331
|
+
label: "Label",
|
|
332
|
+
thread: "Thread"
|
|
333
|
+
},
|
|
334
|
+
hints: {
|
|
335
|
+
message: "Send, read, search, label, and delete emails",
|
|
336
|
+
draft: "Create, get, and delete drafts",
|
|
337
|
+
label: "Create, get, and delete labels",
|
|
338
|
+
thread: "Work with all the messages of a conversation"
|
|
339
|
+
}
|
|
340
|
+
}),
|
|
341
|
+
operation: zod.z.enum(ALL_OPERATIONS).default("send").meta({
|
|
342
|
+
labels: {
|
|
343
|
+
send: "Send",
|
|
344
|
+
reply: "Reply",
|
|
345
|
+
get: "Get",
|
|
346
|
+
getMany: "Get Many",
|
|
347
|
+
markAsRead: "Mark as Read",
|
|
348
|
+
markAsUnread: "Mark as Unread",
|
|
349
|
+
trash: "Move to Trash",
|
|
350
|
+
untrash: "Restore from Trash",
|
|
351
|
+
delete: "Delete",
|
|
352
|
+
addLabels: "Add Labels",
|
|
353
|
+
removeLabels: "Remove Labels",
|
|
354
|
+
create: "Create"
|
|
355
|
+
},
|
|
356
|
+
hints: {
|
|
357
|
+
send: "Send an email",
|
|
358
|
+
reply: "Answer a message in its thread",
|
|
359
|
+
get: "Get one item with its content",
|
|
360
|
+
getMany: "Search or list items",
|
|
361
|
+
markAsRead: "Remove the unread label",
|
|
362
|
+
markAsUnread: "Add the unread label",
|
|
363
|
+
trash: "Move to the trash. Gmail removes it after 30 days",
|
|
364
|
+
untrash: "Move out of the trash",
|
|
365
|
+
delete: "Delete for good. This cannot be undone",
|
|
366
|
+
addLabels: "Add labels to the item",
|
|
367
|
+
removeLabels: "Remove labels from the item",
|
|
368
|
+
create: "Create a new item"
|
|
369
|
+
}
|
|
370
|
+
}),
|
|
371
|
+
messageId: zod.z.string().optional().meta({
|
|
372
|
+
...when(...MESSAGE_ID_OPERATIONS.map((operation) => on("message", operation))),
|
|
373
|
+
title: "Message ID",
|
|
374
|
+
description: "The ID of the message"
|
|
375
|
+
}),
|
|
376
|
+
threadId: zod.z.string().optional().meta({
|
|
377
|
+
...when(on("thread", ...THREAD_ID_OPERATIONS), on("draft", "create")),
|
|
378
|
+
title: "Thread ID",
|
|
379
|
+
description: "The ID of the thread. For a draft: add the draft to this thread. Optional"
|
|
380
|
+
}),
|
|
381
|
+
draftId: zod.z.string().optional().meta({
|
|
382
|
+
showWhen: on("draft", "get", "delete"),
|
|
383
|
+
title: "Draft ID"
|
|
384
|
+
}),
|
|
385
|
+
labelId: zod.z.string().optional().meta({
|
|
386
|
+
showWhen: on("label", "get", "delete"),
|
|
387
|
+
title: "Label ID"
|
|
388
|
+
}),
|
|
389
|
+
to: zod.z.string().optional().meta({
|
|
390
|
+
...when(...COMPOSE),
|
|
391
|
+
title: "To",
|
|
392
|
+
placeholder: "info@example.com",
|
|
393
|
+
description: "Email addresses of the recipients, with commas between. A name works: Nathan Doe <nate@example.com>"
|
|
394
|
+
}),
|
|
395
|
+
subject: zod.z.string().optional().meta({
|
|
396
|
+
...when(...COMPOSE),
|
|
397
|
+
title: "Subject",
|
|
398
|
+
placeholder: "My subject line"
|
|
399
|
+
}),
|
|
400
|
+
emailFormat: zod.z.enum([
|
|
401
|
+
"text",
|
|
402
|
+
"html",
|
|
403
|
+
"both"
|
|
404
|
+
]).default("html").meta({
|
|
405
|
+
...when(...BODY),
|
|
406
|
+
title: "Email Format",
|
|
407
|
+
labels: {
|
|
408
|
+
text: "Text",
|
|
409
|
+
html: "HTML",
|
|
410
|
+
both: "Both"
|
|
411
|
+
},
|
|
412
|
+
hints: {
|
|
413
|
+
text: "Send email as plain text",
|
|
414
|
+
html: "Send email as HTML",
|
|
415
|
+
both: "Send both formats, the email client of the recipient picks one"
|
|
416
|
+
}
|
|
417
|
+
}),
|
|
418
|
+
text: zod.z.string().optional().meta({
|
|
419
|
+
showWhen: BODY.map((rule) => ({
|
|
420
|
+
...rule,
|
|
421
|
+
emailFormat: ["text", "both"]
|
|
422
|
+
})),
|
|
423
|
+
title: "Text",
|
|
424
|
+
description: "Plain text message of the email"
|
|
425
|
+
}),
|
|
426
|
+
html: zod.z.string().optional().meta({
|
|
427
|
+
showWhen: BODY.map((rule) => ({
|
|
428
|
+
...rule,
|
|
429
|
+
emailFormat: ["html", "both"]
|
|
430
|
+
})),
|
|
431
|
+
title: "HTML",
|
|
432
|
+
description: "HTML message of the email"
|
|
433
|
+
}),
|
|
434
|
+
replyAll: zod.z.boolean().default(false).meta({
|
|
435
|
+
...when(on("message", "reply")),
|
|
436
|
+
title: "Reply to All",
|
|
437
|
+
description: "Also send the reply to the other recipients of the message"
|
|
438
|
+
}),
|
|
439
|
+
ccEmail: zod.z.string().optional().meta({
|
|
440
|
+
showWhen: [...COMPOSE],
|
|
441
|
+
...option("CC"),
|
|
442
|
+
placeholder: "cc@example.com",
|
|
443
|
+
description: "Email addresses for CC, with commas between"
|
|
444
|
+
}),
|
|
445
|
+
bccEmail: zod.z.string().optional().meta({
|
|
446
|
+
showWhen: [...COMPOSE],
|
|
447
|
+
...option("BCC"),
|
|
448
|
+
placeholder: "bcc@example.com",
|
|
449
|
+
description: "Email addresses for BCC, with commas between"
|
|
450
|
+
}),
|
|
451
|
+
fromEmail: zod.z.string().optional().meta({
|
|
452
|
+
showWhen: [...BODY],
|
|
453
|
+
...option("From"),
|
|
454
|
+
placeholder: "Nathan Doe <nate@example.com>",
|
|
455
|
+
description: "Name and address of the sender. The address must be an alias of the mailbox. Empty: the mailbox itself"
|
|
456
|
+
}),
|
|
457
|
+
replyTo: zod.z.string().optional().meta({
|
|
458
|
+
showWhen: [...BODY],
|
|
459
|
+
...option("Reply To"),
|
|
460
|
+
placeholder: "info@example.com",
|
|
461
|
+
description: "The email address for the answers of the recipient"
|
|
462
|
+
}),
|
|
463
|
+
attachments: zod.z.string().optional().meta({
|
|
464
|
+
showWhen: [...BODY],
|
|
465
|
+
...option("Attachments"),
|
|
466
|
+
description: "Names of the binary properties that hold the files to attach, with commas between. To show an image in the body: <img src=\"cid:image_1\">"
|
|
467
|
+
}),
|
|
468
|
+
query: zod.z.string().optional().meta({
|
|
469
|
+
showWhen: [...LISTS, on("draft", "getMany")],
|
|
470
|
+
title: "Search",
|
|
471
|
+
placeholder: "from:ann@example.com has:attachment",
|
|
472
|
+
description: "A Gmail search, the same as in the search box of Gmail"
|
|
473
|
+
}),
|
|
474
|
+
labelIds: zod.z.string().optional().meta({
|
|
475
|
+
showWhen: [
|
|
476
|
+
...LISTS,
|
|
477
|
+
on("message", "addLabels", "removeLabels"),
|
|
478
|
+
on("thread", "addLabels", "removeLabels")
|
|
479
|
+
],
|
|
480
|
+
title: "Labels",
|
|
481
|
+
placeholder: "INBOX, Invoices",
|
|
482
|
+
description: "Label names or IDs, with commas between. For a search: only items that have all of them"
|
|
483
|
+
}),
|
|
484
|
+
includeSpamTrash: zod.z.boolean().default(false).meta({
|
|
485
|
+
showWhen: [...LISTS, on("draft", "getMany")],
|
|
486
|
+
...option("Include Spam and Trash")
|
|
487
|
+
}),
|
|
488
|
+
limit: zod.z.number().int().min(1).max(500).default(20).meta({
|
|
489
|
+
showWhen: [
|
|
490
|
+
...LISTS,
|
|
491
|
+
on("draft", "getMany"),
|
|
492
|
+
on("label", "getMany")
|
|
493
|
+
],
|
|
494
|
+
title: "Limit",
|
|
495
|
+
description: "The most items to return"
|
|
496
|
+
}),
|
|
497
|
+
simplify: zod.z.boolean().default(true).meta({
|
|
498
|
+
showWhen: PARSED,
|
|
499
|
+
title: "Simplify",
|
|
500
|
+
description: "Return subject, addresses, text, html, and a list of attachments. Off: the full answer of Gmail"
|
|
501
|
+
}),
|
|
502
|
+
downloadAttachments: zod.z.boolean().default(false).meta({
|
|
503
|
+
showWhen: PARSED,
|
|
504
|
+
title: "Download Attachments",
|
|
505
|
+
description: "Add the files as binary data: attachment_0, attachment_1, and so on"
|
|
506
|
+
}),
|
|
507
|
+
labelName: zod.z.string().optional().meta({
|
|
508
|
+
showWhen: on("label", "create"),
|
|
509
|
+
title: "Name",
|
|
510
|
+
placeholder: "Invoices"
|
|
511
|
+
}),
|
|
512
|
+
labelListVisibility: zod.z.enum([
|
|
513
|
+
"labelShow",
|
|
514
|
+
"labelShowIfUnread",
|
|
515
|
+
"labelHide"
|
|
516
|
+
]).default("labelShow").meta({
|
|
517
|
+
showWhen: on("label", "create"),
|
|
518
|
+
...option("Label List Visibility"),
|
|
519
|
+
labels: {
|
|
520
|
+
labelShow: "Show",
|
|
521
|
+
labelShowIfUnread: "Show if Unread",
|
|
522
|
+
labelHide: "Hide"
|
|
523
|
+
}
|
|
524
|
+
}),
|
|
525
|
+
messageListVisibility: zod.z.enum(["show", "hide"]).default("show").meta({
|
|
526
|
+
showWhen: on("label", "create"),
|
|
527
|
+
...option("Message List Visibility"),
|
|
528
|
+
labels: {
|
|
529
|
+
show: "Show",
|
|
530
|
+
hide: "Hide"
|
|
531
|
+
}
|
|
532
|
+
}),
|
|
533
|
+
timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
|
|
534
|
+
}).superRefine((config, context) => {
|
|
535
|
+
if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
|
|
536
|
+
code: "custom",
|
|
537
|
+
path: ["operation"],
|
|
538
|
+
message: `"${config.operation}" is not an operation of "${config.resource}"`
|
|
539
|
+
});
|
|
540
|
+
});
|
|
541
|
+
// src/request.ts
|
|
542
|
+
/** The labels that Gmail makes for every mailbox. Their ID is their name. */
|
|
543
|
+
const SYSTEM_LABELS = [
|
|
544
|
+
"INBOX",
|
|
545
|
+
"SENT",
|
|
546
|
+
"DRAFT",
|
|
547
|
+
"SPAM",
|
|
548
|
+
"TRASH",
|
|
549
|
+
"UNREAD",
|
|
550
|
+
"STARRED",
|
|
551
|
+
"IMPORTANT",
|
|
552
|
+
"CHAT",
|
|
553
|
+
"CATEGORY_PERSONAL",
|
|
554
|
+
"CATEGORY_SOCIAL",
|
|
555
|
+
"CATEGORY_PROMOTIONS",
|
|
556
|
+
"CATEGORY_UPDATES",
|
|
557
|
+
"CATEGORY_FORUMS"
|
|
558
|
+
];
|
|
559
|
+
/** Names in a list with commas between. Empty parts go away. */
|
|
560
|
+
const splitList = (value) => (value ?? "").split(",").map((part) => part.trim()).filter(Boolean);
|
|
561
|
+
const ID = /^[A-Za-z0-9_-]+$/;
|
|
562
|
+
/** An ID of a message, thread, draft, or label. It goes in a path, so only safe characters pass. */
|
|
563
|
+
function pathId(value, name) {
|
|
564
|
+
const id = (value ?? "").trim();
|
|
565
|
+
if (!id) throw new Error(`"${name}" is needed`);
|
|
566
|
+
if (!ID.test(id)) throw new Error(`"${id}" is not a valid ${name}`);
|
|
567
|
+
return id;
|
|
568
|
+
}
|
|
569
|
+
const listQuery = (options) => ({
|
|
570
|
+
q: options.query?.trim() || void 0,
|
|
571
|
+
labelIds: options.labelIds,
|
|
572
|
+
includeSpamTrash: options.includeSpamTrash ? "true" : void 0,
|
|
573
|
+
maxResults: options.maxResults === void 0 ? void 0 : String(options.maxResults),
|
|
574
|
+
pageToken: options.pageToken
|
|
575
|
+
});
|
|
576
|
+
const profileRequest = () => ({
|
|
577
|
+
method: "GET",
|
|
578
|
+
path: "/profile",
|
|
579
|
+
action: "read the profile"
|
|
580
|
+
});
|
|
581
|
+
const listMessagesRequest = (options) => ({
|
|
582
|
+
method: "GET",
|
|
583
|
+
path: "/messages",
|
|
584
|
+
query: listQuery(options),
|
|
585
|
+
action: "list the messages"
|
|
586
|
+
});
|
|
587
|
+
const getMessageRequest = (id, format = "full", headers = []) => ({
|
|
588
|
+
method: "GET",
|
|
589
|
+
path: `/messages/${pathId(id, "messageId")}`,
|
|
590
|
+
query: {
|
|
591
|
+
format,
|
|
592
|
+
metadataHeaders: format === "metadata" ? headers : void 0
|
|
593
|
+
},
|
|
594
|
+
action: "get the message"
|
|
595
|
+
});
|
|
596
|
+
const getAttachmentRequest = (messageId, attachmentId) => ({
|
|
597
|
+
method: "GET",
|
|
598
|
+
path: `/messages/${pathId(messageId, "messageId")}/attachments/${pathId(attachmentId, "attachmentId")}`,
|
|
599
|
+
action: "get the attachment"
|
|
600
|
+
});
|
|
601
|
+
const sendRequest = (raw, threadId) => ({
|
|
602
|
+
method: "POST",
|
|
603
|
+
path: "/messages/send",
|
|
604
|
+
body: {
|
|
605
|
+
raw,
|
|
606
|
+
...threadId && { threadId }
|
|
607
|
+
},
|
|
608
|
+
action: "send the message"
|
|
609
|
+
});
|
|
610
|
+
const modifyMessageRequest = (id, add, remove) => ({
|
|
611
|
+
method: "POST",
|
|
612
|
+
path: `/messages/${pathId(id, "messageId")}/modify`,
|
|
613
|
+
body: {
|
|
614
|
+
addLabelIds: add,
|
|
615
|
+
removeLabelIds: remove
|
|
616
|
+
},
|
|
617
|
+
action: "change the labels of the message"
|
|
618
|
+
});
|
|
619
|
+
const trashMessageRequest = (id, undo = false) => ({
|
|
620
|
+
method: "POST",
|
|
621
|
+
path: `/messages/${pathId(id, "messageId")}/${undo ? "untrash" : "trash"}`,
|
|
622
|
+
action: undo ? "restore the message" : "move the message to the trash"
|
|
623
|
+
});
|
|
624
|
+
const deleteMessageRequest = (id) => ({
|
|
625
|
+
method: "DELETE",
|
|
626
|
+
path: `/messages/${pathId(id, "messageId")}`,
|
|
627
|
+
action: "delete the message"
|
|
628
|
+
});
|
|
629
|
+
const createDraftRequest = (raw, threadId) => ({
|
|
630
|
+
method: "POST",
|
|
631
|
+
path: "/drafts",
|
|
632
|
+
body: { message: {
|
|
633
|
+
raw,
|
|
634
|
+
...threadId && { threadId }
|
|
635
|
+
} },
|
|
636
|
+
action: "create the draft"
|
|
637
|
+
});
|
|
638
|
+
const getDraftRequest = (id) => ({
|
|
639
|
+
method: "GET",
|
|
640
|
+
path: `/drafts/${pathId(id, "draftId")}`,
|
|
641
|
+
query: { format: "full" },
|
|
642
|
+
action: "get the draft"
|
|
643
|
+
});
|
|
644
|
+
const listDraftsRequest = (options) => ({
|
|
645
|
+
method: "GET",
|
|
646
|
+
path: "/drafts",
|
|
647
|
+
query: listQuery(options),
|
|
648
|
+
action: "list the drafts"
|
|
649
|
+
});
|
|
650
|
+
const deleteDraftRequest = (id) => ({
|
|
651
|
+
method: "DELETE",
|
|
652
|
+
path: `/drafts/${pathId(id, "draftId")}`,
|
|
653
|
+
action: "delete the draft"
|
|
654
|
+
});
|
|
655
|
+
const listLabelsRequest = () => ({
|
|
656
|
+
method: "GET",
|
|
657
|
+
path: "/labels",
|
|
658
|
+
action: "list the labels"
|
|
659
|
+
});
|
|
660
|
+
const getLabelRequest = (id) => ({
|
|
661
|
+
method: "GET",
|
|
662
|
+
path: `/labels/${pathId(id, "labelId")}`,
|
|
663
|
+
action: "get the label"
|
|
664
|
+
});
|
|
665
|
+
const createLabelRequest = (name, listVisibility, messageVisibility) => ({
|
|
666
|
+
method: "POST",
|
|
667
|
+
path: "/labels",
|
|
668
|
+
body: {
|
|
669
|
+
name,
|
|
670
|
+
labelListVisibility: listVisibility,
|
|
671
|
+
messageListVisibility: messageVisibility
|
|
672
|
+
},
|
|
673
|
+
action: "create the label"
|
|
674
|
+
});
|
|
675
|
+
const deleteLabelRequest = (id) => ({
|
|
676
|
+
method: "DELETE",
|
|
677
|
+
path: `/labels/${pathId(id, "labelId")}`,
|
|
678
|
+
action: "delete the label"
|
|
679
|
+
});
|
|
680
|
+
const getThreadRequest = (id) => ({
|
|
681
|
+
method: "GET",
|
|
682
|
+
path: `/threads/${pathId(id, "threadId")}`,
|
|
683
|
+
query: { format: "full" },
|
|
684
|
+
action: "get the thread"
|
|
685
|
+
});
|
|
686
|
+
const listThreadsRequest = (options) => ({
|
|
687
|
+
method: "GET",
|
|
688
|
+
path: "/threads",
|
|
689
|
+
query: listQuery(options),
|
|
690
|
+
action: "list the threads"
|
|
691
|
+
});
|
|
692
|
+
const modifyThreadRequest = (id, add, remove) => ({
|
|
693
|
+
method: "POST",
|
|
694
|
+
path: `/threads/${pathId(id, "threadId")}/modify`,
|
|
695
|
+
body: {
|
|
696
|
+
addLabelIds: add,
|
|
697
|
+
removeLabelIds: remove
|
|
698
|
+
},
|
|
699
|
+
action: "change the labels of the thread"
|
|
700
|
+
});
|
|
701
|
+
const trashThreadRequest = (id, undo = false) => ({
|
|
702
|
+
method: "POST",
|
|
703
|
+
path: `/threads/${pathId(id, "threadId")}/${undo ? "untrash" : "trash"}`,
|
|
704
|
+
action: undo ? "restore the thread" : "move the thread to the trash"
|
|
705
|
+
});
|
|
706
|
+
const deleteThreadRequest = (id) => ({
|
|
707
|
+
method: "DELETE",
|
|
708
|
+
path: `/threads/${pathId(id, "threadId")}`,
|
|
709
|
+
action: "delete the thread"
|
|
710
|
+
});
|
|
711
|
+
const labelsOf = (answer) => {
|
|
712
|
+
return (isObject(answer) && Array.isArray(answer.labels) ? answer.labels : []).flatMap((entry) => {
|
|
713
|
+
const id = isObject(entry) ? text(entry.id) : void 0;
|
|
714
|
+
const name = isObject(entry) ? text(entry.name) : void 0;
|
|
715
|
+
return id && name ? [{
|
|
716
|
+
id,
|
|
717
|
+
name
|
|
718
|
+
}] : [];
|
|
719
|
+
});
|
|
720
|
+
};
|
|
721
|
+
/**
|
|
722
|
+
* Label IDs from IDs or names. A system label (`INBOX`) and an ID (`Label_12`) pass as they are.
|
|
723
|
+
* A name is matched, without case, against the labels of the mailbox. `loadLabels` runs only when
|
|
724
|
+
* a name needs it.
|
|
725
|
+
*/
|
|
726
|
+
async function resolveLabelIds(values, loadLabels) {
|
|
727
|
+
const known = new Set(SYSTEM_LABELS);
|
|
728
|
+
let labels;
|
|
729
|
+
const ids = [];
|
|
730
|
+
for (const value of values) {
|
|
731
|
+
if (known.has(value) || /^Label_\d+$/.test(value)) {
|
|
732
|
+
ids.push(value);
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
labels ??= await loadLabels();
|
|
736
|
+
const found = labels.find((label) => label.id === value) ?? labels.find((label) => label.name.toLowerCase() === value.toLowerCase());
|
|
737
|
+
if (!found) throw new Error(`The label "${value}" does not exist`);
|
|
738
|
+
ids.push(found.id);
|
|
739
|
+
}
|
|
740
|
+
return ids;
|
|
741
|
+
}
|
|
742
|
+
/** The Gmail search text of the filters. The words of the user stay as they are. */
|
|
743
|
+
function searchText(filters) {
|
|
744
|
+
const parts = [];
|
|
745
|
+
if (filters.query?.trim()) parts.push(filters.query.trim());
|
|
746
|
+
if (filters.sender?.trim()) parts.push(`from:(${filters.sender.trim()})`);
|
|
747
|
+
if (filters.readStatus === "unread") parts.push("is:unread");
|
|
748
|
+
if (filters.readStatus === "read") parts.push("is:read");
|
|
749
|
+
if (filters.after !== void 0) parts.push(`after:${Math.floor(filters.after)}`);
|
|
750
|
+
return parts.length > 0 ? parts.join(" ") : void 0;
|
|
751
|
+
}
|
|
752
|
+
/** The attachments from `input.binary`. The content id of each one is its property name. */
|
|
753
|
+
function attachmentsOf(names, input) {
|
|
754
|
+
return splitList(names).map((name) => {
|
|
755
|
+
const file = (0, _zerodot_node_sdk.readBinary)(input, name);
|
|
756
|
+
return {
|
|
757
|
+
filename: file.fileName || "unknown",
|
|
758
|
+
content: Buffer.from(file.data, "base64"),
|
|
759
|
+
contentType: file.mimeType,
|
|
760
|
+
cid: name
|
|
761
|
+
};
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
/** The message as base64url text of the full MIME source. This is the `raw` field of Gmail. */
|
|
765
|
+
async function buildRaw(options, input) {
|
|
766
|
+
if (!options.to?.trim() && !options.cc?.trim() && !options.bcc?.trim()) throw new Error("The message needs a recipient: \"to\", \"cc\", or \"bcc\"");
|
|
767
|
+
const { default: MailComposer } = await import("nodemailer/lib/mail-composer/index.js");
|
|
768
|
+
const { format } = options;
|
|
769
|
+
const headers = {};
|
|
770
|
+
if (options.inReplyTo) headers["In-Reply-To"] = options.inReplyTo;
|
|
771
|
+
if (options.references) headers.References = options.references;
|
|
772
|
+
const composer = new MailComposer({
|
|
773
|
+
from: options.from || void 0,
|
|
774
|
+
to: options.to || void 0,
|
|
775
|
+
cc: options.cc || void 0,
|
|
776
|
+
bcc: options.bcc || void 0,
|
|
777
|
+
replyTo: options.replyTo || void 0,
|
|
778
|
+
subject: options.subject,
|
|
779
|
+
text: format === "text" || format === "both" ? options.text ?? "" : void 0,
|
|
780
|
+
html: format === "html" || format === "both" ? options.html ?? "" : void 0,
|
|
781
|
+
attachments: attachmentsOf(options.attachments, input),
|
|
782
|
+
headers
|
|
783
|
+
});
|
|
784
|
+
return (await new Promise((resolve, reject) => {
|
|
785
|
+
const mime = composer.compile();
|
|
786
|
+
mime.keepBcc = true;
|
|
787
|
+
mime.build((error, message) => error ? reject(error) : resolve(message));
|
|
788
|
+
})).toString("base64url");
|
|
789
|
+
}
|
|
790
|
+
const headersOf = (value) => (Array.isArray(value) ? value : []).flatMap((entry) => {
|
|
791
|
+
const name = isObject(entry) ? text(entry.name) : void 0;
|
|
792
|
+
return name && isObject(entry) ? [{
|
|
793
|
+
name,
|
|
794
|
+
value: String(entry.value ?? "")
|
|
795
|
+
}] : [];
|
|
796
|
+
});
|
|
797
|
+
function toPart(value) {
|
|
798
|
+
const part = isObject(value) ? value : {};
|
|
799
|
+
const body = isObject(part.body) ? part.body : {};
|
|
800
|
+
return {
|
|
801
|
+
partId: text(part.partId),
|
|
802
|
+
mimeType: text(part.mimeType) ?? "application/octet-stream",
|
|
803
|
+
filename: typeof part.filename === "string" ? part.filename : "",
|
|
804
|
+
headers: headersOf(part.headers),
|
|
805
|
+
body: {
|
|
806
|
+
size: typeof body.size === "number" ? body.size : 0,
|
|
807
|
+
data: text(body.data),
|
|
808
|
+
attachmentId: text(body.attachmentId)
|
|
809
|
+
},
|
|
810
|
+
parts: (Array.isArray(part.parts) ? part.parts : []).map(toPart)
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
/** The value of a header. The name has no case. */
|
|
814
|
+
const header = (headers, name) => headers.find((entry) => entry.name.toLowerCase() === name.toLowerCase())?.value;
|
|
815
|
+
function decodeBody(data, contentType) {
|
|
816
|
+
const bytes = Buffer.from(data, "base64url");
|
|
817
|
+
const charset = /charset="?([^";\s]+)/i.exec(contentType ?? "")?.[1] ?? "utf-8";
|
|
818
|
+
try {
|
|
819
|
+
return new TextDecoder(charset).decode(bytes);
|
|
820
|
+
} catch {
|
|
821
|
+
return bytes.toString("utf8");
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
function walk(part, found) {
|
|
825
|
+
const type = part.mimeType.toLowerCase();
|
|
826
|
+
const contentType = header(part.headers, "content-type");
|
|
827
|
+
if (part.body.attachmentId && (part.filename || !type.startsWith("text/"))) found.attachments.push({
|
|
828
|
+
attachmentId: part.body.attachmentId,
|
|
829
|
+
fileName: part.filename || "attachment",
|
|
830
|
+
mimeType: part.mimeType,
|
|
831
|
+
size: part.body.size,
|
|
832
|
+
contentId: header(part.headers, "content-id")?.replace(/^<|>$/g, "") ?? null
|
|
833
|
+
});
|
|
834
|
+
else if (part.body.data && !part.filename) {
|
|
835
|
+
if (type === "text/plain") found.text.push(decodeBody(part.body.data, contentType));
|
|
836
|
+
if (type === "text/html") found.html.push(decodeBody(part.body.data, contentType));
|
|
837
|
+
}
|
|
838
|
+
for (const child of part.parts) walk(child, found);
|
|
839
|
+
}
|
|
840
|
+
/** The simple fields of a Gmail message that has `format=full` (or `metadata`). */
|
|
841
|
+
function toMailItem(message) {
|
|
842
|
+
const raw = isObject(message) ? message : {};
|
|
843
|
+
const payload = toPart(raw.payload);
|
|
844
|
+
const found = {
|
|
845
|
+
text: [],
|
|
846
|
+
html: [],
|
|
847
|
+
attachments: []
|
|
848
|
+
};
|
|
849
|
+
walk(payload, found);
|
|
850
|
+
const millis = Number(raw.internalDate);
|
|
851
|
+
const value = (name) => header(payload.headers, name) ?? null;
|
|
852
|
+
return {
|
|
853
|
+
id: text(raw.id) ?? "",
|
|
854
|
+
threadId: text(raw.threadId) ?? "",
|
|
855
|
+
labelIds: (Array.isArray(raw.labelIds) ? raw.labelIds : []).filter((label) => typeof label === "string"),
|
|
856
|
+
snippet: typeof raw.snippet === "string" ? raw.snippet : "",
|
|
857
|
+
internalDate: Number.isFinite(millis) && millis > 0 ? new Date(millis).toISOString() : null,
|
|
858
|
+
messageId: value("message-id"),
|
|
859
|
+
subject: value("subject"),
|
|
860
|
+
from: value("from"),
|
|
861
|
+
to: value("to"),
|
|
862
|
+
cc: value("cc"),
|
|
863
|
+
bcc: value("bcc"),
|
|
864
|
+
replyTo: value("reply-to"),
|
|
865
|
+
date: value("date"),
|
|
866
|
+
text: found.text.length > 0 ? found.text.join("\n") : null,
|
|
867
|
+
html: found.html.length > 0 ? found.html.join("\n") : null,
|
|
868
|
+
attachments: found.attachments
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
/** Gets the files of a mail. They go in `binary` as `attachment_0`, `attachment_1`, ... */
|
|
872
|
+
async function withAttachments(call, item, property = "attachment_") {
|
|
873
|
+
if (item.attachments.length === 0) return item;
|
|
874
|
+
const binary = {};
|
|
875
|
+
for (const [index, file] of item.attachments.entries()) {
|
|
876
|
+
const answer = await call(getAttachmentRequest(item.id, file.attachmentId));
|
|
877
|
+
const data = isObject(answer) ? text(answer.data) : void 0;
|
|
878
|
+
binary[`${property}${index}`] = (0, _zerodot_node_sdk.toBinary)(Buffer.from(data ?? "", "base64url"), file.fileName, file.mimeType);
|
|
879
|
+
}
|
|
880
|
+
return {
|
|
881
|
+
...item,
|
|
882
|
+
binary
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
/** The ID of a message in an answer of a list call. */
|
|
886
|
+
const idsOf = (answer, key) => {
|
|
887
|
+
return (isObject(answer) && Array.isArray(answer[key]) ? answer[key] : []).flatMap((entry) => {
|
|
888
|
+
const id = isObject(entry) ? text(entry.id) : void 0;
|
|
889
|
+
return id ? [id] : [];
|
|
890
|
+
});
|
|
891
|
+
};
|
|
892
|
+
/** The email address in `Name <a@b.c>` or `a@b.c`, in lower case. */
|
|
893
|
+
const addressOf = (entry) => {
|
|
894
|
+
return (/<([^>]+)>/.exec(entry)?.[1] ?? entry).trim().toLowerCase();
|
|
895
|
+
};
|
|
896
|
+
/** Splits an address list at the commas that are not in quotes. */
|
|
897
|
+
function splitAddresses(value) {
|
|
898
|
+
const out = [];
|
|
899
|
+
let current = "";
|
|
900
|
+
let quoted = false;
|
|
901
|
+
for (const char of value ?? "") {
|
|
902
|
+
if (char === "\"") quoted = !quoted;
|
|
903
|
+
if (char === "," && !quoted) {
|
|
904
|
+
out.push(current.trim());
|
|
905
|
+
current = "";
|
|
906
|
+
} else current += char;
|
|
907
|
+
}
|
|
908
|
+
out.push(current.trim());
|
|
909
|
+
return out.filter(Boolean);
|
|
910
|
+
}
|
|
911
|
+
const REPLY_HEADERS = [
|
|
912
|
+
"Message-ID",
|
|
913
|
+
"References",
|
|
914
|
+
"Subject",
|
|
915
|
+
"From",
|
|
916
|
+
"To",
|
|
917
|
+
"Cc",
|
|
918
|
+
"Reply-To"
|
|
919
|
+
];
|
|
920
|
+
/**
|
|
921
|
+
* What a reply needs from the first message: the thread, the recipients, `Re:` before the
|
|
922
|
+
* subject, and the headers that make the mail a part of the thread. A reply to all also copies
|
|
923
|
+
* the other recipients, except `self`.
|
|
924
|
+
*/
|
|
925
|
+
function replyTarget(message, replyAll, self) {
|
|
926
|
+
const mail = toMailItem(message);
|
|
927
|
+
const raw = isObject(message) ? message : {};
|
|
928
|
+
const payload = isObject(raw.payload) ? raw.payload : {};
|
|
929
|
+
const headers = headersOf(payload.headers);
|
|
930
|
+
const messageId = header(headers, "message-id");
|
|
931
|
+
const references = header(headers, "references");
|
|
932
|
+
const subject = mail.subject ?? "";
|
|
933
|
+
const main = mail.replyTo ?? mail.from ?? "";
|
|
934
|
+
const skip = new Set([addressOf(main), self?.toLowerCase()].filter(Boolean));
|
|
935
|
+
const others = replyAll ? [...splitAddresses(mail.to), ...splitAddresses(mail.cc)].filter((entry) => {
|
|
936
|
+
const address = addressOf(entry);
|
|
937
|
+
if (skip.has(address)) return false;
|
|
938
|
+
skip.add(address);
|
|
939
|
+
return true;
|
|
940
|
+
}) : [];
|
|
941
|
+
return {
|
|
942
|
+
threadId: mail.threadId,
|
|
943
|
+
to: main,
|
|
944
|
+
cc: others.join(", "),
|
|
945
|
+
subject: /^re:/i.test(subject) ? subject : `Re: ${subject}`,
|
|
946
|
+
inReplyTo: messageId,
|
|
947
|
+
references: [references, messageId].filter(Boolean).join(" ") || void 0
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* A message as the node returns it. `simplify` gives the fields of `toMailItem`, and
|
|
952
|
+
* `download` also adds the files as binary data. Without `simplify` the answer of Gmail stays
|
|
953
|
+
* as it is.
|
|
954
|
+
*/
|
|
955
|
+
async function shapeMessage(call, message, simplify, download) {
|
|
956
|
+
if (!simplify) return message;
|
|
957
|
+
const item = toMailItem(message);
|
|
958
|
+
return download ? await withAttachments(call, item) : item;
|
|
959
|
+
}
|
|
960
|
+
/** The IDs of a search, newest first, over all pages up to `limit`. */
|
|
961
|
+
async function searchIds(call, options, limit, key = "messages") {
|
|
962
|
+
const make = key === "messages" ? listMessagesRequest : key === "threads" ? listThreadsRequest : listDraftsRequest;
|
|
963
|
+
const ids = [];
|
|
964
|
+
let pageToken;
|
|
965
|
+
do {
|
|
966
|
+
const answer = await call(make({
|
|
967
|
+
...options,
|
|
968
|
+
maxResults: Math.min(500, limit - ids.length),
|
|
969
|
+
pageToken
|
|
970
|
+
}));
|
|
971
|
+
ids.push(...idsOf(answer, key));
|
|
972
|
+
pageToken = isObject(answer) ? text(answer.nextPageToken) : void 0;
|
|
973
|
+
} while (pageToken && ids.length < limit);
|
|
974
|
+
return ids.slice(0, limit);
|
|
975
|
+
}
|
|
976
|
+
// src/node.ts
|
|
977
|
+
const need = (value, name, operation) => {
|
|
978
|
+
if (value === void 0 || value === "" || typeof value === "string" && !value.trim()) throw new Error(`"${name}" is needed to ${operation}`);
|
|
979
|
+
return value;
|
|
980
|
+
};
|
|
981
|
+
const success = (extra) => ({
|
|
982
|
+
success: true,
|
|
983
|
+
...extra
|
|
984
|
+
});
|
|
985
|
+
async function runMessage(call, config, input, labelIds, listOptions) {
|
|
986
|
+
const { operation } = config;
|
|
987
|
+
const messageId = () => need(config.messageId, "messageId", operation);
|
|
988
|
+
const body = {
|
|
989
|
+
from: config.fromEmail,
|
|
990
|
+
replyTo: config.replyTo,
|
|
991
|
+
format: config.emailFormat,
|
|
992
|
+
text: config.text,
|
|
993
|
+
html: config.html,
|
|
994
|
+
attachments: config.attachments
|
|
995
|
+
};
|
|
996
|
+
switch (operation) {
|
|
997
|
+
case "send": {
|
|
998
|
+
const raw = await buildRaw({
|
|
999
|
+
...body,
|
|
1000
|
+
to: config.to,
|
|
1001
|
+
cc: config.ccEmail,
|
|
1002
|
+
bcc: config.bccEmail,
|
|
1003
|
+
subject: config.subject ?? ""
|
|
1004
|
+
}, input);
|
|
1005
|
+
return await call(sendRequest(raw));
|
|
1006
|
+
}
|
|
1007
|
+
case "reply": {
|
|
1008
|
+
const original = await call(getMessageRequest(messageId(), "metadata", REPLY_HEADERS));
|
|
1009
|
+
const self = config.replyAll ? text((await call(profileRequest())).emailAddress) : void 0;
|
|
1010
|
+
const target = replyTarget(original, config.replyAll, self);
|
|
1011
|
+
const raw = await buildRaw({
|
|
1012
|
+
...body,
|
|
1013
|
+
to: target.to,
|
|
1014
|
+
cc: target.cc,
|
|
1015
|
+
subject: target.subject,
|
|
1016
|
+
inReplyTo: target.inReplyTo,
|
|
1017
|
+
references: target.references
|
|
1018
|
+
}, input);
|
|
1019
|
+
return await call(sendRequest(raw, target.threadId));
|
|
1020
|
+
}
|
|
1021
|
+
case "get": return await shapeMessage(call, await call(getMessageRequest(messageId())), config.simplify, config.downloadAttachments);
|
|
1022
|
+
case "getMany": {
|
|
1023
|
+
const ids = await searchIds(call, await listOptions(), config.limit);
|
|
1024
|
+
const out = [];
|
|
1025
|
+
for (const id of ids) {
|
|
1026
|
+
const message = await call(getMessageRequest(id));
|
|
1027
|
+
out.push(await shapeMessage(call, message, config.simplify, config.downloadAttachments));
|
|
1028
|
+
}
|
|
1029
|
+
return out;
|
|
1030
|
+
}
|
|
1031
|
+
case "markAsRead": return await call(modifyMessageRequest(messageId(), [], ["UNREAD"]));
|
|
1032
|
+
case "markAsUnread": return await call(modifyMessageRequest(messageId(), ["UNREAD"], []));
|
|
1033
|
+
case "trash": return await call(trashMessageRequest(messageId()));
|
|
1034
|
+
case "untrash": return await call(trashMessageRequest(messageId(), true));
|
|
1035
|
+
case "delete": {
|
|
1036
|
+
const id = messageId();
|
|
1037
|
+
await call(deleteMessageRequest(id));
|
|
1038
|
+
return success({ id });
|
|
1039
|
+
}
|
|
1040
|
+
case "addLabels": return await call(modifyMessageRequest(messageId(), await labelIds(), []));
|
|
1041
|
+
case "removeLabels": return await call(modifyMessageRequest(messageId(), [], await labelIds()));
|
|
1042
|
+
}
|
|
1043
|
+
throw new Error(`"${operation}" is not an operation of "message"`);
|
|
1044
|
+
}
|
|
1045
|
+
async function runDraft(call, config, input, listOptions) {
|
|
1046
|
+
const { operation } = config;
|
|
1047
|
+
const shape = async (answer) => {
|
|
1048
|
+
if (!config.simplify || !isObject(answer)) return answer;
|
|
1049
|
+
const item = toMailItem(answer.message);
|
|
1050
|
+
const mail = config.downloadAttachments ? await withAttachments(call, item) : item;
|
|
1051
|
+
return {
|
|
1052
|
+
draftId: text(answer.id) ?? "",
|
|
1053
|
+
...mail
|
|
1054
|
+
};
|
|
1055
|
+
};
|
|
1056
|
+
switch (operation) {
|
|
1057
|
+
case "create": {
|
|
1058
|
+
const raw = await buildRaw({
|
|
1059
|
+
from: config.fromEmail,
|
|
1060
|
+
replyTo: config.replyTo,
|
|
1061
|
+
to: config.to,
|
|
1062
|
+
cc: config.ccEmail,
|
|
1063
|
+
bcc: config.bccEmail,
|
|
1064
|
+
subject: config.subject ?? "",
|
|
1065
|
+
format: config.emailFormat,
|
|
1066
|
+
text: config.text,
|
|
1067
|
+
html: config.html,
|
|
1068
|
+
attachments: config.attachments
|
|
1069
|
+
}, input);
|
|
1070
|
+
return await call(createDraftRequest(raw, config.threadId?.trim() || void 0));
|
|
1071
|
+
}
|
|
1072
|
+
case "get": return await shape(await call(getDraftRequest(need(config.draftId, "draftId", operation))));
|
|
1073
|
+
case "getMany": {
|
|
1074
|
+
const ids = await searchIds(call, await listOptions(), config.limit, "drafts");
|
|
1075
|
+
const out = [];
|
|
1076
|
+
for (const id of ids) out.push(await shape(await call(getDraftRequest(id))));
|
|
1077
|
+
return out;
|
|
1078
|
+
}
|
|
1079
|
+
case "delete": {
|
|
1080
|
+
const id = need(config.draftId, "draftId", operation);
|
|
1081
|
+
await call(deleteDraftRequest(id));
|
|
1082
|
+
return success({ id });
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
throw new Error(`"${operation}" is not an operation of "draft"`);
|
|
1086
|
+
}
|
|
1087
|
+
async function runLabel(call, config) {
|
|
1088
|
+
const { operation } = config;
|
|
1089
|
+
switch (operation) {
|
|
1090
|
+
case "create": return await call(createLabelRequest(need(config.labelName, "labelName", operation).trim(), config.labelListVisibility, config.messageListVisibility));
|
|
1091
|
+
case "get": return await call(getLabelRequest(need(config.labelId, "labelId", operation)));
|
|
1092
|
+
case "getMany": {
|
|
1093
|
+
const answer = await call(listLabelsRequest());
|
|
1094
|
+
return (isObject(answer) && Array.isArray(answer.labels) ? answer.labels : []).slice(0, config.limit);
|
|
1095
|
+
}
|
|
1096
|
+
case "delete": {
|
|
1097
|
+
const id = need(config.labelId, "labelId", operation);
|
|
1098
|
+
await call(deleteLabelRequest(id));
|
|
1099
|
+
return success({ id });
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
throw new Error(`"${operation}" is not an operation of "label"`);
|
|
1103
|
+
}
|
|
1104
|
+
async function runThread(call, config, labelIds, listOptions) {
|
|
1105
|
+
const { operation } = config;
|
|
1106
|
+
const threadId = () => need(config.threadId, "threadId", operation);
|
|
1107
|
+
switch (operation) {
|
|
1108
|
+
case "get": {
|
|
1109
|
+
const answer = await call(getThreadRequest(threadId()));
|
|
1110
|
+
if (!config.simplify || !isObject(answer)) return answer;
|
|
1111
|
+
const messages = Array.isArray(answer.messages) ? answer.messages : [];
|
|
1112
|
+
const items = [];
|
|
1113
|
+
for (const message of messages) items.push(await shapeMessage(call, message, true, config.downloadAttachments));
|
|
1114
|
+
return {
|
|
1115
|
+
id: text(answer.id) ?? "",
|
|
1116
|
+
historyId: text(answer.historyId) ?? "",
|
|
1117
|
+
messages: items
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
case "getMany": return (await searchIds(call, await listOptions(), config.limit, "threads")).map((id) => ({ id }));
|
|
1121
|
+
case "trash": return await call(trashThreadRequest(threadId()));
|
|
1122
|
+
case "untrash": return await call(trashThreadRequest(threadId(), true));
|
|
1123
|
+
case "delete": {
|
|
1124
|
+
const id = threadId();
|
|
1125
|
+
await call(deleteThreadRequest(id));
|
|
1126
|
+
return success({ id });
|
|
1127
|
+
}
|
|
1128
|
+
case "addLabels": return await call(modifyThreadRequest(threadId(), await labelIds(), []));
|
|
1129
|
+
case "removeLabels": return await call(modifyThreadRequest(threadId(), [], await labelIds()));
|
|
1130
|
+
}
|
|
1131
|
+
throw new Error(`"${operation}" is not an operation of "thread"`);
|
|
1132
|
+
}
|
|
1133
|
+
var node_default = (0, _zerodot_node_sdk.defineNode)({
|
|
1134
|
+
type: "gmail.api",
|
|
1135
|
+
label: "Gmail",
|
|
1136
|
+
description: "Send, read, search, and label emails in Gmail",
|
|
1137
|
+
category: "integration",
|
|
1138
|
+
app: "Gmail",
|
|
1139
|
+
actions: [
|
|
1140
|
+
{
|
|
1141
|
+
label: "Send a message",
|
|
1142
|
+
config: {
|
|
1143
|
+
resource: "message",
|
|
1144
|
+
operation: "send"
|
|
1145
|
+
}
|
|
1146
|
+
},
|
|
1147
|
+
{
|
|
1148
|
+
label: "Reply to a message",
|
|
1149
|
+
config: {
|
|
1150
|
+
resource: "message",
|
|
1151
|
+
operation: "reply"
|
|
1152
|
+
}
|
|
1153
|
+
},
|
|
1154
|
+
{
|
|
1155
|
+
label: "Get a message",
|
|
1156
|
+
config: {
|
|
1157
|
+
resource: "message",
|
|
1158
|
+
operation: "get"
|
|
1159
|
+
}
|
|
1160
|
+
},
|
|
1161
|
+
{
|
|
1162
|
+
label: "Get many messages",
|
|
1163
|
+
config: {
|
|
1164
|
+
resource: "message",
|
|
1165
|
+
operation: "getMany"
|
|
1166
|
+
}
|
|
1167
|
+
},
|
|
1168
|
+
{
|
|
1169
|
+
label: "Mark a message as read",
|
|
1170
|
+
config: {
|
|
1171
|
+
resource: "message",
|
|
1172
|
+
operation: "markAsRead"
|
|
1173
|
+
}
|
|
1174
|
+
},
|
|
1175
|
+
{
|
|
1176
|
+
label: "Mark a message as unread",
|
|
1177
|
+
config: {
|
|
1178
|
+
resource: "message",
|
|
1179
|
+
operation: "markAsUnread"
|
|
1180
|
+
}
|
|
1181
|
+
},
|
|
1182
|
+
{
|
|
1183
|
+
label: "Move a message to the trash",
|
|
1184
|
+
config: {
|
|
1185
|
+
resource: "message",
|
|
1186
|
+
operation: "trash"
|
|
1187
|
+
}
|
|
1188
|
+
},
|
|
1189
|
+
{
|
|
1190
|
+
label: "Delete a message",
|
|
1191
|
+
config: {
|
|
1192
|
+
resource: "message",
|
|
1193
|
+
operation: "delete"
|
|
1194
|
+
}
|
|
1195
|
+
},
|
|
1196
|
+
{
|
|
1197
|
+
label: "Add labels to a message",
|
|
1198
|
+
config: {
|
|
1199
|
+
resource: "message",
|
|
1200
|
+
operation: "addLabels"
|
|
1201
|
+
}
|
|
1202
|
+
},
|
|
1203
|
+
{
|
|
1204
|
+
label: "Remove labels from a message",
|
|
1205
|
+
config: {
|
|
1206
|
+
resource: "message",
|
|
1207
|
+
operation: "removeLabels"
|
|
1208
|
+
}
|
|
1209
|
+
},
|
|
1210
|
+
{
|
|
1211
|
+
label: "Create a draft",
|
|
1212
|
+
config: {
|
|
1213
|
+
resource: "draft",
|
|
1214
|
+
operation: "create"
|
|
1215
|
+
}
|
|
1216
|
+
},
|
|
1217
|
+
{
|
|
1218
|
+
label: "Get a draft",
|
|
1219
|
+
config: {
|
|
1220
|
+
resource: "draft",
|
|
1221
|
+
operation: "get"
|
|
1222
|
+
}
|
|
1223
|
+
},
|
|
1224
|
+
{
|
|
1225
|
+
label: "Get many drafts",
|
|
1226
|
+
config: {
|
|
1227
|
+
resource: "draft",
|
|
1228
|
+
operation: "getMany"
|
|
1229
|
+
}
|
|
1230
|
+
},
|
|
1231
|
+
{
|
|
1232
|
+
label: "Delete a draft",
|
|
1233
|
+
config: {
|
|
1234
|
+
resource: "draft",
|
|
1235
|
+
operation: "delete"
|
|
1236
|
+
}
|
|
1237
|
+
},
|
|
1238
|
+
{
|
|
1239
|
+
label: "Create a label",
|
|
1240
|
+
config: {
|
|
1241
|
+
resource: "label",
|
|
1242
|
+
operation: "create"
|
|
1243
|
+
}
|
|
1244
|
+
},
|
|
1245
|
+
{
|
|
1246
|
+
label: "Get a label",
|
|
1247
|
+
config: {
|
|
1248
|
+
resource: "label",
|
|
1249
|
+
operation: "get"
|
|
1250
|
+
}
|
|
1251
|
+
},
|
|
1252
|
+
{
|
|
1253
|
+
label: "Get many labels",
|
|
1254
|
+
config: {
|
|
1255
|
+
resource: "label",
|
|
1256
|
+
operation: "getMany"
|
|
1257
|
+
}
|
|
1258
|
+
},
|
|
1259
|
+
{
|
|
1260
|
+
label: "Delete a label",
|
|
1261
|
+
config: {
|
|
1262
|
+
resource: "label",
|
|
1263
|
+
operation: "delete"
|
|
1264
|
+
}
|
|
1265
|
+
},
|
|
1266
|
+
{
|
|
1267
|
+
label: "Get a thread",
|
|
1268
|
+
config: {
|
|
1269
|
+
resource: "thread",
|
|
1270
|
+
operation: "get"
|
|
1271
|
+
}
|
|
1272
|
+
},
|
|
1273
|
+
{
|
|
1274
|
+
label: "Get many threads",
|
|
1275
|
+
config: {
|
|
1276
|
+
resource: "thread",
|
|
1277
|
+
operation: "getMany"
|
|
1278
|
+
}
|
|
1279
|
+
},
|
|
1280
|
+
{
|
|
1281
|
+
label: "Move a thread to the trash",
|
|
1282
|
+
config: {
|
|
1283
|
+
resource: "thread",
|
|
1284
|
+
operation: "trash"
|
|
1285
|
+
}
|
|
1286
|
+
},
|
|
1287
|
+
{
|
|
1288
|
+
label: "Delete a thread",
|
|
1289
|
+
config: {
|
|
1290
|
+
resource: "thread",
|
|
1291
|
+
operation: "delete"
|
|
1292
|
+
}
|
|
1293
|
+
},
|
|
1294
|
+
{
|
|
1295
|
+
label: "Add labels to a thread",
|
|
1296
|
+
config: {
|
|
1297
|
+
resource: "thread",
|
|
1298
|
+
operation: "addLabels"
|
|
1299
|
+
}
|
|
1300
|
+
},
|
|
1301
|
+
{
|
|
1302
|
+
label: "Remove labels from a thread",
|
|
1303
|
+
config: {
|
|
1304
|
+
resource: "thread",
|
|
1305
|
+
operation: "removeLabels"
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
],
|
|
1309
|
+
icon: "Mail",
|
|
1310
|
+
iconUrl: GMAIL_ICON,
|
|
1311
|
+
config: gmailConfig,
|
|
1312
|
+
defaultConfig: {
|
|
1313
|
+
authentication: "oAuth2",
|
|
1314
|
+
resource: "message",
|
|
1315
|
+
operation: "send",
|
|
1316
|
+
emailFormat: "html",
|
|
1317
|
+
replyAll: false,
|
|
1318
|
+
includeSpamTrash: false,
|
|
1319
|
+
limit: 20,
|
|
1320
|
+
simplify: true,
|
|
1321
|
+
downloadAttachments: false,
|
|
1322
|
+
labelListVisibility: "labelShow",
|
|
1323
|
+
messageListVisibility: "show",
|
|
1324
|
+
timeoutMs: 3e4
|
|
1325
|
+
},
|
|
1326
|
+
credentialTypes: [GMAIL_OAUTH2_CREDENTIAL, GMAIL_SERVICE_ACCOUNT_CREDENTIAL],
|
|
1327
|
+
credentialRules: {
|
|
1328
|
+
[GMAIL_OAUTH2_CREDENTIAL]: { showWhen: { authentication: ["oAuth2"] } },
|
|
1329
|
+
[GMAIL_SERVICE_ACCOUNT_CREDENTIAL]: { showWhen: { authentication: ["serviceAccount"] } }
|
|
1330
|
+
},
|
|
1331
|
+
ports: {
|
|
1332
|
+
in: ["in"],
|
|
1333
|
+
out: ["out"]
|
|
1334
|
+
},
|
|
1335
|
+
subtitle: (config) => typeof config.operation === "string" ? `${String(config.resource ?? "message")}: ${config.operation}` : void 0,
|
|
1336
|
+
async run({ config, input, credential, signal }) {
|
|
1337
|
+
const options = {
|
|
1338
|
+
signal,
|
|
1339
|
+
timeoutMs: config.timeoutMs
|
|
1340
|
+
};
|
|
1341
|
+
const token = await gmailToken(credential, options);
|
|
1342
|
+
const call = (request) => callGmail(token, request, options);
|
|
1343
|
+
const labelIds = () => resolveLabelIds(splitList(need(config.labelIds, "labelIds", config.operation)), async () => labelsOf(await call(listLabelsRequest())));
|
|
1344
|
+
const listOptions = async () => ({
|
|
1345
|
+
query: config.query,
|
|
1346
|
+
labelIds: config.labelIds ? await resolveLabelIds(splitList(config.labelIds), async () => labelsOf(await call(listLabelsRequest()))) : void 0,
|
|
1347
|
+
includeSpamTrash: config.includeSpamTrash
|
|
1348
|
+
});
|
|
1349
|
+
switch (config.resource) {
|
|
1350
|
+
case "message": return {
|
|
1351
|
+
port: "out",
|
|
1352
|
+
data: await runMessage(call, config, input, labelIds, listOptions)
|
|
1353
|
+
};
|
|
1354
|
+
case "draft": return {
|
|
1355
|
+
port: "out",
|
|
1356
|
+
data: await runDraft(call, config, input, listOptions)
|
|
1357
|
+
};
|
|
1358
|
+
case "label": return {
|
|
1359
|
+
port: "out",
|
|
1360
|
+
data: await runLabel(call, config)
|
|
1361
|
+
};
|
|
1362
|
+
case "thread": return {
|
|
1363
|
+
port: "out",
|
|
1364
|
+
data: await runThread(call, config, labelIds, listOptions)
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
});
|
|
1369
|
+
// src/trigger.ts
|
|
1370
|
+
const config = zod.z.object({
|
|
1371
|
+
authentication: zod.z.enum(AUTHENTICATION).default("oAuth2").meta({
|
|
1372
|
+
title: "Authentication",
|
|
1373
|
+
labels: {
|
|
1374
|
+
oAuth2: "OAuth2",
|
|
1375
|
+
serviceAccount: "Service Account"
|
|
1376
|
+
}
|
|
1377
|
+
}),
|
|
1378
|
+
intervalSeconds: zod.z.number().int().min(10).max(86400).default(60).meta({ title: "Check Every (Seconds)" }),
|
|
1379
|
+
query: zod.z.string().optional().meta({
|
|
1380
|
+
title: "Search",
|
|
1381
|
+
placeholder: "has:attachment subject:invoice",
|
|
1382
|
+
description: "A Gmail search. Only new mail that matches it starts a run"
|
|
1383
|
+
}),
|
|
1384
|
+
labelIds: zod.z.string().optional().meta({
|
|
1385
|
+
title: "Labels",
|
|
1386
|
+
placeholder: "INBOX, Invoices",
|
|
1387
|
+
description: "Label names or IDs, with commas between. Only mail with all of them starts a run"
|
|
1388
|
+
}),
|
|
1389
|
+
sender: zod.z.string().optional().meta({
|
|
1390
|
+
title: "Sender",
|
|
1391
|
+
placeholder: "ann@example.com",
|
|
1392
|
+
description: "Only mail from this sender starts a run"
|
|
1393
|
+
}),
|
|
1394
|
+
readStatus: zod.z.enum([
|
|
1395
|
+
"all",
|
|
1396
|
+
"unread",
|
|
1397
|
+
"read"
|
|
1398
|
+
]).default("unread").meta({
|
|
1399
|
+
title: "Read Status",
|
|
1400
|
+
labels: {
|
|
1401
|
+
all: "All",
|
|
1402
|
+
unread: "Unread",
|
|
1403
|
+
read: "Read"
|
|
1404
|
+
}
|
|
1405
|
+
}),
|
|
1406
|
+
includeSpamTrash: zod.z.boolean().default(false).meta({ title: "Include Spam and Trash" }),
|
|
1407
|
+
simplify: zod.z.boolean().default(true).meta({
|
|
1408
|
+
title: "Simplify",
|
|
1409
|
+
description: "Return subject, addresses, text, html, and a list of attachments. Off: the full answer of Gmail"
|
|
1410
|
+
}),
|
|
1411
|
+
downloadAttachments: zod.z.boolean().default(false).meta({
|
|
1412
|
+
title: "Download Attachments",
|
|
1413
|
+
description: "Add the files as binary data: attachment_0, attachment_1, and so on"
|
|
1414
|
+
}),
|
|
1415
|
+
postProcessAction: zod.z.enum(["nothing", "read"]).default("nothing").meta({
|
|
1416
|
+
title: "Action",
|
|
1417
|
+
description: "What to do with a mail after the run starts",
|
|
1418
|
+
labels: {
|
|
1419
|
+
nothing: "Nothing",
|
|
1420
|
+
read: "Mark as read"
|
|
1421
|
+
}
|
|
1422
|
+
}),
|
|
1423
|
+
maxPerPoll: zod.z.number().int().min(1).max(500).default(50).meta({
|
|
1424
|
+
title: "Most Mails per Check",
|
|
1425
|
+
description: "If more mails are new, the next check gets the others"
|
|
1426
|
+
}),
|
|
1427
|
+
timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
|
|
1428
|
+
});
|
|
1429
|
+
const isCursor = (value) => isObject(value) && typeof value.after === "number" && Array.isArray(value.ids) && value.ids.every((id) => typeof id === "string");
|
|
1430
|
+
/** Gmail finds mail by whole seconds. One second back, so that no mail is lost. */
|
|
1431
|
+
const searchFrom = (cursor) => Math.floor(cursor.after / 1e3) - 1;
|
|
1432
|
+
/** The new mails after the cursor, oldest first. `call` is the Gmail call of the poll. */
|
|
1433
|
+
async function newMails(call, cfg, cursor) {
|
|
1434
|
+
const filters = {
|
|
1435
|
+
query: cfg.query,
|
|
1436
|
+
sender: cfg.sender,
|
|
1437
|
+
readStatus: cfg.readStatus,
|
|
1438
|
+
after: searchFrom(cursor)
|
|
1439
|
+
};
|
|
1440
|
+
const labels = splitList(cfg.labelIds);
|
|
1441
|
+
const ids = await searchIds(call, {
|
|
1442
|
+
query: searchText(filters),
|
|
1443
|
+
labelIds: labels.length > 0 ? await resolveLabelIds(labels, async () => labelsOf(await call(listLabelsRequest()))) : void 0,
|
|
1444
|
+
includeSpamTrash: cfg.includeSpamTrash
|
|
1445
|
+
}, 1e3);
|
|
1446
|
+
const seen = new Set(cursor.ids);
|
|
1447
|
+
const found = [];
|
|
1448
|
+
for (const id of ids) {
|
|
1449
|
+
if (seen.has(id)) continue;
|
|
1450
|
+
const message = await call(getMessageRequest(id));
|
|
1451
|
+
const time = Date.parse(toMailItem(message).internalDate ?? "");
|
|
1452
|
+
if (!Number.isFinite(time) || time < cursor.after) continue;
|
|
1453
|
+
found.push({
|
|
1454
|
+
id,
|
|
1455
|
+
time,
|
|
1456
|
+
message
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
found.sort((a, b) => a.time - b.time);
|
|
1460
|
+
return found.slice(0, cfg.maxPerPoll);
|
|
1461
|
+
}
|
|
1462
|
+
/** The cursor after the mails in `sent`. The mails with the last time are kept by ID. */
|
|
1463
|
+
function nextCursor(cursor, sent) {
|
|
1464
|
+
const last = sent.at(-1);
|
|
1465
|
+
if (!last) return cursor;
|
|
1466
|
+
return {
|
|
1467
|
+
after: last.time,
|
|
1468
|
+
ids: sent.filter((mail) => mail.time === last.time).map((m) => m.id)
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
// src/index.ts
|
|
1472
|
+
const nodes = [node_default, (0, _zerodot_node_sdk.defineNode)({
|
|
1473
|
+
type: "gmail.trigger",
|
|
1474
|
+
label: "On new email (Gmail)",
|
|
1475
|
+
description: "Start a run when a new email matches a search or a label",
|
|
1476
|
+
category: "trigger",
|
|
1477
|
+
app: "Gmail",
|
|
1478
|
+
icon: "Mail",
|
|
1479
|
+
iconUrl: GMAIL_ICON,
|
|
1480
|
+
config,
|
|
1481
|
+
defaultConfig: {
|
|
1482
|
+
authentication: "oAuth2",
|
|
1483
|
+
intervalSeconds: 60,
|
|
1484
|
+
readStatus: "unread",
|
|
1485
|
+
includeSpamTrash: false,
|
|
1486
|
+
simplify: true,
|
|
1487
|
+
downloadAttachments: false,
|
|
1488
|
+
postProcessAction: "nothing",
|
|
1489
|
+
maxPerPoll: 50,
|
|
1490
|
+
timeoutMs: 3e4
|
|
1491
|
+
},
|
|
1492
|
+
credentialTypes: [GMAIL_OAUTH2_CREDENTIAL, GMAIL_SERVICE_ACCOUNT_CREDENTIAL],
|
|
1493
|
+
credentialRules: {
|
|
1494
|
+
[GMAIL_OAUTH2_CREDENTIAL]: { showWhen: { authentication: ["oAuth2"] } },
|
|
1495
|
+
[GMAIL_SERVICE_ACCOUNT_CREDENTIAL]: { showWhen: { authentication: ["serviceAccount"] } }
|
|
1496
|
+
},
|
|
1497
|
+
ports: {
|
|
1498
|
+
in: [],
|
|
1499
|
+
out: ["out"]
|
|
1500
|
+
},
|
|
1501
|
+
subtitle: (cfg) => typeof cfg.query === "string" && cfg.query !== "" ? cfg.query : void 0,
|
|
1502
|
+
run: ({ input }) => ({
|
|
1503
|
+
port: "out",
|
|
1504
|
+
data: input
|
|
1505
|
+
}),
|
|
1506
|
+
async poll({ config: cfg, credential, cursor, firstPoll, signal }) {
|
|
1507
|
+
const now = Date.now();
|
|
1508
|
+
if (firstPoll || !isCursor(cursor)) return {
|
|
1509
|
+
items: [],
|
|
1510
|
+
cursor: {
|
|
1511
|
+
after: now,
|
|
1512
|
+
ids: []
|
|
1513
|
+
}
|
|
1514
|
+
};
|
|
1515
|
+
const options = {
|
|
1516
|
+
signal,
|
|
1517
|
+
timeoutMs: cfg.timeoutMs
|
|
1518
|
+
};
|
|
1519
|
+
const token = await gmailToken(credential, options);
|
|
1520
|
+
const call = (request) => callGmail(token, request, options);
|
|
1521
|
+
const mails = await newMails(call, cfg, cursor);
|
|
1522
|
+
const items = [];
|
|
1523
|
+
for (const mail of mails) {
|
|
1524
|
+
const data = await shapeMessage(call, mail.message, cfg.simplify, cfg.downloadAttachments);
|
|
1525
|
+
items.push({
|
|
1526
|
+
key: mail.id,
|
|
1527
|
+
data
|
|
1528
|
+
});
|
|
1529
|
+
if (cfg.postProcessAction === "read") await call(modifyMessageRequest(mail.id, [], ["UNREAD"]));
|
|
1530
|
+
}
|
|
1531
|
+
return {
|
|
1532
|
+
items,
|
|
1533
|
+
cursor: nextCursor(cursor, mails)
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
})];
|
|
1537
|
+
const credentialTypes = [gmailOAuth2Credential, gmailServiceAccountCredential];
|
|
1538
|
+
exports.credentialTypes = credentialTypes;
|
|
1539
|
+
exports.nodes = nodes;
|