deno_fetch 0.272.0

Fetch API implementation for Deno
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
// Copyright 2018-2026 the Deno authors. MIT license.

(function () {
const { core, internals, primordials } = __bootstrap;
const {
  op_fetch,
  op_fetch_promise_is_settled,
  op_fetch_send,
  op_wasm_streaming_feed,
  op_wasm_streaming_set_url,
} = core.ops;
const {
  ArrayPrototypePush,
  ArrayPrototypeSplice,
  ArrayPrototypeFilter,
  ArrayPrototypeIncludes,
  DateNow,
  Error,
  ObjectPrototypeIsPrototypeOf,
  Promise,
  PromisePrototypeThen,
  PromisePrototypeCatch,
  SafeArrayIterator,
  SafePromisePrototypeFinally,
  String,
  StringPrototypeEndsWith,
  StringPrototypeIndexOf,
  StringPrototypeSlice,
  StringPrototypeSplit,
  StringPrototypeStartsWith,
  StringPrototypeToLowerCase,
  StringPrototypeTrim,
  TypeError,
  TypedArrayPrototypeGetByteLength,
  TypedArrayPrototypeGetSymbolToStringTag,
} = primordials;

const webidl = core.loadExtScript("ext:deno_webidl/00_webidl.js");
const { byteLowerCase } = core.loadExtScript("ext:deno_web/00_infra.js");
const {
  errorReadableStream,
  getReadableStreamResourceBacking,
  readableStreamForRid,
  ReadableStreamPrototype,
  resourceForReadableStream,
} = core.loadExtScript("ext:deno_web/06_streams.js");
const { extractBody, InnerBody } = core.loadExtScript(
  "ext:deno_fetch/22_body.js",
);
const { processUrlList, Request, toInnerRequest } = core.loadExtScript(
  "ext:deno_fetch/23_request.js",
);
const {
  abortedNetworkError,
  fromInnerResponse,
  networkError,
  nullBodyStatus,
  redirectStatus,
  toInnerResponse,
} = core.loadExtScript("ext:deno_fetch/23_response.js");
const abortSignal = core.loadExtScript("ext:deno_web/03_abort_signal.js");
const {
  builtinTracer,
  ContextManager,
  enterSpan,
  restoreSnapshot,
} = internals.__telemetry;
const __telemetry = internals.__telemetry;
const {
  updateSpanFromClientResponse,
  updateSpanFromError,
  updateSpanFromRequest,
} = internals.__telemetryUtil;

const REQUEST_BODY_HEADER_NAMES = [
  "content-encoding",
  "content-language",
  "content-location",
  "content-type",
];

const REDIRECT_SENSITIVE_HEADER_NAMES = [
  "authorization",
  "proxy-authorization",
  "cookie",
];

// ============================================================================
// Inspector Network domain instrumentation (Chrome DevTools Protocol).
//
// When `node:inspector` has been loaded and `--inspect` is active, fetch()
// emits `Network.requestWillBeSent` / `responseReceived` / `dataReceived` /
// `loadingFinished` / `loadingFailed` events. The actual emitters and a
// monotonic requestId generator are installed by `ext/node/polyfills/
// inspector.js` onto `internals.__inspectorNetwork` so this layer doesn't
// have to depend on ext/node.
// ============================================================================

function getInspectorNetwork() {
  const ins = internals.__inspectorNetwork;
  if (ins && ins.isEnabled()) return ins;
  return null;
}

// Inspector emission is purely observational - if anything goes wrong
// (inspector detached mid-flight, payload validation in
// `op_inspector_emit_protocol_event`, etc.) we never want it to surface
// as a fetch error to user code. Centralized so the call sites stay
// straight-line.
function safeEmit(fn, params) {
  try {
    fn(params);
  } catch {
    // swallow
  }
}

// Join repeated header values according to Chrome DevTools conventions:
// cookies use `; `, set-cookie uses `\n`, everything else uses `, `.
//
// Response header names are typically lowercased on the wire by hyper, but
// CDP / Node frontends conventionally key `Set-Cookie` with its canonical
// case (the test suite asserts `headers['Set-Cookie']`). Apply a small
// canonicalization for the names that conventionally carry case.
function joinHeaderValuesForCdp(headerList, lowerCaseNames) {
  const out = { __proto__: null };
  for (let i = 0; i < headerList.length; i++) {
    const rawName = headerList[i][0];
    const value = String(headerList[i][1]);
    const lower = byteLowerCase(rawName);
    let name;
    if (lowerCaseNames) {
      name = lower;
    } else if (lower === "set-cookie") {
      name = "Set-Cookie";
    } else {
      name = rawName;
    }
    let separator;
    if (lower === "cookie") {
      separator = "; ";
    } else if (lower === "set-cookie") {
      separator = "\n";
    } else {
      separator = ", ";
    }
    if (out[name] === undefined) {
      out[name] = value;
    } else {
      out[name] = out[name] + separator + value;
    }
  }
  return out;
}

// Parse Content-Type into { mimeType, charset } for `response.mimeType` and
// `response.charset` (and to decide whether `getResponseBody` returns the
// body as a utf-8 string or base64).
function parseContentTypeForCdp(headerList) {
  let raw = null;
  for (let i = 0; i < headerList.length; i++) {
    if (byteLowerCase(headerList[i][0]) === "content-type") {
      raw = String(headerList[i][1]);
      break;
    }
  }
  if (raw === null) return { mimeType: "", charset: "" };
  const semi = StringPrototypeIndexOf(raw, ";");
  const mimeType = semi === -1
    ? StringPrototypeTrim(raw)
    : StringPrototypeTrim(StringPrototypeSlice(raw, 0, semi));
  let charset = "";
  if (semi !== -1) {
    const rest = StringPrototypeSlice(raw, semi + 1);
    const parts = StringPrototypeSplit(rest, ";");
    for (let i = 0; i < parts.length; i++) {
      const p = StringPrototypeTrim(parts[i]);
      if (
        StringPrototypeStartsWith(StringPrototypeToLowerCase(p), "charset=")
      ) {
        charset = StringPrototypeTrim(StringPrototypeSlice(p, 8));
        // Strip optional surrounding quotes.
        if (
          charset.length >= 2 && charset[0] === '"' &&
          charset[charset.length - 1] === '"'
        ) {
          charset = StringPrototypeSlice(charset, 1, charset.length - 1);
        }
        break;
      }
    }
  }
  return { mimeType, charset };
}

// Run a background drain of the inspector branch of a tee'd response stream,
// emitting `Network.dataReceived` per chunk and `Network.loadingFinished` /
// `loadingFailed` when the stream ends. Errors from this drain are swallowed
// so they can't surface as unhandled rejections to user code.
function drainResponseForInspector(inspectorStream, requestId, ins) {
  const reader = inspectorStream.getReader();
  let totalLength = 0;
  (async () => {
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        if (value) {
          const len = TypedArrayPrototypeGetByteLength(value);
          if (len > 0) {
            totalLength += len;
            safeEmit(ins.dataReceived, {
              requestId,
              timestamp: DateNow() / 1000,
              dataLength: len,
              encodedDataLength: len,
              data: value,
            });
          }
        }
      }
      safeEmit(ins.loadingFinished, {
        requestId,
        timestamp: DateNow() / 1000,
        encodedDataLength: totalLength,
      });
    } catch (err) {
      safeEmit(ins.loadingFailed, {
        requestId,
        timestamp: DateNow() / 1000,
        type: "Fetch",
        errorText: err && err.message ? String(err.message) : String(err),
      });
    } finally {
      try {
        reader.releaseLock();
      } catch {
        // releaseLock can throw if the stream errored mid-read; swallowing
        // matches what the wrapping `safeEmit` calls do above.
      }
    }
  })();
}

