summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/pacote/node_modules/make-fetch-happen/index.js
blob: 1eadece3c97253d759d833980eca6cf8348b8543 (plain)
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
'use strict'

let Cache
const CachePolicy = require('http-cache-semantics')
const fetch = require('node-fetch-npm')
const pkg = require('./package.json')
const retry = require('promise-retry')
let ssri
const Stream = require('stream')
const getAgent = require('./agent')
const setWarning = require('./warning')

const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`

const RETRY_ERRORS = [
  'ECONNRESET', // remote socket closed on us
  'ECONNREFUSED', // remote host refused to open connection
  'EADDRINUSE', // failed to bind to a local port (proxy?)
  'ETIMEDOUT' // someone in the transaction is WAY TOO SLOW
  // Known codes we do NOT retry on:
  // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline)
]

const RETRY_TYPES = [
  'request-timeout'
]

// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
module.exports = cachingFetch
cachingFetch.defaults = function (_uri, _opts) {
  const fetch = this
  if (typeof _uri === 'object') {
    _opts = _uri
    _uri = null
  }

  function defaultedFetch (uri, opts) {
    const finalOpts = Object.assign({}, _opts || {}, opts || {})
    return fetch(uri || _uri, finalOpts)
  }

  defaultedFetch.defaults = fetch.defaults
  return defaultedFetch
}

function initializeCache (opts) {
  if (typeof opts.cacheManager === 'string') {
    if (!Cache) {
      // Default cacache-based cache
      Cache = require('./cache')
    }

    opts.cacheManager = new Cache(opts.cacheManager)
  }

  opts.cache = opts.cache || 'default'

  if (opts.cache === 'default' && isHeaderConditional(opts.headers)) {
    // If header list contains `If-Modified-Since`, `If-None-Match`,
    // `If-Unmodified-Since`, `If-Match`, or `If-Range`, fetch will set cache
    // mode to "no-store" if it is "default".
    opts.cache = 'no-store'
  }
}

function configureOptions (_opts) {
  const opts = Object.assign({}, _opts || {})
  opts.method = (opts.method || 'GET').toUpperCase()

  if (opts.retry && typeof opts.retry === 'number') {
    opts.retry = { retries: opts.retry }
  }

  if (opts.retry === false) {
    opts.retry = { retries: 0 }
  }

  if (opts.cacheManager) {
    initializeCache(opts)
  }

  return opts
}

function initializeSsri () {
  if (!ssri) {
    ssri = require('ssri')
  }
}

function cachingFetch (uri, _opts) {
  const opts = configureOptions(_opts)

  if (opts.integrity) {
    initializeSsri()
  }

  const isCachable = (opts.method === 'GET' || opts.method === 'HEAD') &&
    opts.cacheManager &&
    opts.cache !== 'no-store' &&
    opts.cache !== 'reload'

  if (isCachable) {
    const req = new fetch.Request(uri, {
      method: opts.method,
      headers: opts.headers
    })

    return opts.cacheManager.match(req, opts).then(res => {
      if (res) {
        const warningCode = (res.headers.get('Warning') || '').match(/^\d+/)
        if (warningCode && +warningCode >= 100 && +warningCode < 200) {
          // https://tools.ietf.org/html/rfc7234#section-4.3.4
          //
          // If a stored response is selected for update, the cache MUST:
          //
          // * delete any Warning header fields in the stored response with
          //   warn-code 1xx (see Section 5.5);
          //
          // * retain any Warning header fields in the stored response with
          //   warn-code 2xx;
          //
          res.headers.delete('Warning')
        }

        if (opts.cache === 'default' && !isStale(req, res)) {
          return res
        }

        if (opts.cache === 'default' || opts.cache === 'no-cache') {
          return conditionalFetch(req, res, opts)
        }

        if (opts.cache === 'force-cache' || opts.cache === 'only-if-cached') {
          //   112 Disconnected operation
          // SHOULD be included if the cache is intentionally disconnected from
          // the rest of the network for a period of time.
          // (https://tools.ietf.org/html/rfc2616#section-14.46)
          setWarning(res, 112, 'Disconnected operation')
          return res
        }
      }

      if (!res && opts.cache === 'only-if-cached') {
        const errorMsg = `request to ${
          uri
        } failed: cache mode is 'only-if-cached' but no cached response available.`

        const err = new Error(errorMsg)
        err.code = 'ENOTCACHED'
        throw err
      }

      // Missing cache entry, or mode is default (if stale), reload, no-store
      return remoteFetch(req.url, opts)
    })
  }

  return remoteFetch(uri, opts)
}

function iterableToObject (iter) {
  const obj = {}
  for (let k of iter.keys()) {
    obj[k] = iter.get(k)
  }
  return obj
}

function makePolicy (req, res) {
  const _req = {
    url: req.url,
    method: req.method,
    headers: iterableToObject(req.headers)
  }
  const _res = {
    status: res.status,
    headers: iterableToObject(res.headers)
  }

  return new CachePolicy(_req, _res, { shared: false })
}

// https://tools.ietf.org/html/rfc7234#section-4.2
function isStale (req, res) {
  if (!res) {
    return null
  }

  const _req = {
    url: req.url,
    method: req.method,
    headers: iterableToObject(req.headers)
  }

  const policy = makePolicy(req, res)

  const responseTime = res.headers.get('x-local-cache-time') ||
    res.headers.get('date') ||
    0

  policy._responseTime = new Date(responseTime)

  const bool = !policy.satisfiesWithoutRevalidation(_req)
  return bool
}

function mustRevalidate (res) {
  return (res.headers.get('cache-control') || '').match(/must-revalidate/i)
}

function conditionalFetch (req, cachedRes, opts) {
  const _req = {
    url: req.url,
    method: req.method,
    headers: Object.assign({}, opts.headers || {})
  }

  const policy = makePolicy(req, cachedRes)
  opts.headers = policy.revalidationHeaders(_req)

  return remoteFetch(req.url, opts)
    .then(condRes => {
      const revalidatedPolicy = policy.revalidatedPolicy(_req, {
        status: condRes.status,
        headers: iterableToObject(condRes.headers)
      })

      if (condRes.status >= 500 && !mustRevalidate(cachedRes)) {
        //   111 Revalidation failed
        // MUST be included if a cache returns a stale response because an
        // attempt to revalidate the response failed, due to an inability to
        // reach the server.
        // (https://tools.ietf.org/html/rfc2616#section-14.46)
        setWarning(cachedRes, 111, 'Revalidation failed')
        return cachedRes
      }

      if (condRes.status === 304) { // 304 Not Modified
        condRes.body = cachedRes.body
        return opts.cacheManager.put(req, condRes, opts)
          .then(newRes => {
            newRes.headers = new fetch.Headers(revalidatedPolicy.policy.responseHeaders())
            return newRes
          })
      }

      return condRes
    })
    .then(res => res)
    .catch(err => {
      if (mustRevalidate(cachedRes)) {
        throw err
      } else {
        //   111 Revalidation failed
        // MUST be included if a cache returns a stale response because an
        // attempt to revalidate the response failed, due to an inability to
        // reach the server.
        // (https://tools.ietf.org/html/rfc2616#section-14.46)
        setWarning(cachedRes, 111, 'Revalidation failed')
        //   199 Miscellaneous warning
        // The warning text MAY include arbitrary information to be presented to
        // a human user, or logged. A system receiving this warning MUST NOT take
        // any automated action, besides presenting the warning to the user.
        // (https://tools.ietf.org/html/rfc2616#section-14.46)
        setWarning(
          cachedRes,
          199,
          `Miscellaneous Warning ${err.code}: ${err.message}`
        )

        return cachedRes
      }
    })
}

function remoteFetchHandleIntegrity (res, integrity) {
  const oldBod = res.body
  const newBod = ssri.integrityStream({
    integrity
  })
  oldBod.pipe(newBod)
  res.body = newBod
  oldBod.once('error', err => {
    newBod.emit('error', err)
  })
  newBod.once('error', err => {
    oldBod.emit('error', err)
  })
}

function remoteFetch (uri, opts) {
  const agent = getAgent(uri, opts)
  const headers = Object.assign({
    'connection': agent ? 'keep-alive' : 'close',
    'user-agent': USER_AGENT
  }, opts.headers || {})

  const reqOpts = {
    agent,
    body: opts.body,
    compress: opts.compress,
    follow: opts.follow,
    headers: new fetch.Headers(headers),
    method: opts.method,
    redirect: opts.redirect,
    size: opts.size,
    timeout: opts.timeout
  }

  return retry(
    (retryHandler, attemptNum) => {
      const req = new fetch.Request(uri, reqOpts)
      return fetch(req)
        .then(res => {
          res.headers.set('x-fetch-attempts', attemptNum)

          if (opts.integrity) {
            remoteFetchHandleIntegrity(res, opts.integrity)
          }

          const isStream = req.body instanceof Stream

          if (opts.cacheManager) {
            const isMethodGetHead = req.method === 'GET' ||
              req.method === 'HEAD'

            const isCachable = opts.cache !== 'no-store' &&
              isMethodGetHead &&
              makePolicy(req, res).storable() &&
              res.status === 200 // No other statuses should be stored!

            if (isCachable) {
              return opts.cacheManager.put(req, res, opts)
            }

            if (!isMethodGetHead) {
              return opts.cacheManager.delete(req).then(() => {
                if (res.status >= 500 && req.method !== 'POST' && !isStream) {
                  return retryHandler(res)
                }

                return res
              })
            }
          }

          const isRetriable = req.method !== 'POST' &&
            !isStream && (
              res.status === 408 || // Request Timeout
              res.status === 420 || // Enhance Your Calm (usually Twitter rate-limit)
              res.status === 429 || // Too Many Requests ("standard" rate-limiting)
              res.status >= 500 // Assume server errors are momentary hiccups
            )

          if (isRetriable) {
            return retryHandler(res)
          }

          return res
        })
        .catch(err => {
          const code = err.code === 'EPROMISERETRY' ? err.retried.code : err.code

          const isRetryError = RETRY_ERRORS.indexOf(code) === -1 &&
            RETRY_TYPES.indexOf(err.type) === -1

          if (req.method === 'POST' || isRetryError) {
            throw err
          }

          return retryHandler(err)
        })
    },
    opts.retry
  ).catch(err => {
    if (err.status >= 400) {
      return err
    }

    throw err
  })
}

function isHeaderConditional (headers) {
  if (!headers || typeof headers !== 'object') {
    return false
  }

  const modifiers = [
    'if-modified-since',
    'if-none-match',
    'if-unmodified-since',
    'if-match',
    'if-range'
  ]

  return Object.keys(headers)
    .some(h => modifiers.indexOf(h.toLowerCase()) !== -1)
}