index-fetch.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict'
  2. const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')
  3. const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
  4. const fetchImpl = require('./lib/web/fetch').fetch
  5. // Capture __filename at module load time for stack trace augmentation.
  6. // This may be undefined when bundled in environments like Node.js internals.
  7. const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined
  8. function appendFetchStackTrace (err, filename) {
  9. if (!err || typeof err !== 'object') {
  10. return
  11. }
  12. const stack = typeof err.stack === 'string' ? err.stack : ''
  13. const normalizedFilename = filename.replace(/\\/g, '/')
  14. if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
  15. return
  16. }
  17. const capture = {}
  18. Error.captureStackTrace(capture, appendFetchStackTrace)
  19. if (!capture.stack) {
  20. return
  21. }
  22. const captureLines = capture.stack.split('\n').slice(1).join('\n')
  23. err.stack = stack ? `${stack}\n${captureLines}` : capture.stack
  24. }
  25. module.exports.fetch = function fetch (init, options = undefined) {
  26. return fetchImpl(init, options).catch(err => {
  27. if (currentFilename) {
  28. appendFetchStackTrace(err, currentFilename)
  29. } else if (err && typeof err === 'object') {
  30. Error.captureStackTrace(err, module.exports.fetch)
  31. }
  32. throw err
  33. })
  34. }
  35. module.exports.FormData = require('./lib/web/fetch/formdata').FormData
  36. module.exports.Headers = require('./lib/web/fetch/headers').Headers
  37. module.exports.Response = require('./lib/web/fetch/response').Response
  38. module.exports.Request = require('./lib/web/fetch/request').Request
  39. const { CloseEvent, ErrorEvent, MessageEvent, createFastMessageEvent } = require('./lib/web/websocket/events')
  40. module.exports.WebSocket = require('./lib/web/websocket/websocket').WebSocket
  41. module.exports.CloseEvent = CloseEvent
  42. module.exports.ErrorEvent = ErrorEvent
  43. module.exports.MessageEvent = MessageEvent
  44. module.exports.createFastMessageEvent = createFastMessageEvent
  45. module.exports.EventSource = require('./lib/web/eventsource/eventsource').EventSource
  46. const api = require('./lib/api')
  47. const Dispatcher = require('./lib/dispatcher/dispatcher')
  48. Object.assign(Dispatcher.prototype, api)
  49. // Expose the fetch implementation to be enabled in Node.js core via a flag
  50. module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
  51. module.exports.getGlobalDispatcher = getGlobalDispatcher
  52. module.exports.setGlobalDispatcher = setGlobalDispatcher