/**
 * @param {number} rid
 * @returns {Promise<{ status: number, statusText: string, headers: [string, string][], url: string, responseRid: number, error: [string, string]? }>}
 */
function opFetchSend(rid) {
  return op_fetch_send(rid);
}

/**
 * @param {number} responseBodyRid
 * @param {AbortSignal} [terminator]
 * @returns {ReadableStream<Uint8Array>}
 */
function createResponseBodyStream(responseBodyRid, terminator) {
  const readable = readableStreamForRid(responseBodyRid);

  function onAbort() {
    errorReadableStream(readable, terminator.reason);
    core.tryClose(responseBodyRid);
  }

  // TODO(lucacasonato): clean up registration
  terminator[abortSignal.add](onAbort);

  return readable;
}

/**
 * @param {InnerRequest} req
 * @param {boolean} recursive
 * @param {AbortSignal} terminator
 * @returns {Promise<InnerResponse>}
 */
async function mainFetch(req, recursive, terminator, inspectorCtx = null) {
  if (req.blobUrlEntry !== null) {
    if (req.method !== "GET") {
      throw new TypeError("Blob URL fetch only supports GET method");
    }

    const body = new InnerBody(req.blobUrlEntry.stream());
    terminator[abortSignal.add](() => body.error(terminator.reason));
    processUrlList(req.urlList, req.urlListProcessed);

    return {
      headerList: [
        ["content-length", String(req.blobUrlEntry.size)],
        ["content-type", req.blobUrlEntry.type],
      ],
      status: 200,
      statusMessage: "OK",
      body,
      type: "basic",
      url() {
        if (this.urlList.length == 0) return null;
        return this.urlList[this.urlList.length - 1];
      },
      urlList: recursive
        ? []
        : [...new SafeArrayIterator(req.urlListProcessed)],
    };
  }

  /** @type {ReadableStream<Uint8Array> | Uint8Array | null} */
  let reqBody = null;
  let reqRid = null;

  if (req.body) {
    const stream = req.body.streamOrStatic;
    const body = stream.body;

    if (TypedArrayPrototypeGetSymbolToStringTag(body) === "Uint8Array") {
      reqBody = body;
    } else if (typeof body === "string") {
      reqBody = core.encode(body);
    } else if (ObjectPrototypeIsPrototypeOf(ReadableStreamPrototype, stream)) {
      const resourceBacking = getReadableStreamResourceBacking(stream);
      if (resourceBacking) {
        reqRid = resourceBacking.rid;
      } else {
        reqRid = resourceForReadableStream(stream, req.body.length);
      }
    } else {
      throw new TypeError("Invalid body");
    }
  }

  const { requestRid, cancelHandleRid } = op_fetch(
    req.method,
    req.currentUrl(),
    req.headerList,
    req.clientRid,
    reqBody !== null || reqRid !== null,
    reqBody,
    reqRid,
  );

  // ---- Inspector: Network.requestWillBeSent ------------------------------
  // Only fires when `node:inspector` is loaded AND the inspector is currently
  // attached, so the cost is one method call (`isEnabled()`) otherwise.
  //
  // For redirect chains the recursive call carries an `inspectorCtx` with the
  // original requestId plus the previous hop's response, so DevTools sees:
  //   requestWillBeSent(URL_A)
  //   requestWillBeSent(URL_B, redirectResponse=<URL_A's 30x>)
  //   responseReceived(URL_B)
  // with the same requestId throughout, matching Chrome's contract.
  const inspectorNetwork = getInspectorNetwork();
  let inspectorRequestId = inspectorCtx?.requestId ?? null;
  const inspectorRedirectResponse = inspectorCtx?.redirectResponse ?? null;
  if (
    inspectorNetwork !== null && inspectorRequestId === null && !recursive
  ) {
    inspectorRequestId = inspectorNetwork.nextRequestId();
  }
  // If the inspector detached between the initial request and a redirect
  // hop, drop the requestId so we stop emitting half-events for it.
  if (inspectorRequestId !== null && inspectorNetwork === null) {
    inspectorRequestId = null;
  }
  if (inspectorRequestId !== null) {
    // hasPostData reflects whether the request carries a body at all,
    // including streamed bodies (reqRid !== null). The Rust capture uses
    // it to initialize `is_request_finished = !has_post_data`, so getting
    // this right is what keeps streaming-body requests un-finished until
    // a chunked `dataSent` path actually flushes them.
    const hasPostData = reqBody !== null || reqRid !== null;
    let postDataText;
    if (
      reqBody !== null &&
      TypedArrayPrototypeGetSymbolToStringTag(reqBody) === "Uint8Array"
    ) {
      try {
        postDataText = core.decode(reqBody);
      } catch {
        postDataText = undefined;
      }
    }
    const requestHeadersForCdp = joinHeaderValuesForCdp(
      req.headerList,
      /* lowerCaseNames */ true,
    );
    // The buffer's request_charset gates `Network.getRequestPostData`
    // (utf-8 only). Prefer an explicit charset from Content-Type; fall
    // back to utf-8 when we successfully decoded the body as a JS string,
    // since fetch encodes string bodies as utf-8 over the wire.
    let requestCharset = parseContentTypeForCdp(req.headerList).charset ||
      undefined;
    if (requestCharset === undefined && postDataText !== undefined) {
      requestCharset = "utf-8";
    }
    const requestWillBeSentParams = {
      requestId: inspectorRequestId,
      timestamp: DateNow() / 1000,
      wallTime: DateNow() / 1000,
      type: "Fetch",
      request: {
        url: req.currentUrl(),
        method: req.method,
        headers: requestHeadersForCdp,
        hasPostData,
        postData: postDataText,
      },
      // initiator: filled in by `op_inspector_emit_protocol_event` using
      // V8's current stack trace, so the user-code frame at the fetch()
      // call site is preserved.
      charset: requestCharset,
    };
    if (inspectorRedirectResponse !== null) {
      requestWillBeSentParams.redirectResponse = inspectorRedirectResponse;
    }
    safeEmit(inspectorNetwork.requestWillBeSent, requestWillBeSentParams);
    // When we supplied the entire request body inline via
    // `request.postData`, flip the buffer's `is_request_finished` flag
    // immediately so `Network.getRequestPostData` doesn't reject with
    // "Request data is not finished yet". Streaming bodies (reqRid !==
    // null, where postDataText stays undefined) take the chunked
    // `Network.dataSent` path instead and aren't covered here; keeping
    // them un-finished is the desired outcome until that lands.
    if (postDataText !== undefined) {
      safeEmit(inspectorNetwork.dataSent, {
        requestId: inspectorRequestId,
        finished: true,
      });
    }
  }

  function onAbort() {
    if (cancelHandleRid !== null) {
      core.tryClose(cancelHandleRid);
    }
  }
  terminator[abortSignal.add](onAbort);
  let resp;
  try {
    resp = await opFetchSend(requestRid);
  } catch (err) {
    if (inspectorRequestId !== null) {
      safeEmit(inspectorNetwork.loadingFailed, {
        requestId: inspectorRequestId,
        timestamp: DateNow() / 1000,
        type: "Fetch",
        errorText: err && err.message ? String(err.message) : String(err),
      });
    }
    if (terminator.aborted) return abortedNetworkError();
    throw err;
  } finally {
    if (cancelHandleRid !== null) {
      core.tryClose(cancelHandleRid);
    }
  }
  // Re-throw any body errors
  if (resp.error !== null) {
    if (inspectorRequestId !== null) {
      safeEmit(inspectorNetwork.loadingFailed, {
        requestId: inspectorRequestId,
        timestamp: DateNow() / 1000,
        type: "Fetch",
        errorText: resp.error[0],
      });
    }
    const { 0: message, 1: cause } = resp.error;
    throw new TypeError(message, { cause: new Error(cause) });
  }
  if (terminator.aborted) {
    // op_fetch_send resolved successfully, so the FetchResponseResource is already in
    // the resource table. The success path below either closes resp.responseRid
    // (redirect / null-body / HEAD / CONNECT) or hands it to createResponseBodyStream,
    // which owns its lifecycle. Only this aborted-after-resolve branch needs to close
    // the rid manually, otherwise it leaks and trips the test sanitizer.
    core.tryClose(resp.responseRid);
    return abortedNetworkError();
  }

  processUrlList(req.urlList, req.urlListProcessed);

  /** @type {InnerResponse} */
  const response = {
    headerList: resp.headers,
    status: resp.status,
    body: null,
    statusMessage: resp.statusText,
    type: "basic",
    url() {
      if (this.urlList.length == 0) return null;
      return this.urlList[this.urlList.length - 1];
    },
    urlList: req.urlListProcessed,
  };

  // ---- Inspector: Network.responseReceived -------------------------------
  // Skip when we're about to follow a redirect: the 30x response becomes
  // the `redirectResponse` on the next hop's `requestWillBeSent` instead
  // of its own `responseReceived`, matching Chrome DevTools' contract.
  const willFollowRedirect = redirectStatus(resp.status) &&
    req.redirectMode === "follow";
  let cdpResponse = null;
  if (inspectorRequestId !== null) {
    const { mimeType, charset } = parseContentTypeForCdp(resp.headers);
    const responseHeadersForCdp = joinHeaderValuesForCdp(
      resp.headers,
      /* lowerCaseNames */ false,
    );
    cdpResponse = {
      url: resp.url || req.currentUrl(),
      status: resp.status,
      statusText: resp.statusText,
      headers: responseHeadersForCdp,
      mimeType,
      charset,
    };
    if (!willFollowRedirect) {
      safeEmit(inspectorNetwork.responseReceived, {
        requestId: inspectorRequestId,
        timestamp: DateNow() / 1000,
        type: "Fetch",
        response: cdpResponse,
      });
    }
  }

  if (redirectStatus(resp.status)) {
    switch (req.redirectMode) {
      case "error":
        core.close(resp.responseRid);
        if (inspectorRequestId !== null) {
          safeEmit(inspectorNetwork.loadingFailed, {
            requestId: inspectorRequestId,
            timestamp: DateNow() / 1000,
            type: "Fetch",
            errorText:
              "Encountered redirect while redirect mode is set to 'error'",
          });
        }
        return networkError(
          "Encountered redirect while redirect mode is set to 'error'",
        );
      case "follow":
        core.close(resp.responseRid);
        return httpRedirectFetch(
          req,
          response,
          terminator,
          inspectorRequestId !== null
            ? { requestId: inspectorRequestId, redirectResponse: cdpResponse }
            : null,
        );
      case "manual":
        break;
    }
  }

  if (nullBodyStatus(response.status)) {
    core.close(resp.responseRid);
    if (inspectorRequestId !== null) {
      safeEmit(inspectorNetwork.loadingFinished, {
        requestId: inspectorRequestId,
        timestamp: DateNow() / 1000,
        encodedDataLength: 0,
      });
    }
  } else {
    if (req.method === "HEAD" || req.method === "CONNECT") {
      response.body = null;
      core.close(resp.responseRid);
      if (inspectorRequestId !== null) {
        safeEmit(inspectorNetwork.loadingFinished, {
          requestId: inspectorRequestId,
          timestamp: DateNow() / 1000,
          encodedDataLength: 0,
        });
      }
    } else {
      let bodyStream = createResponseBodyStream(resp.responseRid, terminator);
      // Tee the response body so the inspector can drain a copy in the
      // background for `Network.dataReceived` + `loadingFinished` /
      // `getResponseBody`, while the user still consumes the original.
      if (inspectorRequestId !== null) {
        try {
          const tee = bodyStream.tee();
          bodyStream = tee[0];
          drainResponseForInspector(
            tee[1],
            inspectorRequestId,
            inspectorNetwork,
          );
        } catch {
          // tee failed; leave bodyStream untouched, no inspector data
        }
      }
      response.body = new InnerBody(bodyStream);
    }
  }

  if (recursive) return response;

  if (response.urlList.length === 0) {
    processUrlList(req.urlList, req.urlListProcessed);
    response.urlList = [...new SafeArrayIterator(req.urlListProcessed)];
  }

  return response;
}

