1 | 'use strict'
|
2 |
|
3 | const _ = require('lodash')
|
4 | const debug = require('debug')('nock.common')
|
5 | const url = require('url')
|
6 | const timers = require('timers')
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function normalizeRequestOptions(options) {
|
14 | options.proto = options.proto || 'http'
|
15 | options.port = options.port || (options.proto === 'http' ? 80 : 443)
|
16 | if (options.host) {
|
17 | debug('options.host:', options.host)
|
18 | if (!options.hostname) {
|
19 | if (options.host.split(':').length === 2) {
|
20 | options.hostname = options.host.split(':')[0]
|
21 | } else {
|
22 | options.hostname = options.host
|
23 | }
|
24 | }
|
25 | }
|
26 | debug('options.hostname in the end: %j', options.hostname)
|
27 | options.host = `${options.hostname || 'localhost'}:${options.port}`
|
28 | debug('options.host in the end: %j', options.host)
|
29 |
|
30 |
|
31 | ;['hostname', 'host'].forEach(function(attr) {
|
32 | if (options[attr]) {
|
33 | options[attr] = options[attr].toLowerCase()
|
34 | }
|
35 | })
|
36 |
|
37 | return options
|
38 | }
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | function isUtf8Representable(buffer) {
|
48 | const utfEncodedBuffer = buffer.toString('utf8')
|
49 | const reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8')
|
50 | return reconstructedBuffer.equals(buffer)
|
51 | }
|
52 |
|
53 |
|
54 | let requestOverrides = {}
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | function overrideRequests(newRequest) {
|
68 | debug('overriding requests')
|
69 | ;['http', 'https'].forEach(function(proto) {
|
70 | debug('- overriding request for', proto)
|
71 |
|
72 | const moduleName = proto
|
73 | const module = {
|
74 | http: require('http'),
|
75 | https: require('https'),
|
76 | }[moduleName]
|
77 | const overriddenRequest = module.request
|
78 | const overriddenGet = module.get
|
79 |
|
80 | if (requestOverrides[moduleName]) {
|
81 | throw new Error(
|
82 | `Module's request already overridden for ${moduleName} protocol.`
|
83 | )
|
84 | }
|
85 |
|
86 |
|
87 | requestOverrides[moduleName] = {
|
88 | module,
|
89 | request: overriddenRequest,
|
90 | get: overriddenGet,
|
91 | }
|
92 | // https://nodejs.org/api/http.html#http_http_request_url_options_callback
|
93 | module.request = function(input, options, callback) {
|
94 | return newRequest(proto, overriddenRequest.bind(module), [
|
95 | input,
|
96 | options,
|
97 | callback,
|
98 | ])
|
99 | }
|
100 |
|
101 | module.get = function(input, options, callback) {
|
102 | const req = newRequest(proto, overriddenGet.bind(module), [
|
103 | input,
|
104 | options,
|
105 | callback,
|
106 | ])
|
107 | req.end()
|
108 | return req
|
109 | }
|
110 |
|
111 | debug('- overridden request for', proto)
|
112 | })
|
113 | }
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 | function restoreOverriddenRequests() {
|
120 | debug('restoring requests')
|
121 | Object.entries(requestOverrides).forEach(
|
122 | ([proto, { module, request, get }]) => {
|
123 | debug('- restoring request for', proto)
|
124 | module.request = request
|
125 | module.get = get
|
126 | debug('- restored request for', proto)
|
127 | }
|
128 | )
|
129 | requestOverrides = {}
|
130 | }
|
131 |
|
132 |
|
133 |
|
134 |
|
135 |
|
136 | function normalizeOrigin(proto, host, port) {
|
137 | const hostHasPort = host.includes(':')
|
138 | const portIsStandard =
|
139 | (proto === 'http' && (port === 80 || port === '80')) ||
|
140 | (proto === 'https' && (port === 443 || port === '443'))
|
141 | const portStr = hostHasPort || portIsStandard ? '' : `:${port}`
|
142 |
|
143 | return `${proto}://${host}${portStr}`
|
144 | }
|
145 |
|
146 |
|
147 |
|
148 |
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 | function stringifyRequest(options, body) {
|
159 | const { method = 'GET', path = '', port } = options
|
160 | const origin = normalizeOrigin(options.proto, options.hostname, port)
|
161 |
|
162 | const log = {
|
163 | method,
|
164 | url: `${origin}${path}`,
|
165 | headers: options.headers,
|
166 | }
|
167 |
|
168 | if (body) {
|
169 | log.body = body
|
170 | }
|
171 |
|
172 | return JSON.stringify(log, null, 2)
|
173 | }
|
174 |
|
175 | function isContentEncoded(headers) {
|
176 | const contentEncoding = headers['content-encoding']
|
177 | return typeof contentEncoding === 'string' && contentEncoding !== ''
|
178 | }
|
179 |
|
180 | function contentEncoding(headers, encoder) {
|
181 | const contentEncoding = headers['content-encoding']
|
182 | return contentEncoding === encoder
|
183 | }
|
184 |
|
185 | function isJSONContent(headers) {
|
186 |
|
187 | const contentType = String(headers['content-type'] || '').toLowerCase()
|
188 | return contentType.startsWith('application/json')
|
189 | }
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 | function headersFieldNamesToLowerCase(headers) {
|
197 | if (!_.isPlainObject(headers)) {
|
198 | throw Error('Headers must be provided as an object')
|
199 | }
|
200 |
|
201 | const lowerCaseHeaders = {}
|
202 | Object.entries(headers).forEach(([fieldName, fieldValue]) => {
|
203 | const key = fieldName.toLowerCase()
|
204 | if (lowerCaseHeaders[key] !== undefined) {
|
205 | throw Error(
|
206 | `Failed to convert header keys to lower case due to field name conflict: ${key}`
|
207 | )
|
208 | }
|
209 | lowerCaseHeaders[key] = fieldValue
|
210 | })
|
211 |
|
212 | return lowerCaseHeaders
|
213 | }
|
214 |
|
215 | const headersFieldsArrayToLowerCase = headers => [
|
216 | ...new Set(headers.map(fieldName => fieldName.toLowerCase())),
|
217 | ]
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 |
|
228 |
|
229 | function headersInputToRawArray(headers) {
|
230 | if (headers === undefined) {
|
231 | return []
|
232 | }
|
233 |
|
234 | if (Array.isArray(headers)) {
|
235 |
|
236 |
|
237 | if (headers.length % 2) {
|
238 | throw new Error(
|
239 | `Raw headers must be provided as an array with an even number of items. [fieldName, value, ...]`
|
240 | )
|
241 | }
|
242 | return [...headers]
|
243 | }
|
244 |
|
245 |
|
246 | if (_.isMap(headers)) {
|
247 | return [].concat(...Array.from(headers, ([k, v]) => [k.toString(), v]))
|
248 | }
|
249 |
|
250 | if (_.isPlainObject(headers)) {
|
251 | return [].concat(...Object.entries(headers))
|
252 | }
|
253 |
|
254 | throw new Error(
|
255 | `Headers must be provided as an array of raw values, a Map, or a plain Object. ${headers}`
|
256 | )
|
257 | }
|
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 | function headersArrayToObject(rawHeaders) {
|
265 | if (!Array.isArray(rawHeaders)) {
|
266 | throw Error('Expected a header array')
|
267 | }
|
268 |
|
269 | const accumulator = {}
|
270 |
|
271 | forEachHeader(rawHeaders, (value, fieldName) => {
|
272 | addHeaderLine(accumulator, fieldName, value)
|
273 | })
|
274 |
|
275 | return accumulator
|
276 | }
|
277 |
|
278 | const noDuplicatesHeaders = new Set([
|
279 | 'age',
|
280 | 'authorization',
|
281 | 'content-length',
|
282 | 'content-type',
|
283 | 'etag',
|
284 | 'expires',
|
285 | 'from',
|
286 | 'host',
|
287 | 'if-modified-since',
|
288 | 'if-unmodified-since',
|
289 | 'last-modified',
|
290 | 'location',
|
291 | 'max-forwards',
|
292 | 'proxy-authorization',
|
293 | 'referer',
|
294 | 'retry-after',
|
295 | 'user-agent',
|
296 | ])
|
297 |
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 |
|
318 |
|
319 | function addHeaderLine(headers, name, value) {
|
320 | let values
|
321 | if (typeof value === 'function') {
|
322 |
|
323 |
|
324 | values = [value.name]
|
325 | } else if (Array.isArray(value)) {
|
326 | values = value.map(String)
|
327 | } else {
|
328 | values = [String(value)]
|
329 | }
|
330 |
|
331 | const key = name.toLowerCase()
|
332 | if (key === 'set-cookie') {
|
333 |
|
334 | if (headers['set-cookie'] === undefined) {
|
335 | headers['set-cookie'] = values
|
336 | } else {
|
337 | headers['set-cookie'].push(...values)
|
338 | }
|
339 | } else if (noDuplicatesHeaders.has(key)) {
|
340 | if (headers[key] === undefined) {
|
341 |
|
342 | headers[key] = values[0]
|
343 | }
|
344 | } else {
|
345 | if (headers[key] !== undefined) {
|
346 | values = [headers[key], ...values]
|
347 | }
|
348 |
|
349 | const separator = key === 'cookie' ? '; ' : ', '
|
350 | headers[key] = values.join(separator)
|
351 | }
|
352 | }
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 | function deleteHeadersField(headers, fieldNameToDelete) {
|
362 | if (!_.isPlainObject(headers)) {
|
363 | throw Error('headers must be an object')
|
364 | }
|
365 |
|
366 | if (typeof fieldNameToDelete !== 'string') {
|
367 | throw Error('field name must be a string')
|
368 | }
|
369 |
|
370 | const lowerCaseFieldNameToDelete = fieldNameToDelete.toLowerCase()
|
371 |
|
372 |
|
373 | Object.keys(headers)
|
374 | .filter(fieldName => fieldName.toLowerCase() === lowerCaseFieldNameToDelete)
|
375 | .forEach(fieldName => delete headers[fieldName])
|
376 | }
|
377 |
|
378 |
|
379 |
|
380 |
|
381 |
|
382 |
|
383 |
|
384 |
|
385 |
|
386 | function forEachHeader(rawHeaders, callback) {
|
387 | for (let i = 0; i < rawHeaders.length; i += 2) {
|
388 | callback(rawHeaders[i + 1], rawHeaders[i], i)
|
389 | }
|
390 | }
|
391 |
|
392 | function percentDecode(str) {
|
393 | try {
|
394 | return decodeURIComponent(str.replace(/\+/g, ' '))
|
395 | } catch (e) {
|
396 | return str
|
397 | }
|
398 | }
|
399 |
|
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 |
|
407 |
|
408 | function percentEncode(str) {
|
409 | return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
|
410 | return `%${c
|
411 | .charCodeAt(0)
|
412 | .toString(16)
|
413 | .toUpperCase()}`
|
414 | })
|
415 | }
|
416 |
|
417 | function matchStringOrRegexp(target, pattern) {
|
418 | const targetStr =
|
419 | target === undefined || target === null ? '' : String(target)
|
420 |
|
421 | return pattern instanceof RegExp
|
422 | ? pattern.test(targetStr)
|
423 | : targetStr === String(pattern)
|
424 | }
|
425 |
|
426 |
|
427 |
|
428 |
|
429 |
|
430 |
|
431 |
|
432 |
|
433 |
|
434 |
|
435 |
|
436 | function formatQueryValue(key, value, stringFormattingFn) {
|
437 |
|
438 | switch (true) {
|
439 | case typeof value === 'number':
|
440 | case typeof value === 'boolean':
|
441 | value = value.toString()
|
442 | break
|
443 | case value === null:
|
444 | case value === undefined:
|
445 | value = ''
|
446 | break
|
447 | case typeof value === 'string':
|
448 | if (stringFormattingFn) {
|
449 | value = stringFormattingFn(value)
|
450 | }
|
451 | break
|
452 | case value instanceof RegExp:
|
453 | break
|
454 | case Array.isArray(value): {
|
455 | value = value.map(function(val, idx) {
|
456 | return formatQueryValue(idx, val, stringFormattingFn)[1]
|
457 | })
|
458 | break
|
459 | }
|
460 | case typeof value === 'object': {
|
461 | value = Object.entries(value).reduce(function(acc, [subKey, subVal]) {
|
462 | const subPair = formatQueryValue(subKey, subVal, stringFormattingFn)
|
463 | acc[subPair[0]] = subPair[1]
|
464 |
|
465 | return acc
|
466 | }, {})
|
467 | break
|
468 | }
|
469 | }
|
470 |
|
471 | if (stringFormattingFn) key = stringFormattingFn(key)
|
472 | return [key, value]
|
473 | }
|
474 |
|
475 | function isStream(obj) {
|
476 | return (
|
477 | obj &&
|
478 | typeof obj !== 'string' &&
|
479 | !Buffer.isBuffer(obj) &&
|
480 | typeof obj.setEncoding === 'function'
|
481 | )
|
482 | }
|
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 |
|
492 |
|
493 | function normalizeClientRequestArgs(input, options, cb) {
|
494 | if (typeof input === 'string') {
|
495 | input = urlToOptions(new url.URL(input))
|
496 | } else if (input instanceof url.URL) {
|
497 | input = urlToOptions(input)
|
498 | } else {
|
499 | cb = options
|
500 | options = input
|
501 | input = null
|
502 | }
|
503 |
|
504 | if (typeof options === 'function') {
|
505 | cb = options
|
506 | options = input || {}
|
507 | } else {
|
508 | options = Object.assign(input || {}, options)
|
509 | }
|
510 |
|
511 | return { options, callback: cb }
|
512 | }
|
513 |
|
514 |
|
515 |
|
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 | function urlToOptions(url) {
|
522 | const options = {
|
523 | protocol: url.protocol,
|
524 | hostname:
|
525 | typeof url.hostname === 'string' && url.hostname.startsWith('[')
|
526 | ? url.hostname.slice(1, -1)
|
527 | : url.hostname,
|
528 | hash: url.hash,
|
529 | search: url.search,
|
530 | pathname: url.pathname,
|
531 | path: `${url.pathname}${url.search || ''}`,
|
532 | href: url.href,
|
533 | }
|
534 | if (url.port !== '') {
|
535 | options.port = Number(url.port)
|
536 | }
|
537 | if (url.username || url.password) {
|
538 | options.auth = `${url.username}:${url.password}`
|
539 | }
|
540 | return options
|
541 | }
|
542 |
|
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 |
|
553 | const dataEqual = (expected, actual) =>
|
554 | deepEqual(expand(expected), expand(actual))
|
555 |
|
556 |
|
557 |
|
558 |
|
559 |
|
560 |
|
561 |
|
562 |
|
563 |
|
564 | const expand = input =>
|
565 | Object.entries(input).reduce((acc, [k, v]) => _.set(acc, k, v), {})
|
566 |
|
567 |
|
568 |
|
569 |
|
570 |
|
571 |
|
572 | function deepEqual(expected, actual) {
|
573 | debug('deepEqual comparing', typeof expected, expected, typeof actual, actual)
|
574 | if (expected instanceof RegExp) {
|
575 | return expected.test(actual)
|
576 | }
|
577 |
|
578 | if (Array.isArray(expected) || _.isPlainObject(expected)) {
|
579 | if (actual === undefined) {
|
580 | return false
|
581 | }
|
582 |
|
583 | const expKeys = Object.keys(expected)
|
584 | if (expKeys.length !== Object.keys(actual).length) {
|
585 | return false
|
586 | }
|
587 |
|
588 | return expKeys.every(key => deepEqual(expected[key], actual[key]))
|
589 | }
|
590 |
|
591 | return expected === actual
|
592 | }
|
593 |
|
594 | const timeouts = []
|
595 | const intervals = []
|
596 | const immediates = []
|
597 |
|
598 | const wrapTimer = (timer, ids) => (...args) => {
|
599 | const id = timer(...args)
|
600 | ids.push(id)
|
601 | return id
|
602 | }
|
603 |
|
604 | const setTimeout = wrapTimer(timers.setTimeout, timeouts)
|
605 | const setInterval = wrapTimer(timers.setInterval, intervals)
|
606 | const setImmediate = wrapTimer(timers.setImmediate, immediates)
|
607 |
|
608 | function clearTimer(clear, ids) {
|
609 | while (ids.length) {
|
610 | clear(ids.shift())
|
611 | }
|
612 | }
|
613 |
|
614 | function removeAllTimers() {
|
615 | clearTimer(clearTimeout, timeouts)
|
616 | clearTimer(clearInterval, intervals)
|
617 | clearTimer(clearImmediate, immediates)
|
618 | }
|
619 |
|
620 | exports.normalizeClientRequestArgs = normalizeClientRequestArgs
|
621 | exports.normalizeRequestOptions = normalizeRequestOptions
|
622 | exports.normalizeOrigin = normalizeOrigin
|
623 | exports.isUtf8Representable = isUtf8Representable
|
624 | exports.overrideRequests = overrideRequests
|
625 | exports.restoreOverriddenRequests = restoreOverriddenRequests
|
626 | exports.stringifyRequest = stringifyRequest
|
627 | exports.isContentEncoded = isContentEncoded
|
628 | exports.contentEncoding = contentEncoding
|
629 | exports.isJSONContent = isJSONContent
|
630 | exports.headersFieldNamesToLowerCase = headersFieldNamesToLowerCase
|
631 | exports.headersFieldsArrayToLowerCase = headersFieldsArrayToLowerCase
|
632 | exports.headersArrayToObject = headersArrayToObject
|
633 | exports.headersInputToRawArray = headersInputToRawArray
|
634 | exports.deleteHeadersField = deleteHeadersField
|
635 | exports.forEachHeader = forEachHeader
|
636 | exports.percentEncode = percentEncode
|
637 | exports.percentDecode = percentDecode
|
638 | exports.matchStringOrRegexp = matchStringOrRegexp
|
639 | exports.formatQueryValue = formatQueryValue
|
640 | exports.isStream = isStream
|
641 | exports.dataEqual = dataEqual
|
642 | exports.setTimeout = setTimeout
|
643 | exports.setInterval = setInterval
|
644 | exports.setImmediate = setImmediate
|
645 | exports.removeAllTimers = removeAllTimers
|