@nodetool-ai/integration-nodes 0.8.10 → 0.8.16

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 (50) hide show
  1. package/README.md +53 -9
  2. package/dist/.nodetool-build-stamp +1 -1
  3. package/dist/index.d.ts +5 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +11 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/nodes/comfy-graph-cloud.d.ts +113 -0
  8. package/dist/nodes/comfy-graph-cloud.d.ts.map +1 -0
  9. package/dist/nodes/comfy-graph-cloud.js +578 -0
  10. package/dist/nodes/comfy-graph-cloud.js.map +1 -0
  11. package/dist/nodes/comfy-sdk.d.ts +30 -1
  12. package/dist/nodes/comfy-sdk.d.ts.map +1 -1
  13. package/dist/nodes/comfy-sdk.js +143 -32
  14. package/dist/nodes/comfy-sdk.js.map +1 -1
  15. package/dist/nodes/comfy-server-status.d.ts +31 -0
  16. package/dist/nodes/comfy-server-status.d.ts.map +1 -0
  17. package/dist/nodes/comfy-server-status.js +65 -0
  18. package/dist/nodes/comfy-server-status.js.map +1 -0
  19. package/dist/nodes/comfy-server-transport.d.ts +32 -0
  20. package/dist/nodes/comfy-server-transport.d.ts.map +1 -0
  21. package/dist/nodes/comfy-server-transport.js +177 -0
  22. package/dist/nodes/comfy-server-transport.js.map +1 -0
  23. package/dist/nodes/comfy-target.d.ts +26 -0
  24. package/dist/nodes/comfy-target.d.ts.map +1 -0
  25. package/dist/nodes/comfy-target.js +61 -0
  26. package/dist/nodes/comfy-target.js.map +1 -0
  27. package/dist/nodes/comfy-worker-transport.d.ts +16 -0
  28. package/dist/nodes/comfy-worker-transport.d.ts.map +1 -0
  29. package/dist/nodes/comfy-worker-transport.js +153 -0
  30. package/dist/nodes/comfy-worker-transport.js.map +1 -0
  31. package/dist/nodes/comfy.d.ts +3 -8
  32. package/dist/nodes/comfy.d.ts.map +1 -1
  33. package/dist/nodes/comfy.js +5 -72
  34. package/dist/nodes/comfy.js.map +1 -1
  35. package/dist/nodes/kie-dynamic.d.ts.map +1 -1
  36. package/dist/nodes/kie-dynamic.js +13 -10
  37. package/dist/nodes/kie-dynamic.js.map +1 -1
  38. package/dist/nodes/lib-mail.d.ts +202 -0
  39. package/dist/nodes/lib-mail.d.ts.map +1 -0
  40. package/dist/nodes/lib-mail.js +889 -0
  41. package/dist/nodes/lib-mail.js.map +1 -0
  42. package/dist/nodes/mcp-tool.d.ts +64 -0
  43. package/dist/nodes/mcp-tool.d.ts.map +1 -0
  44. package/dist/nodes/mcp-tool.js +159 -0
  45. package/dist/nodes/mcp-tool.js.map +1 -0
  46. package/dist/nodes/wan2gp.d.ts +141 -0
  47. package/dist/nodes/wan2gp.d.ts.map +1 -0
  48. package/dist/nodes/wan2gp.js +505 -0
  49. package/dist/nodes/wan2gp.js.map +1 -0
  50. package/package.json +10 -6
