@amritk/nish-aarch64-linux 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/INSTALL.md +73 -59
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +50 -4
  4. package/package.json +1 -1
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/nish.d.ts +4849 -430
  8. package/runtime/nish.h +25 -0
  9. package/runtime/page.d.ts +53 -0
  10. package/runtime/page.mjs +146 -0
  11. package/runtime/runtime-async.c +557 -0
  12. package/runtime/runtime-wasm.c +63 -7
  13. package/runtime/vite.d.ts +30 -0
  14. package/runtime/vite.mjs +150 -0
  15. package/scripts/build.sh +252 -15
  16. package/std/README.md +107 -82
  17. package/std/base64.ts +34 -5
  18. package/std/bytes.ts +279 -59
  19. package/std/cli-args.ts +296 -70
  20. package/std/cli-flags.ts +184 -19
  21. package/std/cli.ts +475 -54
  22. package/std/collections.ts +121 -23
  23. package/std/compress/checksum.ts +44 -14
  24. package/std/compress/deflate.ts +224 -111
  25. package/std/compress/gzip.ts +217 -53
  26. package/std/compress/zlib.ts +63 -7
  27. package/std/crypto/aes.ts +128 -52
  28. package/std/crypto/base64url.ts +29 -5
  29. package/std/crypto/bcrypt-batch.ts +101 -34
  30. package/std/crypto/bcrypt.ts +93 -27
  31. package/std/crypto/chacha20poly1305.ts +69 -14
  32. package/std/crypto/ct.ts +32 -13
  33. package/std/crypto/ed25519.ts +66 -16
  34. package/std/crypto/hkdf.ts +198 -13
  35. package/std/crypto/hmac.ts +242 -37
  36. package/std/crypto/jwt.ts +204 -72
  37. package/std/crypto/p256.ts +222 -72
  38. package/std/crypto/p384.ts +51 -23
  39. package/std/crypto/pki-roots.ts +32 -2
  40. package/std/crypto/pki.ts +99 -30
  41. package/std/crypto/rsa.ts +56 -22
  42. package/std/crypto/sha1.ts +3 -0
  43. package/std/crypto/sha256.ts +24 -1
  44. package/std/crypto/sha512.ts +99 -14
  45. package/std/crypto/x25519.ts +163 -24
  46. package/std/crypto/x509-random.ts +10 -0
  47. package/std/crypto/x509.ts +133 -66
  48. package/std/host/ring.ts +124 -0
  49. package/std/json-equal.ts +31 -11
  50. package/std/json-format.ts +112 -13
  51. package/std/json-number.ts +76 -26
  52. package/std/json-pointer.ts +23 -1
  53. package/std/json-tokenizer.ts +126 -51
  54. package/std/json-typed.ts +757 -96
  55. package/std/json-value.ts +438 -157
  56. package/std/json.ts +170 -38
  57. package/std/map.ts +25 -7
  58. package/std/math.ts +36 -4
  59. package/std/net/buffer-pool.ts +42 -11
  60. package/std/net/dns-config.ts +109 -23
  61. package/std/net/dns-message.ts +62 -7
  62. package/std/net/dns-resolver.ts +247 -53
  63. package/std/net/dns.ts +203 -35
  64. package/std/net/fetch.ts +1267 -290
  65. package/std/net/handler.ts +296 -80
  66. package/std/net/hpack.ts +290 -77
  67. package/std/net/http-compress.ts +152 -36
  68. package/std/net/http-fields.ts +85 -9
  69. package/std/net/http1-client-codec.ts +129 -44
  70. package/std/net/http1-codec.ts +279 -114
  71. package/std/net/http1-server.ts +409 -139
  72. package/std/net/http2-frame.ts +289 -51
  73. package/std/net/http2-tls.ts +152 -49
  74. package/std/net/http2.ts +314 -160
  75. package/std/net/http3-frame.ts +165 -27
  76. package/std/net/http3-server.ts +282 -131
  77. package/std/net/http3.ts +377 -173
  78. package/std/net/outbound.ts +37 -3
  79. package/std/net/postgres-carrier.ts +144 -8
  80. package/std/net/postgres.ts +898 -260
  81. package/std/net/prefork.ts +202 -65
  82. package/std/net/qpack.ts +120 -32
  83. package/std/net/quic-conn-ack.ts +60 -12
  84. package/std/net/quic-conn-cid.ts +135 -27
  85. package/std/net/quic-conn-params.ts +109 -22
  86. package/std/net/quic-datagram.ts +50 -3
  87. package/std/net/quic-frame.ts +333 -23
  88. package/std/net/quic-listener.ts +161 -75
  89. package/std/net/quic-packet.ts +373 -73
  90. package/std/net/quic-recovery.ts +287 -65
  91. package/std/net/quic-stream.ts +436 -146
  92. package/std/net/quic.ts +693 -323
  93. package/std/net/router.ts +87 -40
  94. package/std/net/tls/client.ts +167 -51
  95. package/std/net/tls/codec.ts +494 -68
  96. package/std/net/tls/record-client.ts +140 -73
  97. package/std/net/tls/record-server.ts +233 -105
  98. package/std/net/tls/record.ts +142 -36
  99. package/std/net/tls/schedule.ts +235 -26
  100. package/std/net/tls/ticket.ts +161 -40
  101. package/std/net/tls/verify.ts +57 -10
  102. package/std/net/tls-tcp.ts +308 -95
  103. package/std/net/tls.ts +276 -102
  104. package/std/net/upstream.ts +81 -45
  105. package/std/net/url.ts +109 -22
  106. package/std/net/websocket.ts +140 -26
  107. package/std/net/webtransport.ts +243 -106
  108. package/std/pair.ts +10 -2
  109. package/std/random.ts +42 -15
  110. package/std/regex.ts +422 -257
  111. package/std/region.ts +70 -15
  112. package/std/secret.ts +52 -11
  113. package/std/sort.ts +17 -2
  114. package/std/sqlite.ts +256 -35
  115. package/std/sync/ring.ts +229 -56
  116. package/std/sync/shm.ts +203 -23
  117. package/std/term-io.ts +154 -78
  118. package/std/term-pixels.ts +144 -19
  119. package/std/term-probe.ts +77 -35
  120. package/std/term-rate.ts +199 -118
  121. package/std/term.ts +400 -175
  122. package/std/testing.ts +130 -32
  123. package/std/text.ts +84 -17
  124. package/std/threads.ts +248 -56
  125. package/std/yaml-json.ts +111 -97
  126. package/std/yaml-lines.ts +47 -15
  127. package/std/yaml-write.ts +45 -30
  128. package/std/yaml.ts +764 -384
package/std/net/fetch.ts CHANGED
@@ -1,8 +1,27 @@
1
1
  /**
2
- * `nish/net/fetch` — a blocking HTTP/1.1 client for command-line
3
- * programs: `fetchSync(request, options)` dials, sends, and answers the
2
+ * `nish/net/fetch` — an HTTP/1.1 client. `fetchSync(request, options)` is the
3
+ * blocking one for command-line programs: it dials, sends, and answers the
4
4
  * response's head with a reader for its body, and a `FetchSyncClient` does the
5
- * same while keeping one connection alive between fetches.
5
+ * same while keeping one connection alive between fetches. `await fetch(url,
6
+ * init)` is the async one: it parks its task on `nish:async` instead of the
7
+ * thread, so `awaitAll(fetch(a), fetch(b))` overlaps the two.
8
+ *
9
+ * import { fetch } from "nish/net/fetch";
10
+ *
11
+ * const r = await fetch("http://127.0.0.1:8080/health");
12
+ * if (r.isOk()) {
13
+ * const body: string = r.value.text();
14
+ * }
15
+ *
16
+ * **The async `fetch`** answers a `Result`: a `FetchResponse` whose body was
17
+ * read whole before it answered (up to `maxBodyBytes`, 256 MiB by default,
18
+ * else `HTTP_E_BODY_TOO_LARGE`), or a `FetchError` with the `HTTP_E_*` code.
19
+ * The connect, every write and every read wait on the executor; the name
20
+ * lookup still blocks, and only `http://` is driven (an `https://` URL answers
21
+ * `HTTP_E_TLS` naming `fetchSync`, never a silent block). A `FetchPool` handed
22
+ * in through `RequestInit.pool` keeps idle connections per route, capped.
23
+ * Policy, proxies, redirects and error codes are the shared code below, so
24
+ * both clients behave alike. It does not run under `--emit-ts`.
6
25
  *
7
26
  * import { HttpOptions, HttpRequest, HttpResponse, fetchSync } from "nish/net/fetch";
8
27
  *
@@ -96,6 +115,7 @@ import {
96
115
  pollWait,
97
116
  tcpConnect,
98
117
  } from "nish:net"
118
+ import { readable, writable } from "nish:async"
99
119
  import { getenv, monotonicNanos, wallClockNanos } from "nish:process"
100
120
  import { PkiRoots, pkiLoadRoots, pkiLoadSystemRoots } from "nish/crypto/pki-roots"
101
121
  import { TlsClient, TlsClientConfig, tlsClientIsIpLiteral } from "nish/net/tls/client"
@@ -157,6 +177,8 @@ const HTTP_CLIENT_PROXY_PORT: i32 = 1080
157
177
  const HTTP_CLIENT_MAX_WAIT_MS: i64 = 3600000
158
178
  /** Nanoseconds in a millisecond. */
159
179
  const HTTP_CLIENT_NS_PER_MS: i64 = 1000000
180
+ /** The largest body the async fetch can hold in one array, whatever `maxBodyBytes` says. */
181
+ const HTTP_CLIENT_ASYNC_BODY_MAX: i64 = 2147483647
160
182
  /** A deadline that never comes: 146 years of monotonic nanoseconds, far below the overflow of a sum with a timeout. */
161
183
  const HTTP_CLIENT_NEVER: i64 = 4611686018 * 1000000000
162
184
  /** netRead's and netWrite's answer when the socket has nothing ready. */
@@ -167,7 +189,13 @@ const HTTP_CLIENT_WRITABLE: i32 = 2
167
189
  /** The size of the client random and of each ephemeral private key a TLS handshake draws. */
168
190
  const HTTP_CLIENT_TLS_KEY_BYTES: i32 = 32
169
191
 
