-
-
Notifications
You must be signed in to change notification settings - Fork 734
/
common.js
428 lines (375 loc) · 12.5 KB
/
common.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
'use strict'
const _ = require('lodash')
const debug = require('debug')('nock.common')
/**
* Normalizes the request options so that it always has `host` property.
*
* @param {Object} options - a parsed options object of the request
*/
const normalizeRequestOptions = function(options) {
options.proto = options.proto || 'http'
options.port = options.port || (options.proto === 'http' ? 80 : 443)
if (options.host) {
debug('options.host:', options.host)
if (!options.hostname) {
if (options.host.split(':').length == 2) {
options.hostname = options.host.split(':')[0]
} else {
options.hostname = options.host
}
}
}
debug('options.hostname in the end: %j', options.hostname)
options.host = `${options.hostname || 'localhost'}:${options.port}`
debug('options.host in the end: %j', options.host)
/// lowercase host names
;['hostname', 'host'].forEach(function(attr) {
if (options[attr]) {
options[attr] = options[attr].toLowerCase()
}
})
return options
}
/**
* Returns false if the data contained in buffer can be reconstructed
* from its utf8 representation.
*
* TODO: Reverse the semantics of this method and refactor calling code
* accordingly. We've inadvertantly gotten it flipped.
*
* @param {Object} buffer - a Buffer object
*/
const isUtf8Representable = function(buffer) {
if (!Buffer.isBuffer(buffer)) {
return false
}
const utfEncodedBuffer = buffer.toString('utf8')
const reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8')
return !reconstructedBuffer.equals(buffer)
}
/**
* If the chunks are Buffer objects then it returns a single Buffer object with the data from all the chunks.
* If the chunks are strings then it returns a single string value with data from all the chunks.
*
* @param {Array} chunks - an array of Buffer objects or strings
*/
const mergeChunks = function(chunks) {
if (_.isEmpty(chunks)) {
return Buffer.alloc(0)
}
// We assume that all chunks are Buffer objects if the first is buffer object.
const areBuffers = Buffer.isBuffer(_.first(chunks))
if (!areBuffers) {
// TODO-coverage: In reality is this ever called with strings instead of
// buffers? Either add a functional test or remove this.
return chunks.join('')
}
return Buffer.concat(chunks)
}
// Array where all information about all the overridden requests are held.
let requestOverride = []
/**
* Overrides the current `request` function of `http` and `https` modules with
* our own version which intercepts issues HTTP/HTTPS requests and forwards them
* to the given `newRequest` function.
*
* @param {Function} newRequest - a function handling requests; it accepts four arguments:
* - proto - a string with the overridden module's protocol name (either `http` or `https`)
* - overriddenRequest - the overridden module's request function already bound to module's object
* - options - the options of the issued request
* - callback - the callback of the issued request
*/
const overrideRequests = function(newRequest) {
debug('overriding requests')
;['http', 'https'].forEach(function(proto) {
debug('- overriding request for', proto)
const moduleName = proto // 1 to 1 match of protocol and module is fortunate :)
const module = {
http: require('http'),
https: require('https'),
}[moduleName]
const overriddenRequest = module.request
const overriddenGet = module.get
if (requestOverride[moduleName]) {
throw new Error(
`Module's request already overridden for ${moduleName} protocol.`
)
}
// Store the properties of the overridden request so that it can be restored later on.
requestOverride[moduleName] = {
module,
request: overriddenRequest,
get: overriddenGet,
}
module.request = function(options, callback) {
// debug('request options:', options);
return newRequest(
proto,
overriddenRequest.bind(module),
options,
callback
)
}
module.get = function(options, callback) {
const req = newRequest(
proto,
overriddenRequest.bind(module),
options,
callback
)
req.end()
return req
}
debug('- overridden request for', proto)
})
}
/**
* Restores `request` function of `http` and `https` modules to values they
* held before they were overridden by us.
*/
const restoreOverriddenRequests = function() {
debug('restoring requests')
// Restore any overridden requests.
_(requestOverride)
.keys()
.each(function(proto) {
debug('- restoring request for', proto)
const override = requestOverride[proto]
// TODO-coverage: `override` is always truthy. Refactor to eliminate the
// uncovered line.
if (override) {
override.module.request = override.request
override.module.get = override.get
debug('- restored request for', proto)
}
})
requestOverride = []
}
/**
* Get high level information about request as string
* @param {Object} options
* @param {string} options.method
* @param {string} options.port
* @param {string} options.proto
* @param {string} options.hostname
* @param {string} options.path
* @param {Object} options.headers
* @param {string|object} body
* @return {string}
*/
function stringifyRequest(options, body) {
const method = options.method || 'GET'
let { port } = options
// TODO-coverage: Add a test to cover the missing condition, or remove if
// not reachable.
if (!port) port = options.proto == 'https' ? '443' : '80'
if (
(options.proto == 'https' && port == '443') ||
(options.proto == 'http' && port == '80')
) {
port = ''
}
if (port) port = `:${port}`
// TODO-coverage: Add a test to cover the missing condition, or remove if
// not reachable.
const path = options.path ? options.path : ''
const log = {
method,
url: `${options.proto}://${options.hostname}${port}${path}`,
headers: options.headers,
}
if (body) {
log.body = body
}
return JSON.stringify(log, null, 2)
}
function isContentEncoded(headers) {
const contentEncoding = _.get(headers, 'content-encoding')
return _.isString(contentEncoding) && contentEncoding !== ''
}
function contentEncoding(headers, encoder) {
const contentEncoding = _.get(headers, 'content-encoding')
return contentEncoding === encoder
}
function isJSONContent(headers) {
let contentType = _.get(headers, 'content-type')
if (Array.isArray(contentType)) {
contentType = contentType[0]
}
contentType = (contentType || '').toLocaleLowerCase()
return contentType === 'application/json'
}
const headersFieldNamesToLowerCase = function(headers) {
if (!_.isObject(headers)) {
// TODO-coverage: Add a test to cover the missing condition, or remove if
// not reachable.
return headers
}
// For each key in the headers, delete its value and reinsert it with lower-case key.
// Keys represent headers field names.
const lowerCaseHeaders = {}
_.forOwn(headers, function(fieldVal, fieldName) {
const lowerCaseFieldName = fieldName.toLowerCase()
if (!_.isUndefined(lowerCaseHeaders[lowerCaseFieldName])) {
throw new Error(
`Failed to convert header keys to lower case due to field name conflict: ${lowerCaseFieldName}`
)
}
lowerCaseHeaders[lowerCaseFieldName] = fieldVal
})
return lowerCaseHeaders
}
const headersFieldsArrayToLowerCase = function(headers) {
return _.uniq(
_.map(headers, function(fieldName) {
return fieldName.toLowerCase()
})
)
}
const headersArrayToObject = function(rawHeaders) {
if (!_.isArray(rawHeaders)) {
return rawHeaders
}
const headers = {}
for (let i = 0, len = rawHeaders.length; i < len; i = i + 2) {
const key = rawHeaders[i].toLowerCase()
const value = rawHeaders[i + 1]
if (headers[key]) {
headers[key] = _.isArray(headers[key]) ? headers[key] : [headers[key]]
headers[key].push(value)
} else {
headers[key] = value
}
}
return headers
}
/**
* Deletes the given `fieldName` property from `headers` object by performing
* case-insensitive search through keys.
*
* @headers {Object} headers - object of header field names and values
* @fieldName {String} field name - string with the case-insensitive field name
*/
const deleteHeadersField = function(headers, fieldNameToDelete) {
if (!_.isObject(headers) || !_.isString(fieldNameToDelete)) {
// TODO-coverage: For `_.isObject(headers)`, add a test to cover the
// missing condition, or remove if not reachable. For
// `_.isString(fieldNameToDelete)`, throw an error and add a test covering
// this case.
return
}
const lowerCaseFieldNameToDelete = fieldNameToDelete.toLowerCase()
// Search through the headers and delete all values whose field name matches the given field name.
_(headers)
.keys()
.each(function(fieldName) {
const lowerCaseFieldName = fieldName.toLowerCase()
if (lowerCaseFieldName === lowerCaseFieldNameToDelete) {
delete headers[fieldName]
// We don't stop here but continue in order to remove *all* matching field names
// (even though if seen regorously there shouldn't be any)
}
})
}
function percentDecode(str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '))
} catch (e) {
return str
}
}
function percentEncode(str) {
// TODO-coverage: either replace this with a library function or add a
// function test which checks that this is correct.
// This looks like:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return `%${c
.charCodeAt(0)
.toString(16)
.toUpperCase()}`
})
}
function matchStringOrRegexp(target, pattern) {
const str =
(!_.isUndefined(target) && target.toString && target.toString()) || ''
return pattern instanceof RegExp
? str.match(pattern)
: str === String(pattern)
}
/**
* Formats a query parameter.
*
* @param key The key of the query parameter to format.
* @param value The value of the query parameter to format.
* @param stringFormattingFn The function used to format string values. Can
* be used to encode or decode the query value.
*
* @returns the formatted [key, value] pair.
*/
function formatQueryValue(key, value, stringFormattingFn) {
// TODO-coverage: Find out what's not covered. Probably refactor code to
// replace `switch(true)` with `if`/`else`.
switch (true) {
case _.isNumber(value): // fall-through
case _.isBoolean(value):
value = value.toString()
break
case _.isUndefined(value): // fall-through
case _.isNull(value):
value = ''
break
case _.isString(value):
if (stringFormattingFn) {
value = stringFormattingFn(value)
}
break
case value instanceof RegExp:
break
case _.isArray(value): {
const tmpArray = new Array(value.length)
for (let i = 0; i < value.length; ++i) {
tmpArray[i] = formatQueryValue(i, value[i], stringFormattingFn)[1]
}
value = tmpArray
break
}
case _.isObject(value): {
const tmpObj = {}
_.forOwn(value, function(subVal, subKey) {
const subPair = formatQueryValue(subKey, subVal, stringFormattingFn)
tmpObj[subPair[0]] = subPair[1]
})
value = tmpObj
break
}
}
if (stringFormattingFn) key = stringFormattingFn(key)
return [key, value]
}
function isStream(obj) {
return (
obj &&
typeof a !== 'string' &&
!Buffer.isBuffer(obj) &&
_.isFunction(obj.setEncoding)
)
}
exports.normalizeRequestOptions = normalizeRequestOptions
exports.isUtf8Representable = isUtf8Representable
exports.mergeChunks = mergeChunks
exports.overrideRequests = overrideRequests
exports.restoreOverriddenRequests = restoreOverriddenRequests
exports.stringifyRequest = stringifyRequest
exports.isContentEncoded = isContentEncoded
exports.contentEncoding = contentEncoding
exports.isJSONContent = isJSONContent
exports.headersFieldNamesToLowerCase = headersFieldNamesToLowerCase
exports.headersFieldsArrayToLowerCase = headersFieldsArrayToLowerCase
exports.headersArrayToObject = headersArrayToObject
exports.deleteHeadersField = deleteHeadersField
exports.percentEncode = percentEncode
exports.percentDecode = percentDecode
exports.matchStringOrRegexp = matchStringOrRegexp
exports.formatQueryValue = formatQueryValue
exports.isStream = isStream