@openfn/language-gmail 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,103 +1,140 @@
1
- # Gmail Message Content Extraction
1
+ # Gmail Adaptor
2
2
 
3
- This adaptor is used to extract specific content from Gmail messages using
4
- custom "desiredContent" configurations. The sample code specifies how to query
5
- Gmail for messages and identify desired attachments and metadata.
3
+ ## What it does
6
4
 
7
- ## How It Works
5
+ This adaptor is used to extract specific content from Gmail messages using custom desired "content" configurations. The sample code specifies how to query Gmail for messages and identify desired attachments and metadata.
8
6
 
9
- 1. Gmail Query: Constructs a Gmail query string to filter relevant messages.
10
- 2. Desired Content Matching: Uses the desiredContents array to identify and
11
- extract:
12
- - Metadata files
13
- - Archive files and their contents
14
- - Message metadata (subject, date, from, body)
15
- 3. Output: Returns a structured collection of matched content.
7
+ Without any parameters, the `getContentsFromMessages()` function will return an array containing every message in the account of the authenticated user including `from`, `date` and `subject`.
16
8
 
17
- ## Usage
9
+ A number of options are available to isolated the desired messages and to customize the output.
18
10
 
19
- The adaptor's primary function is `getContentsFromMessages`
11
+ ## Options
20
12
 
21
- ```js
22
- getContentsFromMessages(userId, query, desiredContents, callback);
23
- ```
13
+ Optional parameters include: `contents`, `query`, `email`, `processedIds`
24
14
 
25
- 1. Set userId with the Gmail account to query.
26
- 2. Customize the query to contain filters as needed. This is the same format a
27
- the query in the Gmail UI.
28
- 3. Specify what content to retrieve from messages (body, subject, attachments,
29
- etc)
15
+ ### options.contents
30
16
 
31
- ## Extracting Message Contents
17
+ Use the `options.contents` array to specify the content to retrieve from each message. Always included are `from`, `date`, and `subject`.
32
18
 
33
- The `desiredContents` array should list what content to retrieve from each
34
- message. Each item should be a string (ie, `"body"` or an object describing an
35
- attachment)
19
+ Each item can be a simple string (ie, `'body'`, `'subject'`) or an MessageContent object offering advanced configuration.
36
20
 
37
- ### Metadata
21
+ #### Basic metadata
38
22
 
39
- The following strings can be extracted:
23
+ The following types of content can be extracted:
40
24
 
41
25
  - `body`: Extracts the message body.
42
26
  - `subject`: Extracts the email subject.
43
27
  - `date`: Extracts the timestamp of the email.
44
28
  - `from`: Extracts the sender's information.
45
29
 
46
- ### Attachment: basic file
30
+ Optionally, each of these content strings can be expanded to include additional specifications:
31
+
32
+ ```js
33
+ const mySubject = {
34
+ type: 'subject',
35
+ name: 'email-title',
36
+ maxLength: 25,
37
+ };
38
+ ```
39
+
40
+ - The `type` property instructs the function which content type to extract.
41
+ - The `name` property allows you to add a custom name to this information.
42
+ - The `maxLength` property allows you to limit the length of the content returned.
43
+
44
+ #### Attachment: basic file
45
+
46
+ Extract content from a file attachment.
47
47
 
48
- Extract the content from a file attachment. Specify the file name with a regular
49
- expression on the `file` key.
48
+ `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to matching a pattern.
50
49
 
51
50
  ```js
52
- {
53
- type: "file",
54
- name: "metadata",
51
+ const myMetadata = {
52
+ type: 'file',
53
+ name: 'metadata',
55
54
  file: /^summary\.txt$/,
56
- }
55
+ };
56
+ ```
57
+
58
+ ```js
59
+ const myMetadata = {
60
+ type: 'file',
61
+ file: 'summary.txt',
62
+ maxLength: 500,
63
+ };
57
64
  ```
58
65
 
59
- ### Attachment: archived file
66
+ #### Attachment: archived file
60
67
 
61
- Extract the content from a file embedded in an archive attachment.
68
+ Extract content from a file embedded in an archive attachment.
62
69
 
63
- Specify the archive with a regular expression on the `archive` key. Extract a
64
- file within the archive with the `file` key.
70
+ - `archive`: Specify the file name of the archive using either a string for an exact match or a regular expression to match a pattern.
71
+ - `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to match a pattern.
65
72
 
