index.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. 'use strict'
  2. const Client = require('./lib/dispatcher/client')
  3. const Dispatcher = require('./lib/dispatcher/dispatcher')
  4. const Pool = require('./lib/dispatcher/pool')
  5. const BalancedPool = require('./lib/dispatcher/balanced-pool')
  6. const Agent = require('./lib/dispatcher/agent')
  7. const ProxyAgent = require('./lib/dispatcher/proxy-agent')
  8. const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
  9. const RetryAgent = require('./lib/dispatcher/retry-agent')
  10. const H2CClient = require('./lib/dispatcher/h2c-client')
  11. const errors = require('./lib/core/errors')
  12. const util = require('./lib/core/util')
  13. const { InvalidArgumentError } = errors
  14. const api = require('./lib/api')
  15. const buildConnector = require('./lib/core/connect')
  16. const MockClient = require('./lib/mock/mock-client')
  17. const { MockCallHistory, MockCallHistoryLog } = require('./lib/mock/mock-call-history')
  18. const MockAgent = require('./lib/mock/mock-agent')
  19. const MockPool = require('./lib/mock/mock-pool')
  20. const mockErrors = require('./lib/mock/mock-errors')
  21. const RetryHandler = require('./lib/handler/retry-handler')
  22. const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')
  23. const DecoratorHandler = require('./lib/handler/decorator-handler')
  24. const RedirectHandler = require('./lib/handler/redirect-handler')
  25. Object.assign(Dispatcher.prototype, api)
  26. module.exports.Dispatcher = Dispatcher
  27. module.exports.Client = Client
  28. module.exports.Pool = Pool
  29. module.exports.BalancedPool = BalancedPool
  30. module.exports.Agent = Agent
  31. module.exports.ProxyAgent = ProxyAgent
  32. module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
  33. module.exports.RetryAgent = RetryAgent
  34. module.exports.H2CClient = H2CClient
  35. module.exports.RetryHandler = RetryHandler
  36. module.exports.DecoratorHandler = DecoratorHandler
  37. module.exports.RedirectHandler = RedirectHandler
  38. module.exports.interceptors = {
  39. redirect: require('./lib/interceptor/redirect'),
  40. responseError: require('./lib/interceptor/response-error'),
  41. retry: require('./lib/interceptor/retry'),
  42. dump: require('./lib/interceptor/dump'),
  43. dns: require('./lib/interceptor/dns'),
  44. cache: require('./lib/interceptor/cache')
  45. }
  46. module.exports.cacheStores = {
  47. MemoryCacheStore: require('./lib/cache/memory-cache-store')
  48. }
  49. const SqliteCacheStore = require('./lib/cache/sqlite-cache-store')
  50. module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore
  51. module.exports.buildConnector = buildConnector
  52. module.exports.errors = errors
  53. module.exports.util = {
  54. parseHeaders: util.parseHeaders,
  55. headerNameToString: util.headerNameToString
  56. }
  57. function makeDispatcher (fn) {
  58. return (url, opts, handler) => {
  59. if (typeof opts === 'function') {
  60. handler = opts
  61. opts = null
  62. }
  63. if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
  64. throw new InvalidArgumentError('invalid url')
  65. }
  66. if (opts != null && typeof opts !== 'object') {
  67. throw new InvalidArgumentError('invalid opts')
  68. }
  69. if (opts && opts.path != null) {
  70. if (typeof opts.path !== 'string') {
  71. throw new InvalidArgumentError('invalid opts.path')
  72. }
  73. let path = opts.path
  74. if (!opts.path.startsWith('/')) {
  75. path = `/${path}`
  76. }
  77. url = new URL(util.parseOrigin(url).origin + path)
  78. } else {
  79. if (!opts) {
  80. opts = typeof url === 'object' ? url : {}
  81. }
  82. url = util.parseURL(url)
  83. }
  84. const { agent, dispatcher = getGlobalDispatcher() } = opts
  85. if (agent) {
  86. throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
  87. }
  88. return fn.call(dispatcher, {
  89. ...opts,
  90. origin: url.origin,
  91. path: url.search ? `${url.pathname}${url.search}` : url.pathname,
  92. method: opts.method || (opts.body ? 'PUT' : 'GET')
  93. }, handler)
  94. }
  95. }
  96. module.exports.setGlobalDispatcher = setGlobalDispatcher
  97. module.exports.getGlobalDispatcher = getGlobalDispatcher
  98. const fetchImpl = require('./lib/web/fetch').fetch
  99. module.exports.fetch = async function fetch (init, options = undefined) {
  100. try {
  101. return await fetchImpl(init, options)
  102. } catch (err) {
  103. if (err && typeof err === 'object') {
  104. Error.captureStackTrace(err)
  105. }
  106. throw err
  107. }
  108. }
  109. module.exports.Headers = require('./lib/web/fetch/headers').Headers
  110. module.exports.Response = require('./lib/web/fetch/response').Response
  111. module.exports.Request = require('./lib/web/fetch/request').Request
  112. module.exports.FormData = require('./lib/web/fetch/formdata').FormData
  113. const { setGlobalOrigin, getGlobalOrigin } = require('./lib/web/fetch/global')
  114. module.exports.setGlobalOrigin = setGlobalOrigin
  115. module.exports.getGlobalOrigin = getGlobalOrigin
  116. const { CacheStorage } = require('./lib/web/cache/cachestorage')
  117. const { kConstruct } = require('./lib/core/symbols')
  118. // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
  119. // in an older version of Node, it doesn't have any use without fetch.
  120. module.exports.caches = new CacheStorage(kConstruct)
  121. const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require('./lib/web/cookies')
  122. module.exports.deleteCookie = deleteCookie
  123. module.exports.getCookies = getCookies
  124. module.exports.getSetCookies = getSetCookies
  125. module.exports.setCookie = setCookie
  126. module.exports.parseCookie = parseCookie
  127. const { parseMIMEType, serializeAMimeType } = require('./lib/web/fetch/data-url')
  128. module.exports.parseMIMEType = parseMIMEType
  129. module.exports.serializeAMimeType = serializeAMimeType
  130. const { CloseEvent, ErrorEvent, MessageEvent } = require('./lib/web/websocket/events')
  131. const { WebSocket, ping } = require('./lib/web/websocket/websocket')
  132. module.exports.WebSocket = WebSocket
  133. module.exports.CloseEvent = CloseEvent
  134. module.exports.ErrorEvent = ErrorEvent
  135. module.exports.MessageEvent = MessageEvent
  136. module.exports.ping = ping
  137. module.exports.WebSocketStream = require('./lib/web/websocket/stream/websocketstream').WebSocketStream
  138. module.exports.WebSocketError = require('./lib/web/websocket/stream/websocketerror').WebSocketError
  139. module.exports.request = makeDispatcher(api.request)
  140. module.exports.stream = makeDispatcher(api.stream)
  141. module.exports.pipeline = makeDispatcher(api.pipeline)
  142. module.exports.connect = makeDispatcher(api.connect)
  143. module.exports.upgrade = makeDispatcher(api.upgrade)
  144. module.exports.MockClient = MockClient
  145. module.exports.MockCallHistory = MockCallHistory
  146. module.exports.MockCallHistoryLog = MockCallHistoryLog
  147. module.exports.MockPool = MockPool
  148. module.exports.MockAgent = MockAgent
  149. module.exports.mockErrors = mockErrors
  150. const { EventSource } = require('./lib/web/eventsource/eventsource')
  151. module.exports.EventSource = EventSource
  152. function install () {
  153. globalThis.fetch = module.exports.fetch
  154. globalThis.Headers = module.exports.Headers
  155. globalThis.Response = module.exports.Response
  156. globalThis.Request = module.exports.Request
  157. globalThis.FormData = module.exports.FormData
  158. globalThis.WebSocket = module.exports.WebSocket
  159. globalThis.CloseEvent = module.exports.CloseEvent
  160. globalThis.ErrorEvent = module.exports.ErrorEvent
  161. globalThis.MessageEvent = module.exports.MessageEvent
  162. globalThis.EventSource = module.exports.EventSource
  163. }
  164. module.exports.install = install