index.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  1. // https://github.com/Ethan-Arrowood/undici-fetch
  2. 'use strict'
  3. const {
  4. Response,
  5. makeNetworkError,
  6. makeAppropriateNetworkError,
  7. filterResponse,
  8. makeResponse
  9. } = require('./response')
  10. const { Headers } = require('./headers')
  11. const { Request, makeRequest } = require('./request')
  12. const zlib = require('zlib')
  13. const {
  14. bytesMatch,
  15. makePolicyContainer,
  16. clonePolicyContainer,
  17. requestBadPort,
  18. TAOCheck,
  19. appendRequestOriginHeader,
  20. responseLocationURL,
  21. requestCurrentURL,
  22. setRequestReferrerPolicyOnRedirect,
  23. tryUpgradeRequestToAPotentiallyTrustworthyURL,
  24. createOpaqueTimingInfo,
  25. appendFetchMetadata,
  26. corsCheck,
  27. crossOriginResourcePolicyCheck,
  28. determineRequestsReferrer,
  29. coarsenedSharedCurrentTime,
  30. createDeferredPromise,
  31. isBlobLike,
  32. sameOrigin,
  33. isCancelled,
  34. isAborted,
  35. isErrorLike,
  36. fullyReadBody,
  37. readableStreamClose,
  38. isomorphicEncode,
  39. urlIsLocal,
  40. urlIsHttpHttpsScheme,
  41. urlHasHttpsScheme
  42. } = require('./util')
  43. const { kState, kHeaders, kGuard, kRealm } = require('./symbols')
  44. const assert = require('assert')
  45. const { safelyExtractBody } = require('./body')
  46. const {
  47. redirectStatus,
  48. nullBodyStatus,
  49. safeMethods,
  50. requestBodyHeader,
  51. subresource,
  52. DOMException
  53. } = require('./constants')
  54. const { kHeadersList } = require('../core/symbols')
  55. const EE = require('events')
  56. const { Readable, pipeline } = require('stream')
  57. const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util')
  58. const { dataURLProcessor, serializeAMimeType } = require('./dataURL')
  59. const { TransformStream } = require('stream/web')
  60. const { getGlobalDispatcher } = require('../global')
  61. const { webidl } = require('./webidl')
  62. const { STATUS_CODES } = require('http')
  63. /** @type {import('buffer').resolveObjectURL} */
  64. let resolveObjectURL
  65. let ReadableStream = globalThis.ReadableStream
  66. class Fetch extends EE {
  67. constructor (dispatcher) {
  68. super()
  69. this.dispatcher = dispatcher
  70. this.connection = null
  71. this.dump = false
  72. this.state = 'ongoing'
  73. // 2 terminated listeners get added per request,
  74. // but only 1 gets removed. If there are 20 redirects,
  75. // 21 listeners will be added.
  76. // See https://github.com/nodejs/undici/issues/1711
  77. // TODO (fix): Find and fix root cause for leaked listener.
  78. this.setMaxListeners(21)
  79. }
  80. terminate (reason) {
  81. if (this.state !== 'ongoing') {
  82. return
  83. }
  84. this.state = 'terminated'
  85. this.connection?.destroy(reason)
  86. this.emit('terminated', reason)
  87. }
  88. // https://fetch.spec.whatwg.org/#fetch-controller-abort
  89. abort (error) {
  90. if (this.state !== 'ongoing') {
  91. return
  92. }
  93. // 1. Set controller’s state to "aborted".
  94. this.state = 'aborted'
  95. // 2. Let fallbackError be an "AbortError" DOMException.
  96. // 3. Set error to fallbackError if it is not given.
  97. if (!error) {
  98. error = new DOMException('The operation was aborted.', 'AbortError')
  99. }
  100. // 4. Let serializedError be StructuredSerialize(error).
  101. // If that threw an exception, catch it, and let
  102. // serializedError be StructuredSerialize(fallbackError).
  103. // 5. Set controller’s serialized abort reason to serializedError.
  104. this.serializedAbortReason = error
  105. this.connection?.destroy(error)
  106. this.emit('terminated', error)
  107. }
  108. }
  109. // https://fetch.spec.whatwg.org/#fetch-method
  110. async function fetch (input, init = {}) {
  111. webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
  112. // 1. Let p be a new promise.
  113. const p = createDeferredPromise()
  114. // 2. Let requestObject be the result of invoking the initial value of
  115. // Request as constructor with input and init as arguments. If this throws
  116. // an exception, reject p with it and return p.
  117. let requestObject
  118. try {
  119. requestObject = new Request(input, init)
  120. } catch (e) {
  121. p.reject(e)
  122. return p.promise
  123. }
  124. // 3. Let request be requestObject’s request.
  125. const request = requestObject[kState]
  126. // 4. If requestObject’s signal’s aborted flag is set, then:
  127. if (requestObject.signal.aborted) {
  128. // 1. Abort the fetch() call with p, request, null, and
  129. // requestObject’s signal’s abort reason.
  130. abortFetch(p, request, null, requestObject.signal.reason)
  131. // 2. Return p.
  132. return p.promise
  133. }
  134. // 5. Let globalObject be request’s client’s global object.
  135. const globalObject = request.client.globalObject
  136. // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
  137. // request’s service-workers mode to "none".
  138. if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
  139. request.serviceWorkers = 'none'
  140. }
  141. // 7. Let responseObject be null.
  142. let responseObject = null
  143. // 8. Let relevantRealm be this’s relevant Realm.
  144. const relevantRealm = null
  145. // 9. Let locallyAborted be false.
  146. let locallyAborted = false
  147. // 10. Let controller be null.
  148. let controller = null
  149. // 11. Add the following abort steps to requestObject’s signal:
  150. addAbortListener(
  151. requestObject.signal,
  152. () => {
  153. // 1. Set locallyAborted to true.
  154. locallyAborted = true
  155. // 2. Assert: controller is non-null.
  156. assert(controller != null)
  157. // 3. Abort controller with requestObject’s signal’s abort reason.
  158. controller.abort(requestObject.signal.reason)
  159. // 4. Abort the fetch() call with p, request, responseObject,
  160. // and requestObject’s signal’s abort reason.
  161. abortFetch(p, request, responseObject, requestObject.signal.reason)
  162. }
  163. )
  164. // 12. Let handleFetchDone given response response be to finalize and
  165. // report timing with response, globalObject, and "fetch".
  166. const handleFetchDone = (response) =>
  167. finalizeAndReportTiming(response, 'fetch')
  168. // 13. Set controller to the result of calling fetch given request,
  169. // with processResponseEndOfBody set to handleFetchDone, and processResponse
  170. // given response being these substeps:
  171. const processResponse = (response) => {
  172. // 1. If locallyAborted is true, terminate these substeps.
  173. if (locallyAborted) {
  174. return
  175. }
  176. // 2. If response’s aborted flag is set, then:
  177. if (response.aborted) {
  178. // 1. Let deserializedError be the result of deserialize a serialized
  179. // abort reason given controller’s serialized abort reason and
  180. // relevantRealm.
  181. // 2. Abort the fetch() call with p, request, responseObject, and
  182. // deserializedError.
  183. abortFetch(p, request, responseObject, controller.serializedAbortReason)
  184. return
  185. }
  186. // 3. If response is a network error, then reject p with a TypeError
  187. // and terminate these substeps.
  188. if (response.type === 'error') {
  189. p.reject(
  190. Object.assign(new TypeError('fetch failed'), { cause: response.error })
  191. )
  192. return
  193. }
  194. // 4. Set responseObject to the result of creating a Response object,
  195. // given response, "immutable", and relevantRealm.
  196. responseObject = new Response()
  197. responseObject[kState] = response
  198. responseObject[kRealm] = relevantRealm
  199. responseObject[kHeaders][kHeadersList] = response.headersList
  200. responseObject[kHeaders][kGuard] = 'immutable'
  201. responseObject[kHeaders][kRealm] = relevantRealm
  202. // 5. Resolve p with responseObject.
  203. p.resolve(responseObject)
  204. }
  205. controller = fetching({
  206. request,
  207. processResponseEndOfBody: handleFetchDone,
  208. processResponse,
  209. dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
  210. })
  211. // 14. Return p.
  212. return p.promise
  213. }
  214. // https://fetch.spec.whatwg.org/#finalize-and-report-timing
  215. function finalizeAndReportTiming (response, initiatorType = 'other') {
  216. // 1. If response is an aborted network error, then return.
  217. if (response.type === 'error' && response.aborted) {
  218. return
  219. }
  220. // 2. If response’s URL list is null or empty, then return.
  221. if (!response.urlList?.length) {
  222. return
  223. }
  224. // 3. Let originalURL be response’s URL list[0].
  225. const originalURL = response.urlList[0]
  226. // 4. Let timingInfo be response’s timing info.
  227. let timingInfo = response.timingInfo
  228. // 5. Let cacheState be response’s cache state.
  229. let cacheState = response.cacheState
  230. // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
  231. if (!urlIsHttpHttpsScheme(originalURL)) {
  232. return
  233. }
  234. // 7. If timingInfo is null, then return.
  235. if (timingInfo === null) {
  236. return
  237. }
  238. // 8. If response’s timing allow passed flag is not set, then:
  239. if (!timingInfo.timingAllowPassed) {
  240. // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
  241. timingInfo = createOpaqueTimingInfo({
  242. startTime: timingInfo.startTime
  243. })
  244. // 2. Set cacheState to the empty string.
  245. cacheState = ''
  246. }
  247. // 9. Set timingInfo’s end time to the coarsened shared current time
  248. // given global’s relevant settings object’s cross-origin isolated
  249. // capability.
  250. // TODO: given global’s relevant settings object’s cross-origin isolated
  251. // capability?
  252. timingInfo.endTime = coarsenedSharedCurrentTime()
  253. // 10. Set response’s timing info to timingInfo.
  254. response.timingInfo = timingInfo
  255. // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
  256. // global, and cacheState.
  257. markResourceTiming(
  258. timingInfo,
  259. originalURL,
  260. initiatorType,
  261. globalThis,
  262. cacheState
  263. )
  264. }
  265. // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
  266. function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
  267. if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
  268. performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
  269. }
  270. }
  271. // https://fetch.spec.whatwg.org/#abort-fetch
  272. function abortFetch (p, request, responseObject, error) {
  273. // Note: AbortSignal.reason was added in node v17.2.0
  274. // which would give us an undefined error to reject with.
  275. // Remove this once node v16 is no longer supported.
  276. if (!error) {
  277. error = new DOMException('The operation was aborted.', 'AbortError')
  278. }
  279. // 1. Reject promise with error.
  280. p.reject(error)
  281. // 2. If request’s body is not null and is readable, then cancel request’s
  282. // body with error.
  283. if (request.body != null && isReadable(request.body?.stream)) {
  284. request.body.stream.cancel(error).catch((err) => {
  285. if (err.code === 'ERR_INVALID_STATE') {
  286. // Node bug?
  287. return
  288. }
  289. throw err
  290. })
  291. }
  292. // 3. If responseObject is null, then return.
  293. if (responseObject == null) {
  294. return
  295. }
  296. // 4. Let response be responseObject’s response.
  297. const response = responseObject[kState]
  298. // 5. If response’s body is not null and is readable, then error response’s
  299. // body with error.
  300. if (response.body != null && isReadable(response.body?.stream)) {
  301. response.body.stream.cancel(error).catch((err) => {
  302. if (err.code === 'ERR_INVALID_STATE') {
  303. // Node bug?
  304. return
  305. }
  306. throw err
  307. })
  308. }
  309. }
  310. // https://fetch.spec.whatwg.org/#fetching
  311. function fetching ({
  312. request,
  313. processRequestBodyChunkLength,
  314. processRequestEndOfBody,
  315. processResponse,
  316. processResponseEndOfBody,
  317. processResponseConsumeBody,
  318. useParallelQueue = false,
  319. dispatcher // undici
  320. }) {
  321. // 1. Let taskDestination be null.
  322. let taskDestination = null
  323. // 2. Let crossOriginIsolatedCapability be false.
  324. let crossOriginIsolatedCapability = false
  325. // 3. If request’s client is non-null, then:
  326. if (request.client != null) {
  327. // 1. Set taskDestination to request’s client’s global object.
  328. taskDestination = request.client.globalObject
  329. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
  330. // isolated capability.
  331. crossOriginIsolatedCapability =
  332. request.client.crossOriginIsolatedCapability
  333. }
  334. // 4. If useParallelQueue is true, then set taskDestination to the result of
  335. // starting a new parallel queue.
  336. // TODO
  337. // 5. Let timingInfo be a new fetch timing info whose start time and
  338. // post-redirect start time are the coarsened shared current time given
  339. // crossOriginIsolatedCapability.
  340. const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
  341. const timingInfo = createOpaqueTimingInfo({
  342. startTime: currenTime
  343. })
  344. // 6. Let fetchParams be a new fetch params whose
  345. // request is request,
  346. // timing info is timingInfo,
  347. // process request body chunk length is processRequestBodyChunkLength,
  348. // process request end-of-body is processRequestEndOfBody,
  349. // process response is processResponse,
  350. // process response consume body is processResponseConsumeBody,
  351. // process response end-of-body is processResponseEndOfBody,
  352. // task destination is taskDestination,
  353. // and cross-origin isolated capability is crossOriginIsolatedCapability.
  354. const fetchParams = {
  355. controller: new Fetch(dispatcher),
  356. request,
  357. timingInfo,
  358. processRequestBodyChunkLength,
  359. processRequestEndOfBody,
  360. processResponse,
  361. processResponseConsumeBody,
  362. processResponseEndOfBody,
  363. taskDestination,
  364. crossOriginIsolatedCapability
  365. }
  366. // 7. If request’s body is a byte sequence, then set request’s body to
  367. // request’s body as a body.
  368. // NOTE: Since fetching is only called from fetch, body should already be
  369. // extracted.
  370. assert(!request.body || request.body.stream)
  371. // 8. If request’s window is "client", then set request’s window to request’s
  372. // client, if request’s client’s global object is a Window object; otherwise
  373. // "no-window".
  374. if (request.window === 'client') {
  375. // TODO: What if request.client is null?
  376. request.window =
  377. request.client?.globalObject?.constructor?.name === 'Window'
  378. ? request.client
  379. : 'no-window'
  380. }
  381. // 9. If request’s origin is "client", then set request’s origin to request’s
  382. // client’s origin.
  383. if (request.origin === 'client') {
  384. // TODO: What if request.client is null?
  385. request.origin = request.client?.origin
  386. }
  387. // 10. If all of the following conditions are true:
  388. // TODO
  389. // 11. If request’s policy container is "client", then:
  390. if (request.policyContainer === 'client') {
  391. // 1. If request’s client is non-null, then set request’s policy
  392. // container to a clone of request’s client’s policy container. [HTML]
  393. if (request.client != null) {
  394. request.policyContainer = clonePolicyContainer(
  395. request.client.policyContainer
  396. )
  397. } else {
  398. // 2. Otherwise, set request’s policy container to a new policy
  399. // container.
  400. request.policyContainer = makePolicyContainer()
  401. }
  402. }
  403. // 12. If request’s header list does not contain `Accept`, then:
  404. if (!request.headersList.contains('accept')) {
  405. // 1. Let value be `*/*`.
  406. const value = '*/*'
  407. // 2. A user agent should set value to the first matching statement, if
  408. // any, switching on request’s destination:
  409. // "document"
  410. // "frame"
  411. // "iframe"
  412. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  413. // "image"
  414. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  415. // "style"
  416. // `text/css,*/*;q=0.1`
  417. // TODO
  418. // 3. Append `Accept`/value to request’s header list.
  419. request.headersList.append('accept', value)
  420. }
  421. // 13. If request’s header list does not contain `Accept-Language`, then
  422. // user agents should append `Accept-Language`/an appropriate value to
  423. // request’s header list.
  424. if (!request.headersList.contains('accept-language')) {
  425. request.headersList.append('accept-language', '*')
  426. }
  427. // 14. If request’s priority is null, then use request’s initiator and
  428. // destination appropriately in setting request’s priority to a
  429. // user-agent-defined object.
  430. if (request.priority === null) {
  431. // TODO
  432. }
  433. // 15. If request is a subresource request, then:
  434. if (subresource.includes(request.destination)) {
  435. // TODO
  436. }
  437. // 16. Run main fetch given fetchParams.
  438. mainFetch(fetchParams)
  439. .catch(err => {
  440. fetchParams.controller.terminate(err)
  441. })
  442. // 17. Return fetchParam's controller
  443. return fetchParams.controller
  444. }
  445. // https://fetch.spec.whatwg.org/#concept-main-fetch
  446. async function mainFetch (fetchParams, recursive = false) {
  447. // 1. Let request be fetchParams’s request.
  448. const request = fetchParams.request
  449. // 2. Let response be null.
  450. let response = null
  451. // 3. If request’s local-URLs-only flag is set and request’s current URL is
  452. // not local, then set response to a network error.
  453. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
  454. response = makeNetworkError('local URLs only')
  455. }
  456. // 4. Run report Content Security Policy violations for request.
  457. // TODO
  458. // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  459. tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
  460. // 6. If should request be blocked due to a bad port, should fetching request
  461. // be blocked as mixed content, or should request be blocked by Content
  462. // Security Policy returns blocked, then set response to a network error.
  463. if (requestBadPort(request) === 'blocked') {
  464. response = makeNetworkError('bad port')
  465. }
  466. // TODO: should fetching request be blocked as mixed content?
  467. // TODO: should request be blocked by Content Security Policy?
  468. // 7. If request’s referrer policy is the empty string, then set request’s
  469. // referrer policy to request’s policy container’s referrer policy.
  470. if (request.referrerPolicy === '') {
  471. request.referrerPolicy = request.policyContainer.referrerPolicy
  472. }
  473. // 8. If request’s referrer is not "no-referrer", then set request’s
  474. // referrer to the result of invoking determine request’s referrer.
  475. if (request.referrer !== 'no-referrer') {
  476. request.referrer = determineRequestsReferrer(request)
  477. }
  478. // 9. Set request’s current URL’s scheme to "https" if all of the following
  479. // conditions are true:
  480. // - request’s current URL’s scheme is "http"
  481. // - request’s current URL’s host is a domain
  482. // - Matching request’s current URL’s host per Known HSTS Host Domain Name
  483. // Matching results in either a superdomain match with an asserted
  484. // includeSubDomains directive or a congruent match (with or without an
  485. // asserted includeSubDomains directive). [HSTS]
  486. // TODO
  487. // 10. If recursive is false, then run the remaining steps in parallel.
  488. // TODO
  489. // 11. If response is null, then set response to the result of running
  490. // the steps corresponding to the first matching statement:
  491. if (response === null) {
  492. response = await (async () => {
  493. const currentURL = requestCurrentURL(request)
  494. if (
  495. // - request’s current URL’s origin is same origin with request’s origin,
  496. // and request’s response tainting is "basic"
  497. (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
  498. // request’s current URL’s scheme is "data"
  499. (currentURL.protocol === 'data:') ||
  500. // - request’s mode is "navigate" or "websocket"
  501. (request.mode === 'navigate' || request.mode === 'websocket')
  502. ) {
  503. // 1. Set request’s response tainting to "basic".
  504. request.responseTainting = 'basic'
  505. // 2. Return the result of running scheme fetch given fetchParams.
  506. return await schemeFetch(fetchParams)
  507. }
  508. // request’s mode is "same-origin"
  509. if (request.mode === 'same-origin') {
  510. // 1. Return a network error.
  511. return makeNetworkError('request mode cannot be "same-origin"')
  512. }
  513. // request’s mode is "no-cors"
  514. if (request.mode === 'no-cors') {
  515. // 1. If request’s redirect mode is not "follow", then return a network
  516. // error.
  517. if (request.redirect !== 'follow') {
  518. return makeNetworkError(
  519. 'redirect mode cannot be "follow" for "no-cors" request'
  520. )
  521. }
  522. // 2. Set request’s response tainting to "opaque".
  523. request.responseTainting = 'opaque'
  524. // 3. Return the result of running scheme fetch given fetchParams.
  525. return await schemeFetch(fetchParams)
  526. }
  527. // request’s current URL’s scheme is not an HTTP(S) scheme
  528. if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
  529. // Return a network error.
  530. return makeNetworkError('URL scheme must be a HTTP(S) scheme')
  531. }
  532. // - request’s use-CORS-preflight flag is set
  533. // - request’s unsafe-request flag is set and either request’s method is
  534. // not a CORS-safelisted method or CORS-unsafe request-header names with
  535. // request’s header list is not empty
  536. // 1. Set request’s response tainting to "cors".
  537. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
  538. // given fetchParams and true.
  539. // 3. If corsWithPreflightResponse is a network error, then clear cache
  540. // entries using request.
  541. // 4. Return corsWithPreflightResponse.
  542. // TODO
  543. // Otherwise
  544. // 1. Set request’s response tainting to "cors".
  545. request.responseTainting = 'cors'
  546. // 2. Return the result of running HTTP fetch given fetchParams.
  547. return await httpFetch(fetchParams)
  548. })()
  549. }
  550. // 12. If recursive is true, then return response.
  551. if (recursive) {
  552. return response
  553. }
  554. // 13. If response is not a network error and response is not a filtered
  555. // response, then:
  556. if (response.status !== 0 && !response.internalResponse) {
  557. // If request’s response tainting is "cors", then:
  558. if (request.responseTainting === 'cors') {
  559. // 1. Let headerNames be the result of extracting header list values
  560. // given `Access-Control-Expose-Headers` and response’s header list.
  561. // TODO
  562. // 2. If request’s credentials mode is not "include" and headerNames
  563. // contains `*`, then set response’s CORS-exposed header-name list to
  564. // all unique header names in response’s header list.
  565. // TODO
  566. // 3. Otherwise, if headerNames is not null or failure, then set
  567. // response’s CORS-exposed header-name list to headerNames.
  568. // TODO
  569. }
  570. // Set response to the following filtered response with response as its
  571. // internal response, depending on request’s response tainting:
  572. if (request.responseTainting === 'basic') {
  573. response = filterResponse(response, 'basic')
  574. } else if (request.responseTainting === 'cors') {
  575. response = filterResponse(response, 'cors')
  576. } else if (request.responseTainting === 'opaque') {
  577. response = filterResponse(response, 'opaque')
  578. } else {
  579. assert(false)
  580. }
  581. }
  582. // 14. Let internalResponse be response, if response is a network error,
  583. // and response’s internal response otherwise.
  584. let internalResponse =
  585. response.status === 0 ? response : response.internalResponse
  586. // 15. If internalResponse’s URL list is empty, then set it to a clone of
  587. // request’s URL list.
  588. if (internalResponse.urlList.length === 0) {
  589. internalResponse.urlList.push(...request.urlList)
  590. }
  591. // 16. If request’s timing allow failed flag is unset, then set
  592. // internalResponse’s timing allow passed flag.
  593. if (!request.timingAllowFailed) {
  594. response.timingAllowPassed = true
  595. }
  596. // 17. If response is not a network error and any of the following returns
  597. // blocked
  598. // - should internalResponse to request be blocked as mixed content
  599. // - should internalResponse to request be blocked by Content Security Policy
  600. // - should internalResponse to request be blocked due to its MIME type
  601. // - should internalResponse to request be blocked due to nosniff
  602. // TODO
  603. // 18. If response’s type is "opaque", internalResponse’s status is 206,
  604. // internalResponse’s range-requested flag is set, and request’s header
  605. // list does not contain `Range`, then set response and internalResponse
  606. // to a network error.
  607. if (
  608. response.type === 'opaque' &&
  609. internalResponse.status === 206 &&
  610. internalResponse.rangeRequested &&
  611. !request.headers.contains('range')
  612. ) {
  613. response = internalResponse = makeNetworkError()
  614. }
  615. // 19. If response is not a network error and either request’s method is
  616. // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
  617. // set internalResponse’s body to null and disregard any enqueuing toward
  618. // it (if any).
  619. if (
  620. response.status !== 0 &&
  621. (request.method === 'HEAD' ||
  622. request.method === 'CONNECT' ||
  623. nullBodyStatus.includes(internalResponse.status))
  624. ) {
  625. internalResponse.body = null
  626. fetchParams.controller.dump = true
  627. }
  628. // 20. If request’s integrity metadata is not the empty string, then:
  629. if (request.integrity) {
  630. // 1. Let processBodyError be this step: run fetch finale given fetchParams
  631. // and a network error.
  632. const processBodyError = (reason) =>
  633. fetchFinale(fetchParams, makeNetworkError(reason))
  634. // 2. If request’s response tainting is "opaque", or response’s body is null,
  635. // then run processBodyError and abort these steps.
  636. if (request.responseTainting === 'opaque' || response.body == null) {
  637. processBodyError(response.error)
  638. return
  639. }
  640. // 3. Let processBody given bytes be these steps:
  641. const processBody = (bytes) => {
  642. // 1. If bytes do not match request’s integrity metadata,
  643. // then run processBodyError and abort these steps. [SRI]
  644. if (!bytesMatch(bytes, request.integrity)) {
  645. processBodyError('integrity mismatch')
  646. return
  647. }
  648. // 2. Set response’s body to bytes as a body.
  649. response.body = safelyExtractBody(bytes)[0]
  650. // 3. Run fetch finale given fetchParams and response.
  651. fetchFinale(fetchParams, response)
  652. }
  653. // 4. Fully read response’s body given processBody and processBodyError.
  654. await fullyReadBody(response.body, processBody, processBodyError)
  655. } else {
  656. // 21. Otherwise, run fetch finale given fetchParams and response.
  657. fetchFinale(fetchParams, response)
  658. }
  659. }
  660. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  661. // given a fetch params fetchParams
  662. async function schemeFetch (fetchParams) {
  663. // Note: since the connection is destroyed on redirect, which sets fetchParams to a
  664. // cancelled state, we do not want this condition to trigger *unless* there have been
  665. // no redirects. See https://github.com/nodejs/undici/issues/1776
  666. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  667. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
  668. return makeAppropriateNetworkError(fetchParams)
  669. }
  670. // 2. Let request be fetchParams’s request.
  671. const { request } = fetchParams
  672. const { protocol: scheme } = requestCurrentURL(request)
  673. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  674. switch (scheme) {
  675. case 'about:': {
  676. // If request’s current URL’s path is the string "blank", then return a new response
  677. // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
  678. // and body is the empty byte sequence as a body.
  679. // Otherwise, return a network error.
  680. return makeNetworkError('about scheme is not supported')
  681. }
  682. case 'blob:': {
  683. if (!resolveObjectURL) {
  684. resolveObjectURL = require('buffer').resolveObjectURL
  685. }
  686. // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
  687. const blobURLEntry = requestCurrentURL(request)
  688. // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
  689. // Buffer.resolveObjectURL does not ignore URL queries.
  690. if (blobURLEntry.search.length !== 0) {
  691. return makeNetworkError('NetworkError when attempting to fetch resource.')
  692. }
  693. const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
  694. // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
  695. // object is not a Blob object, then return a network error.
  696. if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
  697. return makeNetworkError('invalid method')
  698. }
  699. // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
  700. const bodyWithType = safelyExtractBody(blobURLEntryObject)
  701. // 4. Let body be bodyWithType’s body.
  702. const body = bodyWithType[0]
  703. // 5. Let length be body’s length, serialized and isomorphic encoded.
  704. const length = isomorphicEncode(`${body.length}`)
  705. // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
  706. const type = bodyWithType[1] ?? ''
  707. // 7. Return a new response whose status message is `OK`, header list is
  708. // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
  709. const response = makeResponse({
  710. statusText: 'OK',
  711. headersList: [
  712. ['content-length', { name: 'Content-Length', value: length }],
  713. ['content-type', { name: 'Content-Type', value: type }]
  714. ]
  715. })
  716. response.body = body
  717. return response
  718. }
  719. case 'data:': {
  720. // 1. Let dataURLStruct be the result of running the
  721. // data: URL processor on request’s current URL.
  722. const currentURL = requestCurrentURL(request)
  723. const dataURLStruct = dataURLProcessor(currentURL)
  724. // 2. If dataURLStruct is failure, then return a
  725. // network error.
  726. if (dataURLStruct === 'failure') {
  727. return makeNetworkError('failed to fetch the data URL')
  728. }
  729. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  730. const mimeType = serializeAMimeType(dataURLStruct.mimeType)
  731. // 4. Return a response whose status message is `OK`,
  732. // header list is « (`Content-Type`, mimeType) »,
  733. // and body is dataURLStruct’s body as a body.
  734. return makeResponse({
  735. statusText: 'OK',
  736. headersList: [
  737. ['content-type', { name: 'Content-Type', value: mimeType }]
  738. ],
  739. body: safelyExtractBody(dataURLStruct.body)[0]
  740. })
  741. }
  742. case 'file:': {
  743. // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
  744. // When in doubt, return a network error.
  745. return makeNetworkError('not implemented... yet...')
  746. }
  747. case 'http:':
  748. case 'https:': {
  749. // Return the result of running HTTP fetch given fetchParams.
  750. return await httpFetch(fetchParams)
  751. .catch((err) => makeNetworkError(err))
  752. }
  753. default: {
  754. return makeNetworkError('unknown scheme')
  755. }
  756. }
  757. }
  758. // https://fetch.spec.whatwg.org/#finalize-response
  759. function finalizeResponse (fetchParams, response) {
  760. // 1. Set fetchParams’s request’s done flag.
  761. fetchParams.request.done = true
  762. // 2, If fetchParams’s process response done is not null, then queue a fetch
  763. // task to run fetchParams’s process response done given response, with
  764. // fetchParams’s task destination.
  765. if (fetchParams.processResponseDone != null) {
  766. queueMicrotask(() => fetchParams.processResponseDone(response))
  767. }
  768. }
  769. // https://fetch.spec.whatwg.org/#fetch-finale
  770. async function fetchFinale (fetchParams, response) {
  771. // 1. If response is a network error, then:
  772. if (response.type === 'error') {
  773. // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
  774. response.urlList = [fetchParams.request.urlList[0]]
  775. // 2. Set response’s timing info to the result of creating an opaque timing
  776. // info for fetchParams’s timing info.
  777. response.timingInfo = createOpaqueTimingInfo({
  778. startTime: fetchParams.timingInfo.startTime
  779. })
  780. }
  781. // 2. Let processResponseEndOfBody be the following steps:
  782. const processResponseEndOfBody = () => {
  783. // 1. Set fetchParams’s request’s done flag.
  784. fetchParams.request.done = true
  785. // If fetchParams’s process response end-of-body is not null,
  786. // then queue a fetch task to run fetchParams’s process response
  787. // end-of-body given response with fetchParams’s task destination.
  788. if (fetchParams.processResponseEndOfBody != null) {
  789. queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
  790. }
  791. }
  792. // 3. If fetchParams’s process response is non-null, then queue a fetch task
  793. // to run fetchParams’s process response given response, with fetchParams’s
  794. // task destination.
  795. if (fetchParams.processResponse != null) {
  796. queueMicrotask(() => fetchParams.processResponse(response))
  797. }
  798. // 4. If response’s body is null, then run processResponseEndOfBody.
  799. if (response.body == null) {
  800. processResponseEndOfBody()
  801. } else {
  802. // 5. Otherwise:
  803. // 1. Let transformStream be a new a TransformStream.
  804. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
  805. // enqueues chunk in transformStream.
  806. const identityTransformAlgorithm = (chunk, controller) => {
  807. controller.enqueue(chunk)
  808. }
  809. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
  810. // and flushAlgorithm set to processResponseEndOfBody.
  811. const transformStream = new TransformStream({
  812. start () {},
  813. transform: identityTransformAlgorithm,
  814. flush: processResponseEndOfBody
  815. }, {
  816. size () {
  817. return 1
  818. }
  819. }, {
  820. size () {
  821. return 1
  822. }
  823. })
  824. // 4. Set response’s body to the result of piping response’s body through transformStream.
  825. response.body = { stream: response.body.stream.pipeThrough(transformStream) }
  826. }
  827. // 6. If fetchParams’s process response consume body is non-null, then:
  828. if (fetchParams.processResponseConsumeBody != null) {
  829. // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
  830. // process response consume body given response and nullOrBytes.
  831. const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
  832. // 2. Let processBodyError be this step: run fetchParams’s process
  833. // response consume body given response and failure.
  834. const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
  835. // 3. If response’s body is null, then queue a fetch task to run processBody
  836. // given null, with fetchParams’s task destination.
  837. if (response.body == null) {
  838. queueMicrotask(() => processBody(null))
  839. } else {
  840. // 4. Otherwise, fully read response’s body given processBody, processBodyError,
  841. // and fetchParams’s task destination.
  842. await fullyReadBody(response.body, processBody, processBodyError)
  843. }
  844. }
  845. }
  846. // https://fetch.spec.whatwg.org/#http-fetch
  847. async function httpFetch (fetchParams) {
  848. // 1. Let request be fetchParams’s request.
  849. const request = fetchParams.request
  850. // 2. Let response be null.
  851. let response = null
  852. // 3. Let actualResponse be null.
  853. let actualResponse = null
  854. // 4. Let timingInfo be fetchParams’s timing info.
  855. const timingInfo = fetchParams.timingInfo
  856. // 5. If request’s service-workers mode is "all", then:
  857. if (request.serviceWorkers === 'all') {
  858. // TODO
  859. }
  860. // 6. If response is null, then:
  861. if (response === null) {
  862. // 1. If makeCORSPreflight is true and one of these conditions is true:
  863. // TODO
  864. // 2. If request’s redirect mode is "follow", then set request’s
  865. // service-workers mode to "none".
  866. if (request.redirect === 'follow') {
  867. request.serviceWorkers = 'none'
  868. }
  869. // 3. Set response and actualResponse to the result of running
  870. // HTTP-network-or-cache fetch given fetchParams.
  871. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
  872. // 4. If request’s response tainting is "cors" and a CORS check
  873. // for request and response returns failure, then return a network error.
  874. if (
  875. request.responseTainting === 'cors' &&
  876. corsCheck(request, response) === 'failure'
  877. ) {
  878. return makeNetworkError('cors failure')
  879. }
  880. // 5. If the TAO check for request and response returns failure, then set
  881. // request’s timing allow failed flag.
  882. if (TAOCheck(request, response) === 'failure') {
  883. request.timingAllowFailed = true
  884. }
  885. }
  886. // 7. If either request’s response tainting or response’s type
  887. // is "opaque", and the cross-origin resource policy check with
  888. // request’s origin, request’s client, request’s destination,
  889. // and actualResponse returns blocked, then return a network error.
  890. if (
  891. (request.responseTainting === 'opaque' || response.type === 'opaque') &&
  892. crossOriginResourcePolicyCheck(
  893. request.origin,
  894. request.client,
  895. request.destination,
  896. actualResponse
  897. ) === 'blocked'
  898. ) {
  899. return makeNetworkError('blocked')
  900. }
  901. // 8. If actualResponse’s status is a redirect status, then:
  902. if (redirectStatus.includes(actualResponse.status)) {
  903. // 1. If actualResponse’s status is not 303, request’s body is not null,
  904. // and the connection uses HTTP/2, then user agents may, and are even
  905. // encouraged to, transmit an RST_STREAM frame.
  906. // See, https://github.com/whatwg/fetch/issues/1288
  907. if (request.redirect !== 'manual') {
  908. fetchParams.controller.connection.destroy()
  909. }
  910. // 2. Switch on request’s redirect mode:
  911. if (request.redirect === 'error') {
  912. // Set response to a network error.
  913. response = makeNetworkError('unexpected redirect')
  914. } else if (request.redirect === 'manual') {
  915. // Set response to an opaque-redirect filtered response whose internal
  916. // response is actualResponse.
  917. // NOTE(spec): On the web this would return an `opaqueredirect` response,
  918. // but that doesn't make sense server side.
  919. // See https://github.com/nodejs/undici/issues/1193.
  920. response = actualResponse
  921. } else if (request.redirect === 'follow') {
  922. // Set response to the result of running HTTP-redirect fetch given
  923. // fetchParams and response.
  924. response = await httpRedirectFetch(fetchParams, response)
  925. } else {
  926. assert(false)
  927. }
  928. }
  929. // 9. Set response’s timing info to timingInfo.
  930. response.timingInfo = timingInfo
  931. // 10. Return response.
  932. return response
  933. }
  934. // https://fetch.spec.whatwg.org/#http-redirect-fetch
  935. async function httpRedirectFetch (fetchParams, response) {
  936. // 1. Let request be fetchParams’s request.
  937. const request = fetchParams.request
  938. // 2. Let actualResponse be response, if response is not a filtered response,
  939. // and response’s internal response otherwise.
  940. const actualResponse = response.internalResponse
  941. ? response.internalResponse
  942. : response
  943. // 3. Let locationURL be actualResponse’s location URL given request’s current
  944. // URL’s fragment.
  945. let locationURL
  946. try {
  947. locationURL = responseLocationURL(
  948. actualResponse,
  949. requestCurrentURL(request).hash
  950. )
  951. // 4. If locationURL is null, then return response.
  952. if (locationURL == null) {
  953. return response
  954. }
  955. } catch (err) {
  956. // 5. If locationURL is failure, then return a network error.
  957. return makeNetworkError(err)
  958. }
  959. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
  960. // error.
  961. if (!urlIsHttpHttpsScheme(locationURL)) {
  962. return makeNetworkError('URL scheme must be a HTTP(S) scheme')
  963. }
  964. // 7. If request’s redirect count is 20, then return a network error.
  965. if (request.redirectCount === 20) {
  966. return makeNetworkError('redirect count exceeded')
  967. }
  968. // 8. Increase request’s redirect count by 1.
  969. request.redirectCount += 1
  970. // 9. If request’s mode is "cors", locationURL includes credentials, and
  971. // request’s origin is not same origin with locationURL’s origin, then return
  972. // a network error.
  973. if (
  974. request.mode === 'cors' &&
  975. (locationURL.username || locationURL.password) &&
  976. !sameOrigin(request, locationURL)
  977. ) {
  978. return makeNetworkError('cross origin not allowed for request mode "cors"')
  979. }
  980. // 10. If request’s response tainting is "cors" and locationURL includes
  981. // credentials, then return a network error.
  982. if (
  983. request.responseTainting === 'cors' &&
  984. (locationURL.username || locationURL.password)
  985. ) {
  986. return makeNetworkError(
  987. 'URL cannot contain credentials for request mode "cors"'
  988. )
  989. }
  990. // 11. If actualResponse’s status is not 303, request’s body is non-null,
  991. // and request’s body’s source is null, then return a network error.
  992. if (
  993. actualResponse.status !== 303 &&
  994. request.body != null &&
  995. request.body.source == null
  996. ) {
  997. return makeNetworkError()
  998. }
  999. // 12. If one of the following is true
  1000. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  1001. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  1002. if (
  1003. ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
  1004. (actualResponse.status === 303 &&
  1005. !['GET', 'HEAD'].includes(request.method))
  1006. ) {
  1007. // then:
  1008. // 1. Set request’s method to `GET` and request’s body to null.
  1009. request.method = 'GET'
  1010. request.body = null
  1011. // 2. For each headerName of request-body-header name, delete headerName from
  1012. // request’s header list.
  1013. for (const headerName of requestBodyHeader) {
  1014. request.headersList.delete(headerName)
  1015. }
  1016. }
  1017. // 13. If request’s current URL’s origin is not same origin with locationURL’s
  1018. // origin, then for each headerName of CORS non-wildcard request-header name,
  1019. // delete headerName from request’s header list.
  1020. if (!sameOrigin(requestCurrentURL(request), locationURL)) {
  1021. // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
  1022. request.headersList.delete('authorization')
  1023. }
  1024. // 14. If request’s body is non-null, then set request’s body to the first return
  1025. // value of safely extracting request’s body’s source.
  1026. if (request.body != null) {
  1027. assert(request.body.source != null)
  1028. request.body = safelyExtractBody(request.body.source)[0]
  1029. }
  1030. // 15. Let timingInfo be fetchParams’s timing info.
  1031. const timingInfo = fetchParams.timingInfo
  1032. // 16. Set timingInfo’s redirect end time and post-redirect start time to the
  1033. // coarsened shared current time given fetchParams’s cross-origin isolated
  1034. // capability.
  1035. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
  1036. coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1037. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
  1038. // redirect start time to timingInfo’s start time.
  1039. if (timingInfo.redirectStartTime === 0) {
  1040. timingInfo.redirectStartTime = timingInfo.startTime
  1041. }
  1042. // 18. Append locationURL to request’s URL list.
  1043. request.urlList.push(locationURL)
  1044. // 19. Invoke set request’s referrer policy on redirect on request and
  1045. // actualResponse.
  1046. setRequestReferrerPolicyOnRedirect(request, actualResponse)
  1047. // 20. Return the result of running main fetch given fetchParams and true.
  1048. return mainFetch(fetchParams, true)
  1049. }
  1050. // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
  1051. async function httpNetworkOrCacheFetch (
  1052. fetchParams,
  1053. isAuthenticationFetch = false,
  1054. isNewConnectionFetch = false
  1055. ) {
  1056. // 1. Let request be fetchParams’s request.
  1057. const request = fetchParams.request
  1058. // 2. Let httpFetchParams be null.
  1059. let httpFetchParams = null
  1060. // 3. Let httpRequest be null.
  1061. let httpRequest = null
  1062. // 4. Let response be null.
  1063. let response = null
  1064. // 5. Let storedResponse be null.
  1065. // TODO: cache
  1066. // 6. Let httpCache be null.
  1067. const httpCache = null
  1068. // 7. Let the revalidatingFlag be unset.
  1069. const revalidatingFlag = false
  1070. // 8. Run these steps, but abort when the ongoing fetch is terminated:
  1071. // 1. If request’s window is "no-window" and request’s redirect mode is
  1072. // "error", then set httpFetchParams to fetchParams and httpRequest to
  1073. // request.
  1074. if (request.window === 'no-window' && request.redirect === 'error') {
  1075. httpFetchParams = fetchParams
  1076. httpRequest = request
  1077. } else {
  1078. // Otherwise:
  1079. // 1. Set httpRequest to a clone of request.
  1080. httpRequest = makeRequest(request)
  1081. // 2. Set httpFetchParams to a copy of fetchParams.
  1082. httpFetchParams = { ...fetchParams }
  1083. // 3. Set httpFetchParams’s request to httpRequest.
  1084. httpFetchParams.request = httpRequest
  1085. }
  1086. // 3. Let includeCredentials be true if one of
  1087. const includeCredentials =
  1088. request.credentials === 'include' ||
  1089. (request.credentials === 'same-origin' &&
  1090. request.responseTainting === 'basic')
  1091. // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
  1092. // body is non-null; otherwise null.
  1093. const contentLength = httpRequest.body ? httpRequest.body.length : null
  1094. // 5. Let contentLengthHeaderValue be null.
  1095. let contentLengthHeaderValue = null
  1096. // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
  1097. // `PUT`, then set contentLengthHeaderValue to `0`.
  1098. if (
  1099. httpRequest.body == null &&
  1100. ['POST', 'PUT'].includes(httpRequest.method)
  1101. ) {
  1102. contentLengthHeaderValue = '0'
  1103. }
  1104. // 7. If contentLength is non-null, then set contentLengthHeaderValue to
  1105. // contentLength, serialized and isomorphic encoded.
  1106. if (contentLength != null) {
  1107. contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
  1108. }
  1109. // 8. If contentLengthHeaderValue is non-null, then append
  1110. // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
  1111. // list.
  1112. if (contentLengthHeaderValue != null) {
  1113. httpRequest.headersList.append('content-length', contentLengthHeaderValue)
  1114. }
  1115. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
  1116. // contentLengthHeaderValue) to httpRequest’s header list.
  1117. // 10. If contentLength is non-null and httpRequest’s keepalive is true,
  1118. // then:
  1119. if (contentLength != null && httpRequest.keepalive) {
  1120. // NOTE: keepalive is a noop outside of browser context.
  1121. }
  1122. // 11. If httpRequest’s referrer is a URL, then append
  1123. // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
  1124. // to httpRequest’s header list.
  1125. if (httpRequest.referrer instanceof URL) {
  1126. httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
  1127. }
  1128. // 12. Append a request `Origin` header for httpRequest.
  1129. appendRequestOriginHeader(httpRequest)
  1130. // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
  1131. appendFetchMetadata(httpRequest)
  1132. // 14. If httpRequest’s header list does not contain `User-Agent`, then
  1133. // user agents should append `User-Agent`/default `User-Agent` value to
  1134. // httpRequest’s header list.
  1135. if (!httpRequest.headersList.contains('user-agent')) {
  1136. httpRequest.headersList.append('user-agent', 'undici')
  1137. }
  1138. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
  1139. // list contains `If-Modified-Since`, `If-None-Match`,
  1140. // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
  1141. // httpRequest’s cache mode to "no-store".
  1142. if (
  1143. httpRequest.cache === 'default' &&
  1144. (httpRequest.headersList.contains('if-modified-since') ||
  1145. httpRequest.headersList.contains('if-none-match') ||
  1146. httpRequest.headersList.contains('if-unmodified-since') ||
  1147. httpRequest.headersList.contains('if-match') ||
  1148. httpRequest.headersList.contains('if-range'))
  1149. ) {
  1150. httpRequest.cache = 'no-store'
  1151. }
  1152. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
  1153. // no-cache cache-control header modification flag is unset, and
  1154. // httpRequest’s header list does not contain `Cache-Control`, then append
  1155. // `Cache-Control`/`max-age=0` to httpRequest’s header list.
  1156. if (
  1157. httpRequest.cache === 'no-cache' &&
  1158. !httpRequest.preventNoCacheCacheControlHeaderModification &&
  1159. !httpRequest.headersList.contains('cache-control')
  1160. ) {
  1161. httpRequest.headersList.append('cache-control', 'max-age=0')
  1162. }
  1163. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1164. if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
  1165. // 1. If httpRequest’s header list does not contain `Pragma`, then append
  1166. // `Pragma`/`no-cache` to httpRequest’s header list.
  1167. if (!httpRequest.headersList.contains('pragma')) {
  1168. httpRequest.headersList.append('pragma', 'no-cache')
  1169. }
  1170. // 2. If httpRequest’s header list does not contain `Cache-Control`,
  1171. // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
  1172. if (!httpRequest.headersList.contains('cache-control')) {
  1173. httpRequest.headersList.append('cache-control', 'no-cache')
  1174. }
  1175. }
  1176. // 18. If httpRequest’s header list contains `Range`, then append
  1177. // `Accept-Encoding`/`identity` to httpRequest’s header list.
  1178. if (httpRequest.headersList.contains('range')) {
  1179. httpRequest.headersList.append('accept-encoding', 'identity')
  1180. }
  1181. // 19. Modify httpRequest’s header list per HTTP. Do not append a given
  1182. // header if httpRequest’s header list contains that header’s name.
  1183. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
  1184. if (!httpRequest.headersList.contains('accept-encoding')) {
  1185. if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
  1186. httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
  1187. } else {
  1188. httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
  1189. }
  1190. }
  1191. // 20. If includeCredentials is true, then:
  1192. if (includeCredentials) {
  1193. // 1. If the user agent is not configured to block cookies for httpRequest
  1194. // (see section 7 of [COOKIES]), then:
  1195. // TODO: credentials
  1196. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1197. // TODO: credentials
  1198. }
  1199. // 21. If there’s a proxy-authentication entry, use it as appropriate.
  1200. // TODO: proxy-authentication
  1201. // 22. Set httpCache to the result of determining the HTTP cache
  1202. // partition, given httpRequest.
  1203. // TODO: cache
  1204. // 23. If httpCache is null, then set httpRequest’s cache mode to
  1205. // "no-store".
  1206. if (httpCache == null) {
  1207. httpRequest.cache = 'no-store'
  1208. }
  1209. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
  1210. // then:
  1211. if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
  1212. // TODO: cache
  1213. }
  1214. // 9. If aborted, then return the appropriate network error for fetchParams.
  1215. // TODO
  1216. // 10. If response is null, then:
  1217. if (response == null) {
  1218. // 1. If httpRequest’s cache mode is "only-if-cached", then return a
  1219. // network error.
  1220. if (httpRequest.mode === 'only-if-cached') {
  1221. return makeNetworkError('only if cached')
  1222. }
  1223. // 2. Let forwardResponse be the result of running HTTP-network fetch
  1224. // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
  1225. const forwardResponse = await httpNetworkFetch(
  1226. httpFetchParams,
  1227. includeCredentials,
  1228. isNewConnectionFetch
  1229. )
  1230. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
  1231. // in the range 200 to 399, inclusive, invalidate appropriate stored
  1232. // responses in httpCache, as per the "Invalidation" chapter of HTTP
  1233. // Caching, and set storedResponse to null. [HTTP-CACHING]
  1234. if (
  1235. !safeMethods.includes(httpRequest.method) &&
  1236. forwardResponse.status >= 200 &&
  1237. forwardResponse.status <= 399
  1238. ) {
  1239. // TODO: cache
  1240. }
  1241. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
  1242. // then:
  1243. if (revalidatingFlag && forwardResponse.status === 304) {
  1244. // TODO: cache
  1245. }
  1246. // 5. If response is null, then:
  1247. if (response == null) {
  1248. // 1. Set response to forwardResponse.
  1249. response = forwardResponse
  1250. // 2. Store httpRequest and forwardResponse in httpCache, as per the
  1251. // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
  1252. // TODO: cache
  1253. }
  1254. }
  1255. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1256. response.urlList = [...httpRequest.urlList]
  1257. // 12. If httpRequest’s header list contains `Range`, then set response’s
  1258. // range-requested flag.
  1259. if (httpRequest.headersList.contains('range')) {
  1260. response.rangeRequested = true
  1261. }
  1262. // 13. Set response’s request-includes-credentials to includeCredentials.
  1263. response.requestIncludesCredentials = includeCredentials
  1264. // 14. If response’s status is 401, httpRequest’s response tainting is not
  1265. // "cors", includeCredentials is true, and request’s window is an environment
  1266. // settings object, then:
  1267. // TODO
  1268. // 15. If response’s status is 407, then:
  1269. if (response.status === 407) {
  1270. // 1. If request’s window is "no-window", then return a network error.
  1271. if (request.window === 'no-window') {
  1272. return makeNetworkError()
  1273. }
  1274. // 2. ???
  1275. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1276. if (isCancelled(fetchParams)) {
  1277. return makeAppropriateNetworkError(fetchParams)
  1278. }
  1279. // 4. Prompt the end user as appropriate in request’s window and store
  1280. // the result as a proxy-authentication entry. [HTTP-AUTH]
  1281. // TODO: Invoke some kind of callback?
  1282. // 5. Set response to the result of running HTTP-network-or-cache fetch given
  1283. // fetchParams.
  1284. // TODO
  1285. return makeNetworkError('proxy authentication required')
  1286. }
  1287. // 16. If all of the following are true
  1288. if (
  1289. // response’s status is 421
  1290. response.status === 421 &&
  1291. // isNewConnectionFetch is false
  1292. !isNewConnectionFetch &&
  1293. // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1294. (request.body == null || request.body.source != null)
  1295. ) {
  1296. // then:
  1297. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1298. if (isCancelled(fetchParams)) {
  1299. return makeAppropriateNetworkError(fetchParams)
  1300. }
  1301. // 2. Set response to the result of running HTTP-network-or-cache
  1302. // fetch given fetchParams, isAuthenticationFetch, and true.
  1303. // TODO (spec): The spec doesn't specify this but we need to cancel
  1304. // the active response before we can start a new one.
  1305. // https://github.com/whatwg/fetch/issues/1293
  1306. fetchParams.controller.connection.destroy()
  1307. response = await httpNetworkOrCacheFetch(
  1308. fetchParams,
  1309. isAuthenticationFetch,
  1310. true
  1311. )
  1312. }
  1313. // 17. If isAuthenticationFetch is true, then create an authentication entry
  1314. if (isAuthenticationFetch) {
  1315. // TODO
  1316. }
  1317. // 18. Return response.
  1318. return response
  1319. }
  1320. // https://fetch.spec.whatwg.org/#http-network-fetch
  1321. async function httpNetworkFetch (
  1322. fetchParams,
  1323. includeCredentials = false,
  1324. forceNewConnection = false
  1325. ) {
  1326. assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
  1327. fetchParams.controller.connection = {
  1328. abort: null,
  1329. destroyed: false,
  1330. destroy (err) {
  1331. if (!this.destroyed) {
  1332. this.destroyed = true
  1333. this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
  1334. }
  1335. }
  1336. }
  1337. // 1. Let request be fetchParams’s request.
  1338. const request = fetchParams.request
  1339. // 2. Let response be null.
  1340. let response = null
  1341. // 3. Let timingInfo be fetchParams’s timing info.
  1342. const timingInfo = fetchParams.timingInfo
  1343. // 4. Let httpCache be the result of determining the HTTP cache partition,
  1344. // given request.
  1345. // TODO: cache
  1346. const httpCache = null
  1347. // 5. If httpCache is null, then set request’s cache mode to "no-store".
  1348. if (httpCache == null) {
  1349. request.cache = 'no-store'
  1350. }
  1351. // 6. Let networkPartitionKey be the result of determining the network
  1352. // partition key given request.
  1353. // TODO
  1354. // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
  1355. // "no".
  1356. const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
  1357. // 8. Switch on request’s mode:
  1358. if (request.mode === 'websocket') {
  1359. // Let connection be the result of obtaining a WebSocket connection,
  1360. // given request’s current URL.
  1361. // TODO
  1362. } else {
  1363. // Let connection be the result of obtaining a connection, given
  1364. // networkPartitionKey, request’s current URL’s origin,
  1365. // includeCredentials, and forceNewConnection.
  1366. // TODO
  1367. }
  1368. // 9. Run these steps, but abort when the ongoing fetch is terminated:
  1369. // 1. If connection is failure, then return a network error.
  1370. // 2. Set timingInfo’s final connection timing info to the result of
  1371. // calling clamp and coarsen connection timing info with connection’s
  1372. // timing info, timingInfo’s post-redirect start time, and fetchParams’s
  1373. // cross-origin isolated capability.
  1374. // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
  1375. // and request’s body’s source is null, then append (`Transfer-Encoding`,
  1376. // `chunked`) to request’s header list.
  1377. // 4. Set timingInfo’s final network-request start time to the coarsened
  1378. // shared current time given fetchParams’s cross-origin isolated
  1379. // capability.
  1380. // 5. Set response to the result of making an HTTP request over connection
  1381. // using request with the following caveats:
  1382. // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
  1383. // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
  1384. // - If request’s body is non-null, and request’s body’s source is null,
  1385. // then the user agent may have a buffer of up to 64 kibibytes and store
  1386. // a part of request’s body in that buffer. If the user agent reads from
  1387. // request’s body beyond that buffer’s size and the user agent needs to
  1388. // resend request, then instead return a network error.
  1389. // - Set timingInfo’s final network-response start time to the coarsened
  1390. // shared current time given fetchParams’s cross-origin isolated capability,
  1391. // immediately after the user agent’s HTTP parser receives the first byte
  1392. // of the response (e.g., frame header bytes for HTTP/2 or response status
  1393. // line for HTTP/1.x).
  1394. // - Wait until all the headers are transmitted.
  1395. // - Any responses whose status is in the range 100 to 199, inclusive,
  1396. // and is not 101, are to be ignored, except for the purposes of setting
  1397. // timingInfo’s final network-response start time above.
  1398. // - If request’s header list contains `Transfer-Encoding`/`chunked` and
  1399. // response is transferred via HTTP/1.0 or older, then return a network
  1400. // error.
  1401. // - If the HTTP request results in a TLS client certificate dialog, then:
  1402. // 1. If request’s window is an environment settings object, make the
  1403. // dialog available in request’s window.
  1404. // 2. Otherwise, return a network error.
  1405. // To transmit request’s body body, run these steps:
  1406. let requestBody = null
  1407. // 1. If body is null and fetchParams’s process request end-of-body is
  1408. // non-null, then queue a fetch task given fetchParams’s process request
  1409. // end-of-body and fetchParams’s task destination.
  1410. if (request.body == null && fetchParams.processRequestEndOfBody) {
  1411. queueMicrotask(() => fetchParams.processRequestEndOfBody())
  1412. } else if (request.body != null) {
  1413. // 2. Otherwise, if body is non-null:
  1414. // 1. Let processBodyChunk given bytes be these steps:
  1415. const processBodyChunk = async function * (bytes) {
  1416. // 1. If the ongoing fetch is terminated, then abort these steps.
  1417. if (isCancelled(fetchParams)) {
  1418. return
  1419. }
  1420. // 2. Run this step in parallel: transmit bytes.
  1421. yield bytes
  1422. // 3. If fetchParams’s process request body is non-null, then run
  1423. // fetchParams’s process request body given bytes’s length.
  1424. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
  1425. }
  1426. // 2. Let processEndOfBody be these steps:
  1427. const processEndOfBody = () => {
  1428. // 1. If fetchParams is canceled, then abort these steps.
  1429. if (isCancelled(fetchParams)) {
  1430. return
  1431. }
  1432. // 2. If fetchParams’s process request end-of-body is non-null,
  1433. // then run fetchParams’s process request end-of-body.
  1434. if (fetchParams.processRequestEndOfBody) {
  1435. fetchParams.processRequestEndOfBody()
  1436. }
  1437. }
  1438. // 3. Let processBodyError given e be these steps:
  1439. const processBodyError = (e) => {
  1440. // 1. If fetchParams is canceled, then abort these steps.
  1441. if (isCancelled(fetchParams)) {
  1442. return
  1443. }
  1444. // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
  1445. if (e.name === 'AbortError') {
  1446. fetchParams.controller.abort()
  1447. } else {
  1448. fetchParams.controller.terminate(e)
  1449. }
  1450. }
  1451. // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
  1452. // processBodyError, and fetchParams’s task destination.
  1453. requestBody = (async function * () {
  1454. try {
  1455. for await (const bytes of request.body.stream) {
  1456. yield * processBodyChunk(bytes)
  1457. }
  1458. processEndOfBody()
  1459. } catch (err) {
  1460. processBodyError(err)
  1461. }
  1462. })()
  1463. }
  1464. try {
  1465. // socket is only provided for websockets
  1466. const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
  1467. if (socket) {
  1468. response = makeResponse({ status, statusText, headersList, socket })
  1469. } else {
  1470. const iterator = body[Symbol.asyncIterator]()
  1471. fetchParams.controller.next = () => iterator.next()
  1472. response = makeResponse({ status, statusText, headersList })
  1473. }
  1474. } catch (err) {
  1475. // 10. If aborted, then:
  1476. if (err.name === 'AbortError') {
  1477. // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1478. fetchParams.controller.connection.destroy()
  1479. // 2. Return the appropriate network error for fetchParams.
  1480. return makeAppropriateNetworkError(fetchParams)
  1481. }
  1482. return makeNetworkError(err)
  1483. }
  1484. // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
  1485. // if it is suspended.
  1486. const pullAlgorithm = () => {
  1487. fetchParams.controller.resume()
  1488. }
  1489. // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
  1490. // controller with reason, given reason.
  1491. const cancelAlgorithm = (reason) => {
  1492. fetchParams.controller.abort(reason)
  1493. }
  1494. // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
  1495. // the user agent.
  1496. // TODO
  1497. // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
  1498. // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
  1499. // TODO
  1500. // 15. Let stream be a new ReadableStream.
  1501. // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
  1502. // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
  1503. // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
  1504. if (!ReadableStream) {
  1505. ReadableStream = require('stream/web').ReadableStream
  1506. }
  1507. const stream = new ReadableStream(
  1508. {
  1509. async start (controller) {
  1510. fetchParams.controller.controller = controller
  1511. },
  1512. async pull (controller) {
  1513. await pullAlgorithm(controller)
  1514. },
  1515. async cancel (reason) {
  1516. await cancelAlgorithm(reason)
  1517. }
  1518. },
  1519. {
  1520. highWaterMark: 0,
  1521. size () {
  1522. return 1
  1523. }
  1524. }
  1525. )
  1526. // 17. Run these steps, but abort when the ongoing fetch is terminated:
  1527. // 1. Set response’s body to a new body whose stream is stream.
  1528. response.body = { stream }
  1529. // 2. If response is not a network error and request’s cache mode is
  1530. // not "no-store", then update response in httpCache for request.
  1531. // TODO
  1532. // 3. If includeCredentials is true and the user agent is not configured
  1533. // to block cookies for request (see section 7 of [COOKIES]), then run the
  1534. // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
  1535. // the value of each header whose name is a byte-case-insensitive match for
  1536. // `Set-Cookie` in response’s header list, if any, and request’s current URL.
  1537. // TODO
  1538. // 18. If aborted, then:
  1539. // TODO
  1540. // 19. Run these steps in parallel:
  1541. // 1. Run these steps, but abort when fetchParams is canceled:
  1542. fetchParams.controller.on('terminated', onAborted)
  1543. fetchParams.controller.resume = async () => {
  1544. // 1. While true
  1545. while (true) {
  1546. // 1-3. See onData...
  1547. // 4. Set bytes to the result of handling content codings given
  1548. // codings and bytes.
  1549. let bytes
  1550. let isFailure
  1551. try {
  1552. const { done, value } = await fetchParams.controller.next()
  1553. if (isAborted(fetchParams)) {
  1554. break
  1555. }
  1556. bytes = done ? undefined : value
  1557. } catch (err) {
  1558. if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
  1559. // zlib doesn't like empty streams.
  1560. bytes = undefined
  1561. } else {
  1562. bytes = err
  1563. // err may be propagated from the result of calling readablestream.cancel,
  1564. // which might not be an error. https://github.com/nodejs/undici/issues/2009
  1565. isFailure = true
  1566. }
  1567. }
  1568. if (bytes === undefined) {
  1569. // 2. Otherwise, if the bytes transmission for response’s message
  1570. // body is done normally and stream is readable, then close
  1571. // stream, finalize response for fetchParams and response, and
  1572. // abort these in-parallel steps.
  1573. readableStreamClose(fetchParams.controller.controller)
  1574. finalizeResponse(fetchParams, response)
  1575. return
  1576. }
  1577. // 5. Increase timingInfo’s decoded body size by bytes’s length.
  1578. timingInfo.decodedBodySize += bytes?.byteLength ?? 0
  1579. // 6. If bytes is failure, then terminate fetchParams’s controller.
  1580. if (isFailure) {
  1581. fetchParams.controller.terminate(bytes)
  1582. return
  1583. }
  1584. // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
  1585. // into stream.
  1586. fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
  1587. // 8. If stream is errored, then terminate the ongoing fetch.
  1588. if (isErrored(stream)) {
  1589. fetchParams.controller.terminate()
  1590. return
  1591. }
  1592. // 9. If stream doesn’t need more data ask the user agent to suspend
  1593. // the ongoing fetch.
  1594. if (!fetchParams.controller.controller.desiredSize) {
  1595. return
  1596. }
  1597. }
  1598. }
  1599. // 2. If aborted, then:
  1600. function onAborted (reason) {
  1601. // 2. If fetchParams is aborted, then:
  1602. if (isAborted(fetchParams)) {
  1603. // 1. Set response’s aborted flag.
  1604. response.aborted = true
  1605. // 2. If stream is readable, then error stream with the result of
  1606. // deserialize a serialized abort reason given fetchParams’s
  1607. // controller’s serialized abort reason and an
  1608. // implementation-defined realm.
  1609. if (isReadable(stream)) {
  1610. fetchParams.controller.controller.error(
  1611. fetchParams.controller.serializedAbortReason
  1612. )
  1613. }
  1614. } else {
  1615. // 3. Otherwise, if stream is readable, error stream with a TypeError.
  1616. if (isReadable(stream)) {
  1617. fetchParams.controller.controller.error(new TypeError('terminated', {
  1618. cause: isErrorLike(reason) ? reason : undefined
  1619. }))
  1620. }
  1621. }
  1622. // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1623. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
  1624. fetchParams.controller.connection.destroy()
  1625. }
  1626. // 20. Return response.
  1627. return response
  1628. async function dispatch ({ body }) {
  1629. const url = requestCurrentURL(request)
  1630. /** @type {import('../..').Agent} */
  1631. const agent = fetchParams.controller.dispatcher
  1632. return new Promise((resolve, reject) => agent.dispatch(
  1633. {
  1634. path: url.pathname + url.search,
  1635. origin: url.origin,
  1636. method: request.method,
  1637. body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body,
  1638. headers: request.headersList.entries,
  1639. maxRedirections: 0,
  1640. upgrade: request.mode === 'websocket' ? 'websocket' : undefined
  1641. },
  1642. {
  1643. body: null,
  1644. abort: null,
  1645. onConnect (abort) {
  1646. // TODO (fix): Do we need connection here?
  1647. const { connection } = fetchParams.controller
  1648. if (connection.destroyed) {
  1649. abort(new DOMException('The operation was aborted.', 'AbortError'))
  1650. } else {
  1651. fetchParams.controller.on('terminated', abort)
  1652. this.abort = connection.abort = abort
  1653. }
  1654. },
  1655. onHeaders (status, headersList, resume, statusText) {
  1656. if (status < 200) {
  1657. return
  1658. }
  1659. let codings = []
  1660. let location = ''
  1661. const headers = new Headers()
  1662. for (let n = 0; n < headersList.length; n += 2) {
  1663. const key = headersList[n + 0].toString('latin1')
  1664. const val = headersList[n + 1].toString('latin1')
  1665. if (key.toLowerCase() === 'content-encoding') {
  1666. // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
  1667. // "All content-coding values are case-insensitive..."
  1668. codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
  1669. } else if (key.toLowerCase() === 'location') {
  1670. location = val
  1671. }
  1672. headers.append(key, val)
  1673. }
  1674. this.body = new Readable({ read: resume })
  1675. const decoders = []
  1676. const willFollow = request.redirect === 'follow' &&
  1677. location &&
  1678. redirectStatus.includes(status)
  1679. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
  1680. if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
  1681. for (const coding of codings) {
  1682. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
  1683. if (coding === 'x-gzip' || coding === 'gzip') {
  1684. decoders.push(zlib.createGunzip({
  1685. // Be less strict when decoding compressed responses, since sometimes
  1686. // servers send slightly invalid responses that are still accepted
  1687. // by common browsers.
  1688. // Always using Z_SYNC_FLUSH is what cURL does.
  1689. flush: zlib.constants.Z_SYNC_FLUSH,
  1690. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1691. }))
  1692. } else if (coding === 'deflate') {
  1693. decoders.push(zlib.createInflate())
  1694. } else if (coding === 'br') {
  1695. decoders.push(zlib.createBrotliDecompress())
  1696. } else {
  1697. decoders.length = 0
  1698. break
  1699. }
  1700. }
  1701. }
  1702. resolve({
  1703. status,
  1704. statusText,
  1705. headersList: headers[kHeadersList],
  1706. body: decoders.length
  1707. ? pipeline(this.body, ...decoders, () => { })
  1708. : this.body.on('error', () => {})
  1709. })
  1710. return true
  1711. },
  1712. onData (chunk) {
  1713. if (fetchParams.controller.dump) {
  1714. return
  1715. }
  1716. // 1. If one or more bytes have been transmitted from response’s
  1717. // message body, then:
  1718. // 1. Let bytes be the transmitted bytes.
  1719. const bytes = chunk
  1720. // 2. Let codings be the result of extracting header list values
  1721. // given `Content-Encoding` and response’s header list.
  1722. // See pullAlgorithm.
  1723. // 3. Increase timingInfo’s encoded body size by bytes’s length.
  1724. timingInfo.encodedBodySize += bytes.byteLength
  1725. // 4. See pullAlgorithm...
  1726. return this.body.push(bytes)
  1727. },
  1728. onComplete () {
  1729. if (this.abort) {
  1730. fetchParams.controller.off('terminated', this.abort)
  1731. }
  1732. fetchParams.controller.ended = true
  1733. this.body.push(null)
  1734. },
  1735. onError (error) {
  1736. if (this.abort) {
  1737. fetchParams.controller.off('terminated', this.abort)
  1738. }
  1739. this.body?.destroy(error)
  1740. fetchParams.controller.terminate(error)
  1741. reject(error)
  1742. },
  1743. onUpgrade (status, headersList, socket) {
  1744. if (status !== 101) {
  1745. return
  1746. }
  1747. const headers = new Headers()
  1748. for (let n = 0; n < headersList.length; n += 2) {
  1749. const key = headersList[n + 0].toString('latin1')
  1750. const val = headersList[n + 1].toString('latin1')
  1751. headers.append(key, val)
  1752. }
  1753. resolve({
  1754. status,
  1755. statusText: STATUS_CODES[status],
  1756. headersList: headers[kHeadersList],
  1757. socket
  1758. })
  1759. return true
  1760. }
  1761. }
  1762. ))
  1763. }
  1764. }
  1765. module.exports = {
  1766. fetch,
  1767. Fetch,
  1768. fetching,
  1769. finalizeAndReportTiming
  1770. }