66
73
  ```js
67
- {
68
- type: "archive",
69
- name: "data",
70
- archive: /_device_data\.zip$/,
74
+ const myArchivedFile = {
75
+ type: 'archive',
76
+ name: 'data',
77
+ archive: 'devicedata.zip',
71
78
  file: /_CURRENT_DATA_\w*?\.json$/,
72
- }
79
+ maxLength: 5000,
80
+ };
73
81
  ```
74
82
 
75
- ## Query Setup
83
+ ```js
84
+ options.contents = [mySubject, 'body', myMetadata, myArchivedFile];
85
+ ```
76
86
 
77
- The query variable is constructed to filter Gmail messages:
87
+ ### options.query
78
88
 
79
- - Inbox messages with the subject containing "30DTR Data".
80
- - Messages sent within the last 31 days.
89
+ Use a `query` parameter to filter the messages returned.
81
90
 
82
- ## Example
91
+ The query syntax supports the same query format as the Gmail `search` box.
83
92
 
84
- ```js
85
- const userId = 'tester@gmail.com';
93
+ ```
94
+ options.query = 'from:someuser@example.com rfc822msgid:<somemsgid@example.com> is:unread';
95
+ ```
96
+
97
+ A full list of supported search operations can be found here: [Refine searches in Gmail](https://support.google.com/mail/answer/7190)
98
+
99
+ ### options.email
100
+
101
+ Optionally specify the email address used for the Gmail account. This almost always the same email associated with the authenticated user so this parameter is optional.
102
+
103
+ ```
104
+ options.email = '<EMAIL>';
105
+ ```
86
106
 
87
- const querySubject = encodeURIComponent('device data summary');
107
+ ### options.processedIds
88
108
 
89
- // All messages newer than 30 days ago
90
- const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
91
- const queryAfterDate = new Date(Date.now() - 30 * MILLISECONDS_PER_DAY)
92
- .toISOString()
93
- .split('T')[0];
109
+ In some scenarios, it may be necessary to skip certain messages to prevent the retrieval of duplicate data. Passing an array of messageIds will allow the function to skip these messages if any of the ids are encountered in the returned messages.
94
110
 
95
- const query = `in:inbox subject:${querySubject} after:${queryAfterDate}`;
111
+ ```
112
+ options.processedIds = [
113
+ '194e3cf1ca0ccd66',
114
+ '283e2df2ca0ecd75',
115
+ '572e1af3ca0bcd84',
116
+ ];
117
+ ```
118
+
119
+ ## Example jobs
120
+
121
+ ```js
122
+ const query = 'in:inbox newer_than:2d';
123
+ const contents = ['body'];
124
+ getContentsFromMessages({ query, contents });
125
+ ```
126
+
127
+ ```js
128
+ const subject = 'device data summary'.replace(' ', '+');
129
+ const query = `in:inbox subject:${subject} newer_than:1m`;
130
+
131
+ const email = 'special_assigned_delegate@gmail.com';
96
132
 
97
133
  const metadataFile = {
98
134
  type: 'file',
99
135
  name: 'metadata',
100
- file: /^summary\.txt$/,
136
+ file: /summary\.txt$/,
137
+ maxLength: 500,
101
138
  };
102
139
 
