zapier-platform-core 11.1.1 → 11.2.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 CHANGED
@@ -1,4 +1,3 @@
1
1
  Copyright (c) Zapier, Inc.
2
2
 
3
- This repository is part of Zapier Platform, of which license terms can be found at
4
- https://zapier.com/platform/tos.
3
+ This repository is part of Zapier Platform. By downloading, installing, accessing, or using any part of the Zapier Platform, including this repository, you agree to the Zapier Platform Agreement, which can be found at: https://zapier.com/platform/tos. If you do not agree to the Zapier Platform Agreement, you may not download, install, access, or use any part of the Zapier Platform, including this repository.
package/index.d.ts CHANGED
@@ -71,6 +71,9 @@ declare class AppError extends Error {
71
71
  declare class HaltedError extends Error {}
72
72
  declare class ExpiredAuthError extends Error {}
73
73
  declare class RefreshAuthError extends Error {}
74
+ declare class ThrottledError extends Error {
75
+ constructor(message: string, delay?: number);
76
+ }
74
77
 
75
78
  // copied http stuff from external typings
76
79
  export interface HttpRequestOptions {
@@ -188,5 +191,6 @@ export interface ZObject {
188
191
  HaltedError: typeof HaltedError;
189
192
  ExpiredAuthError: typeof ExpiredAuthError;
190
193
  RefreshAuthError: typeof RefreshAuthError;
194
+ ThrottledError: typeof ThrottledError;
191
195
  };
192
196
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapier-platform-core",
3
- "version": "11.1.1",
3
+ "version": "11.2.0",
4
4
  "description": "The core SDK for CLI apps in the Zapier Developer Platform.",
5
5
  "repository": "zapier/zapier-platform",
6
6
  "homepage": "https://platform.zapier.com/",
@@ -35,7 +35,7 @@
35
35
  "validate": "yarn test && yarn smoke-test && yarn lint"
36
36
  },
37
37
  "engines": {
38
- "node": ">=10",
38
+ "node": ">=12",
39
39
  "npm": ">=5.6.0"
40
40
  },
41
41
  "engineStrict": true,
@@ -46,14 +46,16 @@
46
46
  "dotenv": "9.0.2",
47
47
  "form-data": "4.0.0",
48
48
  "lodash": "4.17.21",
49
- "node-fetch": "2.6.1",
49
+ "mime-types": "2.1.34",
50
+ "node-fetch": "2.6.6",
50
51
  "oauth-sign": "0.9.0",
51
52
  "semver": "7.3.5",
52
- "zapier-platform-schema": "11.1.1"
53
+ "zapier-platform-schema": "11.2.0"
53
54
  },
54
55
  "devDependencies": {
55
56
  "adm-zip": "0.5.5",
56
57
  "aws-sdk": "^2.905.0",
58
+ "dicer": "^0.3.0",
57
59
  "fs-extra": "^10.0.0",
58
60
  "mock-fs": "^4.14.0"
59
61
  },
