@openfn/language-gmail 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.
@@ -0,0 +1,19 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$comment": "OAuth2",
4
+ "properties": {
5
+ "access_token": {
6
+ "title": "Access Token",
7
+ "type": "string",
8
+ "description": "Your Gmail access token",
9
+ "writeOnly": true,
10
+ "minLength": 1,
11
+ "examples": [
12
+ "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlGWERwYmhax0rZNRlQyU3ZRdVhoODQ2WVR3RUlCdyIsI"
13
+ ]
14
+ }
15
+ },
16
+ "type": "object",
17
+ "additionalProperties": true,
18
+ "required": ["access_token"]
19
+ }
package/dist/index.cjs ADDED
@@ -0,0 +1,369 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
+ mod
22
+ ));
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+
25
+ // src/index.js
26
+ var src_exports = {};
27
+ __export(src_exports, {
28
+ alterState: () => import_language_common2.alterState,
29
+ combine: () => import_language_common2.combine,
30
+ cursor: () => import_language_common2.cursor,
31
+ dataPath: () => import_language_common2.dataPath,
32
+ dataValue: () => import_language_common2.dataValue,
33
+ default: () => src_default,
34
+ each: () => import_language_common2.each,
35
+ execute: () => execute,
36
+ field: () => import_language_common2.field,
37
+ fields: () => import_language_common2.fields,
38
+ fn: () => import_language_common2.fn,
39
+ fnIf: () => import_language_common2.fnIf,
40
+ getContentsFromMessages: () => getContentsFromMessages,
41
+ http: () => import_language_common2.http,
42
+ lastReferenceValue: () => import_language_common2.lastReferenceValue,
43
+ merge: () => import_language_common2.merge,
44
+ sourceValue: () => import_language_common2.sourceValue
45
+ });
46
+ module.exports = __toCommonJS(src_exports);
47
+
48
+ // src/Adaptor.js
49
+ var Adaptor_exports = {};
50
+ __export(Adaptor_exports, {
51
+ alterState: () => import_language_common2.alterState,
52
+ combine: () => import_language_common2.combine,
53
+ cursor: () => import_language_common2.cursor,
54
+ dataPath: () => import_language_common2.dataPath,
55
+ dataValue: () => import_language_common2.dataValue,
56
+ each: () => import_language_common2.each,
57
+ execute: () => execute,
58
+ field: () => import_language_common2.field,
59
+ fields: () => import_language_common2.fields,
60
+ fn: () => import_language_common2.fn,
61
+ fnIf: () => import_language_common2.fnIf,
62
+ getContentsFromMessages: () => getContentsFromMessages,
63
+ http: () => import_language_common2.http,
64
+ lastReferenceValue: () => import_language_common2.lastReferenceValue,
65
+ merge: () => import_language_common2.merge,
66
+ sourceValue: () => import_language_common2.sourceValue
67
+ });
68
+ var import_language_common = require("@openfn/language-common");
69
+ var import_util = require("@openfn/language-common/util");
70
+
71
+ // src/Utils.js
72
+ var import_unzipper = __toESM(require("unzipper"), 1);
73
+ var import_googleapis = require("googleapis");
74
+ var gmail;
75
+ async function getMessagesResult(userId, query, lastPageToken) {
76
+ try {
77
+ const { data } = await gmail.users.messages.list({
78
+ userId,
79
+ q: query,
80
+ maxResults: 3,
81
+ pageToken: lastPageToken
82
+ });
83
+ return {
84
+ messages: data.messages,
85
+ nextPageToken: data.nextPageToken
86
+ };
87
+ } catch (error) {
88
+ throw new Error("Error fetching messages: " + error.message);
89
+ }
90
+ }
91
+ async function getMessageResult(userId, messageId) {
92
+ var _a, _b;
93
+ const { data } = await gmail.users.messages.get({
94
+ userId,
95
+ id: messageId,
96
+ format: "full"
97
+ });
98
+ return {
99
+ userId,
100
+ messageId,
101
+ parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
102
+ headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
103
+ };
104
+ }
105
+ function getDesiredContent(hint) {
106
+ const desiredContent = typeof hint === "string" ? { type: hint } : hint;
107
+ if (!desiredContent.type) {
108
+ if (desiredContent.archive) {
109
+ desiredContent.type = "archive";
110
+ } else if (desiredContent.file) {
111
+ desiredContent.type = "file";
112
+ }
113
+ }
114
+ if (!desiredContent.type) {
115
+ console.error(`Unable to determine desired content type: ${hint}`);
116
+ throw new Error("No desired content type provided.");
117
+ }
118
+ if (!desiredContent.name) {
119
+ desiredContent.name = desiredContent.type;
120
+ }
121
+ return desiredContent;
122
+ }
123
+ async function getMessageContent(message, desiredContent) {
124
+ switch (desiredContent.type) {
125
+ case "archive":
126
+ return await getFileFromArchiveFromAttachment(message, desiredContent);
127
+ case "file":
128
+ return await getFileFromAttachment(message, desiredContent);
129
+ case "body":
130
+ return getBodyFromMessage(message, desiredContent);
131
+ case "subject":
132
+ case "from":
133
+ case "date":
134
+ return getValueFromMessageHeader(message, desiredContent);
135
+ default:
136
+ return `Unsupported content type: ${desiredContent.type}`;
137
+ }
138
+ }
139
+ function createConnection(state) {
140
+ const { access_token } = state.configuration;
141
+ const auth = new import_googleapis.google.auth.OAuth2();
142
+ auth.credentials = { access_token };
143
+ gmail = import_googleapis.google.gmail({ version: "v1", auth });
144
+ return state;
145
+ }
146
+ function removeConnection(state) {
147
+ gmail = void 0;
148
+ return state;
149
+ }
150
+ async function getFileFromArchiveFromAttachment(message, desiredContent) {
151
+ const attachmentResult = await getAttachmentResult(
152
+ message,
153
+ desiredContent.archive
154
+ );
155
+ return await extractFileFromArchiveAttachment(
156
+ attachmentResult,
157
+ desiredContent
158
+ );
159
+ }
160
+ async function getFileFromAttachment(message, desiredContent) {
161
+ const attachmentResult = await getAttachmentResult(
162
+ message,
163
+ desiredContent.file
164
+ );
165
+ return await extractFileFromAttachment(attachmentResult, desiredContent);
166
+ }
167
+ async function getAttachmentResult(message, expression) {
168
+ var _a;
169
+ const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
170
+ return isExpressionMatch(p.filename, expression);
171
+ });
172
+ if (!part) {
173
+ console.info(`Attachment not found for: ${expression}`);
174
+ return null;
175
+ }
176
+ const { data } = await gmail.users.messages.attachments.get({
177
+ userId: message.userId,
178
+ messageId: message.messageId,
179
+ id: part.body.attachmentId
180
+ });
181
+ return {
182
+ data: data == null ? void 0 : data.data,
183
+ filename: part.filename,
184
+ expression
185
+ };
186
+ }
187
+ async function extractFileFromArchiveAttachment(attachment, desiredContent) {
188
+ if (!attachment) {
189
+ return null;
190
+ }
191
+ if (!attachment.data) {
192
+ console.error(
193
+ `Data not found in the archive attachment for: ${attachment.expression}`
194
+ );
195
+ return null;
196
+ }
197
+ const compressedBuffer = Buffer.from(attachment.data, "base64");
198
+ const directory = await import_unzipper.default.Open.buffer(compressedBuffer);
199
+ const file = directory == null ? void 0 : directory.files.find(
200
+ (f) => isExpressionMatch(f.path, desiredContent.file)
201
+ );
202
+ if (!file) {
203
+ console.info(`File not found in the archive for: ${desiredContent.file}`);
204
+ return null;
205
+ }
206
+ const fileBuffer = await file.buffer();
207
+ const fileString = fileBuffer.toString("base64");
208
+ const fileContent = Buffer.from(fileString, "base64").toString("utf-8");
209
+ return {
210
+ archiveFilename: attachment.filename,
211
+ filename: file.path,
212
+ content: desiredContent.maxLength ? fileContent.substring(0, desiredContent.maxLength) : fileContent
213
+ };
214
+ }
215
+ async function extractFileFromAttachment(attachment, desiredContent) {
216
+ if (!attachment) {
217
+ return null;
218
+ }
219
+ if (!attachment.data) {
220
+ console.error(
221
+ `Data not found in the file attachment for: ${attachment.expression}`
222
+ );
223
+ return null;
224
+ }
225
+ const fileContent = Buffer.from(attachment.data, "base64").toString("utf-8");
226
+ return {
227
+ filename: attachment.filename,
228
+ content: desiredContent.maxLength ? fileContent.substring(0, desiredContent.maxLength) : fileContent
229
+ };
230
+ }
231
+ function getBodyFromMessage(message, desiredContent) {
232
+ var _a, _b;
233
+ const bodyPart = (_a = message.parts) == null ? void 0 : _a.find(
234
+ (part) => part.mimeType === "multipart/alternative"
235
+ );
236
+ const textBodyPart = bodyPart == null ? void 0 : bodyPart.parts.find(
237
+ (part) => part.mimeType === "text/plain"
238
+ );
239
+ const textBody = (_b = textBodyPart == null ? void 0 : textBodyPart.body) == null ? void 0 : _b.data;
240
+ if (textBody) {
241
+ const body = Buffer.from(textBody, "base64").toString("utf-8");
242
+ return desiredContent.maxLength ? body.substring(0, desiredContent.maxLength) : body;
243
+ }
244
+ return null;
245
+ }
246
+ function getValueFromMessageHeader(message, desiredContent) {
247
+ var _a;
248
+ const header = (_a = message.headers) == null ? void 0 : _a.find(
249
+ (h) => h.name.toLowerCase() === desiredContent.type
250
+ );
251
+ if (!header) {
252
+ return null;
253
+ }
254
+ const value = header.value;
255
+ if (desiredContent.type === "date") {
256
+ return new Date(value);
257
+ }
258
+ return desiredContent.maxLength ? value.substring(0, desiredContent.maxLength) : value;
259
+ }
260
+ function isExpressionMatch(text, expression) {
261
+ var _a;
262
+ try {
263
+ return ((_a = expression == null ? void 0 : expression.constructor) == null ? void 0 : _a.name) === "RegExp" ? expression.test(text) : text.includes(expression);
264
+ } catch (e) {
265
+ return false;
266
+ }
267
+ }
268
+
269
+ // src/Adaptor.js
270
+ var import_language_common2 = require("@openfn/language-common");
271
+ function getContentsFromMessages(userId, userOptions) {
272
+ return async (state) => {
273
+ var _a, _b;
274
+ const [resolvedUserId, resolvedUserOptions] = (0, import_util.expandReferences)(
275
+ state,
276
+ userId,
277
+ userOptions
278
+ );
279
+ const defaultOptions = {
280
+ desiredContents: ["from", "date", "subject", "body"]
281
+ };
282
+ const options = { ...defaultOptions, ...resolvedUserOptions || {} };
283
+ const contents = [];
284
+ const currentIds = [];
285
+ const previousIds = Array.isArray(options.processedIds) ? options.processedIds : [];
286
+ let nextPageToken = null;
287
+ do {
288
+ const messagesResult = await getMessagesResult(
289
+ resolvedUserId,
290
+ options.query,
291
+ nextPageToken
292
+ );
293
+ if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
294
+ console.log("No messages found.");
295
+ break;
296
+ }
297
+ nextPageToken = messagesResult.nextPageToken;
298
+ const currentPageIds = messagesResult.messages.map((message) => message.id);
299
+ const unprocessedIds = currentPageIds.filter(
300
+ (id) => !previousIds.includes(id)
301
+ );
302
+ for (const messageId of unprocessedIds) {
303
+ const content = {
304
+ messageId
305
+ };
306
+ const messageResult = await getMessageResult(userId, messageId);
307
+ for (const desiredContentHint of options.desiredContents) {
308
+ const desiredContent = getDesiredContent(desiredContentHint);
309
+ const messageContent = await getMessageContent(
310
+ messageResult,
311
+ desiredContent
312
+ );
313
+ if (messageContent && content[desiredContent.name]) {
314
+ throw new Error(
315
+ `Duplicate content name detected: ${desiredContent.name}`
316
+ );
317
+ }
318
+ content[_b = desiredContent.name] ?? (content[_b] = messageContent);
319
+ }
320
+ contents.push(content);
321
+ }
322
+ currentIds.push(...currentPageIds);
323
+ } while (nextPageToken);
324
+ const nextState = {
325
+ ...(0, import_language_common.composeNextState)(state, contents),
326
+ processedIds: currentIds
327
+ };
328
+ return nextState;
329
+ };
330
+ }
331
+ function execute(...operations) {
332
+ const initialState = {
333
+ references: [],
334
+ data: null
335
+ };
336
+ return (state) => {
337
+ return (0, import_language_common.execute)(
338
+ createConnection,
339
+ ...operations,
340
+ removeConnection
341
+ )({
342
+ ...initialState,
343
+ ...state,
344
+ configuration: (0, import_util.normalizeOauthConfig)(state.configuration)
345
+ });
346
+ };
347
+ }
348
+
349
+ // src/index.js
350
+ var src_default = Adaptor_exports;
351
+ // Annotate the CommonJS export names for ESM import in node:
352
+ 0 && (module.exports = {
353
+ alterState,
354
+ combine,
355
+ cursor,
356
+ dataPath,
357
+ dataValue,
358
+ each,
359
+ execute,
360
+ field,
361
+ fields,
362
+ fn,
363
+ fnIf,
364
+ getContentsFromMessages,
365
+ http,
366
+ lastReferenceValue,
367
+ merge,
368
+ sourceValue
369
+ });