/**
 * @param {InnerRequest} request
 * @param {InnerResponse} response
 * @param {AbortSignal} terminator
 * @param {?{requestId: string, redirectResponse: object}} inspectorCtx
 *   When present, carries the inspector requestId across the redirect so
 *   the next hop's `requestWillBeSent` keeps the same id and gets the
 *   previous response attached as `redirectResponse`.
 * @returns {Promise<InnerResponse>}
 */
function httpRedirectFetch(request, response, terminator, inspectorCtx = null) {
  const locationHeaders = ArrayPrototypeFilter(
    response.headerList,
    (entry) => byteLowerCase(entry[0]) === "location",
  );
  if (locationHeaders.length === 0) {
    return response;
  }

  const currentURL = new URL(request.currentUrl());
  const locationURL = new URL(
    locationHeaders[0][1],
    response.url() ?? undefined,
  );
  if (locationURL.hash === "") {
    locationURL.hash = currentURL.hash;
  }
  if (locationURL.protocol !== "https:" && locationURL.protocol !== "http:") {
    return networkError("Can not redirect to a non HTTP(s) url");
  }
  if (request.redirectCount === 20) {
    return networkError("Maximum number of redirects (20) reached");
  }
  request.redirectCount++;
  if (
    response.status !== 303 &&
    request.body !== null &&
    request.body.source === null
  ) {
    return networkError(
      "Can not redeliver a streaming request body after a redirect",
    );
  }
  if (
    ((response.status === 301 || response.status === 302) &&
      request.method === "POST") ||
    (response.status === 303 &&
      request.method !== "GET" &&
      request.method !== "HEAD")
  ) {
    request.method = "GET";
    request.body = null;
    for (let i = 0; i < request.headerList.length; i++) {
      if (
        ArrayPrototypeIncludes(
          REQUEST_BODY_HEADER_NAMES,
          byteLowerCase(request.headerList[i][0]),
        )
      ) {
        ArrayPrototypeSplice(request.headerList, i, 1);
        i--;
      }
    }
  }

  // Drop confidential headers when redirecting to a less secure protocol
  // or to a different domain that is not a superdomain
  if (
    (locationURL.protocol !== currentURL.protocol &&
      locationURL.protocol !== "https:") ||
    (locationURL.host !== currentURL.host &&
      !isSubdomain(locationURL.host, currentURL.host))
  ) {
    for (let i = 0; i < request.headerList.length; i++) {
      if (
        ArrayPrototypeIncludes(
          REDIRECT_SENSITIVE_HEADER_NAMES,
          byteLowerCase(request.headerList[i][0]),
        )
      ) {
        ArrayPrototypeSplice(request.headerList, i, 1);
        i--;
      }
    }
  }

  if (request.body !== null) {
    const res = extractBody(request.body.source);
    request.body = res.body;
  }
  ArrayPrototypePush(request.urlList, () => locationURL.href);
  return mainFetch(request, true, terminator, inspectorCtx);
}