package/src/errors.js CHANGED
@@ -32,6 +32,7 @@ class ResponseError extends Error {
32
32
  status: response.status,
33
33
  headers: {
34
34
  'content-type': response.headers.get('content-type'),
35
+ 'retry-after': response.headers.get('retry-after'),
35
36
  },
36
37
  content,
37
38
  request: {
@@ -44,6 +45,19 @@ class ResponseError extends Error {
44
45
  }
45
46
  }
46
47
 
48
+ class ThrottledError extends Error {
49
+ constructor(message, delay) {
50
+ super(
51
+ JSON.stringify({
52
+ message,
53
+ delay,
54
+ })
55
+ );
56
+ this.name = 'ThrottledError';
57
+ this.doNotContextify = true;
58
+ }
59
+ }
60
+
47
61
  // Make some of the errors we'll use!
48
62
  const createError = (name) => {
49
63
  const NewError = function (message = '') {
@@ -77,6 +91,7 @@ const exceptions = _.reduce(
77
91
  {
78
92
  Error: AppError,
79
93
  ResponseError,
94
+ ThrottledError,
80
95
  }
81
96
  );
82
97
 
@@ -1,14 +1,18 @@
1
1
  'use strict';
2
2
 
3
- const _ = require('lodash');
3
+ const fs = require('fs');
4
+ const os = require('os');
4
5
  const path = require('path');
5
- const FormData = require('form-data');
6
+ const { pipeline } = require('stream');
7
+ const { promisify } = require('util');
8
+ const { randomBytes } = require('crypto');
9
+
10
+ const _ = require('lodash');
6
11
  const contentDisposition = require('content-disposition');
12
+ const FormData = require('form-data');
13
+ const mime = require('mime-types');
7
14
 
8
15
  const request = require('./request-client-internal');
9
- const ZapierPromise = require('./promise');
10
-
11
- const isPromise = (obj) => obj && typeof obj.then === 'function';
12
16
 
13
17
  const UPLOAD_MAX_SIZE = 1000 * 1000 * 150; // 150mb, in zapier backend too
14
18
 
@@ -19,32 +23,186 @@ const LENGTH_ERR_MESSAGE =
19
23
  const DEFAULT_FILE_NAME = 'unnamedfile';
20
24
  const DEFAULT_CONTENT_TYPE = 'application/octet-stream';
21
25
 
22
- const uploader = (
26
+ const streamPipeline = promisify(pipeline);
27
+
28
+ const filenameFromURL = (url) => {
29
+ try {
30
+ return decodeURIComponent(path.posix.basename(new URL(url).pathname));
31
+ } catch (error) {
32
+ return null;
33
+ }
34
+ };
35
+
36
+ const filenameFromHeader = (response) => {
37
+ const cd = response.headers.get('content-disposition');
38
+ let filename;
39
+ if (cd) {
40
+ try {
41
+ filename = contentDisposition.parse(cd).parameters.filename;
42
+ } catch (error) {
43
+ return null;
44
+ }
45
+ }
46
+ return filename || null;
47
+ };
48
+
49
+ const resolveRemoteStream = async (stream) => {
50
+ // Download to a temp file, get the file size, and create a readable stream
51
+ // from the temp file.
52
+ //
53
+ // The streamPipeline usage is taken from
54
+ // https://github.com/node-fetch/node-fetch#streams
55
+ const tmpFilePath = path.join(
56
+ os.tmpdir(),
57
+ 'stash-' + randomBytes(16).toString('hex')
58
+ );
59
+
60
+ try {
61
+ await streamPipeline(stream, fs.createWriteStream(tmpFilePath));
62
+ } catch (error) {
63
+ try {
64
+ fs.unlinkSync(tmpFilePath);
65
+ } catch (e) {
66
+ // File doesn't exist? Probably okay
67
+ }
68
+ throw error;
69
+ }
70
+
71
+ const length = fs.statSync(tmpFilePath).size;
72
+ const readStream = fs.createReadStream(tmpFilePath);
73
+
74
+ readStream.on('end', () => {
75
+ // Burn after reading
76
+ try {
77
+ fs.unlinkSync(tmpFilePath);
78
+ } catch (e) {
79
+ // TODO: We probably want to log warning here
80
+ }
81
+ });
82
+
83
+ return {
84
+ streamOrData: readStream,
85
+ length,
86
+ };
87
+ };
88
+
89
+ const resolveResponseToStream = async (response) => {
90
+ // Get filename from content-disposition header or URL
91
+ let filename =
92
+ filenameFromHeader(response) ||
93
+ filenameFromURL(response.url || _.get(response, ['request', 'url'])) ||
94
+ DEFAULT_FILE_NAME;
95
+
96
+ const contentType = response.headers.get('content-type');
97
+ if (contentType && !path.extname(filename)) {
98
+ const ext = mime.extension(contentType);
99
+ if (ext && ext !== 'bin') {
100
+ filename += '.' + ext;
101
+ }
102
+ }
103
+
104
+ if (response.body && typeof response.body.pipe === 'function') {
105
+ // streamable response created by z.request({ raw: true })
106
+ return {
107
+ ...(await resolveRemoteStream(response.body)),
108
+ contentType: contentType || DEFAULT_CONTENT_TYPE,
109
+ filename,
110
+ };
111
+ }
112
+
113
+ // regular response created by z.request({ raw: false })
114
+ return {
115
+ streamOrData: response.content,
116
+ length: Buffer.byteLength(response.content),
117
+ contentType: contentType || DEFAULT_CONTENT_TYPE,
118
+ filename,
119
+ };
120
+ };
121
+
122
+ const resolveStreamWithMeta = async (stream) => {
123
+ const isLocalFile = stream.path && fs.existsSync(stream.path);
124
+ if (isLocalFile) {
125
+ const filename = path.basename(stream.path);
126
+ return {
127
+ streamOrData: stream,
128
+ length: fs.statSync(stream.path).size,
129
+ contentType: mime.lookup(filename) || DEFAULT_CONTENT_TYPE,
130
+ filename,
131
+ };
132
+ }
133
+
134
+ return {
135
+ ...(await resolveRemoteStream(stream)),
136
+ contentType: DEFAULT_CONTENT_TYPE,
137
+ filename: DEFAULT_FILE_NAME,
138
+ };
139
+ };
140
+
141
+ // Returns an object with fields:
142
+ // * streamOrData: a readable stream, a string, or a Buffer
143
+ // * length: content length in bytes
144
+ // * contentType
145
+ // * filename
146
+ const resolveToBufferStringStream = async (responseOrData) => {
147
+ if (typeof responseOrData === 'string' || responseOrData instanceof String) {
148
+ // The .toString() call only makes a difference for the String object case.
149
+ // It converts a String object to a regular string.
150
+ const str = responseOrData.toString();
151
+ return {
152
+ streamOrData: str,
153
+ length: Buffer.byteLength(str),
154
+ contentType: 'text/plain',
155
+ filename: `${DEFAULT_FILE_NAME}.txt`,
156
+ };
157
+ } else if (Buffer.isBuffer(responseOrData)) {
158
+ return {
159
+ streamOrData: responseOrData,
160
+ length: responseOrData.length,
161
+ contentType: DEFAULT_CONTENT_TYPE,
162
+ filename: DEFAULT_FILE_NAME,
163
+ };
164
+ } else if (
165
+ (responseOrData.body && typeof responseOrData.body.pipe === 'function') ||
166
+ typeof responseOrData.content === 'string'
167
+ ) {
168
+ return resolveResponseToStream(responseOrData);
169
+ } else if (typeof responseOrData.pipe === 'function') {
170
+ return resolveStreamWithMeta(responseOrData);
171
+ }
172
+
173
+ throw new TypeError(
174
+ `z.stashFile() cannot stash type '${typeof responseOrData}'. ` +
175
+ 'Pass it a request, readable stream, string, or Buffer.'
176
+ );
177
+ };
178
+
179
+ const uploader = async (
23
180
  signedPostData,
24
181
  bufferStringStream,
25
182
  knownLength,
26
183
  filename,
27
184
  contentType
28
185
  ) => {
29
- const form = new FormData();
30
-
31
186
  if (knownLength && knownLength > UPLOAD_MAX_SIZE) {
32
- return ZapierPromise.reject(
33
- new Error(`${knownLength} is too big, ${UPLOAD_MAX_SIZE} is the max`)
34
- );
187
+ throw new Error(`${knownLength} is too big, ${UPLOAD_MAX_SIZE} is the max`);
35
188
  }
189
+ filename = path.basename(filename).replace('"', '');
36
190
 
37
- _.each(signedPostData.fields, (value, key) => {
38
- form.append(key, value);
39
- });
191
+ const fields = {
192
+ ...signedPostData.fields,
193
+ 'Content-Disposition': contentDisposition(filename),
194
+ 'Content-Type': contentType,
195
+ };
40
196
 
41
- filename = path.basename(filename || DEFAULT_FILE_NAME).replace('"', '');
197
+ const form = new FormData();
42
198
 
43
- form.append('Content-Disposition', contentDisposition(filename));
199
+ Object.entries(fields).forEach(([key, value]) => {
200
+ form.append(key, value);
201
+ });
44
202
 
45
203
  form.append('file', bufferStringStream, {
46
- contentType,
47
204
  knownLength,
205
+ contentType,
48
206
  filename,
49
207
  });
50
208
 
@@ -56,120 +214,93 @@ const uploader = (
56
214
  }
57
215
 
58
216
  // Send to S3 with presigned request.
59
- return request({
217
+ const response = await request({
60
218
  url: signedPostData.url,
61
219
  method: 'POST',
62
220
  body: form,
63
- }).then((res) => {
64
- if (res.status === 204) {
65
- return `${signedPostData.url}${signedPostData.fields.key}`;
66
- }
67
- if (
68
- res.content.indexOf(
69
- 'You must provide the Content-Length HTTP header.'
70
- ) !== -1
71
- ) {
72
- throw new Error(LENGTH_ERR_MESSAGE);
73
- }
74
- throw new Error(`Got ${res.status} - ${res.content}`);
75
221
  });
222
+
223
+ if (response.status === 204) {
224
+ return new URL(signedPostData.fields.key, signedPostData.url).href;
225
+ }
226
+
227
+ if (
228
+ response.content &&
229
+ response.content.includes &&
230
+ response.content.includes(
231
+ 'You must provide the Content-Length HTTP header.'
232
+ )
233
+ ) {
234
+ throw new Error(LENGTH_ERR_MESSAGE);
235
+ }
236
+
237
+ throw new Error(`Got ${response.status} - ${response.content}`);
76
238
  };
77
239
 
78
240
  // Designed to be some user provided function/api.
79
241
  const createFileStasher = (input) => {
80
242
  const rpc = _.get(input, '_zapier.rpc');
81
243
 
82
- return (bufferStringStream, knownLength, filename, contentType) => {
244
+ return async (requestOrData, knownLength, filename, contentType) => {
83
245
  // TODO: maybe this could be smart?
84
246
  // if it is already a public url, do we pass through? or upload?
85
247
  if (!rpc) {
86
- return ZapierPromise.reject(new Error('rpc is not available'));
248
+ throw new Error('rpc is not available');
87
249
  }
88
250
 
89
- const method = _.get(input, ['_zapier', 'event', 'method'], '');
90
- const isValidSource =
91
- method.startsWith('hydrators.') ||
92
- method.startsWith('creates.') ||
93
- // key regex from KeySchema
94
- method.match(/^resources\.[a-zA-Z][a-zA-Z0-9_]*\.create\./);
95
-
96
- if (!isValidSource) {
97
- return ZapierPromise.reject(
98
- new Error(
99
- 'Files can only be stashed within a create or hydration function/method.'
100
- )
251
+ const isRunningOnHydrator = _.get(
252
+ input,
253
+ '_zapier.event.method',
254
+ ''
255
+ ).startsWith('hydrators.');
256
+ const isRunningOnCreate = _.get(
257
+ input,
258
+ '_zapier.event.method',
259
+ ''
260
+ ).startsWith('creates.');
261
+
262
+ if (!isRunningOnHydrator && !isRunningOnCreate) {
263
+ throw new Error(
264
+ 'Files can only be stashed within a create or hydration function/method.'
101
265
  );
102
266
  }
103
267
 
104
- const fileContentType = contentType || DEFAULT_CONTENT_TYPE;
105
-
106
- return rpc('get_presigned_upload_post_data', fileContentType).then(
107
- (result) => {
108
- const parseFinalResponse = (stream) => {
109
- let newBufferStringStream = stream;
110
-
111
- // if stream is string, don't update headers, just return as is
112
- if (_.isString(stream)) {
113
- newBufferStringStream = stream;
114
- } else if (stream) {
115
- if (Buffer.isBuffer(stream)) {
116
- newBufferStringStream = stream;
117
- } else if (Buffer.isBuffer(stream.dataBuffer)) {
118
- newBufferStringStream = stream.dataBuffer;
119
- } else if (stream.body && typeof stream.body.pipe === 'function') {
120
- newBufferStringStream = stream.body;
121
- } else if (stream.content) {
122
- newBufferStringStream = stream.content;
123
- }
124
-
125
- // if stream has headers update knownLength and filename to reflect the header values
126
- if (stream.headers) {
127
- knownLength = knownLength || stream.getHeader('content-length');
128
- const cd = stream.getHeader('content-disposition');
129
- if (cd) {
130
- filename =
131
- filename || contentDisposition.parse(cd).parameters.filename;
132
- }
133
- }
134
- // if stream is not defined, error
135
- } else {
136
- throw new Error('Cannot stash a file of unknown type.');
137
- }
138
-
139
- // send final response to uploader
140
- return uploader(
141
- result,
142
- newBufferStringStream,
143
- knownLength,
144
- filename,
145
- fileContentType
146
- );
147
- };
148
-
149
- const formResponse = (response) => {
150
- // determine if string is streamed based on if raw:true
151
- const isStreamed = _.get(response, 'request.raw', false);
152
-
153
- // if it's streamed, buffer first
154
- if (isStreamed) {
155
- return response.buffer().then((buffer) => {
156
- response.dataBuffer = buffer;
157
- return parseFinalResponse(response);
158
- });
159
- } else {
160
- return parseFinalResponse(response);
161
- }
162
- };
163
-
164
- // if stream is a promise, wait until resolved
165
- if (isPromise(bufferStringStream)) {
166
- return bufferStringStream.then((maybeResponse) => {
167
- return formResponse(maybeResponse);
168
- });
169
- } else {
170
- return formResponse(bufferStringStream);
171
- }
172
- }
268
+ // requestOrData can be one of these:
269
+ // * string
270
+ // * Buffer
271
+ // * z.request() - a Promise of a regular response
272
+ // * z.request({ raw: true }) - a Promise of a "streamable" response
273
+ // * await z.request() - a regular response
274
+ // * await z.request({ raw: true }) - a streamable response
275
+ //
276
+ // After the following, requestOrData is resolved to responseOrData, which
277
+ // is either:
278
+ // - string
279
+ // - Buffer
280
+ // - a regular response
281
+ // - a streamable response
282
+ const [signedPostData, responseOrData] = await Promise.all([
283
+ rpc('get_presigned_upload_post_data'),
284
+ requestOrData,
285
+ ]);
286
+
287
+ if (responseOrData.throwForStatus) {
288
+ responseOrData.throwForStatus();
289
+ }
290
+
291
+ const {
292
+ streamOrData,
293
+ length,
294
+ contentType: _contentType,
295
+ filename: _filename,
296
+ } = await resolveToBufferStringStream(responseOrData);
297
+
298
+ return uploader(
299
+ signedPostData,
300
+ streamOrData,
301
+ knownLength || length,
302
+ filename || _filename,
303
+ contentType || _contentType
173
304
  );
174
305
  };
175
306
  };
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Writable } = require('stream');
4
+
3
5
  const fetch = require('node-fetch');
4
6
 
5
7
  // XXX: PatchedRequest is to get past node-fetch's check that forbids GET requests
@@ -7,10 +9,10 @@ const fetch = require('node-fetch');
7
9
  // https://github.com/node-fetch/node-fetch/blob/v2.6.0/src/request.js#L75-L78
8
10
  class PatchedRequest extends fetch.Request {
9
11
  constructor(url, opts) {
10
- const origMethod = (opts.method || 'GET').toUpperCase();
12
+ const origMethod = ((opts && opts.method) || 'GET').toUpperCase();
11
13
 
12
14
  const isGetWithBody =
13
- (origMethod === 'GET' || origMethod === 'HEAD') && opts.body;
15
+ (origMethod === 'GET' || origMethod === 'HEAD') && opts && opts.body;
14
16
  let newOpts = opts;
15
17
  if (isGetWithBody) {
16
18
  // Temporary remove body to fool fetch.Request constructor
@@ -50,9 +52,31 @@ class PatchedRequest extends fetch.Request {
50
52
 
51
53
  const newFetch = (url, opts) => {
52
54
  const request = new PatchedRequest(url, opts);
55
+
53
56
  // fetch actually accepts a Request object as an argument. It'll clone the
54
57
  // request internally, that's why the PatchedRequest.body hack works.
55
- return fetch(request);
58
+ const responsePromise = fetch(request);
59
+
60
+ // node-fetch clones request.body and use the cloned body internally. We need
61
+ // to make sure to consume the original body stream so its internal buffer is
62
+ // not filled up, which causes it to pause.
63
+ // See https://github.com/node-fetch/node-fetch/issues/151
64
+ //
65
+ // Exclude form-data object to be consistent with
66
+ // https://github.com/node-fetch/node-fetch/blob/v2.6.6/src/body.js#L403-L412
67
+ if (
68
+ request.body &&
69
+ typeof request.body.pipe === 'function' &&
70
+ typeof request.body.getBoundary !== 'function'
71
+ ) {
72
+ const nullStream = new Writable();
73
+ nullStream._write = function (chunk, encoding, done) {
74
+ done();
75
+ };
76
+ request.body.pipe(nullStream);
77
+ }
78
+
79
+ return responsePromise;
56
80
  };
57
81
 
58
82
  newFetch.Promise = require('./promise');