@@ -0,0 +1,889 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseNode, prop } from "@nodetool-ai/node-sdk";
8
+ import { tagAsServer } from "@nodetool-ai/nodes-utils";
9
+ const GMAIL_IMAP_HOST = "imap.gmail.com";
10
+ const GMAIL_IMAP_PORT = 993;
11
+ const ALL_MAIL_FOLDER = "[Gmail]/All Mail";
12
+ const GMAIL_SMTP_HOST = "smtp.gmail.com";
13
+ const GMAIL_SMTP_PORT = 465;
14
+ /** Longest body, in characters, a search result carries. */
15
+ const MAX_BODY_CHARS = 10_000;
16
+ const MISSING_CREDENTIALS = "GOOGLE_MAIL_USER and GOOGLE_APP_PASSWORD must be configured in settings.";
17
+ /**
18
+ * Create an ImapFlow client connected to Gmail using an app password.
19
+ *
20
+ * `imapflow` loads here, not at module scope, so a run that never touches mail
21
+ * never loads an IMAP client.
22
+ */
23
+ async function createImapClient(user, appPassword) {
24
+ const { ImapFlow } = await import("imapflow");
25
+ const client = new ImapFlow({
26
+ host: GMAIL_IMAP_HOST,
27
+ port: GMAIL_IMAP_PORT,
28
+ secure: true,
29
+ auth: { user, pass: appPassword },
30
+ logger: false
31
+ });
32
+ // ImapFlow is an EventEmitter. A socket error with no "error" listener is
33
+ // thrown as an uncaught exception and takes the server process down. The same
34
+ // failure also rejects the command in flight, which is where the node reports
35
+ // it, so the listener only has to exist.
36
+ client.on("error", () => { });
37
+ await client.connect();
38
+ return client;
39
+ }
40
+ /**
41
+ * Run `work` on a connected client and always log out. A logout that fails must
42
+ * not replace the error `work` threw.
43
+ */
44
+ async function withImapClient(secrets, work) {
45
+ const user = secrets["GOOGLE_MAIL_USER"];
46
+ const pass = secrets["GOOGLE_APP_PASSWORD"];
47
+ if (!user || !pass) {
48
+ throw new Error(MISSING_CREDENTIALS);
49
+ }
50
+ const client = await createImapClient(user, pass);
51
+ try {
52
+ return await work(client);
53
+ }
54
+ finally {
55
+ await client.logout().catch(() => {
56
+ /* Intentional: best-effort logout during cleanup */
57
+ });
58
+ }
59
+ }
60
+ /** IMAP special-use role of each Gmail system folder the nodes offer. */
61
+ const SPECIAL_USE_BY_FOLDER = {
62
+ "[Gmail]/Sent Mail": "\\Sent",
63
+ "[Gmail]/Drafts": "\\Drafts",
64
+ "[Gmail]/Spam": "\\Junk",
65
+ "[Gmail]/Trash": "\\Trash",
66
+ [ALL_MAIL_FOLDER]: "\\All"
67
+ };
68
+ /**
69
+ * The path of a Gmail system folder on this account. Gmail names these folders
70
+ * in the account's language ("[Gmail]/Gesendet"), and some regions use
71
+ * "[Google Mail]" in place of "[Gmail]", so the English path only exists on
72
+ * some accounts. The special-use role is the same everywhere. A folder with no
73
+ * role, such as INBOX, or an account that does not list the role, keeps the
74
+ * path it was given.
75
+ */
76
+ async function resolveFolder(client, folder) {
77
+ const specialUse = SPECIAL_USE_BY_FOLDER[folder];
78
+ if (!specialUse)
79
+ return folder;
80
+ const mailboxes = await client.list();
81
+ return mailboxes.find((m) => m.specialUse === specialUse)?.path ?? folder;
82
+ }
83
+ /** Run `work` with `folder` selected, releasing the mailbox lock afterwards. */
84
+ async function inMailbox(client, folder, work) {
85
+ const lock = await client.getMailboxLock(folder);
86
+ try {
87
+ return await work();
88
+ }
89
+ finally {
90
+ lock.release();
91
+ }
92
+ }
93
+ /**
94
+ * UIDs of the messages whose Message-ID header matches, in the mailbox that is
95
+ * open. IMAP numbers messages by position, and the position moves when mail
96
+ * arrives or is expunged, so every follow-up command takes UIDs.
97
+ */
98
+ async function findUidsByMessageId(client, messageId) {
99
+ const found = await client.search({ header: { "message-id": messageId } }, { uid: true });
100
+ if (!found || found.length === 0) {
101
+ throw new Error(`Message not found: ${messageId}`);
102
+ }
103
+ return found;
104
+ }
105
+ /**
106
+ * Compute a date threshold from a named filter.
107
+ */
108
+ function dateThreshold(filter) {
109
+ const now = new Date();
110
+ switch (filter) {
111
+ case "SINCE_ONE_HOUR":
112
+ return new Date(now.getTime() - 60 * 60 * 1000);
113
+ case "SINCE_ONE_DAY":
114
+ return new Date(now.getTime() - 24 * 60 * 60 * 1000);
115
+ case "SINCE_ONE_WEEK":
116
+ return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
117
+ case "SINCE_ONE_MONTH":
118
+ return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
119
+ case "SINCE_ONE_YEAR":
120
+ return new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
121
+ default:
122
+ return new Date(now.getTime() - 24 * 60 * 60 * 1000);
123
+ }
124
+ }
125
+ /**
126
+ * A date ImapFlow returned (the `Date` header or the arrival time) as a `Date`,
127
+ * or `undefined` when it is missing or invalid. ImapFlow returns the raw header
128
+ * string when a date does not parse, and a message with a broken `Date` header
129
+ * is still mail the workflow should see.
130
+ */
131
+ function envelopeDate(value) {
132
+ if (!value)
133
+ return undefined;
134
+ const date = value instanceof Date ? value : new Date(value);
135
+ return Number.isNaN(date.getTime()) ? undefined : date;
136
+ }
137
+ /** The email dict `GmailSearch` and `EmailTrigger` both emit. */
138
+ async function emailFromMessage(msg, sent) {
139
+ const envelope = msg.envelope || {};
140
+ return {
141
+ subject: envelope.subject ?? "",
142
+ from: envelope.from?.[0]?.address ?? "",
143
+ to: envelope.to?.map((a) => a.address).join(", ") ?? "",
144
+ date: sent?.toISOString() ?? "",
145
+ message_id: envelope.messageId ?? "",
146
+ body: msg.source ? await bodyText(msg.source) : ""
147
+ };
148
+ }
149
+ /**
150
+ * Readable text of a raw message. Real mail is multipart, quoted-printable or
151
+ * base64, so the bytes after the header block are not text. `mailparser`
152
+ * decodes the MIME structure and turns an HTML-only message into text.
153
+ */
154
+ async function bodyText(source) {
155
+ const { simpleParser } = await import("mailparser");
156
+ const parsed = await simpleParser(source);
157
+ return (parsed.text ?? "").trim().slice(0, MAX_BODY_CHARS);
158
+ }
159
+ export class GmailSearchLibNode extends BaseNode {
160
+ static nodeType = "lib.mail.GmailSearch";
161
+ static title = "Gmail Search";
162
+ static description = "Searches a Gmail mailbox over IMAP by sender, recipient, subject, body, keyword and date, and yields the matching emails newest first. Each field is a plain filter. Gmail search operators such as from: or is:unread are not supported.\n email, gmail, search\n\n Use cases:\n - Search for emails based on specific criteria\n - Retrieve emails from a specific sender\n - Filter emails by subject, sender, or date";
163
+ static metadataOutputTypes = {
164
+ email: "dict",
165
+ message_id: "str",
166
+ subject: "str",
167
+ sender: "str",
168
+ date: "str",
169
+ body: "str",
170
+ emails: "list",
171
+ message_ids: "list"
172
+ };
173
+ static inlineFields = ["from_address", "subject"];
174
+ static inputFields = ["text"];
175
+ static requiredSettings = [
176
+ "GOOGLE_MAIL_USER",
177
+ "GOOGLE_APP_PASSWORD"
178
+ ];
179
+ static inputMode = "buffered";
180
+ static outputCorrelation = {
181
+ email: { kind: "iteration", source: "__execution__", group: "items" },
182
+ message_id: { kind: "iteration", source: "__execution__", group: "items" },
183
+ subject: { kind: "iteration", source: "__execution__", group: "items" },
184
+ sender: { kind: "iteration", source: "__execution__", group: "items" },
185
+ date: { kind: "iteration", source: "__execution__", group: "items" },
186
+ body: { kind: "iteration", source: "__execution__", group: "items" },
187
+ emails: { kind: "single", source: "__execution__" },
188
+ message_ids: { kind: "single", source: "__execution__" }
189
+ };
190
+ async _fetchEmails() {
191
+ return withImapClient(this._secrets, async (client) => {
192
+ const threshold = dateThreshold(String(this.date_filter ?? "SINCE_ONE_DAY"));
193
+ // IMAP's SINCE compares calendar days, so the server returns the whole
194
+ // day even for "since one hour". The threshold is applied again to each
195
+ // message's arrival time below, the clock SINCE itself uses. A sender's
196
+ // Date header can be hours or days off for mail that sat in a queue.
197
+ const query = { since: threshold };
198
+ const from = String(this.from_address ?? "");
199
+ if (from)
200
+ query.from = from;
201
+ const to = String(this.to_address ?? "");
202
+ if (to)
203
+ query.to = to;
204
+ const subject = String(this.subject ?? "");
205
+ if (subject)
206
+ query.subject = subject;
207
+ const body = String(this.body ?? "");
208
+ if (body)
209
+ query.body = body;
210
+ const text = String(this.text ?? "");
211
+ if (text)
212
+ query.text = text;
213
+ // Gmail shows its labels as folders, not as IMAP keyword flags, so a
214
+ // `keyword` search never matches one. `labels` is Gmail's own criterion.
215
+ const labels = String(this.keywords ?? "")
216
+ .split(",")
217
+ .map((label) => label.trim())
218
+ .filter(Boolean);
219
+ if (labels.length > 0)
220
+ query.labels = { has: labels };
221
+ const maxResults = Math.max(1, Number(this.max_results ?? 50));
222
+ const folder = await resolveFolder(client, String(this.folder ?? "INBOX"));
223
+ return inMailbox(client, folder, async () => {
224
+ const uids = (await client.search(query, { uid: true })) || [];
225
+ if (uids.length === 0)
226
+ return [];
227
+ // UIDs grow with arrival, so the newest mail has the highest UIDs. Take
228
+ // them before fetching, otherwise a busy mailbox returns the oldest
229
+ // `max_results` matches and drops the mail the workflow is after.
230
+ const newest = [...uids].sort((a, b) => b - a).slice(0, maxResults);
231
+ const fetched = new Map();
232
+ for await (const msg of client.fetch(newest.join(","), { envelope: true, source: true, uid: true, internalDate: true }, { uid: true })) {
233
+ const envelope = msg.envelope || {};
234
+ const sent = envelopeDate(envelope.date);
235
+ const arrived = envelopeDate(msg.internalDate) ?? sent;
236
+ if (arrived && arrived < threshold)
237
+ continue;
238
+ fetched.set(msg.uid, {
239
+ email: await emailFromMessage(msg, sent),
240
+ message_id: String(envelope.messageId ?? "")
241
+ });
242
+ }
243
+ // The server answers in ascending UID order whatever order was asked.
244
+ return newest
245
+ .map((uid) => fetched.get(uid))
246
+ .filter((item) => item !== undefined);
247
+ });
248
+ });
249
+ }
250
+ async *genProcess() {
251
+ const results = await this._fetchEmails();
252
+ // Stream individual emails with the email dict plus its decomposed fields
253
+ // so downstream nodes can wire to subject/sender/body/date directly without
254
+ // an EmailFields step.
255
+ for (const item of results) {
256
+ yield {
257
+ email: item.email,
258
+ message_id: item.message_id,
259
+ subject: String(item.email.subject ?? ""),
260
+ sender: String(item.email.from ?? ""),
261
+ date: String(item.email.date ?? ""),
262
+ body: String(item.email.body ?? "")
263
+ };
264
+ }
265
+ // Emit collected lists as final output
266
+ yield {
267
+ emails: results.map((r) => r.email),
268
+ message_ids: results.map((r) => r.message_id)
269
+ };
270
+ }
271
+ async process() {
272
+ const results = await this._fetchEmails();
273
+ const first = results[0]?.email ?? {};
274
+ return {
275
+ email: first,
276
+ message_id: results[0]?.message_id ?? "",
277
+ subject: String(first.subject ?? ""),
278
+ sender: String(first.from ?? ""),
279
+ date: String(first.date ?? ""),
280
+ body: String(first.body ?? ""),
281
+ emails: results.map((r) => r.email),
282
+ message_ids: results.map((r) => r.message_id)
283
+ };
284
+ }
285
+ }
286
+ __decorate([
287
+ prop({
288
+ type: "str",
289
+ default: "",
290
+ title: "From Address",
291
+ description: "Sender's email address to search for"
292
+ })
293
+ ], GmailSearchLibNode.prototype, "from_address", void 0);
294
+ __decorate([
295
+ prop({
296
+ type: "str",
297
+ default: "",
298
+ title: "To Address",
299
+ description: "Recipient's email address to search for"
300
+ })
301
+ ], GmailSearchLibNode.prototype, "to_address", void 0);
302
+ __decorate([
303
+ prop({
304
+ type: "str",
305
+ default: "",
306
+ title: "Subject",
307
+ description: "Text to search for in email subject"
308
+ })
309
+ ], GmailSearchLibNode.prototype, "subject", void 0);
310
+ __decorate([
311
+ prop({
312
+ type: "str",
313
+ default: "",
314
+ title: "Body",
315
+ description: "Text to search for in email body"
316
+ })
317
+ ], GmailSearchLibNode.prototype, "body", void 0);
318
+ __decorate([
319
+ prop({
320
+ type: "enum",
321
+ default: "SINCE_ONE_DAY",
322
+ title: "Date Filter",
323
+ description: "Date filter to search for",
324
+ values: [
325
+ "SINCE_ONE_HOUR",
326
+ "SINCE_ONE_DAY",
327
+ "SINCE_ONE_WEEK",
328
+ "SINCE_ONE_MONTH",
329
+ "SINCE_ONE_YEAR"
330
+ ]
331
+ })
332
+ ], GmailSearchLibNode.prototype, "date_filter", void 0);
333
+ __decorate([
334
+ prop({
335
+ type: "str",
336
+ default: "",
337
+ title: "Keywords",
338
+ description: "Custom keywords or labels to search for"
339
+ })
340
+ ], GmailSearchLibNode.prototype, "keywords", void 0);
341
+ __decorate([
342
+ prop({
343
+ type: "enum",
344
+ default: "INBOX",
345
+ title: "Folder",
346
+ description: "Email folder to search in",
347
+ values: [
348
+ "INBOX",
349
+ "[Gmail]/Sent Mail",
350
+ "[Gmail]/Drafts",
351
+ "[Gmail]/Spam",
352
+ "[Gmail]/Trash"
353
+ ]
354
+ })
355
+ ], GmailSearchLibNode.prototype, "folder", void 0);
356
+ __decorate([
357
+ prop({
358
+ type: "str",
359
+ default: "",
360
+ title: "Text",
361
+ description: "General text to search for anywhere in the email"
362
+ })
363
+ ], GmailSearchLibNode.prototype, "text", void 0);
364
+ __decorate([
365
+ prop({
366
+ type: "int",
367
+ default: 50,
368
+ title: "Max Results",
369
+ description: "Maximum number of emails to return, newest first"
370
+ })
371
+ ], GmailSearchLibNode.prototype, "max_results", void 0);
372
+ export class AddLabelLibNode extends BaseNode {
373
+ static nodeType = "lib.mail.AddLabel";
374
+ static title = "Add Label";
375
+ static description = "Adds a label to a Gmail message.\n email, gmail, label";
376
+ static metadataOutputTypes = {
377
+ output: "bool"
378
+ };
379
+ static inlineFields = ["message_id", "label"];
380
+ static inputFields = [];
381
+ static requiredSettings = [
382
+ "GOOGLE_MAIL_USER",
383
+ "GOOGLE_APP_PASSWORD"
384
+ ];
385
+ async process() {
386
+ const messageId = String(this.message_id ?? "");
387
+ const label = String(this.label ?? "");
388
+ if (!messageId)
389
+ throw new Error("Message ID is required");
390
+ if (!label)
391
+ throw new Error("Label is required");
392
+ return withImapClient(this._secrets, (client) => inMailbox(client, "INBOX", async () => {
393
+ const uids = await findUidsByMessageId(client, messageId);
394
+ // Gmail shows a label as an IMAP folder. Copying the message into the
395
+ // folder applies the label and leaves the message in the inbox.
396
+ const copied = await client.messageCopy(uids, label, { uid: true });
397
+ return { output: Boolean(copied) };
398
+ }));
399
+ }
400
+ }
401
+ __decorate([
402
+ prop({
403
+ type: "str",
404
+ default: "",
405
+ title: "Message Id",
406
+ description: "Message ID to label"
407
+ })
408
+ ], AddLabelLibNode.prototype, "message_id", void 0);
409
+ __decorate([
410
+ prop({
411
+ type: "str",
412
+ default: "",
413
+ title: "Label",
414
+ description: "Label to add to the message"
415
+ })
416
+ ], AddLabelLibNode.prototype, "label", void 0);
417
+ export class MoveToArchiveLibNode extends BaseNode {
418
+ static nodeType = "lib.mail.MoveToArchive";
419
+ static title = "Move To Archive";
420
+ static description = "Moves specified emails to Gmail archive.\n email, gmail, archive";
421
+ static metadataOutputTypes = {
422
+ output: "bool"
423
+ };
424
+ static inlineFields = ["message_id"];
425
+ static inputFields = [];
426
+ static requiredSettings = [
427
+ "GOOGLE_MAIL_USER",
428
+ "GOOGLE_APP_PASSWORD"
429
+ ];
430
+ async process() {
431
+ const messageId = String(this.message_id ?? "");
432
+ if (!messageId)
433
+ throw new Error("Message ID is required");
434
+ return withImapClient(this._secrets, async (client) => {
435
+ const allMail = await resolveFolder(client, ALL_MAIL_FOLDER);
436
+ return inMailbox(client, "INBOX", async () => {
437
+ const uids = await findUidsByMessageId(client, messageId);
438
+ // In Gmail, archiving is leaving the inbox: moving the message to All
439
+ // Mail drops the Inbox label. messageMove resolves to false when the
440
+ // server did not move anything.
441
+ const moved = await client.messageMove(uids, allMail, { uid: true });
442
+ return { output: Boolean(moved) };
443
+ });
444
+ });
445
+ }
446
+ }
447
+ __decorate([
448
+ prop({
449
+ type: "str",
450
+ default: "",
451
+ title: "Message Id",
452
+ description: "Message ID to archive"
453
+ })
454
+ ], MoveToArchiveLibNode.prototype, "message_id", void 0);
455
+ // ---------------------------------------------------------------------------
456
+ // SendEmail
457
+ // ---------------------------------------------------------------------------
458
+ /** Most recipients (to, cc and bcc together) one message may name. */
459
+ const MAX_RECIPIENTS = 100;
460
+ /**
461
+ * A plain `local@domain.tld` address. Display names, quoted local parts and
462
+ * comments are not accepted: each of them is a way to smuggle extra syntax
463
+ * into a header, and a workflow that wants to mail "Ada <ada@example.com>" can
464
+ * pass the bare address.
465
+ */
466
+ const ADDRESS_PATTERN = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
467
+ /**
468
+ * A header value must stay on one line. A CR or LF inside a subject or an
469
+ * address would end the header and start a new one (`Bcc:`, `Content-Type:`),
470
+ * so such a value is refused outright instead of being cleaned up.
471
+ */
472
+ function assertSingleLine(label, value) {
473
+ if (/[\r\n\0]/.test(value)) {
474
+ throw new Error(`${label} must not contain line breaks`);
475
+ }
476
+ }
477
+ /**
478
+ * The addresses in a comma or semicolon separated list. Every entry must be a
479
+ * plain address. An empty list is valid and returns no entries.
480
+ */
481
+ function parseRecipients(label, value) {
482
+ const raw = String(value ?? "");
483
+ assertSingleLine(label, raw);
484
+ const addresses = [];
485
+ for (const part of raw.split(/[,;]/)) {
486
+ const address = part.trim();
487
+ if (!address)
488
+ continue;
489
+ if (address.length > 254 || !ADDRESS_PATTERN.test(address)) {
490
+ throw new Error(`${label} has an invalid email address: ${address.slice(0, 80)}`);
491
+ }
492
+ addresses.push(address);
493
+ }
494
+ return addresses;
495
+ }
496
+ export class SendEmailLibNode extends BaseNode {
497
+ static nodeType = "lib.mail.SendEmail";
498
+ static title = "Send Email";
499
+ static description = "Sends an email from a Gmail account over SMTP with a Google app password. Recipients are plain addresses separated by commas. Attachments are not supported.\n email, gmail, send, smtp, mail";
500
+ static metadataOutputTypes = {
501
+ message_id: "str",
502
+ accepted: "list[str]",
503
+ rejected: "list[str]"
504
+ };
505
+ static inlineFields = ["to", "subject"];
506
+ static inputFields = ["text"];
507
+ static requiredSettings = [
508
+ "GOOGLE_MAIL_USER",
509
+ "GOOGLE_APP_PASSWORD"
510
+ ];
511
+ // Sending mail leaves the system and cannot be undone, so a reactive run
512
+ // never fires it without an explicit action. Retrying a send that failed
513
+ // halfway could deliver the message twice, so it is not retry safe either.
514
+ static effect = "external";
515
+ async process() {
516
+ const user = this._secrets["GOOGLE_MAIL_USER"];
517
+ const pass = this._secrets["GOOGLE_APP_PASSWORD"];
518
+ if (!user || !pass) {
519
+ throw new Error(MISSING_CREDENTIALS);
520
+ }
521
+ const to = parseRecipients("To", this.to);
522
+ const cc = parseRecipients("Cc", this.cc);
523
+ const bcc = parseRecipients("Bcc", this.bcc);
524
+ if (to.length + cc.length + bcc.length === 0) {
525
+ throw new Error("At least one recipient is required");
526
+ }
527
+ if (to.length + cc.length + bcc.length > MAX_RECIPIENTS) {
528
+ throw new Error(`A message may have at most ${MAX_RECIPIENTS} recipients`);
529
+ }
530
+ const subject = String(this.subject ?? "");
531
+ assertSingleLine("Subject", subject);
532
+ const text = String(this.text ?? "");
533
+ const html = String(this.html ?? "");
534
+ if (!text && !html) {
535
+ throw new Error("Text or Html body is required");
536
+ }
537
+ // The sender comes from settings, not from the workflow, and goes into the
538
+ // From header, so it is held to the same rule as the recipients.
539
+ if (parseRecipients("GOOGLE_MAIL_USER", user).length !== 1) {
540
+ throw new Error("GOOGLE_MAIL_USER must be one email address");
541
+ }
542
+ // `nodemailer` loads here, not at module scope, so a run that never sends
543
+ // mail never loads an SMTP client.
544
+ const { createTransport } = await import("nodemailer");
545
+ const transport = createTransport({
546
+ host: GMAIL_SMTP_HOST,
547
+ port: GMAIL_SMTP_PORT,
548
+ secure: true,
549
+ auth: { user, pass },
550
+ // A mail server that stops answering must not hold the run forever.
551
+ connectionTimeout: 15_000,
552
+ greetingTimeout: 15_000,
553
+ socketTimeout: 30_000
554
+ });
555
+ try {
556
+ const info = await transport.sendMail({
557
+ from: user,
558
+ to,
559
+ cc,
560
+ bcc,
561
+ subject,
562
+ text: text || undefined,
563
+ html: html || undefined
564
+ });
565
+ return {
566
+ message_id: String(info.messageId ?? ""),
567
+ accepted: (info.accepted ?? []).map(String),
568
+ rejected: (info.rejected ?? []).map(String)
569
+ };
570
+ }
571
+ catch (error) {
572
+ const reason = error instanceof Error ? error.message : String(error);
573
+ throw new Error(`Sending the email failed: ${reason}`);
574
+ }
575
+ finally {
576
+ transport.close();
577
+ }
578
+ }
579
+ }
580
+ __decorate([
581
+ prop({
582
+ type: "str",
583
+ default: "",
584
+ title: "To",
585
+ description: "Recipient email addresses, separated by commas"
586
+ })
587
+ ], SendEmailLibNode.prototype, "to", void 0);
588
+ __decorate([
589
+ prop({
590
+ type: "str",
591
+ default: "",
592
+ title: "Cc",
593
+ description: "Cc email addresses, separated by commas"
594
+ })
595
+ ], SendEmailLibNode.prototype, "cc", void 0);
596
+ __decorate([
597
+ prop({
598
+ type: "str",
599
+ default: "",
600
+ title: "Bcc",
601
+ description: "Bcc email addresses, separated by commas"
602
+ })
603
+ ], SendEmailLibNode.prototype, "bcc", void 0);
604
+ __decorate([
605
+ prop({
606
+ type: "str",
607
+ default: "",
608
+ title: "Subject",
609
+ description: "Subject line. It must be a single line."
610
+ })
611
+ ], SendEmailLibNode.prototype, "subject", void 0);
612
+ __decorate([
613
+ prop({
614
+ type: "str",
615
+ default: "",
616
+ title: "Text",
617
+ description: "Plain text body"
618
+ })
619
+ ], SendEmailLibNode.prototype, "text", void 0);
620
+ __decorate([
621
+ prop({
622
+ type: "str",
623
+ default: "",
624
+ title: "Html",
625
+ description: "Optional HTML body. Mail clients that show HTML use it, the others use the text body."
626
+ })
627
+ ], SendEmailLibNode.prototype, "html", void 0);
628
+ // ---------------------------------------------------------------------------
629
+ // EmailTrigger
630
+ // ---------------------------------------------------------------------------
631
+ /** Most messages one poll starts a run for. Mail beyond it is picked up by the next poll. */
632
+ const MAX_MESSAGES_PER_POLL = 100;
633
+ const DEFAULT_MESSAGES_PER_POLL = 10;
634
+ /** Gmail throttles IMAP logins, so a poll more often than this is refused. */
635
+ const MIN_POLL_SECONDS = 30;
636
+ function encodeCursor(cursor) {
637
+ return JSON.stringify(cursor);
638
+ }
639
+ function decodeCursor(raw) {
640
+ if (!raw)
641
+ return null;
642
+ try {
643
+ const parsed = JSON.parse(raw);
644
+ if (parsed !== null &&
645
+ typeof parsed === "object" &&
646
+ parsed.v === 1 &&
647
+ typeof parsed.uidValidity === "string" &&
648
+ Number.isInteger(parsed.lastUid) &&
649
+ parsed.lastUid >= 0) {
650
+ return parsed;
651
+ }
652
+ }
653
+ catch {
654
+ /* Intentional: a cursor that does not parse is treated as no cursor */
655
+ }
656
+ return null;
657
+ }
658
+ function emailEvent(email) {
659
+ return {
660
+ email,
661
+ message_id: String(email.message_id ?? ""),
662
+ subject: String(email.subject ?? ""),
663
+ sender: String(email.from ?? ""),
664
+ date: String(email.date ?? ""),
665
+ body: String(email.body ?? ""),
666
+ source: "email",
667
+ event_type: "new_mail"
668
+ };
669
+ }
670
+ export class EmailTriggerLibNode extends BaseNode {
671
+ static nodeType = "lib.mail.EmailTrigger";
672
+ static title = "Email Trigger";
673
+ static description = "Starts a workflow in the background when new mail arrives in a Gmail folder. The server checks the folder over IMAP on a schedule and starts one run for each new message. Mail that is already there when the trigger is turned on does not start a run.\n trigger, email, gmail, imap, mail, inbox, new mail";
674
+ static metadataOutputTypes = {
675
+ email: "dict",
676
+ message_id: "str",
677
+ subject: "str",
678
+ sender: "str",
679
+ date: "str",
680
+ body: "str",
681
+ source: "str",
682
+ event_type: "str"
683
+ };
684
+ static inlineFields = ["interval_seconds", "from_address"];
685
+ static inputFields = [];
686
+ static requiredSettings = [
687
+ "GOOGLE_MAIL_USER",
688
+ "GOOGLE_APP_PASSWORD"
689
+ ];
690
+ static isTrigger = true;
691
+ async process() {
692
+ return {};
693
+ }
694
+ /**
695
+ * Wake-up entry point. The poller below hands each new message to the run as
696
+ * the event payload.
697
+ */
698
+ async emitTriggerEvent(event, outputs) {
699
+ const payload = event.payload;
700
+ // A bare tick from a host without the poller carries no mail, and a run
701
+ // with empty mail outputs would only confuse the workflow.
702
+ if (payload === null ||
703
+ typeof payload !== "object" ||
704
+ payload.source !== "email") {
705
+ return;
706
+ }
707
+ const email = payload.email;
708
+ if (email === null || typeof email !== "object")
709
+ return;
710
+ for (const [key, value] of Object.entries(emailEvent(email))) {
711
+ await outputs.emit(key, value);
712
+ }
713
+ }
714
+ /** The search filters this node's properties describe. */
715
+ _filters() {
716
+ const query = {};
717
+ const from = String(this.from_address ?? "").trim();
718
+ if (from)
719
+ query.from = from;
720
+ const subject = String(this.subject ?? "").trim();
721
+ if (subject)
722
+ query.subject = subject;
723
+ return query;
724
+ }
725
+ _limit() {
726
+ const value = Math.floor(Number(this.max_messages));
727
+ if (!Number.isFinite(value))
728
+ return DEFAULT_MESSAGES_PER_POLL;
729
+ return Math.min(MAX_MESSAGES_PER_POLL, Math.max(1, value));
730
+ }
731
+ static pollTrigger = (input) => EmailTriggerLibNode.poll(input);
732
+ /**
733
+ * One check of the folder, called by the host each time the registration's
734
+ * schedule is due.
735
+ *
736
+ * The cursor is the highest UID the trigger has seen, with the folder's
737
+ * UIDVALIDITY. UIDs only grow in a folder, so "UID above the cursor" is the
738
+ * set of new messages, and a restart that reloads the cursor neither starts
739
+ * a run for old mail nor skips new mail.
740
+ *
741
+ * The first check has no cursor. It records where the folder ends and starts
742
+ * no run, so turning the trigger on does not run the workflow once per
743
+ * message already in the folder.
744
+ */
745
+ static async poll(input) {
746
+ const node = new EmailTriggerLibNode(input.properties);
747
+ const filters = node._filters();
748
+ const limit = node._limit();
749
+ const previous = decodeCursor(input.cursor);
750
+ return withImapClient(input.secrets, async (client) => {
751
+ const folder = await resolveFolder(client, String(node.folder ?? "INBOX"));
752
+ return inMailbox(client, folder, async () => {
753
+ const box = client.mailbox;
754
+ if (!box) {
755
+ throw new Error(`Could not open the mail folder ${folder}`);
756
+ }
757
+ const uidValidity = String(box.uidValidity);
758
+ // Read before the search. Mail that arrives after this point has a UID
759
+ // at or above `uidNext`, so the cursor never jumps over it.
760
+ const newestUid = Math.max(0, Number(box.uidNext) - 1);
761
+ if (!previous || previous.uidValidity !== uidValidity) {
762
+ return {
763
+ events: [],
764
+ cursor: encodeCursor({ v: 1, uidValidity, lastUid: newestUid })
765
+ };
766
+ }
767
+ // IMAP answers "N:*" with the newest message even when its UID is below
768
+ // N, so the range alone would return the last message again on every
769
+ // check. The UIDs are filtered here as well.
770
+ const found = (await client.search({ ...filters, uid: `${previous.lastUid + 1}:*` }, { uid: true })) || [];
771
+ const fresh = found
772
+ .filter((uid) => uid > previous.lastUid)
773
+ .sort((a, b) => a - b);
774
+ const batch = fresh.slice(0, limit);
775
+ const events = [];
776
+ if (batch.length > 0) {
777
+ const fetched = new Map();
778
+ for await (const msg of client.fetch(batch.join(","), { envelope: true, source: true, uid: true }, { uid: true })) {
779
+ fetched.set(msg.uid, await emailFromMessage(msg, envelopeDate(msg.envelope?.date)));
780
+ }
781
+ for (const uid of batch) {
782
+ const email = fetched.get(uid);
783
+ // A message deleted between the search and the fetch is gone.
784
+ if (!email)
785
+ continue;
786
+ events.push({
787
+ id: `${uidValidity}:${uid}`,
788
+ payload: { source: "email", event_type: "new_mail", email },
789
+ cursor: encodeCursor({ v: 1, uidValidity, lastUid: uid })
790
+ });
791
+ }
792
+ }
793
+ // More mail is waiting than one check starts runs for. Stop at the last
794
+ // message of the batch so the next check starts right behind it.
795
+ const cutShort = fresh.length > batch.length;
796
+ const lastUid = cutShort
797
+ ? batch[batch.length - 1]
798
+ : Math.max(previous.lastUid, newestUid, ...batch);
799
+ return {
800
+ events,
801
+ cursor: encodeCursor({ v: 1, uidValidity, lastUid })
802
+ };
803
+ });
804
+ });
805
+ }
806
+ /**
807
+ * Editor run, with no trigger event: yields the newest matching messages
808
+ * once, so a workflow under construction has real mail to work with.
809
+ */
810
+ async *genProcess() {
811
+ const emails = await withImapClient(this._secrets, async (client) => {
812
+ const folder = await resolveFolder(client, String(this.folder ?? "INBOX"));
813
+ return inMailbox(client, folder, async () => {
814
+ const uids = (await client.search(this._filters(), { uid: true })) || [];
815
+ const newest = [...uids].sort((a, b) => b - a).slice(0, this._limit());
816
+ const fetched = new Map();
817
+ for await (const msg of client.fetch(newest.join(","), { envelope: true, source: true, uid: true }, { uid: true })) {
818
+ fetched.set(msg.uid, await emailFromMessage(msg, envelopeDate(msg.envelope?.date)));
819
+ }
820
+ // Oldest first, the order a live trigger would deliver them in.
821
+ return [...newest]
822
+ .reverse()
823
+ .map((uid) => fetched.get(uid))
824
+ .filter((email) => email !== undefined);
825
+ });
826
+ });
827
+ for (const email of emails) {
828
+ yield emailEvent(email);
829
+ }
830
+ }
831
+ }
832
+ __decorate([
833
+ prop({
834
+ type: "enum",
835
+ default: "INBOX",
836
+ title: "Folder",
837
+ description: "Email folder to watch",
838
+ values: [
839
+ "INBOX",
840
+ "[Gmail]/Sent Mail",
841
+ "[Gmail]/Drafts",
842
+ "[Gmail]/Spam",
843
+ "[Gmail]/Trash"
844
+ ]
845
+ })
846
+ ], EmailTriggerLibNode.prototype, "folder", void 0);
847
+ __decorate([
848
+ prop({
849
+ type: "str",
850
+ default: "",
851
+ title: "From Address",
852
+ description: "Only start a run for mail from this sender"
853
+ })
854
+ ], EmailTriggerLibNode.prototype, "from_address", void 0);
855
+ __decorate([
856
+ prop({
857
+ type: "str",
858
+ default: "",
859
+ title: "Subject",
860
+ description: "Only start a run for mail whose subject contains this text"
861
+ })
862
+ ], EmailTriggerLibNode.prototype, "subject", void 0);
863
+ __decorate([
864
+ prop({
865
+ type: "float",
866
+ default: 60,
867
+ title: "Poll Interval Seconds",
868
+ description: `Seconds between checks of the folder, at least ${MIN_POLL_SECONDS}`,
869
+ min: MIN_POLL_SECONDS
870
+ })
871
+ ], EmailTriggerLibNode.prototype, "interval_seconds", void 0);
872
+ __decorate([
873
+ prop({
874
+ type: "int",
875
+ default: DEFAULT_MESSAGES_PER_POLL,
876
+ title: "Max Messages Per Check",
877
+ description: "Most new messages that start a run in one check. The rest wait for the next check.",
878
+ min: 1,
879
+ max: MAX_MESSAGES_PER_POLL
880
+ })
881
+ ], EmailTriggerLibNode.prototype, "max_messages", void 0);
882
+ export const LIB_MAIL_NODES = tagAsServer([
883
+ GmailSearchLibNode,
884
+ AddLabelLibNode,
885
+ MoveToArchiveLibNode,
886
+ SendEmailLibNode,
887
+ EmailTriggerLibNode
888
+ ]);
889
+ //# sourceMappingURL=lib-mail.js.map