170
- /** A short name for an `HTTP_E_*` code, for messages: "dns", "read timeout", ... */
192
+ /**
193
+ * A short name for an `HTTP_E_*` code, for messages: "dns", "read timeout",
194
+ * ... A fetch's `errorText` starts with it.
195
+ *
196
+ * @param code An `HTTP_E_*` code, such as a client's `error`.
197
+ * @returns The code's name, "none" for `HTTP_E_NONE`, or "unknown" for a number that is no code.
198
+ */
171
199
  export const httpErrorName = (code: i32): string => {
172
200
  // Indexed by code: the order of the HTTP_E_* constants above.
173
201
  const names: string[] = [
@@ -202,13 +230,22 @@ export const httpErrorName = (code: i32): string => {
202
230
  * `Authorization` field, so a password is never sent by accident.
203
231
  */
204
232
  export class HttpRequest {
233
+ /** The request method, sent as given, such as `GET` or `POST`. */
205
234
  method: string
235
+ /** The absolute URL the request is sent to. */
206
236
  url: string
237
+ /** The header field names, in the order they are sent. */
207
238
  names: string[]
239
+ /** The header field values, each beside its name in `names`. */
208
240
  values: string[]
209
241
  /** Null for no body at all; an empty array sends `Content-Length: 0`. */
210
242
  body: u8[] | null = null
211
243
 
244
+ /**
245
+ * A request with no header fields and no body.
246
+ * @param method The request method, such as `GET`.
247
+ * @param url The absolute `http://` or `https://` URL to send it to.
248
+ */
212
249
  constructor(method: string, url: string) {
213
250
  this.method = method
214
251
  this.url = url
@@ -216,7 +253,11 @@ export class HttpRequest {
216
253
  this.values = []
217
254
  }
218
255
 
219
- /** Appends one header field; nothing is checked until the request is written. */
256
+ /**
257
+ * Appends one header field; nothing is checked until the request is written.
258
+ * @param name The field name.
259
+ * @param value The field value; one holding a CR or LF makes the fetch fail.
260
+ */
220
261
  header(name: string, value: string): void {
221
262
  this.names.push(name)
222
263
  this.values.push(value)
@@ -246,10 +287,13 @@ export class HttpOptions {
246
287
  readTimeoutMs: i32 = 30000
247
288
  /** The budget for a whole fetch, its body included; 0 or less for none. */
248
289
  totalTimeoutMs: i32 = 0
290
+ /** The most redirect hops one fetch follows; past them the fetch fails. */
249
291
  maxRedirects: i32 = 5
250
292
  /** The status line and the header section, each at most this. */
251
293
  maxHeaderBytes: i32 = 65536
294
+ /** Follow a redirect rather than answer it; only to the same origin unless `crossOriginRedirects` is set. */
252
295
  followRedirects: boolean = false
296
+ /** Let a followed redirect go to another origin (see the module comment). */
253
297
  crossOriginRedirects: boolean = false
254
298
  /** Read the proxy settings from the environment (see the module comment). */
255
299
  useEnvProxy: boolean = true
@@ -261,28 +305,36 @@ export class HttpOptions {
261
305
  * `names` are lower-cased and in the order they arrived, beside `values`.
262
306
  */
263
307
  export class HttpResponse {
308
+ /** The status code, such as 200. */
264
309
  status: i32 = 0
310
+ /** The reason phrase the server sent beside the status. */
265
311
  reason: string = ""
312
+ /** The URL that answered, which differs from the request's after a redirect. */
266
313
  url: string = ""
314
+ /** The header field names, lower-cased, in the order they arrived. */
267
315
  names: string[]
316
+ /** The header field values, each beside its name in `names`. */
268
317
  values: string[]
318
+ /** The reader for the response's body. */
269
319
  body: HttpBodyReader
270
320
 
321
+ /**
322
+ * A response with no status and no fields yet; the client fills them in.
323
+ * @param body The reader for the body that follows the head.
324
+ */
271
325
  constructor(body: HttpBodyReader) {
272
326
  this.names = []
273
327
  this.values = []
274
328
  this.body = body
275
329
  }
276
330
 
277
- /** The first value of the field `name`, in any case; null when the response has none. */
331
+ /**
332
+ * The first value of the field `name`, in any case.
333
+ * @param name The field name to look for.
334
+ * @returns The value, or null when the response has no such field.
335
+ */
278
336
  header(name: string): string | null {
279
- const lower: string = httpClientLower(name)
280
- for (let i: i32 = 0; i < toI32(this.names.length) && i < toI32(this.values.length); i += 1) {
281
- if (this.names[i] === lower) {
282
- return this.values[i]
283
- }
284
- }
285
- return null
337
+ return httpClientField(this.names, this.values, name)
286
338
  }
287
339
  }
288
340
 
@@ -293,9 +345,15 @@ export class HttpResponse {
293
345
  * client that made it, and only until that client starts its next fetch.
294
346
  */
295
347
  export class HttpBodyReader {
348
+ /** The client that made the response; it carries the connection the body arrives on. */
296
349
  client: FetchSyncClient
297
- generation: i32
350
+ private generation: i32
298
351
 
352
+ /**
353
+ * A reader for the body of one response.
354
+ * @param client The client that made the response.
355
+ * @param generation The client's response number, so a reader stops reading once the client moves on.
356
+ */
299
357
  constructor(client: FetchSyncClient, generation: i32) {
300
358
  this.client = client
301
359
  this.generation = generation
@@ -308,6 +366,10 @@ export class HttpBodyReader {
308
366
  * event stream is read event by event. A window outside `buf` panics; an
309
367
  * empty one answers 0 at once, reading nothing, so 0 means the end only
310
368
  * when `n` is positive.
369
+ * @param buf Where the body bytes are written.
370
+ * @param off Where in `buf` the first byte goes.
371
+ * @param n The most bytes to read.
372
+ * @returns How many bytes were read, 0 at the end of the body, or a negated `HTTP_E_*` code.
311
373
  */
312
374
  read(buf: u8[], off: i32, n: i32): i32 {
313
375
  if (off < 0 || n < 0 || toI64(off) + toI64(n) > toI64(buf.length)) {
@@ -322,6 +384,8 @@ export class HttpBodyReader {
322
384
  /**
323
385
  * The rest of the body in one array, or null on an error or once it passes
324
386
  * `limit` bytes (`HTTP_E_BODY_TOO_LARGE`, and the connection is closed).
387
+ * @param limit The most body bytes to accept.
388
+ * @returns The body, or null on an error or a body past `limit`.
325
389
  */
326
390
  readAll(limit: i32): u8[] | null {
327
391
  let size: i32 = 4096
@@ -373,67 +437,77 @@ export class HttpBodyReader {
373
437
  */
374
438
  export class FetchSyncClient {
375
439
  // Declared widest first, so no byte of a client is padding.
440
+ /** The options every fetch through this client follows. */
376
441
  options: HttpOptions
442
+ /** A sentence saying why the last failure happened, for a log; "" after a fetch that answered. */
377
443
  errorText: string = ""
378
444
  /** The proxy settings in use; "" for none. `setProxies` replaces them. */
379
- httpProxy: string = ""
380
- httpsProxy: string = ""
381
- noProxy: string = ""
445
+ private httpProxy: string = ""
446
+ private httpsProxy: string = ""
447
+ private noProxy: string = ""
382
448
  /** Where `fd` leads: an origin, or the proxy an http request went through. */
383
- route: string = ""
449
+ private route: string = ""
384
450
  /** The outbound policy `fd` was dialled under; a connection is reused only under the same one. */
385
- routePolicy: OutboundPolicy | null = null
386
- parser: Http1ResponseParser
451
+ private routePolicy: OutboundPolicy | null = null
452
+ private parser: Http1ResponseParser
387
453
  /** The TLS connection over `fd` to an https origin; null over plain http. */
388
- tls: TlsRecordClient | null = null
454
+ private tls: TlsRecordClient | null = null
389
455
  /** The roots an https server's chain must end at, read on the client's first https fetch. */
390
- trust: TlsClientTrust | null = null
391
- ready: i32[]
392
- rbuf: u8[]
456
+ private trust: TlsClientTrust | null = null
457
+ private ready: i32[]
458
+ private rbuf: u8[]
393
459
  /** Where TLS application data is read before the parser takes it; empty until the first https connection. */
394
- plain: u8[]
460
+ private plain: u8[]
395
461
  /** The fetch's end in monotonic nanoseconds; `HTTP_CLIENT_NEVER` for none. */
396
- deadline: i64 = 0
462
+ private deadline: i64 = 0
397
463
  /** The last failure's `HTTP_E_*` code; `HTTP_E_NONE` after a fetch that answered. */
398
464
  error: i32 = 0
399
- fd: i32 = -1
465
+ private fd: i32 = -1
400
466
  /** The fd registered in `loop`, and for what. */
401
- loop: i32 = -1
402
- watched: i32 = -1
403
- watchedEvents: i32 = 0
467
+ private loop: i32 = -1
468
+ private watched: i32 = -1
469
+ private watchedEvents: i32 = 0
404
470
  /** Counts responses; a reader reads only while its own is the open one. */
405
- generation: i32 = 0
471
+ private generation: i32 = 0
406
472
  /** How the latest response's body failed, `HTTP_E_NONE` while it has not; its reader answers it again. */
407
- bodyError: i32 = 0
473
+ private bodyError: i32 = 0
408
474
  /** Where the latest response's unread body bytes start in `parser`, and how many. */
409
- pendOff: i32 = 0
410
- pendLen: i32 = 0
475
+ private pendOff: i32 = 0
476
+ private pendLen: i32 = 0
411
477
  /** Whether `fd` has carried a response before the one in flight. */
412
478
  reused: boolean = false
413
479
  /** Whether any byte of the response in flight has arrived. */
414
- gotByte: boolean = false
480
+ private gotByte: boolean = false
415
481
  /** Whether the failure in hand was the connection going away, which a retry may cure. */
416
- lost: boolean = false
482
+ private lost: boolean = false
417
483
  /** Whether the latest response's body is unread. */
418
- bodyOpen: boolean = false
419
- /** Whether this is `fetchSync`'s client, closed whole once its one body is done with. */
484
+ private bodyOpen: boolean = false
485
+ /** Whether this is `fetchSync`'s client, closed whole once its one body is done with. @internal */
420
486
  once: boolean = false
421
487
 
488
+ /**
489
+ * A client with no connection open yet, its proxy settings read from the
490
+ * environment when `useEnvProxy` is set.
491
+ * @param options How every fetch through the client behaves.
492
+ */
422
493
  constructor(options: HttpOptions) {
423
494
  this.options = options
424
495
  this.parser = httpClientParser(options)
425
496
  this.ready = new Array<i32>(8)
426
497
  this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
427
498
  this.plain = []
428
- if (options.useEnvProxy) {
429
- const cgi: boolean = getenv("REQUEST_METHOD") !== null
430
- this.httpProxy = httpChooseProxy(getenv("http_proxy"), getenv("HTTP_PROXY"), !cgi)
431
- this.httpsProxy = httpChooseProxy(getenv("https_proxy"), getenv("HTTPS_PROXY"), true)
432
- this.noProxy = httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true)
433
- }
499
+ const proxies: string[] = httpClientEnvProxies(options)
500
+ this.httpProxy = proxies[0]
501
+ this.httpsProxy = proxies[1]
502
+ this.noProxy = proxies[2]
434
503
  }
435
504
 
436
- /** Replaces the proxy settings, as the three variables would set them; "" for none. */
505
+ /**
506
+ * Replaces the proxy settings, as the three variables would set them; "" for none.
507
+ * @param httpProxy The proxy for http URLs, as `http_proxy` would give it.
508
+ * @param httpsProxy The proxy for https URLs, as `https_proxy` would give it.
509
+ * @param noProxy The hosts reached without a proxy, as `no_proxy` would list them.
510
+ */
437
511
  setProxies(httpProxy: string, httpsProxy: string, noProxy: string): void {
438
512
  this.httpProxy = httpProxy
439
513
  this.httpsProxy = httpsProxy
@@ -445,6 +519,8 @@ export class FetchSyncClient {
445
519
  * redirects as the options say; null on a failure, with `error` and
446
520
  * `errorText` set. The body is read through the response's `body` before
447
521
  * the next fetch.
522
+ * @param req The request to send.
523
+ * @returns The response, its body still to be read, or null on a failure.
448
524
  */
449
525
  fetch(req: HttpRequest): HttpResponse | null {
450
526
  this.error = HTTP_E_NONE
@@ -454,29 +530,16 @@ export class FetchSyncClient {
454
530
  this.drop()
455
531
  }
456
532
  this.generation += 1
457
- const total: i32 = httpClientTotalMs(this.options)
458
- this.deadline = total > 0 ? monotonicNanos() + toI64(total) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
459
- let url: Url | null = urlParse(req.url)
460
- if (url === null || (url.scheme !== "http" && url.scheme !== "https")) {
461
- this.fail(HTTP_E_URL, `not an absolute http or https URL: ${httpClientRedact(url)}`)
462
- return null
463
- }
464
- const refusal: string = this.hostRefusal(url)
465
- if (refusal !== "") {
466
- this.fail(HTTP_E_BLOCKED, refusal)
533
+ this.deadline = httpClientDeadline(this.options)
534
+ const fault: HttpClientFault = new HttpClientFault()
535
+ let url: Url | null = httpClientTarget(req.url, this.options, fault)
536
+ if (url === null) {
537
+ this.fail(fault.code, fault.text)
467
538
  return null
468
539
  }
469
- let method: string = req.method
470
- let body: u8[] | null = req.body
471
- const names: string[] = []
472
- const values: string[] = []
473
- for (let i: i32 = 0; i < toI32(req.names.length) && i < toI32(req.values.length); i += 1) {
474
- names.push(req.names[i])
475
- values.push(req.values[i])
476
- }
477
- let hops: i32 = 0
540
+ const hop: HttpClientHop = new HttpClientHop(req.method, req.body, req.names, req.values)
478
541
  while (url !== null) {
479
- const res: HttpResponse | null = this.exchange(url, method, names, values, body)
542
+ const res: HttpResponse | null = this.exchange(url, hop.method, hop.names, hop.values, hop.body)
480
543
  if (res === null) {
481
544
  return null
482
545
  }
@@ -484,70 +547,16 @@ export class FetchSyncClient {
484
547
  if (!this.options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
485
548
  return res
486
549
  }
487
- const next: Url | null = urlResolve(url, location)
488
- const maxRedirects: i32 = httpClientMaxRedirects(this.options)
489
- if (hops >= maxRedirects) {
490
- return this.refuse(
491
- HTTP_E_TOO_MANY_REDIRECTS,
492
- `more than ${maxRedirects} redirects, the last to ${httpClientRedact(next)}`
493
- )
494
- }
495
- if (next === null || (next.scheme !== "http" && next.scheme !== "https")) {
496
- return this.refuse(
497
- HTTP_E_REDIRECT_REFUSED,
498
- `a redirect to ${httpClientRedact(next)}, which is not an http or https URL`
499
- )
500
- }
501
- if (url.scheme === "https" && next.scheme === "http") {
502
- return this.refuse(
503
- HTTP_E_REDIRECT_REFUSED,
504
- `a redirect from https to http (${httpClientRedact(next)})`
505
- )
506
- }
507
- const hopRefusal: string = this.hostRefusal(next)
508
- if (hopRefusal !== "") {
509
- return this.refuse(HTTP_E_BLOCKED, hopRefusal)
510
- }
511
- const from: string | null = urlOrigin(url)
512
- const to: string | null = urlOrigin(next)
513
- if (from === null || to === null || from !== to) {
514
- if (!this.options.crossOriginRedirects) {
515
- return this.refuse(
516
- HTTP_E_REDIRECT_REFUSED,
517
- `a redirect to another origin (${httpClientRedact(next)})`
518
- )
519
- }
520
- // Credentials were meant for the first origin, not for wherever it points.
521
- httpClientDropField(names, values, "authorization")
522
- httpClientDropField(names, values, "proxy-authorization")
523
- httpClientDropField(names, values, "cookie")
524
- httpClientDropField(names, values, "host")
525
- }
526
- const status: i32 = res.status
527
- if (
528
- (status === 303 && method !== "HEAD") ||
529
- ((status === 301 || status === 302) && method === "POST")
530
- ) {
531
- method = "GET"
532
- body = null
533
- httpClientDropField(names, values, "content-type")
550
+ const next: Url | null = httpClientRedirect(hop, this.options, url, res.status, location, fault)
551
+ if (next === null) {
552
+ return this.refuse(fault.code, fault.text)
534
553
  }
535
554
  this.drain()
536
- hops += 1
537
555
  url = next
538
556
  }
539
557
  return null
540
558
  }
541
559
 
542
- /** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
543
- hostRefusal(url: Url): string {
544
- const policy: OutboundPolicy | null = this.options.outbound
545
- if (policy === null || outboundHostAllowed(policy, url.host)) {
546
- return ""
547
- }
548
- return `${httpClientRedact(url)} names a host the outbound policy does not allow`
549
- }
550
-
551
560
  /** Closes the connection; the client can still fetch, on a new one. */
552
561
  close(): void {
553
562
  this.drop()
@@ -562,7 +571,7 @@ export class FetchSyncClient {
562
571
  * leads to the same place, once more on a fresh one when a kept connection
563
572
  * turns out to be gone (see the module comment).
564
573
  */
565
- exchange(
574
+ private exchange(
566
575
  url: Url,
567
576
  method: string,
568
577
  names: string[],
@@ -593,33 +602,23 @@ export class FetchSyncClient {
593
602
  * there, else a new one, through a proxy when the settings say so. False on
594
603
  * a failure, with the error set.
595
604
  */
596
- open(url: Url): boolean {
597
- const port: i32 = url.port >= 0 ? url.port : urlDefaultPort(url.scheme)
598
- // A proxy would look the name up itself, past the policy's address check.
599
- const proxyText: string =
600
- this.options.outbound !== null
601
- ? ""
602
- : httpProxyFor(url.scheme, url.host, port, this.httpProxy, this.httpsProxy, this.noProxy)
603
- let proxy: Url | null = null
604
- if (proxyText !== "") {
605
- proxy = httpClientProxyUrl(proxyText)
606
- if (proxy === null) {
607
- this.fail(
608
- HTTP_E_PROXY,
609
- `the proxy setting is not an http:// URL with a host: ${httpClientRedact(
610
- urlParse(proxyText.indexOf("://") >= 0 ? proxyText : "http://" + proxyText)
611
- )}`
612
- )
613
- return false
614
- }
615
- }
616
- const origin: string = `${url.scheme}://${httpClientHostText(url.host)}:${port}`
617
- let route: string = origin
618
- if (proxy !== null && url.scheme === "http") {
619
- route = `proxy ${httpClientHostText(proxy.host)}:${proxy.port}`
620
- } else if (proxy !== null) {
621
- route = `${origin} via ${httpClientHostText(proxy.host)}:${proxy.port}`
605
+ private open(url: Url): boolean {
606
+ const fault: HttpClientFault = new HttpClientFault()
607
+ const way: HttpClientRoute | null = httpClientRoute(
608
+ url,
609
+ this.options,
610
+ this.httpProxy,
611
+ this.httpsProxy,
612
+ this.noProxy,
613
+ fault
614
+ )
615
+ if (way === null) {
616
+ this.fail(fault.code, fault.text)
617
+ return false
622
618
  }
619
+ const proxy: Url | null = way.proxy
620
+ const port: i32 = way.port
621
+ const route: string = way.route
623
622
  if (
624
623
  this.fd >= 0 &&
625
624
  this.route === route &&
@@ -635,9 +634,7 @@ export class FetchSyncClient {
635
634
  if (url.scheme === "https" && !this.loadTrust()) {
636
635
  return false
637
636
  }
638
- const dialHost: string = proxy !== null ? proxy.host : url.host
639
- const dialPort: i32 = proxy !== null ? proxy.port : port
640
- const fd: i32 = this.dial(dialHost, dialPort)
637
+ const fd: i32 = this.dial(way.dialHost, way.dialPort)
641
638
  if (fd < 0) {
642
639
  return false
643
640
  }
@@ -668,7 +665,7 @@ export class FetchSyncClient {
668
665
  * the PEM file `rootsPemPath` names, else the system's. False, with the
669
666
  * error set, when none could be read, since no server could then be trusted.
670
667
  */
671
- loadTrust(): boolean {
668
+ private loadTrust(): boolean {
672
669
  if (this.trust !== null) {
673
670
  return true
674
671
  }
@@ -690,7 +687,7 @@ export class FetchSyncClient {
690
687
  * clock's time before its Finished is read. True once the connection is
691
688
  * open and the client's last flight sent; false with the error set.
692
689
  */
693
- secure(host: string, early: u8[]): boolean {
690
+ private secure(host: string, early: u8[]): boolean {
694
691
  const trust: TlsClientTrust | null = this.trust
695
692
  if (trust === null) {
696
693
  this.fail(HTTP_E_CERTIFICATE, "no trusted root certificates are loaded")
@@ -744,7 +741,7 @@ export class FetchSyncClient {
744
741
  * Asks `proxy`, on the fresh `fd`, for a tunnel to `host:port`. True once
745
742
  * the proxy answers 2xx, every byte after its head belonging to the tunnel.
746
743
  */
747
- tunnel(host: string, port: i32, proxy: Url): boolean {
744
+ private tunnel(host: string, port: i32, proxy: Url): boolean {
748
745
  const authority: string = `${httpClientHostText(host)}:${port}`
749
746
  const names: string[] = ["Host"]
750
747
  const values: string[] = [authority]
@@ -785,58 +782,25 @@ export class FetchSyncClient {
785
782
  }
786
783
 
787
784
  /** Writes the request on `fd` and reads its response's head. */
788
- send(url: Url, method: string, names: string[], values: string[], body: u8[] | null): HttpResponse | null {
789
- const viaProxy: boolean = this.route.startsWith("proxy ")
790
- const sendNames: string[] = []
791
- const sendValues: string[] = []
792
- let hasHost: boolean = false
793
- let hasProxyAuth: boolean = false
794
- for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
795
- // Read before any call, which is where the bounds proof forgets a length.
796
- const name: string = names[i]
797
- const value: string = values[i]
798
- hasHost = hasHost || httpClientNameIs(name, "host")
799
- const proxyAuth: boolean = httpClientNameIs(name, "proxy-authorization")
800
- if (proxyAuth && !viaProxy) {
801
- // Only an http proxy reads it: sent direct or through a tunnel, it
802
- // would hand the proxy's credentials to the origin.
803
- continue
804
- }
805
- hasProxyAuth = hasProxyAuth || proxyAuth
806
- sendNames.push(name)
807
- sendValues.push(value)
808
- }
809
- const hostText: string = httpClientHostText(url.host)
810
- const authority: string = url.port >= 0 ? `${hostText}:${url.port}` : hostText
811
- if (!hasHost) {
812
- sendNames.push("Host")
813
- sendValues.push(authority)
814
- }
815
- let target: string = url.path === "" ? "/" : url.path
816
- const query: string | null = url.query
817
- if (query !== null) {
818
- target = target + "?" + query
819
- }
820
- if (viaProxy) {
821
- target = `${url.scheme}://${authority}${target}`
822
- const proxy: Url | null = httpClientProxyUrl(this.httpProxy)
823
- const auth: string | null = proxy !== null ? httpClientProxyAuth(proxy) : ""
824
- if (auth === null) {
825
- this.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
826
- return null
827
- }
828
- if (auth !== "" && !hasProxyAuth) {
829
- sendNames.push("Proxy-Authorization")
830
- sendValues.push(auth)
831
- }
832
- }
833
- const bodyLength: i64 = body !== null ? toI64(body.length) : toI64(-2)
834
- const head: u8[] | null = http1RequestHead(method, target, sendNames, sendValues, bodyLength)
785
+ private send(
786
+ url: Url,
787
+ method: string,
788
+ names: string[],
789
+ values: string[],
790
+ body: u8[] | null
791
+ ): HttpResponse | null {
792
+ const fault: HttpClientFault = new HttpClientFault()
793
+ const head: u8[] | null = httpClientRequestHead(
794
+ url,
795
+ method,
796
+ names,
797
+ values,
798
+ body,
799
+ this.route.startsWith("proxy ") ? this.httpProxy : "",
800
+ fault
801
+ )
835
802
  if (head === null) {
836
- this.fail(
837
- HTTP_E_REQUEST,
838
- `the request ${method} ${httpClientRedact(url)} was refused: a bad method, target or header field`
839
- )
803
+ this.fail(fault.code, fault.text)
840
804
  return null
841
805
  }
842
806
  this.gotByte = false
@@ -871,7 +835,7 @@ export class FetchSyncClient {
871
835
  }
872
836
 
873
837
  /** Reads up to the final response's head: `HTTP1_HEAD`, `HTTP1_UPGRADE`, or -1 with the error set. */
874
- head(): i32 {
838
+ private head(): i32 {
875
839
  let event: i32 = this.pump()
876
840
  while (event === HTTP1_INFORMATIONAL) {
877
841
  event = this.pump()
@@ -884,7 +848,7 @@ export class FetchSyncClient {
884
848
  }
885
849
 
886
850
  /** The parser's next event, reading from the socket as it needs; -1 with the error set. */
887
- pump(): i32 {
851
+ private pump(): i32 {
888
852
  let event: i32 = this.parser.next()
889
853
  while (event === HTTP1_NEED_MORE) {
890
854
  if (!this.fill()) {
@@ -892,35 +856,17 @@ export class FetchSyncClient {
892
856
  }
893
857
  event = this.parser.next()
894
858
  }
895
- if (event === HTTP1_ERROR) {
896
- const code: i32 = this.parser.error
897
- if (code === HTTP1_E_BODY_LIMIT) {
898
- this.fail(
899
- HTTP_E_BODY_TOO_LARGE,
900
- `the body is larger than maxBodyBytes (${httpClientBodyCap(this.options)})`
901
- )
902
- } else {
903
- // A response the server closed part way through is a connection lost,
904
- // as one closed before any byte is; it is never sent again, because
905
- // a byte of it came.
906
- this.lost = code === HTTP1_E_TRUNCATED
907
- this.fail(
908
- HTTP_E_PROTOCOL,
909
- `the response broke HTTP/1.1: ${this.parser.errorText} (http1 error ${code})`
910
- )
911
- }
912
- return -1
913
- }
914
- if (event === HTTP1_CLOSED) {
915
- this.lost = true
916
- this.fail(HTTP_E_IO, "the server closed the connection before it answered")
859
+ if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
860
+ const fault: HttpClientFault = new HttpClientFault()
861
+ this.lost = httpClientParserFault(this.parser, event, this.options, fault)
862
+ this.fail(fault.code, fault.text)
917
863
  return -1
918
864
  }
919
865
  return event
920
866
  }
921
867
 
922
868
  /** One read of the response into the parser, waiting up to `readTimeoutMs`; false with the error set. */
923
- fill(): boolean {
869
+ private fill(): boolean {
924
870
  if (this.overdue()) {
925
871
  return false
926
872
  }
@@ -962,7 +908,7 @@ export class FetchSyncClient {
962
908
  * `readTimeoutMs`: the count, 0 at the end of the stream, or -1 with the
963
909
  * error set.
964
910
  */
965
- readRaw(want: i32): i32 {
911
+ private readRaw(want: i32): i32 {
966
912
  const until: i64 = this.readDeadline()
967
913
  let n: i32 = netRead(this.fd, this.rbuf, 0, want)
968
914
  while (n === HTTP_CLIENT_WOULD_BLOCK) {
@@ -982,7 +928,7 @@ export class FetchSyncClient {
982
928
  }
983
929
 
984
930
  /** One read of the socket into the TLS connection `conn`, waiting up to `readTimeoutMs`; false with the error set. */
985
- receiveTls(conn: TlsRecordClient): boolean {
931
+ private receiveTls(conn: TlsRecordClient): boolean {
986
932
  const room: i32 = conn.space()
987
933
  const want: i32 = room < HTTP_CLIENT_READ_BYTES ? room : HTTP_CLIENT_READ_BYTES
988
934
  if (want <= 0) {
@@ -1004,7 +950,7 @@ export class FetchSyncClient {
1004
950
  }
1005
951
 
1006
952
  /** Sends everything `conn` has sealed, waiting as `writeRaw` does; false with the error set. */
1007
- flushTls(conn: TlsRecordClient): boolean {
953
+ private flushTls(conn: TlsRecordClient): boolean {
1008
954
  while (conn.outputEnd > conn.outputStart) {
1009
955
  const len: i32 = conn.outputEnd - conn.outputStart
1010
956
  if (!this.writeRaw(conn.output, conn.outputStart, len)) {
@@ -1017,7 +963,7 @@ export class FetchSyncClient {
1017
963
  }
1018
964
 
1019
965
  /** Sets the error for the failed TLS connection `conn`, saying how it failed. */
1020
- failTls(conn: TlsRecordClient): void {
966
+ private failTls(conn: TlsRecordClient): void {
1021
967
  if (conn.ended && !conn.peerClosed) {
1022
968
  this.fail(HTTP_E_TLS, "the server closed the connection without a TLS close_notify")
1023
969
  } else if (conn.peerAlert > 0) {
@@ -1028,7 +974,7 @@ export class FetchSyncClient {
1028
974
  }
1029
975
 
1030
976
  /** Writes `bytes[off, off + len)` on the connection, through TLS for an https origin; false with the error set. */
1031
- writeAll(bytes: u8[], off: i32, len: i32): boolean {
977
+ private writeAll(bytes: u8[], off: i32, len: i32): boolean {
1032
978
  const conn: TlsRecordClient | null = this.tls
1033
979
  if (conn === null) {
1034
980
  return this.writeRaw(bytes, off, len)
@@ -1052,7 +998,7 @@ export class FetchSyncClient {
1052
998
  }
1053
999
 
1054
1000
  /** Writes `bytes[off, off + len)` to `fd`, waiting up to `readTimeoutMs` each time it is full. */
1055
- writeRaw(bytes: u8[], off: i32, len: i32): boolean {
1001
+ private writeRaw(bytes: u8[], off: i32, len: i32): boolean {
1056
1002
  let at: i32 = off
1057
1003
  const end: i32 = off + len
1058
1004
  while (at < end) {
@@ -1081,7 +1027,7 @@ export class FetchSyncClient {
1081
1027
  * Looks `host` up and connects to its addresses in turn, every step within
1082
1028
  * `connectTimeoutMs` together: the connected fd, or -1 with the error set.
1083
1029
  */
1084
- dial(host: string, port: i32): i32 {
1030
+ private dial(host: string, port: i32): i32 {
1085
1031
  const start: i64 = monotonicNanos()
1086
1032
  const budget: i32 = this.options.connectTimeoutMs
1087
1033
  let until: i64 = budget > 0 ? start + toI64(budget) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
@@ -1094,39 +1040,13 @@ export class FetchSyncClient {
1094
1040
  this.fail(code, `no time was left to connect to ${host}`)
1095
1041
  return -1
1096
1042
  }
1097
- let lookupMs: i64 = (until - start) / HTTP_CLIENT_NS_PER_MS
1098
- if (lookupMs < toI64(1)) {
1099
- lookupMs = toI64(1)
1100
- } else if (lookupMs > toI64(2147483647)) {
1101
- lookupMs = toI64(2147483647)
1102
- }
1103
1043
  const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
1104
- const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
1105
- const count: i32 = resolveHost(host, toI32(lookupMs), port, addresses, ttls)
1106
- if (count === DNS_RESOLVE_TIMEOUT && until < HTTP_CLIENT_NEVER) {
1107
- this.failWait(code, `${host} was not looked up within ${budget} ms`)
1108
- return -1
1109
- }
1110
- if (count <= 0) {
1111
- this.fail(
1112
- HTTP_E_DNS,
1113
- `${host} could not be looked up (${count === 0 ? "no address" : `resolver code ${count}`})`
1114
- )
1044
+ const fault: HttpClientFault = new HttpClientFault()
1045
+ const usable: i32 = httpClientResolve(host, port, this.options, start, until, code, addresses, fault)
1046
+ if (usable < 0) {
1047
+ this.fail(fault.code, fault.text)
1115
1048
  return -1
1116
1049
  }
1117
- let usable: i32 = count < DNS_RESOLVE_MAX_ADDRESSES ? count : DNS_RESOLVE_MAX_ADDRESSES
1118
- const policy: OutboundPolicy | null = this.options.outbound
1119
- if (policy !== null) {
1120
- // Only the bytes checked here are connected to: no second lookup a rebinding answer could change.
1121
- usable = outboundFilter(policy, addresses, usable)
1122
- if (usable === 0) {
1123
- this.fail(
1124
- HTTP_E_BLOCKED,
1125
- `${host} resolves to ${outboundAddressText(addresses, 0)}, which the outbound policy does not allow`
1126
- )
1127
- return -1
1128
- }
1129
- }
1130
1050
  const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
1131
1051
  let last: i32 = 0
1132
1052
  for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
@@ -1161,7 +1081,7 @@ export class FetchSyncClient {
1161
1081
  * `HTTP_E_TOTAL_TIMEOUT` for whichever deadline passed, `HTTP_E_IO` when
1162
1082
  * the poll loop cannot be made.
1163
1083
  */
1164
- wait(fd: i32, events: i32, until: i64, code: i32): i32 {
1084
+ private wait(fd: i32, events: i32, until: i64, code: i32): i32 {
1165
1085
  if (!this.watch(fd, events)) {
1166
1086
  return HTTP_E_IO
1167
1087
  }
@@ -1190,7 +1110,7 @@ export class FetchSyncClient {
1190
1110
  }
1191
1111
 
1192
1112
  /** Puts `fd` in the poll loop, waiting for `events`: false when the loop cannot be made. */
1193
- watch(fd: i32, events: i32): boolean {
1113
+ private watch(fd: i32, events: i32): boolean {
1194
1114
  if (this.loop < 0) {
1195
1115
  this.loop = pollCreate()
1196
1116
  if (this.loop < 0) {
@@ -1220,7 +1140,7 @@ export class FetchSyncClient {
1220
1140
  * server that spoke while idle answered nothing yet asked, and is closing
1221
1141
  * or out of step, so the connection is not reused.
1222
1142
  */
1223
- quiet(): boolean {
1143
+ private quiet(): boolean {
1224
1144
  return (
1225
1145
  !this.leftover() &&
1226
1146
  this.watch(this.fd, HTTP_CLIENT_READABLE) &&
@@ -1229,7 +1149,7 @@ export class FetchSyncClient {
1229
1149
  }
1230
1150
 
1231
1151
  /** Whether bytes past the last response are held, in the parser or the TLS layer. */
1232
- leftover(): boolean {
1152
+ private leftover(): boolean {
1233
1153
  const conn: TlsRecordClient | null = this.tls
1234
1154
  if (conn !== null && (conn.plainEnd > conn.plainStart || conn.reader.end > conn.reader.start)) {
1235
1155
  return true
@@ -1238,7 +1158,7 @@ export class FetchSyncClient {
1238
1158
  }
1239
1159
 
1240
1160
  /** Takes `fd` out of the poll loop before it is closed. */
1241
- unwatch(fd: i32): void {
1161
+ private unwatch(fd: i32): void {
1242
1162
  if (this.watched === fd && this.watched >= 0) {
1243
1163
  pollRemove(this.loop, fd)
1244
1164
  this.watched = -1
@@ -1246,13 +1166,13 @@ export class FetchSyncClient {
1246
1166
  }
1247
1167
 
1248
1168
  /** When the wait for the server's next byte ends: `readTimeoutMs` from now. */
1249
- readDeadline(): i64 {
1169
+ private readDeadline(): i64 {
1250
1170
  const ms: i32 = this.options.readTimeoutMs
1251
1171
  return ms > 0 ? monotonicNanos() + toI64(ms) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
1252
1172
  }
1253
1173
 
1254
1174
  /** Closes the connection, if any, and forgets the open body. */
1255
- drop(): void {
1175
+ private drop(): void {
1256
1176
  const conn: TlsRecordClient | null = this.tls
1257
1177
  if (conn !== null) {
1258
1178
  conn.close()
@@ -1282,7 +1202,7 @@ export class FetchSyncClient {
1282
1202
  * Reads past a redirect's body so the connection can carry the next
1283
1203
  * request; a body too long to be worth reading, or any failure, closes it.
1284
1204
  */
1285
- drain(): void {
1205
+ private drain(): void {
1286
1206
  const sink: u8[] = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1287
1207
  let left: i32 = HTTP_CLIENT_DRAIN_BYTES
1288
1208
  while (this.bodyOpen && left > 0) {
@@ -1299,7 +1219,7 @@ export class FetchSyncClient {
1299
1219
  this.errorText = ""
1300
1220
  }
1301
1221
 
1302
- /** `HttpBodyReader.read` for the response numbered `generation`. */
1222
+ /** `HttpBodyReader.read` for the response numbered `generation`. @internal */
1303
1223
  readBody(generation: i32, buf: u8[], off: i32, n: i32): i32 {
1304
1224
  if (generation !== this.generation) {
1305
1225
  // The client's error is the later fetch's; a stale reader leaves it be.
@@ -1337,7 +1257,7 @@ export class FetchSyncClient {
1337
1257
  }
1338
1258
 
1339
1259
  /** Closes the connection a body is done with, and `fetchSync`'s whole client with it. */
1340
- release(): void {
1260
+ private release(): void {
1341
1261
  if (this.once) {
1342
1262
  this.close()
1343
1263
  } else {
@@ -1345,7 +1265,7 @@ export class FetchSyncClient {
1345
1265
  }
1346
1266
  }
1347
1267
 
1348
- /** `readAll`'s refusal: the body passed the caller's limit. */
1268
+ /** `readAll`'s refusal: the body passed the caller's limit. @internal */
1349
1269
  refuseBody(limit: i32): void {
1350
1270
  this.release()
1351
1271
  this.fail(HTTP_E_BODY_TOO_LARGE, `the body is larger than the ${limit} bytes asked for`)
@@ -1356,7 +1276,7 @@ export class FetchSyncClient {
1356
1276
  * Fails with `HTTP_E_TOTAL_TIMEOUT` once the fetch's deadline has passed:
1357
1277
  * a server that always has the next byte ready never lets a wait see it.
1358
1278
  */
1359
- overdue(): boolean {
1279
+ private overdue(): boolean {
1360
1280
  if (this.deadline < HTTP_CLIENT_NEVER && monotonicNanos() >= this.deadline) {
1361
1281
  this.failWait(HTTP_E_TOTAL_TIMEOUT, "")
1362
1282
  return true
@@ -1365,24 +1285,18 @@ export class FetchSyncClient {
1365
1285
  }
1366
1286
 
1367
1287
  /** Sets the error for a wait that ended with `code`, `text` saying what timed out. */
1368
- failWait(code: i32, text: string): void {
1369
- if (code === HTTP_E_TOTAL_TIMEOUT) {
1370
- this.fail(code, `the fetch ran past ${httpClientTotalMs(this.options)} ms`)
1371
- } else if (code === HTTP_E_IO) {
1372
- this.fail(code, "the poll loop failed")
1373
- } else {
1374
- this.fail(code, text)
1375
- }
1288
+ private failWait(code: i32, text: string): void {
1289
+ this.fail(code, httpClientWaitText(code, this.options, text))
1376
1290
  }
1377
1291
 
1378
1292
  /** Refuses a redirect: closes the connection, whose response is left unread, and fails. */
1379
- refuse(code: i32, text: string): HttpResponse | null {
1293
+ private refuse(code: i32, text: string): HttpResponse | null {
1380
1294
  this.drop()
1381
1295
  this.fail(code, text)
1382
1296
  return null
1383
1297
  }
1384
1298
 
1385
- fail(code: i32, text: string): void {
1299
+ private fail(code: i32, text: string): void {
1386
1300
  this.error = code
1387
1301
  this.errorText = `${httpErrorName(code)}: ${text}`
1388
1302
  }
@@ -1392,6 +1306,10 @@ export class FetchSyncClient {
1392
1306
  * One fetch on a client of its own, closed once the body has been read or
1393
1307
  * the fetch failed. Null on a failure, with no way to say why: a program
1394
1308
  * that reports its errors fetches through a `FetchSyncClient`.
1309
+ *
1310
+ * @param req The request to send, as a `FetchSyncClient` takes it.
1311
+ * @param options The client's limits, timeouts, TLS trust and proxies for this one fetch.
1312
+ * @returns The response, the last one when redirects were followed, or null on any failure.
1395
1313
  */
1396
1314
  export const fetchSync = (req: HttpRequest, options: HttpOptions): HttpResponse | null => {
1397
1315
  const client: FetchSyncClient = new FetchSyncClient(options)
@@ -1406,6 +1324,11 @@ export const fetchSync = (req: HttpRequest, options: HttpOptions): HttpResponse
1406
1324
  /**
1407
1325
  * A proxy variable's value: `lower` when it is set and not empty, else
1408
1326
  * `upper` when `upperAllowed`, else "". `HTTP_PROXY` is not allowed under CGI.
1327
+ *
1328
+ * @param lower The lower-case variable's value, such as `http_proxy`'s, or null when it is unset.
1329
+ * @param upper The upper-case variable's value, such as `HTTP_PROXY`'s, or null when it is unset.
1330
+ * @param upperAllowed Whether the upper-case variable may be read: false for `HTTP_PROXY` under CGI, where a request's `Proxy` header sets it.
1331
+ * @returns The chosen variable's value, a proxy URL or for `no_proxy` a comma-separated host list, or "" when neither applies.
1409
1332
  */
1410
1333
  export const httpChooseProxy = (
1411
1334
  lower: string | null,
@@ -1425,6 +1348,14 @@ export const httpChooseProxy = (
1425
1348
  * The proxy a request to `scheme://host:port` goes through, given the three
1426
1349
  * settings: `httpsProxy` for https, `httpProxy` for http, and "" for none or
1427
1350
  * when `noProxy` names the host.
1351
+ *
1352
+ * @param scheme The request URL's scheme, lower-cased; one other than `http` or `https` gets no proxy.
1353
+ * @param host The request URL's host, matched against `noProxy`.
1354
+ * @param port The port the request goes to, matched against an entry's `:port`.
1355
+ * @param httpProxy The proxy URL for `http` requests, or "" for none.
1356
+ * @param httpsProxy The proxy URL for `https` requests, or "" for none.
1357
+ * @param noProxy The comma-separated hosts that go direct, as `httpNoProxyMatch` reads them.
1358
+ * @returns The proxy URL the request goes through, or "" when it goes direct.
1428
1359
  */
1429
1360
  export const httpProxyFor = (
1430
1361
  scheme: string,
@@ -1452,6 +1383,11 @@ export const httpProxyFor = (
1452
1383
  * (with or without a leading dot), or an IP address that matches only itself;
1453
1384
  * any of them may end in `:port`, and an IPv6 address with a port is written
1454
1385
  * in brackets. Case does not matter. Address ranges are not understood.
1386
+ *
1387
+ * @param noProxy The list, as `NO_PROXY` holds it; an entry that does not parse is skipped.
1388
+ * @param host The request's host name or IP address; trailing dots do not matter.
1389
+ * @param port The port the request goes to.
1390
+ * @returns True when an entry names the host (and its port, if it has one), so the request goes direct.
1455
1391
  */
1456
1392
  export const httpNoProxyMatch = (noProxy: string, host: string, port: i32): boolean => {
1457
1393
  const name: string = httpClientTrimDots(httpClientLower(host))
@@ -1724,3 +1660,1044 @@ const httpClientProxyAuth = (proxy: Url): string | null => {
1724
1660
  }
1725
1661
  return "Basic " + base64Encode(httpFieldBytes(user + ":" + password))
1726
1662
  }
1663
+
1664
+ /** The first value of the field `name`, in any case, from parallel name and value lists; null when there is none. */
1665
+ const httpClientField = (names: string[], values: string[], name: string): string | null => {
1666
+ const lower: string = httpClientLower(name)
1667
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
1668
+ if (names[i] === lower) {
1669
+ return values[i]
1670
+ }
1671
+ }
1672
+ return null
1673
+ }
1674
+
1675
+ /**
1676
+ * The proxy settings the environment gives, as [http, https, no-proxy]; ""
1677
+ * for each when `useEnvProxy` is off. A CGI program (`REQUEST_METHOD` set)
1678
+ * ignores `HTTP_PROXY`, which a request's `Proxy:` header could have set.
1679
+ */
1680
+ const httpClientEnvProxies = (options: HttpOptions): string[] => {
1681
+ if (!options.useEnvProxy) {
1682
+ return ["", "", ""]
1683
+ }
1684
+ const cgi: boolean = getenv("REQUEST_METHOD") !== null
1685
+ return [
1686
+ httpChooseProxy(getenv("http_proxy"), getenv("HTTP_PROXY"), !cgi),
1687
+ httpChooseProxy(getenv("https_proxy"), getenv("HTTPS_PROXY"), true),
1688
+ httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true),
1689
+ ]
1690
+ }
1691
+
1692
+ /** When a fetch starting now must be done by, on the monotonic clock; `HTTP_CLIENT_NEVER` with no total timeout. */
1693
+ const httpClientDeadline = (options: HttpOptions): i64 => {
1694
+ const total: i32 = httpClientTotalMs(options)
1695
+ return total > 0 ? monotonicNanos() + toI64(total) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
1696
+ }
1697
+
1698
+ /** A failure a shared step found: an `HTTP_E_*` code and its sentence, before the code's name is put in front. */
1699
+ class HttpClientFault {
1700
+ code: i32 = 0
1701
+ text: string = ""
1702
+
1703
+ fail(code: i32, text: string): void {
1704
+ this.code = code
1705
+ this.text = text
1706
+ }
1707
+ }
1708
+
1709
+ /** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
1710
+ const httpClientHostRefusal = (options: HttpOptions, url: Url): string => {
1711
+ const policy: OutboundPolicy | null = options.outbound
1712
+ if (policy === null || outboundHostAllowed(policy, url.host)) {
1713
+ return ""
1714
+ }
1715
+ return `${httpClientRedact(url)} names a host the outbound policy does not allow`
1716
+ }
1717
+
1718
+ /** The request's URL, parsed and checked against the scheme and the policy; null with `fault` set. */
1719
+ const httpClientTarget = (text: string, options: HttpOptions, fault: HttpClientFault): Url | null => {
1720
+ const url: Url | null = urlParse(text)
1721
+ if (url === null || (url.scheme !== "http" && url.scheme !== "https")) {
1722
+ fault.fail(HTTP_E_URL, `not an absolute http or https URL: ${httpClientRedact(url)}`)
1723
+ return null
1724
+ }
1725
+ const refusal: string = httpClientHostRefusal(options, url)
1726
+ if (refusal !== "") {
1727
+ fault.fail(HTTP_E_BLOCKED, refusal)
1728
+ return null
1729
+ }
1730
+ return url
1731
+ }
1732
+
1733
+ /** What the next hop of a fetch sends: the method, body and fields a redirect may rewrite, and the hops taken. */
1734
+ class HttpClientHop {
1735
+ method: string
1736
+ body: u8[] | null
1737
+ names: string[]
1738
+ values: string[]
1739
+ hops: i32 = 0
1740
+
1741
+ constructor(method: string, body: u8[] | null, names: string[], values: string[]) {
1742
+ this.method = method
1743
+ this.body = body
1744
+ this.names = []
1745
+ this.values = []
1746
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
1747
+ // Read before any call, which is where the bounds proof forgets a length.
1748
+ const name: string = names[i]
1749
+ const value: string = values[i]
1750
+ this.names.push(name)
1751
+ this.values.push(value)
1752
+ }
1753
+ }
1754
+ }
1755
+
1756
+ /**
1757
+ * Where a redirect from `url` to `location` goes, with `hop` rewritten for
1758
+ * it: credentials dropped across origins, a 303 (or a 301/302 after POST)
1759
+ * turned into GET. Null with `fault` set when the redirect is refused.
1760
+ */
1761
+ const httpClientRedirect = (
1762
+ hop: HttpClientHop,
1763
+ options: HttpOptions,
1764
+ url: Url,
1765
+ status: i32,
1766
+ location: string,
1767
+ fault: HttpClientFault
1768
+ ): Url | null => {
1769
+ const next: Url | null = urlResolve(url, location)
1770
+ const maxRedirects: i32 = httpClientMaxRedirects(options)
1771
+ if (hop.hops >= maxRedirects) {
1772
+ fault.fail(
1773
+ HTTP_E_TOO_MANY_REDIRECTS,
1774
+ `more than ${maxRedirects} redirects, the last to ${httpClientRedact(next)}`
1775
+ )
1776
+ return null
1777
+ }
1778
+ if (next === null || (next.scheme !== "http" && next.scheme !== "https")) {
1779
+ fault.fail(
1780
+ HTTP_E_REDIRECT_REFUSED,
1781
+ `a redirect to ${httpClientRedact(next)}, which is not an http or https URL`
1782
+ )
1783
+ return null
1784
+ }
1785
+ if (url.scheme === "https" && next.scheme === "http") {
1786
+ fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect from https to http (${httpClientRedact(next)})`)
1787
+ return null
1788
+ }
1789
+ const refusal: string = httpClientHostRefusal(options, next)
1790
+ if (refusal !== "") {
1791
+ fault.fail(HTTP_E_BLOCKED, refusal)
1792
+ return null
1793
+ }
1794
+ const from: string | null = urlOrigin(url)
1795
+ const to: string | null = urlOrigin(next)
1796
+ if (from === null || to === null || from !== to) {
1797
+ if (!options.crossOriginRedirects) {
1798
+ fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect to another origin (${httpClientRedact(next)})`)
1799
+ return null
1800
+ }
1801
+ // Credentials were meant for the first origin, not for wherever it points.
1802
+ httpClientDropField(hop.names, hop.values, "authorization")
1803
+ httpClientDropField(hop.names, hop.values, "proxy-authorization")
1804
+ httpClientDropField(hop.names, hop.values, "cookie")
1805
+ httpClientDropField(hop.names, hop.values, "host")
1806
+ }
1807
+ if (
1808
+ (status === 303 && hop.method !== "HEAD") ||
1809
+ ((status === 301 || status === 302) && hop.method === "POST")
1810
+ ) {
1811
+ hop.method = "GET"
1812
+ hop.body = null
1813
+ httpClientDropField(hop.names, hop.values, "content-type")
1814
+ }
1815
+ hop.hops += 1
1816
+ return next
1817
+ }
1818
+
1819
+ /** Where a connection for one URL goes: the address to dial, the proxy if any, and the route a kept connection must match. */
1820
+ class HttpClientRoute {
1821
+ proxy: Url | null = null
1822
+ dialHost: string = ""
1823
+ route: string = ""
1824
+ port: i32 = 0
1825
+ dialPort: i32 = 0
1826
+ }
1827
+
1828
+ /**
1829
+ * The route to `url` under the proxy settings: none under an outbound
1830
+ * policy, since a proxy would look the name up past the policy's address
1831
+ * check. Null with `fault` set when the proxy setting is malformed.
1832
+ */
1833
+ const httpClientRoute = (
1834
+ url: Url,
1835
+ options: HttpOptions,
1836
+ httpProxy: string,
1837
+ httpsProxy: string,
1838
+ noProxy: string,
1839
+ fault: HttpClientFault
1840
+ ): HttpClientRoute | null => {
1841
+ const way: HttpClientRoute = new HttpClientRoute()
1842
+ const port: i32 = url.port >= 0 ? url.port : urlDefaultPort(url.scheme)
1843
+ way.port = port
1844
+ const proxyText: string =
1845
+ options.outbound !== null ? "" : httpProxyFor(url.scheme, url.host, port, httpProxy, httpsProxy, noProxy)
1846
+ let proxy: Url | null = null
1847
+ if (proxyText !== "") {
1848
+ proxy = httpClientProxyUrl(proxyText)
1849
+ if (proxy === null) {
1850
+ fault.fail(
1851
+ HTTP_E_PROXY,
1852
+ `the proxy setting is not an http:// URL with a host: ${httpClientRedact(
1853
+ urlParse(proxyText.indexOf("://") >= 0 ? proxyText : "http://" + proxyText)
1854
+ )}`
1855
+ )
1856
+ return null
1857
+ }
1858
+ }
1859
+ const origin: string = `${url.scheme}://${httpClientHostText(url.host)}:${port}`
1860
+ way.route = origin
1861
+ way.dialHost = url.host
1862
+ way.dialPort = port
1863
+ if (proxy !== null) {
1864
+ way.proxy = proxy
1865
+ way.dialHost = proxy.host
1866
+ way.dialPort = proxy.port
1867
+ way.route =
1868
+ url.scheme === "http"
1869
+ ? `proxy ${httpClientHostText(proxy.host)}:${proxy.port}`
1870
+ : `${origin} via ${httpClientHostText(proxy.host)}:${proxy.port}`
1871
+ }
1872
+ return way
1873
+ }
1874
+
1875
+ /**
1876
+ * The bytes of a request's head: `Host` added when the fields lack it, the
1877
+ * absolute-form target and the proxy's credentials when `httpProxy` is the
1878
+ * http proxy the request goes through ("" for none), and a
1879
+ * `Proxy-Authorization` field dropped when it is not. Null with `fault` set.
1880
+ */
1881
+ const httpClientRequestHead = (
1882
+ url: Url,
1883
+ method: string,
1884
+ names: string[],
1885
+ values: string[],
1886
+ body: u8[] | null,
1887
+ httpProxy: string,
1888
+ fault: HttpClientFault
1889
+ ): u8[] | null => {
1890
+ const viaProxy: boolean = httpProxy !== ""
1891
+ const sendNames: string[] = []
1892
+ const sendValues: string[] = []
1893
+ let hasHost: boolean = false
1894
+ let hasProxyAuth: boolean = false
1895
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
1896
+ // Read before any call, which is where the bounds proof forgets a length.
1897
+ const name: string = names[i]
1898
+ const value: string = values[i]
1899
+ hasHost = hasHost || httpClientNameIs(name, "host")
1900
+ const proxyAuth: boolean = httpClientNameIs(name, "proxy-authorization")
1901
+ if (proxyAuth && !viaProxy) {
1902
+ // Only an http proxy reads it: sent direct or through a tunnel, it
1903
+ // would hand the proxy's credentials to the origin.
1904
+ continue
1905
+ }
1906
+ hasProxyAuth = hasProxyAuth || proxyAuth
1907
+ sendNames.push(name)
1908
+ sendValues.push(value)
1909
+ }
1910
+ const hostText: string = httpClientHostText(url.host)
1911
+ const authority: string = url.port >= 0 ? `${hostText}:${url.port}` : hostText
1912
+ if (!hasHost) {
1913
+ sendNames.push("Host")
1914
+ sendValues.push(authority)
1915
+ }
1916
+ let target: string = url.path === "" ? "/" : url.path
1917
+ const query: string | null = url.query
1918
+ if (query !== null) {
1919
+ target = target + "?" + query
1920
+ }
1921
+ if (viaProxy) {
1922
+ target = `${url.scheme}://${authority}${target}`
1923
+ const proxy: Url | null = httpClientProxyUrl(httpProxy)
1924
+ const auth: string | null = proxy !== null ? httpClientProxyAuth(proxy) : ""
1925
+ if (auth === null) {
1926
+ fault.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
1927
+ return null
1928
+ }
1929
+ if (auth !== "" && !hasProxyAuth) {
1930
+ sendNames.push("Proxy-Authorization")
1931
+ sendValues.push(auth)
1932
+ }
1933
+ }
1934
+ const bodyLength: i64 = body !== null ? toI64(body.length) : toI64(-2)
1935
+ const head: u8[] | null = http1RequestHead(method, target, sendNames, sendValues, bodyLength)
1936
+ if (head === null) {
1937
+ fault.fail(
1938
+ HTTP_E_REQUEST,
1939
+ `the request ${method} ${httpClientRedact(url)} was refused: a bad method, target or header field`
1940
+ )
1941
+ }
1942
+ return head
1943
+ }
1944
+
1945
+ /**
1946
+ * The failure behind a parser's `HTTP1_ERROR` or `HTTP1_CLOSED` `event`, in
1947
+ * `fault`: true when the connection was lost (closed before or part way
1948
+ * through the response), which is what lets a kept connection be retried.
1949
+ */
1950
+ const httpClientParserFault = (
1951
+ parser: Http1ResponseParser,
1952
+ event: i32,
1953
+ options: HttpOptions,
1954
+ fault: HttpClientFault
1955
+ ): boolean => {
1956
+ if (event === HTTP1_CLOSED) {
1957
+ fault.fail(HTTP_E_IO, "the server closed the connection before it answered")
1958
+ return true
1959
+ }
1960
+ const code: i32 = parser.error
1961
+ if (code === HTTP1_E_BODY_LIMIT) {
1962
+ fault.fail(HTTP_E_BODY_TOO_LARGE, `the body is larger than maxBodyBytes (${httpClientBodyCap(options)})`)
1963
+ return false
1964
+ }
1965
+ fault.fail(HTTP_E_PROTOCOL, `the response broke HTTP/1.1: ${parser.errorText} (http1 error ${code})`)
1966
+ // A response the server closed part way through is a connection lost, as
1967
+ // one closed before any byte is; it is never sent again, because a byte of
1968
+ // it came.
1969
+ return code === HTTP1_E_TRUNCATED
1970
+ }
1971
+
1972
+ /** The sentence for a failed wait: the total timeout and a broken poll loop have fixed ones, anything else `text`. */
1973
+ const httpClientWaitText = (code: i32, options: HttpOptions, text: string): string => {
1974
+ if (code === HTTP_E_TOTAL_TIMEOUT) {
1975
+ return `the fetch ran past ${httpClientTotalMs(options)} ms`
1976
+ }
1977
+ if (code === HTTP_E_IO) {
1978
+ return "the poll loop failed"
1979
+ }
1980
+ return text
1981
+ }
1982
+
1983
+ /**
1984
+ * Looks `host` up within `start`..`until` into `addresses` and keeps those
1985
+ * the outbound policy allows: how many to try, or -1 with `fault` set (`code`
1986
+ * names the deadline a lookup that timed out ran past). The lookup blocks.
1987
+ */
1988
+ const httpClientResolve = (
1989
+ host: string,
1990
+ port: i32,
1991
+ options: HttpOptions,
1992
+ start: i64,
1993
+ until: i64,
1994
+ code: i32,
1995
+ addresses: u8[],
1996
+ fault: HttpClientFault
1997
+ ): i32 => {
1998
+ let lookupMs: i64 = (until - start) / HTTP_CLIENT_NS_PER_MS
1999
+ if (lookupMs < toI64(1)) {
2000
+ lookupMs = toI64(1)
2001
+ } else if (lookupMs > toI64(2147483647)) {
2002
+ lookupMs = toI64(2147483647)
2003
+ }
2004
+ const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
2005
+ const count: i32 = resolveHost(host, toI32(lookupMs), port, addresses, ttls)
2006
+ if (count === DNS_RESOLVE_TIMEOUT && until < HTTP_CLIENT_NEVER) {
2007
+ fault.fail(
2008
+ code,
2009
+ httpClientWaitText(code, options, `${host} was not looked up within ${options.connectTimeoutMs} ms`)
2010
+ )
2011
+ return -1
2012
+ }
2013
+ if (count <= 0) {
2014
+ fault.fail(
2015
+ HTTP_E_DNS,
2016
+ `${host} could not be looked up (${count === 0 ? "no address" : `resolver code ${count}`})`
2017
+ )
2018
+ return -1
2019
+ }
2020
+ let usable: i32 = count < DNS_RESOLVE_MAX_ADDRESSES ? count : DNS_RESOLVE_MAX_ADDRESSES
2021
+ const policy: OutboundPolicy | null = options.outbound
2022
+ if (policy !== null) {
2023
+ // Only the bytes checked here are connected to: no second lookup a rebinding answer could change.
2024
+ usable = outboundFilter(policy, addresses, usable)
2025
+ if (usable === 0) {
2026
+ fault.fail(
2027
+ HTTP_E_BLOCKED,
2028
+ `${host} resolves to ${outboundAddressText(addresses, 0)}, which the outbound policy does not allow`
2029
+ )
2030
+ return -1
2031
+ }
2032
+ }
2033
+ return usable
2034
+ }
2035
+
2036
+ // ---- The async fetch ---------------------------------------------------------
2037
+
2038
+ /** How many idle connections a `FetchPool` holds at most, over every route. */
2039
+ const FETCH_POOL_SLOTS: i32 = 64
2040
+
2041
+ /**
2042
+ * Why an async `fetch` failed: an `HTTP_E_*` code and its sentence, the
2043
+ * code's name first, as `FetchSyncClient.errorText` reads. The text never
2044
+ * holds a URL's credentials or query.
2045
+ */
2046
+ export class FetchError {
2047
+ /** The `HTTP_E_*` code. */
2048
+ code: i32
2049
+ /** The code's name, a colon and what went wrong, such as `dns: example.invalid could not be looked up`. */
2050
+ text: string
2051
+
2052
+ /**
2053
+ * A failure with its code and text.
2054
+ * @param code The `HTTP_E_*` code.
2055
+ * @param text The code's name, a colon and the sentence.
2056
+ */
2057
+ constructor(code: i32, text: string) {
2058
+ this.code = code
2059
+ this.text = text
2060
+ }
2061
+ }
2062
+
2063
+ /**
2064
+ * A response `fetch` answered, its body already read whole: the body is
2065
+ * read before `fetch` answers, up to `maxBodyBytes`, so `text()` and
2066
+ * `bytes()` are plain calls. `names` are lower-cased and in the order they
2067
+ * arrived, beside `values`; `url` is the URL that answered.
2068
+ */
2069
+ export class FetchResponse {
2070
+ /** The status code, such as 200. */
2071
+ status: i32 = 0
2072
+ /** The reason phrase the server sent beside the status. */
2073
+ reason: string = ""
2074
+ /** The URL that answered, which differs from the request's after a redirect. */
2075
+ url: string = ""
2076
+ /** The header field names, lower-cased, in the order they arrived. */
2077
+ names: string[]
2078
+ /** The header field values, each beside its name in `names`. */
2079
+ values: string[]
2080
+ /** The body, de-chunked; empty for a `HEAD` or a status that has none. */
2081
+ body: u8[]
2082
+
2083
+ /** A response with no status, fields or body yet; `fetch` fills them in. */
2084
+ constructor() {
2085
+ this.names = []
2086
+ this.values = []
2087
+ this.body = []
2088
+ }
2089
+
2090
+ /**
2091
+ * The first value of the field `name`, in any case.
2092
+ * @param name The field name to look for.
2093
+ * @returns The value, or null when the response has no such field.
2094
+ */
2095
+ header(name: string): string | null {
2096
+ return httpClientField(this.names, this.values, name)
2097
+ }
2098
+
2099
+ /**
2100
+ * The body as a string, its bytes unchanged: nothing checks that they are UTF-8.
2101
+ * @returns The body's text.
2102
+ */
2103
+ text(): string {
2104
+ return String.fromBytes(this.body, HTTP_CLIENT_ZERO, toI32(this.body.length))
2105
+ }
2106
+
2107
+ /**
2108
+ * The body's bytes.
2109
+ * @returns The body, the same array as `body`.
2110
+ */
2111
+ bytes(): u8[] {
2112
+ return this.body
2113
+ }
2114
+ }
2115
+
2116
+ /**
2117
+ * Connections an async `fetch` leaves open for the next one to the same
2118
+ * place, held by the caller and handed in through `RequestInit.pool`. At
2119
+ * most `maxIdlePerOrigin` wait per route and 64 in all; a kept connection
2120
+ * the server closed, or sent a byte on unasked, is closed when it is next
2121
+ * looked at. A fetch under an outbound policy never keeps or takes one.
2122
+ */
2123
+ export class FetchPool {
2124
+ /** The most idle connections kept for one route (origin, or proxy). */
2125
+ maxIdlePerOrigin: i32
2126
+ private fds: i32[]
2127
+ private routes: string[]
2128
+ private probe: u8[]
2129
+
2130
+ /**
2131
+ * An empty pool.
2132
+ * @param maxIdlePerOrigin The most idle connections kept for one route; 0 keeps none.
2133
+ */
2134
+ constructor(maxIdlePerOrigin: i32 = 4) {
2135
+ this.maxIdlePerOrigin = maxIdlePerOrigin
2136
+ this.fds = []
2137
+ this.routes = []
2138
+ this.probe = new Array<u8>(1)
2139
+ for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
2140
+ this.fds.push(toI32(-1))
2141
+ this.routes.push("")
2142
+ }
2143
+ }
2144
+
2145
+ /**
2146
+ * How many idle connections the pool holds.
2147
+ * @returns The count, over every route.
2148
+ */
2149
+ idle(): i32 {
2150
+ let count: i32 = 0
2151
+ for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
2152
+ if (this.fds[i] >= 0) {
2153
+ count += 1
2154
+ }
2155
+ }
2156
+ return count
2157
+ }
2158
+
2159
+ /** Closes every idle connection; the pool can still keep new ones. */
2160
+ close(): void {
2161
+ for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
2162
+ this.drop(i)
2163
+ }
2164
+ }
2165
+
2166
+ /**
2167
+ * A quiet idle connection for `route`, taken out of the pool; -1 for none.
2168
+ * A connection that reads anything, its end included, is closed instead.
2169
+ * @internal
2170
+ */
2171
+ take(route: string): i32 {
2172
+ for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
2173
+ if (this.fds[i] < 0 || this.routes[i] !== route) {
2174
+ continue
2175
+ }
2176
+ const fd: i32 = this.fds[i]
2177
+ if (netRead(fd, this.probe, HTTP_CLIENT_ZERO, 1) === HTTP_CLIENT_WOULD_BLOCK) {
2178
+ this.fds[i] = -1
2179
+ this.routes[i] = ""
2180
+ return fd
2181
+ }
2182
+ this.drop(i)
2183
+ }
2184
+ return -1
2185
+ }
2186
+
2187
+ /** Keeps `fd` for `route` when there is room, else closes it. @internal */
2188
+ put(route: string, fd: i32): void {
2189
+ let same: i32 = 0
2190
+ let free: i32 = -1
2191
+ for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
2192
+ if (this.fds[i] < 0) {
2193
+ free = free < 0 ? i : free
2194
+ } else if (this.routes[i] === route) {
2195
+ same += 1
2196
+ }
2197
+ }
2198
+ if (same >= this.maxIdlePerOrigin || free < 0) {
2199
+ netClose(fd)
2200
+ return
2201
+ }
2202
+ this.fds[free] = fd
2203
+ this.routes[free] = route
2204
+ }
2205
+
2206
+ private drop(i: i32): void {
2207
+ if (this.fds[i] >= 0) {
2208
+ netClose(this.fds[i])
2209
+ }
2210
+ this.fds[i] = -1
2211
+ this.routes[i] = ""
2212
+ }
2213
+ }
2214
+
2215
+ /**
2216
+ * What an async `fetch` sends and how it behaves. `options` are
2217
+ * `HttpOptions` as `fetchSync` reads them, except that `readTimeoutMs`
2218
+ * bounds no wait (a wait has no deadline yet), `connectTimeoutMs` bounds
2219
+ * only the name lookup, and `totalTimeoutMs` is checked each time a wait
2220
+ * ends. `pool` keeps connections for later fetches; null closes each one
2221
+ * when its fetch is done.
2222
+ */
2223
+ export class RequestInit {
2224
+ /** The request method, sent as given; `GET` by default. */
2225
+ method: string = "GET"
2226
+ /** The header field names, in the order they are sent. */
2227
+ names: string[]
2228
+ /** The header field values, each beside its name in `names`. */
2229
+ values: string[]
2230
+ /** Null for no body at all; an empty array sends `Content-Length: 0`. */
2231
+ body: u8[] | null = null
2232
+ /** The limits, policy and redirect and proxy settings (see above for the timeouts). */
2233
+ options: HttpOptions
2234
+ /** Where idle connections are kept between fetches; null for none. */
2235
+ pool: FetchPool | null = null
2236
+
2237
+ /** A `GET` with no fields, no body, default options and no pool. */
2238
+ constructor() {
2239
+ this.names = []
2240
+ this.values = []
2241
+ this.options = new HttpOptions()
2242
+ }
2243
+
2244
+ /**
2245
+ * Appends one header field; nothing is checked until the request is written.
2246
+ * @param name The field name.
2247
+ * @param value The field value; one holding a CR or LF makes the fetch fail.
2248
+ * @returns This init, so calls chain.
2249
+ */
2250
+ header(name: string, value: string): RequestInit {
2251
+ this.names.push(name)
2252
+ this.values.push(value)
2253
+ return this
2254
+ }
2255
+ }
2256
+
2257
+ /** One connection an async fetch drives, and the state of the exchange on it. */
2258
+ class HttpClientConn {
2259
+ deadline: i64
2260
+ options: HttpOptions
2261
+ parser: Http1ResponseParser
2262
+ rbuf: u8[]
2263
+ fault: HttpClientFault
2264
+ route: string = ""
2265
+ httpProxy: string
2266
+ httpsProxy: string
2267
+ noProxy: string
2268
+ fd: i32 = -1
2269
+ gotByte: boolean = false
2270
+ lost: boolean = false
2271
+ reused: boolean = false
2272
+
2273
+ constructor(options: HttpOptions) {
2274
+ this.options = options
2275
+ this.deadline = httpClientDeadline(options)
2276
+ this.parser = httpClientParser(options)
2277
+ this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
2278
+ this.fault = new HttpClientFault()
2279
+ const proxies: string[] = httpClientEnvProxies(options)
2280
+ this.httpProxy = proxies[0]
2281
+ this.httpsProxy = proxies[1]
2282
+ this.noProxy = proxies[2]
2283
+ }
2284
+
2285
+ /** Fails with `HTTP_E_TOTAL_TIMEOUT` once the fetch's deadline has passed. */
2286
+ overdue(): boolean {
2287
+ if (this.deadline < HTTP_CLIENT_NEVER && monotonicNanos() >= this.deadline) {
2288
+ this.fault.fail(HTTP_E_TOTAL_TIMEOUT, httpClientWaitText(HTTP_E_TOTAL_TIMEOUT, this.options, ""))
2289
+ return true
2290
+ }
2291
+ return false
2292
+ }
2293
+
2294
+ /** Closes the connection, if one is open. */
2295
+ close(): void {
2296
+ if (this.fd >= 0) {
2297
+ netClose(this.fd)
2298
+ this.fd = -1
2299
+ }
2300
+ }
2301
+
2302
+ /** Hands the connection back to `pool` when the response left it clean to reuse, else closes it. */
2303
+ release(pool: FetchPool | null): void {
2304
+ if (
2305
+ pool !== null &&
2306
+ this.fd >= 0 &&
2307
+ this.options.outbound === null &&
2308
+ this.parser.keepAlive() &&
2309
+ this.parser.buffered() === 0
2310
+ ) {
2311
+ pool.put(this.route, this.fd)
2312
+ this.fd = -1
2313
+ return
2314
+ }
2315
+ this.close()
2316
+ }
2317
+ }
2318
+
2319
+ /** One read of the response into the parser, parking the task until the socket has bytes; false with the fault set. */
2320
+ const httpClientFillAsync = async (conn: HttpClientConn): Promise<boolean> => {
2321
+ if (conn.overdue()) {
2322
+ return false
2323
+ }
2324
+ let n: i32 = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
2325
+ while (n === HTTP_CLIENT_WOULD_BLOCK) {
2326
+ const ready = await readable(conn.fd)
2327
+ if (!ready) {
2328
+ conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
2329
+ return false
2330
+ }
2331
+ if (conn.overdue()) {
2332
+ return false
2333
+ }
2334
+ n = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
2335
+ }
2336
+ if (n > 0) {
2337
+ conn.gotByte = true
2338
+ conn.parser.feed(conn.rbuf, HTTP_CLIENT_ZERO, n)
2339
+ return true
2340
+ }
2341
+ if (n === 0) {
2342
+ conn.parser.finish()
2343
+ return true
2344
+ }
2345
+ conn.lost = true
2346
+ conn.fault.fail(HTTP_E_IO, `reading from the server failed (errno ${-n})`)
2347
+ return false
2348
+ }
2349
+
2350
+ /** The parser's next event, reading as it needs; -1 with the fault set. */
2351
+ const httpClientPumpAsync = async (conn: HttpClientConn): Promise<i32> => {
2352
+ let event: i32 = conn.parser.next()
2353
+ while (event === HTTP1_NEED_MORE) {
2354
+ const filled = await httpClientFillAsync(conn)
2355
+ if (!filled) {
2356
+ return -1
2357
+ }
2358
+ event = conn.parser.next()
2359
+ }
2360
+ if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
2361
+ conn.lost = httpClientParserFault(conn.parser, event, conn.options, conn.fault)
2362
+ return -1
2363
+ }
2364
+ return event
2365
+ }
2366
+
2367
+ /** Writes `bytes`, parking the task while the socket is full; false with the fault set. */
2368
+ const httpClientWriteAsync = async (conn: HttpClientConn, bytes: u8[]): Promise<boolean> => {
2369
+ let at: i32 = 0
2370
+ const end: i32 = toI32(bytes.length)
2371
+ while (at < end) {
2372
+ if (conn.overdue()) {
2373
+ return false
2374
+ }
2375
+ const n: i32 = netWrite(conn.fd, bytes, at, end - at)
2376
+ if (n > 0) {
2377
+ at += n
2378
+ } else if (n === HTTP_CLIENT_WOULD_BLOCK || n === 0) {
2379
+ const ready = await writable(conn.fd)
2380
+ if (!ready) {
2381
+ conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
2382
+ return false
2383
+ }
2384
+ } else {
2385
+ conn.lost = true
2386
+ conn.fault.fail(HTTP_E_IO, `writing to the server failed (errno ${-n})`)
2387
+ return false
2388
+ }
2389
+ }
2390
+ return true
2391
+ }
2392
+
2393
+ /**
2394
+ * Looks `host` up (blocking, within `connectTimeoutMs`) and connects to its
2395
+ * addresses in turn, parking the task while each connect is in flight: the
2396
+ * connected fd, or -1 with the fault set.
2397
+ */
2398
+ const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32): Promise<i32> => {
2399
+ const start: i64 = monotonicNanos()
2400
+ const budget: i32 = conn.options.connectTimeoutMs
2401
+ let until: i64 = budget > 0 ? start + toI64(budget) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
2402
+ let code: i32 = HTTP_E_CONNECT_TIMEOUT
2403
+ if (conn.deadline < HTTP_CLIENT_NEVER && conn.deadline <= until) {
2404
+ until = conn.deadline
2405
+ code = HTTP_E_TOTAL_TIMEOUT
2406
+ }
2407
+ if (until <= start) {
2408
+ conn.fault.fail(code, httpClientWaitText(code, conn.options, `no time was left to connect to ${host}`))
2409
+ return -1
2410
+ }
2411
+ const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
2412
+ const usable: i32 = httpClientResolve(host, port, conn.options, start, until, code, addresses, conn.fault)
2413
+ if (usable < 0) {
2414
+ return -1
2415
+ }
2416
+ const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
2417
+ let last: i32 = 0
2418
+ for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
2419
+ copyBytes(one, 0, addresses, i * DNS_ADDRESS_BYTES, DNS_ADDRESS_BYTES)
2420
+ const fd: i32 = tcpConnect(one)
2421
+ if (fd < 0) {
2422
+ last = fd
2423
+ continue
2424
+ }
2425
+ const ready = await writable(fd)
2426
+ if (conn.overdue()) {
2427
+ netClose(fd)
2428
+ return -1
2429
+ }
2430
+ const result: i32 = ready ? connectResult(fd) : -5
2431
+ if (result === 0) {
2432
+ return fd
2433
+ }
2434
+ netClose(fd)
2435
+ last = result
2436
+ }
2437
+ conn.fault.fail(HTTP_E_REFUSED, `could not connect to ${host} port ${port} (errno ${-last})`)
2438
+ return -1
2439
+ }
2440
+
2441
+ /**
2442
+ * Makes `conn` a connection to where `url` goes: one the pool kept when
2443
+ * there is one, else a new one, through an http proxy when the settings say
2444
+ * so. False with the fault set; an https URL is refused before anything is
2445
+ * dialled, since its TLS handshake would block the process.
2446
+ */
2447
+ const httpClientOpenAsync = async (
2448
+ conn: HttpClientConn,
2449
+ url: Url,
2450
+ pool: FetchPool | null,
2451
+ fresh: boolean
2452
+ ): Promise<boolean> => {
2453
+ if (url.scheme === "https") {
2454
+ conn.fault.fail(
2455
+ HTTP_E_TLS,
2456
+ `${httpClientRedact(url)} is https, which the async fetch does not drive yet; use fetchSync`
2457
+ )
2458
+ return false
2459
+ }
2460
+ const way: HttpClientRoute | null = httpClientRoute(
2461
+ url,
2462
+ conn.options,
2463
+ conn.httpProxy,
2464
+ conn.httpsProxy,
2465
+ conn.noProxy,
2466
+ conn.fault
2467
+ )
2468
+ if (way === null) {
2469
+ return false
2470
+ }
2471
+ conn.route = way.route
2472
+ conn.parser = httpClientParser(conn.options)
2473
+ conn.reused = false
2474
+ if (pool !== null && !fresh && conn.options.outbound === null) {
2475
+ const kept: i32 = pool.take(way.route)
2476
+ if (kept >= 0) {
2477
+ conn.fd = kept
2478
+ conn.reused = true
2479
+ return true
2480
+ }
2481
+ }
2482
+ const fd: i32 = await httpClientDialAsync(conn, way.dialHost, way.dialPort)
2483
+ if (fd < 0) {
2484
+ return false
2485
+ }
2486
+ conn.fd = fd
2487
+ return true
2488
+ }
2489
+
2490
+ /** Writes the request on `conn` and reads up to its final response's head; false with the fault set. */
2491
+ const httpClientSendAsync = async (conn: HttpClientConn, url: Url, hop: HttpClientHop): Promise<boolean> => {
2492
+ const head: u8[] | null = httpClientRequestHead(
2493
+ url,
2494
+ hop.method,
2495
+ hop.names,
2496
+ hop.values,
2497
+ hop.body,
2498
+ conn.route.startsWith("proxy ") ? conn.httpProxy : "",
2499
+ conn.fault
2500
+ )
2501
+ if (head === null) {
2502
+ return false
2503
+ }
2504
+ conn.gotByte = false
2505
+ conn.lost = false
2506
+ conn.parser.expect(hop.method === "HEAD", false)
2507
+ const wrote = await httpClientWriteAsync(conn, head)
2508
+ if (!wrote) {
2509
+ return false
2510
+ }
2511
+ const body: u8[] | null = hop.body
2512
+ if (body !== null) {
2513
+ const sent = await httpClientWriteAsync(conn, body)
2514
+ if (!sent) {
2515
+ return false
2516
+ }
2517
+ }
2518
+ let event: i32 = await httpClientPumpAsync(conn)
2519
+ while (event === HTTP1_INFORMATIONAL) {
2520
+ event = await httpClientPumpAsync(conn)
2521
+ }
2522
+ if (event < 0) {
2523
+ return false
2524
+ }
2525
+ if (event !== HTTP1_HEAD) {
2526
+ conn.fault.fail(HTTP_E_PROTOCOL, `the response ended before its head (event ${event})`)
2527
+ return false
2528
+ }
2529
+ return true
2530
+ }
2531
+
2532
+ /**
2533
+ * Reads the body into `res`, at most `limit` bytes: 1 at its end, 0 when it
2534
+ * passed `limit` (the connection is then not reusable), -1 with the fault set.
2535
+ */
2536
+ const httpClientBodyAsync = async (conn: HttpClientConn, res: FetchResponse, limit: i64): Promise<i32> => {
2537
+ let buf: u8[] = new Array<u8>(0)
2538
+ let len: i32 = 0
2539
+ let event: i32 = await httpClientPumpAsync(conn)
2540
+ while (event !== HTTP1_END) {
2541
+ if (event < 0) {
2542
+ return -1
2543
+ }
2544
+ if (event === HTTP1_BODY) {
2545
+ const take: i32 = conn.parser.bodyLen
2546
+ const need: i64 = toI64(len) + toI64(take)
2547
+ if (need > limit) {
2548
+ return 0
2549
+ }
2550
+ if (need > HTTP_CLIENT_ASYNC_BODY_MAX) {
2551
+ // A raised maxBodyBytes cannot carry a body past one array's reach.
2552
+ conn.fault.fail(
2553
+ HTTP_E_BODY_TOO_LARGE,
2554
+ `the body is larger than one array holds (${HTTP_CLIENT_ASYNC_BODY_MAX} bytes)`
2555
+ )
2556
+ return -1
2557
+ }
2558
+ if (need > toI64(buf.length)) {
2559
+ let room: i64 = toI64(buf.length) * toI64(2)
2560
+ if (room < need) {
2561
+ room = need
2562
+ }
2563
+ if (room > HTTP_CLIENT_ASYNC_BODY_MAX) {
2564
+ room = HTTP_CLIENT_ASYNC_BODY_MAX
2565
+ }
2566
+ const grown: u8[] = new Array<u8>(toI32(room))
2567
+ copyBytes(grown, 0, buf, 0, len)
2568
+ buf = grown
2569
+ }
2570
+ copyBytes(buf, len, conn.parser.body, conn.parser.bodyOff, take)
2571
+ len += take
2572
+ }
2573
+ event = await httpClientPumpAsync(conn)
2574
+ }
2575
+ if (len === toI32(buf.length)) {
2576
+ res.body = buf
2577
+ } else {
2578
+ const exact: u8[] = new Array<u8>(len)
2579
+ copyBytes(exact, 0, buf, 0, len)
2580
+ res.body = exact
2581
+ }
2582
+ return 1
2583
+ }
2584
+
2585
+ /**
2586
+ * One request and its whole response on `conn`, once more on a fresh
2587
+ * connection when a kept one turns out to be gone before any byte of an
2588
+ * idempotent request's answer came. Null with the fault set.
2589
+ */
2590
+ const httpClientExchangeAsync = async (
2591
+ conn: HttpClientConn,
2592
+ url: Url,
2593
+ hop: HttpClientHop,
2594
+ pool: FetchPool | null,
2595
+ redirectable: boolean
2596
+ ): Promise<FetchResponse | null> => {
2597
+ for (let attempt: i32 = 0; attempt < 2; attempt += 1) {
2598
+ const opened = await httpClientOpenAsync(conn, url, pool, attempt > 0)
2599
+ if (!opened) {
2600
+ return null
2601
+ }
2602
+ const sent = await httpClientSendAsync(conn, url, hop)
2603
+ if (sent) {
2604
+ const res: FetchResponse = new FetchResponse()
2605
+ res.status = conn.parser.status
2606
+ res.reason = conn.parser.reason
2607
+ res.url = httpClientUrlText(url)
2608
+ for (
2609
+ let i: i32 = 0;
2610
+ i < toI32(conn.parser.names.length) && i < toI32(conn.parser.values.length);
2611
+ i += 1
2612
+ ) {
2613
+ res.names.push(conn.parser.names[i])
2614
+ res.values.push(conn.parser.values[i])
2615
+ }
2616
+ // A redirect's own body is read only far enough to keep its connection.
2617
+ const hopping: boolean =
2618
+ redirectable && httpClientIsRedirect(res.status) && res.header("location") !== null
2619
+ const limit: i64 = hopping ? toI64(HTTP_CLIENT_DRAIN_BYTES) : httpClientBodyCap(conn.options)
2620
+ const read: i32 = await httpClientBodyAsync(conn, res, limit)
2621
+ if (read < 0) {
2622
+ conn.close()
2623
+ if (!hopping) {
2624
+ return null
2625
+ }
2626
+ // As fetchSync's drain: a redirect's body that fails to read costs
2627
+ // only its connection, never the fetch.
2628
+ conn.fault.fail(HTTP_E_NONE, "")
2629
+ } else if (read === 0) {
2630
+ conn.close()
2631
+ } else {
2632
+ conn.release(pool)
2633
+ }
2634
+ return res
2635
+ }
2636
+ const retry: boolean = conn.reused && conn.lost && !conn.gotByte && httpClientIdempotent(hop.method)
2637
+ conn.close()
2638
+ if (!retry) {
2639
+ return null
2640
+ }
2641
+ }
2642
+ return null
2643
+ }
2644
+
2645
+ /** `fetch` before its answer is wrapped: the response, or null with `fault` set. */
2646
+ const httpClientFetchAsync = async (
2647
+ text: string,
2648
+ init: RequestInit,
2649
+ fault: HttpClientFault
2650
+ ): Promise<FetchResponse | null> => {
2651
+ const options: HttpOptions = init.options
2652
+ const conn: HttpClientConn = new HttpClientConn(options)
2653
+ conn.fault = fault
2654
+ let url: Url | null = httpClientTarget(text, options, fault)
2655
+ if (url === null) {
2656
+ return null
2657
+ }
2658
+ const hop: HttpClientHop = new HttpClientHop(init.method, init.body, init.names, init.values)
2659
+ while (url !== null) {
2660
+ const res: FetchResponse | null = await httpClientExchangeAsync(
2661
+ conn,
2662
+ url,
2663
+ hop,
2664
+ init.pool,
2665
+ options.followRedirects
2666
+ )
2667
+ if (res === null) {
2668
+ return null
2669
+ }
2670
+ const location: string | null = res.header("location")
2671
+ if (!options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
2672
+ return res
2673
+ }
2674
+ url = httpClientRedirect(hop, options, url, res.status, location, fault)
2675
+ }
2676
+ return null
2677
+ }
2678
+
2679
+ /**
2680
+ * Fetches `url` without blocking the process: the task waits on the
2681
+ * executor while the connection is made, the request written and the
2682
+ * response read, so other tasks run meanwhile and `awaitAll(fetch(a),
2683
+ * fetch(b))` overlaps the two. The body is read whole, up to
2684
+ * `maxBodyBytes`, before the answer comes. Only http is driven this way: an
2685
+ * https URL answers `HTTP_E_TLS` (use `fetchSync`). The name lookup still
2686
+ * blocks. Policy, proxy, redirect and error rules are `fetchSync`'s.
2687
+ *
2688
+ * @param url The absolute `http://` URL to fetch.
2689
+ * @param init The method, fields, body, options and pool; null for a plain `GET`.
2690
+ * @returns The response with its body, or the failure: never a panic.
2691
+ */
2692
+ export const fetch = async (
2693
+ url: string,
2694
+ init: RequestInit | null = null
2695
+ ): Promise<Result<FetchResponse, FetchError>> => {
2696
+ const req: RequestInit = init !== null ? init : new RequestInit()
2697
+ const fault: HttpClientFault = new HttpClientFault()
2698
+ const res: FetchResponse | null = await httpClientFetchAsync(url, req, fault)
2699
+ if (res === null) {
2700
+ return Err(new FetchError(fault.code, `${httpErrorName(fault.code)}: ${fault.text}`))
2701
+ }
2702
+ return Ok(res)
2703
+ }