-
Notifications
You must be signed in to change notification settings - Fork 749
/
utils.js
451 lines (397 loc) · 11.5 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
'use strict';
const EventEmitter = require('events').EventEmitter;
const qs = require('qs');
const crypto = require('crypto');
const hasOwn = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
// Certain sandboxed environments (our known example right now are CloudFlare
// Workers) may make `child_process` unavailable. Because `exec` isn't critical
// to the operation of stripe-node, we handle this unavailability gracefully.
let exec = null;
try {
exec = require('child_process').exec;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
}
const OPTIONS_KEYS = [
'apiKey',
'idempotencyKey',
'stripeAccount',
'apiVersion',
'maxNetworkRetries',
'timeout',
'host',
];
const DEPRECATED_OPTIONS = {
api_key: 'apiKey',
idempotency_key: 'idempotencyKey',
stripe_account: 'stripeAccount',
stripe_version: 'apiVersion',
stripeVersion: 'apiVersion',
};
const DEPRECATED_OPTIONS_KEYS = Object.keys(DEPRECATED_OPTIONS);
const utils = (module.exports = {
isOptionsHash(o) {
return (
o &&
typeof o === 'object' &&
(OPTIONS_KEYS.some((prop) => hasOwn(o, prop)) ||
DEPRECATED_OPTIONS_KEYS.some((prop) => hasOwn(o, prop)))
);
},
/**
* Stringifies an Object, accommodating nested objects
* (forming the conventional key 'parent[child]=value')
*/
stringifyRequestData: (data) => {
return (
qs
.stringify(data, {
serializeDate: (d) => Math.floor(d.getTime() / 1000),
})
// Don't use strict form encoding by changing the square bracket control
// characters back to their literals. This is fine by the server, and
// makes these parameter strings easier to read.
.replace(/%5B/g, '[')
.replace(/%5D/g, ']')
);
},
/**
* Outputs a new function with interpolated object property values.
* Use like so:
* const fn = makeURLInterpolator('some/url/{param1}/{param2}');
* fn({ param1: 123, param2: 456 }); // => 'some/url/123/456'
*/
makeURLInterpolator: (() => {
const rc = {
'\n': '\\n',
'"': '\\"',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
};
return (str) => {
const cleanString = str.replace(/["\n\r\u2028\u2029]/g, ($0) => rc[$0]);
return (outputs) => {
return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) =>
encodeURIComponent(outputs[$1] || '')
);
};
};
})(),
extractUrlParams: (path) => {
const params = path.match(/\{\w+\}/g);
if (!params) {
return [];
}
return params.map((param) => param.replace(/[{}]/g, ''));
},
/**
* Return the data argument from a list of arguments
*
* @param {object[]} args
* @returns {object}
*/
getDataFromArgs(args) {
if (!Array.isArray(args) || !args[0] || typeof args[0] !== 'object') {
return {};
}
if (!utils.isOptionsHash(args[0])) {
return args.shift();
}
const argKeys = Object.keys(args[0]);
const optionKeysInArgs = argKeys.filter((key) =>
OPTIONS_KEYS.includes(key)
);
// In some cases options may be the provided as the first argument.
// Here we're detecting a case where there are two distinct arguments
// (the first being args and the second options) and with known
// option keys in the first so that we can warn the user about it.
if (
optionKeysInArgs.length > 0 &&
optionKeysInArgs.length !== argKeys.length
) {
emitWarning(
`Options found in arguments (${optionKeysInArgs.join(
', '
)}). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.`
);
}
return {};
},
/**
* Return the options hash from a list of arguments
*/
getOptionsFromArgs: (args) => {
const opts = {
auth: null,
headers: {},
settings: {},
};
if (args.length > 0) {
const arg = args[args.length - 1];
if (typeof arg === 'string') {
opts.auth = args.pop();
} else if (utils.isOptionsHash(arg)) {
const params = {...args.pop()};
const extraKeys = Object.keys(params).filter(
(key) => !OPTIONS_KEYS.includes(key)
);
if (extraKeys.length) {
const nonDeprecated = extraKeys.filter((key) => {
if (!DEPRECATED_OPTIONS[key]) {
return true;
}
const newParam = DEPRECATED_OPTIONS[key];
if (params[newParam]) {
throw Error(
`Both '${newParam}' and '${key}' were provided; please remove '${key}', which is deprecated.`
);
}
/**
* TODO turn this into a hard error in a future major version (once we have fixed our docs).
*/
emitWarning(`'${key}' is deprecated; use '${newParam}' instead.`);
params[newParam] = params[key];
});
if (nonDeprecated.length) {
emitWarning(
`Invalid options found (${extraKeys.join(', ')}); ignoring.`
);
}
}
if (params.apiKey) {
opts.auth = params.apiKey;
}
if (params.idempotencyKey) {
opts.headers['Idempotency-Key'] = params.idempotencyKey;
}
if (params.stripeAccount) {
opts.headers['Stripe-Account'] = params.stripeAccount;
}
if (params.apiVersion) {
opts.headers['Stripe-Version'] = params.apiVersion;
}
if (Number.isInteger(params.maxNetworkRetries)) {
opts.settings.maxNetworkRetries = params.maxNetworkRetries;
}
if (Number.isInteger(params.timeout)) {
opts.settings.timeout = params.timeout;
}
if (params.host) {
opts.host = params.host;
}
}
}
return opts;
},
/**
* Provide simple "Class" extension mechanism
*/
protoExtend(sub) {
const Super = this;
const Constructor = hasOwn(sub, 'constructor')
? sub.constructor
: function(...args) {
Super.apply(this, args);
};
// This initialization logic is somewhat sensitive to be compatible with
// divergent JS implementations like the one found in Qt. See here for more
// context:
//
// https://github.com/stripe/stripe-node/pull/334
Object.assign(Constructor, Super);
Constructor.prototype = Object.create(Super.prototype);
Object.assign(Constructor.prototype, sub);
return Constructor;
},
/**
* Secure compare, from https://github.com/freewil/scmp
*/
secureCompare: (a, b) => {
a = Buffer.from(a);
b = Buffer.from(b);
// return early here if buffer lengths are not equal since timingSafeEqual
// will throw if buffer lengths are not equal
if (a.length !== b.length) {
return false;
}
// use crypto.timingSafeEqual if available (since Node.js v6.6.0),
// otherwise use our own scmp-internal function.
if (crypto.timingSafeEqual) {
return crypto.timingSafeEqual(a, b);
}
const len = a.length;
let result = 0;
for (let i = 0; i < len; ++i) {
result |= a[i] ^ b[i];
}
return result === 0;
},
/**
* Remove empty values from an object
*/
removeNullish: (obj) => {
if (typeof obj !== 'object') {
throw new Error('Argument must be an object');
}
return Object.keys(obj).reduce((result, key) => {
if (obj[key] != null) {
result[key] = obj[key];
}
return result;
}, {});
},
/**
* Normalize standard HTTP Headers:
* {'foo-bar': 'hi'}
* becomes
* {'Foo-Bar': 'hi'}
*/
normalizeHeaders: (obj) => {
if (!(obj && typeof obj === 'object')) {
return obj;
}
return Object.keys(obj).reduce((result, header) => {
result[utils.normalizeHeader(header)] = obj[header];
return result;
}, {});
},
/**
* Stolen from https://github.com/marten-de-vries/header-case-normalizer/blob/master/index.js#L36-L41
* without the exceptions which are irrelevant to us.
*/
normalizeHeader: (header) => {
return header
.split('-')
.map(
(text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()
)
.join('-');
},
/**
* Determine if file data is a derivative of EventEmitter class.
* https://nodejs.org/api/events.html#events_events
*/
checkForStream: (obj) => {
if (obj.file && obj.file.data) {
return obj.file.data instanceof EventEmitter;
}
return false;
},
callbackifyPromiseWithTimeout: (promise, callback) => {
if (callback) {
// Ensure callback is called outside of promise stack.
return promise.then(
(res) => {
setTimeout(() => {
callback(null, res);
}, 0);
},
(err) => {
setTimeout(() => {
callback(err, null);
}, 0);
}
);
}
return promise;
},
/**
* Allow for special capitalization cases (such as OAuth)
*/
pascalToCamelCase: (name) => {
if (name === 'OAuth') {
return 'oauth';
} else {
return name[0].toLowerCase() + name.substring(1);
}
},
emitWarning,
/**
* Node's built in `exec` function sometimes throws outright,
* and sometimes has a callback with an error,
* depending on the type of error.
*
* This unifies that interface.
*/
safeExec: (cmd, cb) => {
// Occurs if we couldn't load the `child_process` module, which might
// happen in certain sandboxed environments like a CloudFlare Worker.
if (utils._exec === null) {
cb(new Error('exec not available'), null);
return;
}
try {
utils._exec(cmd, cb);
} catch (e) {
cb(e, null);
}
},
// For mocking in tests.
_exec: exec,
isObject: (obj) => {
const type = typeof obj;
return (type === 'function' || type === 'object') && !!obj;
},
// For use in multipart requests
flattenAndStringify: (data) => {
const result = {};
const step = (obj, prevKey) => {
Object.keys(obj).forEach((key) => {
const value = obj[key];
const newKey = prevKey ? `${prevKey}[${key}]` : key;
if (utils.isObject(value)) {
if (!Buffer.isBuffer(value) && !value.hasOwnProperty('data')) {
// Non-buffer non-file Objects are recursively flattened
return step(value, newKey);
} else {
// Buffers and file objects are stored without modification
result[newKey] = value;
}
} else {
// Primitives are converted to strings
result[newKey] = String(value);
}
});
};
step(data);
return result;
},
/**
* https://stackoverflow.com/a/2117523
*/
uuid4: () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
},
validateInteger: (name, n, defaultVal) => {
if (!Number.isInteger(n)) {
if (defaultVal !== undefined) {
return defaultVal;
} else {
throw new Error(`${name} must be an integer`);
}
}
return n;
},
determineProcessUserAgentProperties: () => {
return typeof process === 'undefined'
? {}
: {
lang_version: process.version,
platform: process.platform,
};
},
});
function emitWarning(warning) {
if (typeof process.emitWarning !== 'function') {
return console.warn(
`Stripe: ${warning}`
); /* eslint-disable-line no-console */
}
return process.emitWarning(warning, 'Stripe');
}