/**
 * @param {RequestInfo} input
 * @param {RequestInit} init
 */
function fetch(input, init = undefined) {
  let span;
  let snapshot;
  try {
    if (__telemetry.TRACING_ENABLED) {
      span = builtinTracer().startSpan("fetch", { kind: 2 });
      snapshot = enterSpan(span);
    }

    // There is an async dispatch later that causes a stack trace disconnect.
    // We reconnect it by assigning the result of that dispatch to `opPromise`,
    // awaiting `opPromise` in an inner function also named `fetch()` and
    // returning the result from that.
    let opPromise = undefined;
    // 1.
    const result = new Promise((resolve, reject) => {
      const prefix = "Failed to execute 'fetch'";
      webidl.requiredArguments(arguments.length, 1, prefix);
      // 2.
      const requestObject = new Request(input, init);

      if (span) {
        const context = ContextManager.active();
        for (
          const propagator of new SafeArrayIterator(__telemetry.PROPAGATORS)
        ) {
          propagator.inject(context, requestObject.headers, {
            set(carrier, key, value) {
              carrier.append(key, value);
            },
          });
        }

        updateSpanFromRequest(span, requestObject);
      }

      // 3.
      const request = toInnerRequest(requestObject);
      // 4.
      if (requestObject.signal.aborted) {
        if (span) {
          // Handles this case here as this is the only case where `result` promise
          // is settled immediately.
          updateSpanFromError(span, requestObject.signal.reason);
        }
        reject(abortFetch(request, null, requestObject.signal.reason));
        return;
      }
      // 7.
      let responseObject = null;
      // 9.
      let locallyAborted = false;
      // 10.
      function onabort() {
        locallyAborted = true;
        reject(
          abortFetch(request, responseObject, requestObject.signal.reason),
        );
      }
      requestObject.signal[abortSignal.add](onabort);

      if (!requestObject.headers.has("Accept")) {
        ArrayPrototypePush(request.headerList, ["Accept", "*/*"]);
      }

      if (!requestObject.headers.has("Accept-Language")) {
        ArrayPrototypePush(request.headerList, ["Accept-Language", "*"]);
      }

      // 12.
      opPromise = PromisePrototypeCatch(
        PromisePrototypeThen(
          mainFetch(request, false, requestObject.signal),
          (response) => {
            // 12.1.
            if (locallyAborted) return;
            // 12.2.
            if (response.aborted) {
              reject(
                abortFetch(
                  request,
                  responseObject,
                  requestObject.signal.reason,
                ),
              );
              requestObject.signal[abortSignal.remove](onabort);
              return;
            }
            // 12.3.
            if (response.type === "error") {
              const err = new TypeError(
                "Fetch failed: " + (response.error ?? "unknown error"),
              );
              reject(err);
              requestObject.signal[abortSignal.remove](onabort);
              return;
            }
            responseObject = fromInnerResponse(response, "immutable");

            if (span) {
              updateSpanFromClientResponse(span, responseObject);
            }

            resolve(responseObject);
            requestObject.signal[abortSignal.remove](onabort);
          },
        ),
        (err) => {
          reject(err);
          requestObject.signal[abortSignal.remove](onabort);
        },
      );
    });

    if (opPromise) {
      PromisePrototypeCatch(result, (e) => {
        if (span) {
          updateSpanFromError(span, e);
        }
      });
      return (async function fetch() {
      try {
        await opPromise;
        return result;
      } finally {
        span?.end();
      }
      })();
    }
    // We need to end the span when the promise settles.
    // WPT has a test that aborted fetch is settled in the same tick.
    // This means we cannot wrap the promise if it is already settled.
    // But this is OK, because we can just immediately end the span
    // in that case.
    if (span) {
      // XXX: This should always be true, otherwise `opPromise` would be present.
      if (op_fetch_promise_is_settled(result)) {
        // It's already settled.
        span?.end();
      } else {
        // Not settled yet, we can return a new wrapper promise.
        return SafePromisePrototypeFinally(result, () => {
          span?.end();
        });
      }
    }
    return result;
  } finally {
    if (snapshot) restoreSnapshot(snapshot);
  }
}