103
140
  const dataFile = {
@@ -107,63 +144,114 @@ const dataFile = {
107
144
  file: /_CURRENT_DATA_\w*?\.json$/,
108
145
  };
109
146
 
110
- const desiredContents = [
111
- 'body',
112
- 'subject',
113
- 'date',
114
- 'from',
115
- metadataFile,
116
- dataFile,
117
- ];
147
+ const contents = [metadataFile, dataFile];
118
148
 
119
- getContentsFromMessages(userId, query, desiredContents, state =>
120
- console.log(state.data)
121
- );
149
+ getContentsFromMessages({ query, email, contents });
122
150
  ```
123
151
 
124
- ## Sample Output
152
+ ## Sample `state.data` Output
125
153
 
126
- For each matched message, the extracted content is returned in a collection of
127
- content blocks. Here's an example for a single match message:
154
+ For each matched message, the extracted content is returned as a message object of content properties. Here's an example `state.data` for a single matched message:
128
155
 
129
156
  ```js
130
157
  [
131
158
  {
132
159
  messageId: '1934c017c1752c01',
133
- contents: [
134
- {
135
- name: 'subject',
136
- value: 'Fwd: FW: Facility Temperature Report (Summary Data)',
137
- },
138
- {
139
- name: 'date',
140
- value: '2024-11-20T23:56:08.000Z',
141
- },
142
- {
143
- name: 'from',
144
- value: 'Friendly Sender <sender@gmail.com>',
145
- },
146
- {
147
- name: 'metadata',
148
- value:
149
- '{\n "appInfo": {\n "isAutomaticTime": true,\n "isTrueTime": true,\n "os": "Android",\n "osVe" }',
150
- path: '004800123457501820383131_20241115T102926Z.json',
151
- },
152
- {
153
- name: 'data',
154
- value:
155
- '{\n "AMOD": "VL45",\n "AMFR": "ICECO",\n "ASER": "BJBC 08 30",\n "ADOP": "2024-04-01",\n "APQS": "E003/XX" }',
156
- path: '004800123457501820383131_CURRENT_DATA_P100DT9H45M46S_20241115T102926Z.json',
157
- },
158
- ],
160
+ from: 'Friendly Sender <sender@gmail.com>',
161
+ date: '2024-11-20T23:56:08.000Z',
162
+ subject: 'Fwd: FW: Facility Anomaly Report (Summary Data)',
163
+ metadata: {
164
+ filename: 'daily_summary.txt',
165
+ content: '{ "appInfo": { "isAutomaticTime": true }',
166
+ },
167
+ data: {
168
+ archiveFilename: '0031_device_data.zip',
169
+ filename: '0031_CURRENT_DATA_P100DT9H45M46S_20241115T102926Z.json',
170
+ content: '{ "AMOD": "VL45", "AMFR": "ICECO" }',
171
+ },
159
172
  },
160
173
  ];
161
174
  ```
162
175
 
163
- Each content block represents a specific piece of information extracted:
176
+ Each property on the message object represents a specific piece of information extracted:
164
177
 
165
- - **subject**: Contains the email subject.
166
- - **date**: The timestamp when the email was sent.
167
178
  - **from**: Sender's email and name.
168
- - **metadata**: Metadata file content, with its file path.
169
- - **data**: Data file content, with its file path.
179
+ - **date**: The timestamp when the email was sent.
180
+ - **subject**: Contains the email subject.
181
+ - **metadata**: Metadata-named file content, with its matched file name.
182
+ - **data**: Data-named archive file content, with its matched archive name and file name.
183
+
184
+ ## Acquiring an access token
185
+
186
+ The Gmail adaptor implicitly uses the Gmail account of the Google account that is used to authenticate the application.
187
+
188
+ Allowing the Gmail adaptor to access a Gmail account is a multi-step process.
189
+
190
+ ### Create an OAuth 2.0 client ID
191
+
192
+ Follow the instructions are found here:
193
+ https://support.google.com/googleapi/answer/6158849
194
+
195
+ - Go to [Google Cloud Platform Console](https://console.cloud.google.com/)
196
+ - Go to "APIs & Services"
197
+ - Click "Credentials"
198
+ - Click "Create Credentials"
199
+ - Select "OAuth client ID"
200
+ - Select "Create OAuth client ID"
201
+ - Select Application type "Web application"
202
+ - Add a uniquely-identifiable name
203
+ - Click "Create"
204
+ - On the resulting popup screen, find and click "DOWNLOAD JSON" and save this file to a secure location.
205
+
206
+ ### Use the Postman application to query the OAuth enpoint and retrieve an access token
207
+
208
+ Initially, you'll need to configure an authentication request using Postman's built-in OAuth 2.0 implementation:
209
+
210
+ - Open Postman
211
+ - Create a new request
212
+ - Switch to the "Authorization" tab
213
+ - On the left side, select Type OAuth 2.0
214
+ - On the right side, scroll down to the "Configure New Token" section
215
+ - Fill out the form using information from the downloaded json file from the
216
+ previous section
217
+ - Token Name: Google Oauth
218
+ - Grant Type: Authorization Code
219
+ - Auth URL: (found in the json file as auth_url)
220
+ - Access Token URL: (found in the json file as token_url)
221
+ - Client ID: (found in the json file as client_id)
222
+ - Client Secret: (found in the json file as client_secret)
223
+ - Scope: https://www.googleapis.com/auth/gmail.readonly
224
+ - State: (any random string is fine)
225
+ - Client Authentication: Send as Basic Auth header
226
+
227
+ Once the form is filled out, repeat these steps each hour to retrieve a new
228
+ access token:
229
+
230
+ - Click on "Get New Access Token"
231
+ - A browser will open and you'll be asked to authenticate with your Google Account
232
+ - Accept the request to allow this OAuth session to access your Google Account.
233
+ - In the MANAGE ACCESS TOKENS popup, find and copy the new Access Token
234
+ - This access token will be valid for 1 hour.
235
+
236
+ ### Configure OpenFn CLI to find the access token
237
+
238
+ The Gmail adaptor looks for the access token in the configuration section under `access_token`.
239
+
240
+ Example configuration using a workflow:
241
+
242
+ ```
243
+ "workflow": {
244
+ "steps": [
245
+ {
246
+ "id": "getGmailContent",
247
+ "adaptors": [
248
+ "gmail"
249
+ ],
250
+ "expression": "path/to/gmail.js",
251
+ "configuration": {
252
+ "access_token": "(access token acquired from Postman)"
253
+ }
254
+ }
255
+ ]
256
+ }
257
+ ```
package/ast.json CHANGED
@@ -3,8 +3,7 @@
3
3
  {
4
4
  "name": "getContentsFromMessages",
5
5
  "params": [
6
- "userId",
7
- "userOptions"
6
+ "options"
8
7
  ],
9
8
  "docs": {
10
9
  "description": "Used to isolate the type of content to retrieve from the message.",
@@ -16,7 +15,7 @@
16
15
  "type": "NameExpression",
17
16
  "name": "Object"
18
17
  },
19
- "name": "DesiredContent"
18
+ "name": "MessageContent"
20
19
  },
21
20
  {
22
21
  "title": "public",
@@ -27,27 +26,25 @@
27
26
  "title": "property",
28
27
  "description": "Message content type. Valid types: from, date, subject, body, archive, file.",
29
28
  "type": {
30
- "type": "NameExpression",
31
- "name": "string"
29
+ "type": "OptionalType",
30
+ "expression": {
31
+ "type": "NameExpression",
32
+ "name": "string"
33
+ }
32
34
  },
33
35
  "name": "type"
34
36
  },
35
37
  {
36
38
  "title": "property",
37
- "description": "A custom description for the content type. Optional.",
39
+ "description": "A custom description for the content type.",
38
40
  "type": {
39
41
  "type": "OptionalType",
40
42
  "expression": {
41
- "type": "NullableType",
42
- "expression": {
43
- "type": "NameExpression",
44
- "name": "string"
45
- },
46
- "prefix": false
43
+ "type": "NameExpression",
44
+ "name": "string"
47
45
  }
48
46
  },
49
- "name": "name",
50
- "default": "null"
47
+ "name": "name"
51
48
  },
52
49
  {
53
50
  "title": "property",
@@ -93,7 +90,7 @@
93
90
  },
94
91
  {
95
92
  "title": "property",
96
- "description": "Maximum number of characters to retrieve from the content. Optional.",
93
+ "description": "Maximum number of characters to retrieve from the content.",
97
94
  "type": {
98
95
  "type": "OptionalType",
99
96
  "expression": {
@@ -105,8 +102,7 @@
105
102
  "prefix": false
106
103
  }
107
104
  },
108
- "name": "maxLength",
109
- "default": "null"
105
+ "name": "maxLength"
110
106
  }
111
107
  ]
112
108
  },
package/dist/index.cjs CHANGED
@@ -72,13 +72,13 @@ var import_util = require("@openfn/language-common/util");
72
72
  var import_unzipper = __toESM(require("unzipper"), 1);
73
73
  var import_googleapis = require("googleapis");
74
74
  var gmail;
75
- async function getMessagesResult(userId, query, lastPageToken) {
75
+ async function getMessagesResult(userId, query, pageToken) {
76
76
  try {
77
77
  const { data } = await gmail.users.messages.list({
78
78
  userId,
79
79
  q: query,
80
- maxResults: 3,
81
- pageToken: lastPageToken
80
+ maxResults: 20,
81
+ pageToken
82
82
  });
83
83
  return {
84
84
  messages: data.messages,
@@ -102,23 +102,37 @@ async function getMessageResult(userId, messageId) {
102
102
  headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
103
103
  };
104
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";
105
+ function getContentIndicators(defaultContentRequests, contentRequests) {
106
+ const indicators = /* @__PURE__ */ new Map();
107
+ const requests = [
108
+ ...defaultContentRequests || [],
109
+ ...contentRequests || []
110
+ ];
111
+ for (const request of requests) {
112
+ const indicator = getContentIndicator(request);
113
+ indicators.set(indicator.type, indicator);
114
+ }
115
+ return Array.from(indicators.values());
116
+ }
117
+ function getContentIndicator(contentRequest) {
118
+ const contentIndicator = typeof contentRequest === "string" ? { type: contentRequest } : { ...contentRequest };
119
+ if (!contentIndicator.type) {
120
+ if (contentIndicator.archive) {
121
+ contentIndicator.type = "archive";
122
+ } else if (contentIndicator.file) {
123
+ contentIndicator.type = "file";
112
124
  }
113
125
  }
114
- if (!desiredContent.type) {
115
- console.error(`Unable to determine desired content type: ${hint}`);
126
+ if (!contentIndicator.type) {
127
+ console.error(
128
+ `Unable to determine desired content type: ${contentRequest}`
129
+ );
116
130
  throw new Error("No desired content type provided.");
117
131
  }
118
- if (!desiredContent.name) {
119
- desiredContent.name = desiredContent.type;
132
+ if (!contentIndicator.name) {
133
+ contentIndicator.name = contentIndicator.type;
120
134
  }
121
- return desiredContent;
135
+ return contentIndicator;
122
136
  }
123
137
  async function getMessageContent(message, desiredContent) {
124
138
  switch (desiredContent.type) {
@@ -128,9 +142,9 @@ async function getMessageContent(message, desiredContent) {
128
142
  return await getFileFromAttachment(message, desiredContent);
129
143
  case "body":
130
144
  return getBodyFromMessage(message, desiredContent);
131
- case "subject":
132
145
  case "from":
133
146
  case "date":
147
+ case "subject":
134
148
  return getValueFromMessageHeader(message, desiredContent);
135
149
  default:
136
150
  return `Unsupported content type: ${desiredContent.type}`;
@@ -268,26 +282,31 @@ function isExpressionMatch(text, expression) {
268
282
 
269
283
  // src/Adaptor.js
270
284
  var import_language_common2 = require("@openfn/language-common");
271
- function getContentsFromMessages(userId, userOptions) {
285
+ function getContentsFromMessages(options) {
272
286
  return async (state) => {
273
287
  var _a, _b;
274
- const [resolvedUserId, resolvedUserOptions] = (0, import_util.expandReferences)(
275
- state,
276
- userId,
277
- userOptions
278
- );
288
+ const [resolvedOptions] = (0, import_util.expandReferences)(state, options);
279
289
  const defaultOptions = {
280
- desiredContents: ["from", "date", "subject", "body"]
290
+ contents: ["from", "date", "subject"],
291
+ userId: "me"
281
292
  };
282
- const options = { ...defaultOptions, ...resolvedUserOptions || {} };
293
+ const opts = {
294
+ userId: resolvedOptions.email ?? defaultOptions.userId,
295
+ query: resolvedOptions.query,
296
+ processedIds: resolvedOptions.processedIds
297
+ };
298
+ const contentIndicators = getContentIndicators(
299
+ defaultOptions.contents,
300
+ resolvedOptions.contents
301
+ );
283
302
  const contents = [];
284
303
  const currentIds = [];
285
- const previousIds = Array.isArray(options.processedIds) ? options.processedIds : [];
304
+ const previousIds = Array.isArray(opts.processedIds) ? opts.processedIds : [];
286
305
  let nextPageToken = null;
287
306
  do {
288
307
  const messagesResult = await getMessagesResult(
289
- resolvedUserId,
290
- options.query,
308
+ opts.userId,
309
+ opts.query,
291
310
  nextPageToken
292
311
  );
293
312
  if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
@@ -303,19 +322,18 @@ function getContentsFromMessages(userId, userOptions) {
303
322
  const content = {
304
323
  messageId
305
324
  };
306
- const messageResult = await getMessageResult(userId, messageId);
307
- for (const desiredContentHint of options.desiredContents) {
308
- const desiredContent = getDesiredContent(desiredContentHint);
325
+ const messageResult = await getMessageResult(opts.userId, messageId);
326
+ for (const contentIndicator of contentIndicators) {
309
327
  const messageContent = await getMessageContent(
310
328
  messageResult,
311
- desiredContent
329
+ contentIndicator
312
330
  );
313
- if (messageContent && content[desiredContent.name]) {
331
+ if (messageContent && content[contentIndicator.name]) {
314
332
  throw new Error(
315
- `Duplicate content name detected: ${desiredContent.name}`
333
+ `Duplicate content name detected: ${contentIndicator.name}`
316
334
  );
317
335
  }
318
- content[_b = desiredContent.name] ?? (content[_b] = messageContent);
336
+ content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
319
337
  }
320
338
  contents.push(content);
321
339
  }
package/dist/index.js CHANGED
@@ -37,13 +37,13 @@ import {
37
37
  import unzipper from "unzipper";
38
38
  import { google } from "googleapis";
39
39
  var gmail;
40
- async function getMessagesResult(userId, query, lastPageToken) {
40
+ async function getMessagesResult(userId, query, pageToken) {
41
41
  try {
42
42
  const { data } = await gmail.users.messages.list({
43
43
  userId,
44
44
  q: query,
45
- maxResults: 3,
46
- pageToken: lastPageToken
45
+ maxResults: 20,
46
+ pageToken
47
47
  });
48
48
  return {
49
49
  messages: data.messages,
@@ -67,23 +67,37 @@ async function getMessageResult(userId, messageId) {
67
67
  headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
68
68
  };
69
69
  }
70
- function getDesiredContent(hint) {
71
- const desiredContent = typeof hint === "string" ? { type: hint } : hint;
72
- if (!desiredContent.type) {
73
- if (desiredContent.archive) {
74
- desiredContent.type = "archive";
75
- } else if (desiredContent.file) {
76
- desiredContent.type = "file";
70
+ function getContentIndicators(defaultContentRequests, contentRequests) {
71
+ const indicators = /* @__PURE__ */ new Map();
72
+ const requests = [
73
+ ...defaultContentRequests || [],
74
+ ...contentRequests || []
75
+ ];
76
+ for (const request of requests) {
77
+ const indicator = getContentIndicator(request);
78
+ indicators.set(indicator.type, indicator);
79
+ }
80
+ return Array.from(indicators.values());
81
+ }
82
+ function getContentIndicator(contentRequest) {
83
+ const contentIndicator = typeof contentRequest === "string" ? { type: contentRequest } : { ...contentRequest };
84
+ if (!contentIndicator.type) {
85
+ if (contentIndicator.archive) {
86
+ contentIndicator.type = "archive";
87
+ } else if (contentIndicator.file) {
88
+ contentIndicator.type = "file";
77
89
  }
78
90
  }
79
- if (!desiredContent.type) {
80
- console.error(`Unable to determine desired content type: ${hint}`);
91
+ if (!contentIndicator.type) {
92
+ console.error(
93
+ `Unable to determine desired content type: ${contentRequest}`
94
+ );
81
95
  throw new Error("No desired content type provided.");
82
96
  }
83
- if (!desiredContent.name) {
84
- desiredContent.name = desiredContent.type;
97
+ if (!contentIndicator.name) {
98
+ contentIndicator.name = contentIndicator.type;
85
99
  }
86
- return desiredContent;
100
+ return contentIndicator;
87
101
  }
88
102
  async function getMessageContent(message, desiredContent) {
89
103
  switch (desiredContent.type) {
@@ -93,9 +107,9 @@ async function getMessageContent(message, desiredContent) {
93
107
  return await getFileFromAttachment(message, desiredContent);
94
108
  case "body":
95
109
  return getBodyFromMessage(message, desiredContent);
96
- case "subject":
97
110
  case "from":
98
111
  case "date":
112
+ case "subject":
99
113
  return getValueFromMessageHeader(message, desiredContent);
100
114
  default:
101
115
  return `Unsupported content type: ${desiredContent.type}`;
@@ -248,26 +262,31 @@ import {
248
262
  merge,
249
263
  sourceValue
250
264
  } from "@openfn/language-common";
251
- function getContentsFromMessages(userId, userOptions) {
265
+ function getContentsFromMessages(options) {
252
266
  return async (state) => {
253
267
  var _a, _b;
254
- const [resolvedUserId, resolvedUserOptions] = expandReferences(
255
- state,
256
- userId,
257
- userOptions
258
- );
268
+ const [resolvedOptions] = expandReferences(state, options);
259
269
  const defaultOptions = {
260
- desiredContents: ["from", "date", "subject", "body"]
270
+ contents: ["from", "date", "subject"],
271
+ userId: "me"
261
272
  };
262
- const options = { ...defaultOptions, ...resolvedUserOptions || {} };
273
+ const opts = {
274
+ userId: resolvedOptions.email ?? defaultOptions.userId,
275
+ query: resolvedOptions.query,
276
+ processedIds: resolvedOptions.processedIds
277
+ };
278
+ const contentIndicators = getContentIndicators(
279
+ defaultOptions.contents,
280
+ resolvedOptions.contents
281
+ );
263
282
  const contents = [];
264
283
  const currentIds = [];
265
- const previousIds = Array.isArray(options.processedIds) ? options.processedIds : [];
284
+ const previousIds = Array.isArray(opts.processedIds) ? opts.processedIds : [];
266
285
  let nextPageToken = null;
267
286
  do {
268
287
  const messagesResult = await getMessagesResult(
269
- resolvedUserId,
270
- options.query,
288
+ opts.userId,
289
+ opts.query,
271
290
  nextPageToken
272
291
  );
273
292
  if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
@@ -283,19 +302,18 @@ function getContentsFromMessages(userId, userOptions) {
283
302
  const content = {
284
303
  messageId
285
304
  };
286
- const messageResult = await getMessageResult(userId, messageId);
287
- for (const desiredContentHint of options.desiredContents) {
288
- const desiredContent = getDesiredContent(desiredContentHint);
305
+ const messageResult = await getMessageResult(opts.userId, messageId);
306
+ for (const contentIndicator of contentIndicators) {
289
307
  const messageContent = await getMessageContent(
290
308
  messageResult,
291
- desiredContent
309
+ contentIndicator
292
310
  );
293
- if (messageContent && content[desiredContent.name]) {
311
+ if (messageContent && content[contentIndicator.name]) {
294
312
  throw new Error(
295
- `Duplicate content name detected: ${desiredContent.name}`
313
+ `Duplicate content name detected: ${contentIndicator.name}`
296
314
  );
297
315
  }
298
- content[_b = desiredContent.name] ?? (content[_b] = messageContent);
316
+ content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
299
317
  }
300
318
  contents.push(content);
301
319
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-gmail",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "OpenFn gmail adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,42 +1,51 @@
1
1
  /**
2
2
  * Used to isolate the type of content to retrieve from the message.
3
- * @typedef {Object} DesiredContent
3
+ * @typedef {Object} MessageContent
4
4
  * @public
5
- * @property {string} type - Message content type. Valid types: from, date, subject, body, archive, file.
6
- * @property {string?} [name=null] - A custom description for the content type. Optional.
5
+ * @property {string} [type] - Message content type. Valid types: from, date, subject, body, archive, file.
6
+ * @property {string} [name] - A custom description for the content type.
7
7
  * @property {RegExp|string} [archive] - Identifier to isolate the desired attachment when type is 'archive'.
8
8
  * Use a regular expression for pattern matching or a string for a literal match. Required if type is 'archive'.
9
9
  * @property {RegExp|string} [file] - Identifier to isolate the desired attachment when type is 'file' or 'archive'.
10
10
  * Use a regular expression for pattern matching or a string for a literal match. Required if type is 'file' or 'archive'.
11
- * @property {number?} [maxLength=null] - Maximum number of characters to retrieve from the content. Optional.
11
+ * @property {number?} [maxLength] - Maximum number of characters to retrieve from the content.
12
12
  */
13
13
  /**
14
14
  * Configurable options provided to the Gmail adaptor.
15
15
  * @typedef {Object} Options
16
16
  * @public
17
- * @property {string} userId - The email address of the Gmail account.
18
- * @property {string?} [query=null] - Custom query to limit the messages result. Adheres to the Gmail search syntax. Optional.
19
- * @property {Array<string|DesiredContent>?} [desiredContents=['from', 'date', 'subject', 'body']]
20
- * An array of strings or DesiredContent objects used to specify which parts of the message to retrieve. Optional, default is `['from', 'date', 'subject', 'body']`.
21
- * @property {Array<string>?} [processedIds=null] - Ignore message ids which have already been processed. Optional.
17
+ * @property {string?} [query] - Gmail search query string.
18
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject', 'body']]
19
+ * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
20
+ * @property {Array<string>} [processedIds] - Ignore message ids which have already been processed.
21
+ * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
22
22
  */
23
23
  /**
24
- * Requests contents from messages of a Gmail account.
24
+ * Downloads contents from messages of a Gmail account.
25
25
  * @public
26
26
  * @function
27
- * @param {string} userId - The email address of the account to retrieve messages from.
28
- * @param {Options} userOptions - Customized options including desired contents and query.
29
- * @returns {Function} A function that processes the state.
30
- * @example
27
+ * @param {Options} options - Customized options including desired contents and query.
28
+ * @state {Array} data - The returned message objects, of the form `{ messageId, contents } `
29
+ * @state {Array<string>} processedIds - An array of string ids processed by this request
30
+ * @returns {Operation}
31
+ * @example <caption>Get a message with a specific subject</caption>
32
+ * getContentsFromMessages(
33
+ * {
34
+ * query: 'subject:my+test+message'
35
+ * }
36
+ * )
37
+ * @example <caption>Get messages after a specific date, with subject and report.txt attachment</caption>
31
38
  * getContentsFromMessages(
32
- * 'test@tester.com',
33
39
  * {
34
- * query: 'in:inbox subject:my+test+message',
35
- * desiredContents: ['date', 'from', 'subject', { type: 'body', maxLength: 50 }]
40
+ * query: 'after:15/01/2025',
41
+ * contents: [
42
+ * 'subject',
43
+ * { type: 'file', name: 'metadata', file: 'report.txt'}
44
+ * ]
36
45
  * }
37
46
  * )
38
47
  */
39
- export function getContentsFromMessages(userId: string, userOptions: Options): Function;
48
+ export function getContentsFromMessages(options: Options): Operation;
40
49
  /**
41
50
  * Execute a sequence of operations.
42
51
  * Wraps `language-common/execute`, and prepends initial state for http.
@@ -48,7 +57,7 @@ export function execute(...operations: Operations): Operation;
48
57
  /**
49
58
  * Used to isolate the type of content to retrieve from the message.
50
59
  */
51
- export type DesiredContent = any;
60
+ export type MessageContent = any;
52
61
  /**
53
62
  * Configurable options provided to the Gmail adaptor.
54
63
  */
package/types/Utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export function getMessagesResult(userId: any, query: any, lastPageToken: any): Promise<{
1
+ export function getMessagesResult(userId: any, query: any, pageToken: any): Promise<{
2
2
  messages: any;
3
3
  nextPageToken: any;
4
4
  }>;
@@ -8,7 +8,7 @@ export function getMessageResult(userId: any, messageId: any): Promise<{
8
8
  parts: any;
9
9
  headers: any;
10
10
  }>;
11
- export function getDesiredContent(hint: any): any;
11
+ export function getContentIndicators(defaultContentRequests: any, contentRequests: any): any[];
12
12
  export function getMessageContent(message: any, desiredContent: any): Promise<any>;
13
13
  export function createConnection(state: any): any;
14
14
  export function removeConnection(state: any): any;