function abortFetch(request, responseObject, error) {
  if (request.body !== null) {
    // Cancel the body if we haven't taken it as a resource yet
    if (!request.body.streamOrStatic.locked) {
      request.body.cancel(error);
    }
  }
  if (responseObject !== null) {
    const response = toInnerResponse(responseObject);
    if (response.body !== null) response.body.error(error);
  }
  return error;
}

/**
 * Checks if the given string is a subdomain of the given domain.
 *
 * @param {String} subdomain
 * @param {String} domain
 * @returns {Boolean}
 */
function isSubdomain(subdomain, domain) {
  const dot = subdomain.length - domain.length - 1;
  return (
    dot > 0 &&
    subdomain[dot] === "." &&
    StringPrototypeEndsWith(subdomain, domain)
  );
}

/**
 * Handle the Response argument to the WebAssembly streaming APIs, after
 * resolving if it was passed as a promise. This function should be registered
 * through `Deno.core.setWasmStreamingCallback`.
 *
 * @param {any} source The source parameter that the WebAssembly streaming API
 * was called with. If it was called with a Promise, `source` is the resolved
 * value of that promise.
 * @param {number} rid An rid that represents the wasm streaming resource.
 */
function handleWasmStreaming(source, rid) {
  // This implements part of
  // https://webassembly.github.io/spec/web-api/#compile-a-potential-webassembly-response
  try {
    const res = webidl.converters["Response"](
      source,
      "Failed to execute 'WebAssembly.compileStreaming'",
      "Argument 1",
    );

    // 2.3.
    // The spec is ambiguous here, see
    // https://github.com/WebAssembly/spec/issues/1138. The WPT tests expect
    // the raw value of the Content-Type attribute lowercased. We ignore this
    // for file:// because file fetches don't have a Content-Type.
    if (!StringPrototypeStartsWith(res.url, "file://")) {
      const contentType = res.headers.get("Content-Type");
      if (
        typeof contentType !== "string" ||
        StringPrototypeToLowerCase(contentType) !== "application/wasm"
      ) {
        throw new TypeError("Invalid WebAssembly content type");
      }
    }

    // 2.5.
    if (!res.ok) {
      throw new TypeError(
        `Failed to receive WebAssembly content: HTTP status code ${res.status}`,
      );
    }

    // Pass the resolved URL to v8.
    op_wasm_streaming_set_url(rid, res.url);

    if (res.body !== null) {
      // 2.6.
      // Rather than consuming the body as an ArrayBuffer, this passes each
      // chunk to the feed as soon as it's available.
      PromisePrototypeThen(
        (async () => {
          const reader = res.body.getReader();
          while (true) {
            const { value: chunk, done } = await reader.read();
            if (done) break;
            op_wasm_streaming_feed(rid, chunk);
          }
        })(),
        // 2.7
        () => core.close(rid),
        // 2.8
        (err) => core.abortWasmStreaming(rid, err),
      );
    } else {
      // 2.7
      core.close(rid);
    }
  } catch (err) {
    // 2.8
    core.abortWasmStreaming(rid, err);
  }
}

return { fetch, handleWasmStreaming, mainFetch };
})();