dsh-model-proxy-switch 0.0.0-stage → 1.0.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -2
  3. package/client.js +473 -0
  4. package/cordis.patch.yml +7 -0
  5. package/icon.svg +13 -0
  6. package/index.js +341 -0
  7. package/locale/en.json +25 -0
  8. package/locale/zh.json +25 -0
  9. package/package.json +55 -4
  10. package/vendor/http-proxy.js +542 -0
  11. package/vendor/node_modules/undici/LICENSE +21 -0
  12. package/vendor/node_modules/undici/README.md +741 -0
  13. package/vendor/node_modules/undici/docs/docs/api/Agent.md +84 -0
  14. package/vendor/node_modules/undici/docs/docs/api/BalancedPool.md +99 -0
  15. package/vendor/node_modules/undici/docs/docs/api/CacheStorage.md +30 -0
  16. package/vendor/node_modules/undici/docs/docs/api/CacheStore.md +164 -0
  17. package/vendor/node_modules/undici/docs/docs/api/Client.md +290 -0
  18. package/vendor/node_modules/undici/docs/docs/api/ClientStats.md +27 -0
  19. package/vendor/node_modules/undici/docs/docs/api/Connector.md +115 -0
  20. package/vendor/node_modules/undici/docs/docs/api/ContentType.md +57 -0
  21. package/vendor/node_modules/undici/docs/docs/api/Cookies.md +128 -0
  22. package/vendor/node_modules/undici/docs/docs/api/Debug.md +62 -0
  23. package/vendor/node_modules/undici/docs/docs/api/DiagnosticsChannel.md +317 -0
  24. package/vendor/node_modules/undici/docs/docs/api/Dispatcher.md +1393 -0
  25. package/vendor/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md +159 -0
  26. package/vendor/node_modules/undici/docs/docs/api/Errors.md +49 -0
  27. package/vendor/node_modules/undici/docs/docs/api/EventSource.md +45 -0
  28. package/vendor/node_modules/undici/docs/docs/api/Fetch.md +60 -0
  29. package/vendor/node_modules/undici/docs/docs/api/GlobalInstallation.md +139 -0
  30. package/vendor/node_modules/undici/docs/docs/api/H2CClient.md +263 -0
  31. package/vendor/node_modules/undici/docs/docs/api/MockAgent.md +603 -0
  32. package/vendor/node_modules/undici/docs/docs/api/MockCallHistory.md +197 -0
  33. package/vendor/node_modules/undici/docs/docs/api/MockCallHistoryLog.md +43 -0
  34. package/vendor/node_modules/undici/docs/docs/api/MockClient.md +81 -0
  35. package/vendor/node_modules/undici/docs/docs/api/MockErrors.md +12 -0
  36. package/vendor/node_modules/undici/docs/docs/api/MockPool.md +555 -0
  37. package/vendor/node_modules/undici/docs/docs/api/Pool.md +84 -0
  38. package/vendor/node_modules/undici/docs/docs/api/PoolStats.md +35 -0
  39. package/vendor/node_modules/undici/docs/docs/api/ProxyAgent.md +229 -0
  40. package/vendor/node_modules/undici/docs/docs/api/RedirectHandler.md +93 -0
  41. package/vendor/node_modules/undici/docs/docs/api/RetryAgent.md +50 -0
  42. package/vendor/node_modules/undici/docs/docs/api/RetryHandler.md +118 -0
  43. package/vendor/node_modules/undici/docs/docs/api/RoundRobinPool.md +145 -0
  44. package/vendor/node_modules/undici/docs/docs/api/SnapshotAgent.md +616 -0
  45. package/vendor/node_modules/undici/docs/docs/api/Socks5ProxyAgent.md +275 -0
  46. package/vendor/node_modules/undici/docs/docs/api/Util.md +25 -0
  47. package/vendor/node_modules/undici/docs/docs/api/WebSocket.md +141 -0
  48. package/vendor/node_modules/undici/docs/docs/api/api-lifecycle.md +91 -0
  49. package/vendor/node_modules/undici/docs/docs/best-practices/client-certificate.md +64 -0
  50. package/vendor/node_modules/undici/docs/docs/best-practices/crawling.md +58 -0
  51. package/vendor/node_modules/undici/docs/docs/best-practices/mocking-request.md +190 -0
  52. package/vendor/node_modules/undici/docs/docs/best-practices/proxy.md +127 -0
  53. package/vendor/node_modules/undici/docs/docs/best-practices/undici-vs-builtin-fetch.md +224 -0
  54. package/vendor/node_modules/undici/docs/docs/best-practices/writing-tests.md +63 -0
  55. package/vendor/node_modules/undici/index-fetch.js +65 -0
  56. package/vendor/node_modules/undici/index.d.ts +3 -0
  57. package/vendor/node_modules/undici/index.js +234 -0
  58. package/vendor/node_modules/undici/lib/api/abort-signal.js +59 -0
  59. package/vendor/node_modules/undici/lib/api/api-connect.js +110 -0
  60. package/vendor/node_modules/undici/lib/api/api-pipeline.js +252 -0
  61. package/vendor/node_modules/undici/lib/api/api-request.js +214 -0
  62. package/vendor/node_modules/undici/lib/api/api-stream.js +209 -0
  63. package/vendor/node_modules/undici/lib/api/api-upgrade.js +111 -0
  64. package/vendor/node_modules/undici/lib/api/index.js +7 -0
  65. package/vendor/node_modules/undici/lib/api/readable.js +580 -0
  66. package/vendor/node_modules/undici/lib/cache/memory-cache-store.js +279 -0
  67. package/vendor/node_modules/undici/lib/cache/sqlite-cache-store.js +467 -0
  68. package/vendor/node_modules/undici/lib/core/connect.js +159 -0
  69. package/vendor/node_modules/undici/lib/core/constants.js +143 -0
  70. package/vendor/node_modules/undici/lib/core/diagnostics.js +227 -0
  71. package/vendor/node_modules/undici/lib/core/errors.js +477 -0
  72. package/vendor/node_modules/undici/lib/core/request.js +485 -0
  73. package/vendor/node_modules/undici/lib/core/socks5-client.js +422 -0
  74. package/vendor/node_modules/undici/lib/core/socks5-utils.js +212 -0
  75. package/vendor/node_modules/undici/lib/core/symbols.js +76 -0
  76. package/vendor/node_modules/undici/lib/core/tree.js +160 -0
  77. package/vendor/node_modules/undici/lib/core/util.js +992 -0
  78. package/vendor/node_modules/undici/lib/dispatcher/agent.js +162 -0
  79. package/vendor/node_modules/undici/lib/dispatcher/balanced-pool.js +221 -0
  80. package/vendor/node_modules/undici/lib/dispatcher/client-h1.js +1744 -0
  81. package/vendor/node_modules/undici/lib/dispatcher/client-h2.js +1056 -0
  82. package/vendor/node_modules/undici/lib/dispatcher/client.js +669 -0
  83. package/vendor/node_modules/undici/lib/dispatcher/dispatcher-base.js +196 -0
  84. package/vendor/node_modules/undici/lib/dispatcher/dispatcher.js +48 -0
  85. package/vendor/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js +146 -0
  86. package/vendor/node_modules/undici/lib/dispatcher/fixed-queue.js +135 -0
  87. package/vendor/node_modules/undici/lib/dispatcher/h2c-client.js +51 -0
  88. package/vendor/node_modules/undici/lib/dispatcher/pool-base.js +214 -0
  89. package/vendor/node_modules/undici/lib/dispatcher/pool.js +118 -0
  90. package/vendor/node_modules/undici/lib/dispatcher/proxy-agent.js +319 -0
  91. package/vendor/node_modules/undici/lib/dispatcher/retry-agent.js +35 -0
  92. package/vendor/node_modules/undici/lib/dispatcher/round-robin-pool.js +137 -0
  93. package/vendor/node_modules/undici/lib/dispatcher/socks5-proxy-agent.js +260 -0
  94. package/vendor/node_modules/undici/lib/encoding/index.js +33 -0
  95. package/vendor/node_modules/undici/lib/global.js +59 -0
  96. package/vendor/node_modules/undici/lib/handler/cache-handler.js +824 -0
  97. package/vendor/node_modules/undici/lib/handler/cache-revalidation-handler.js +124 -0
  98. package/vendor/node_modules/undici/lib/handler/decorator-handler.js +67 -0
  99. package/vendor/node_modules/undici/lib/handler/deduplication-handler.js +504 -0
  100. package/vendor/node_modules/undici/lib/handler/redirect-handler.js +245 -0
  101. package/vendor/node_modules/undici/lib/handler/retry-handler.js +504 -0
  102. package/vendor/node_modules/undici/lib/handler/unwrap-handler.js +106 -0
  103. package/vendor/node_modules/undici/lib/handler/wrap-handler.js +105 -0
  104. package/vendor/node_modules/undici/lib/interceptor/cache.js +621 -0
  105. package/vendor/node_modules/undici/lib/interceptor/decompress.js +561 -0
  106. package/vendor/node_modules/undici/lib/interceptor/deduplicate.js +117 -0
  107. package/vendor/node_modules/undici/lib/interceptor/dns.js +571 -0
  108. package/vendor/node_modules/undici/lib/interceptor/dump.js +99 -0
  109. package/vendor/node_modules/undici/lib/interceptor/redirect.js +21 -0
  110. package/vendor/node_modules/undici/lib/interceptor/response-error.js +95 -0
  111. package/vendor/node_modules/undici/lib/interceptor/retry.js +19 -0
  112. package/vendor/node_modules/undici/lib/llhttp/.gitkeep +0 -0
  113. package/vendor/node_modules/undici/lib/llhttp/constants.d.ts +195 -0
  114. package/vendor/node_modules/undici/lib/llhttp/constants.js +531 -0
  115. package/vendor/node_modules/undici/lib/llhttp/llhttp-wasm.js +15 -0
  116. package/vendor/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js +15 -0
  117. package/vendor/node_modules/undici/lib/llhttp/utils.d.ts +2 -0
  118. package/vendor/node_modules/undici/lib/llhttp/utils.js +12 -0
  119. package/vendor/node_modules/undici/lib/mock/mock-agent.js +232 -0
  120. package/vendor/node_modules/undici/lib/mock/mock-call-history.js +248 -0
  121. package/vendor/node_modules/undici/lib/mock/mock-client.js +68 -0
  122. package/vendor/node_modules/undici/lib/mock/mock-errors.js +29 -0
  123. package/vendor/node_modules/undici/lib/mock/mock-interceptor.js +209 -0
  124. package/vendor/node_modules/undici/lib/mock/mock-pool.js +68 -0
  125. package/vendor/node_modules/undici/lib/mock/mock-symbols.js +32 -0
  126. package/vendor/node_modules/undici/lib/mock/mock-utils.js +486 -0
  127. package/vendor/node_modules/undici/lib/mock/pending-interceptors-formatter.js +43 -0
  128. package/vendor/node_modules/undici/lib/mock/snapshot-agent.js +353 -0
  129. package/vendor/node_modules/undici/lib/mock/snapshot-recorder.js +588 -0
  130. package/vendor/node_modules/undici/lib/mock/snapshot-utils.js +158 -0
  131. package/vendor/node_modules/undici/lib/util/cache.js +676 -0
  132. package/vendor/node_modules/undici/lib/util/date.js +670 -0
  133. package/vendor/node_modules/undici/lib/util/promise.js +28 -0
  134. package/vendor/node_modules/undici/lib/util/runtime-features.js +124 -0
  135. package/vendor/node_modules/undici/lib/util/stats.js +32 -0
  136. package/vendor/node_modules/undici/lib/util/timers.js +425 -0
  137. package/vendor/node_modules/undici/lib/web/cache/cache.js +864 -0
  138. package/vendor/node_modules/undici/lib/web/cache/cachestorage.js +152 -0
  139. package/vendor/node_modules/undici/lib/web/cache/util.js +45 -0
  140. package/vendor/node_modules/undici/lib/web/cookies/constants.js +12 -0
  141. package/vendor/node_modules/undici/lib/web/cookies/index.js +201 -0
  142. package/vendor/node_modules/undici/lib/web/cookies/parse.js +315 -0
  143. package/vendor/node_modules/undici/lib/web/cookies/util.js +371 -0
  144. package/vendor/node_modules/undici/lib/web/eventsource/eventsource-stream.js +575 -0
  145. package/vendor/node_modules/undici/lib/web/eventsource/eventsource.js +504 -0
  146. package/vendor/node_modules/undici/lib/web/eventsource/util.js +29 -0
  147. package/vendor/node_modules/undici/lib/web/fetch/LICENSE +21 -0
  148. package/vendor/node_modules/undici/lib/web/fetch/body.js +509 -0
  149. package/vendor/node_modules/undici/lib/web/fetch/constants.js +131 -0
  150. package/vendor/node_modules/undici/lib/web/fetch/data-url.js +596 -0
  151. package/vendor/node_modules/undici/lib/web/fetch/formdata-parser.js +586 -0
  152. package/vendor/node_modules/undici/lib/web/fetch/formdata.js +259 -0
  153. package/vendor/node_modules/undici/lib/web/fetch/global.js +40 -0
  154. package/vendor/node_modules/undici/lib/web/fetch/headers.js +719 -0
  155. package/vendor/node_modules/undici/lib/web/fetch/index.js +2413 -0
  156. package/vendor/node_modules/undici/lib/web/fetch/request.js +1115 -0
  157. package/vendor/node_modules/undici/lib/web/fetch/response.js +641 -0
  158. package/vendor/node_modules/undici/lib/web/fetch/util.js +1522 -0
  159. package/vendor/node_modules/undici/lib/web/infra/index.js +243 -0
  160. package/vendor/node_modules/undici/lib/web/subresource-integrity/Readme.md +9 -0
  161. package/vendor/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js +307 -0
  162. package/vendor/node_modules/undici/lib/web/webidl/index.js +1006 -0
  163. package/vendor/node_modules/undici/lib/web/websocket/connection.js +339 -0
  164. package/vendor/node_modules/undici/lib/web/websocket/constants.js +126 -0
  165. package/vendor/node_modules/undici/lib/web/websocket/events.js +331 -0
  166. package/vendor/node_modules/undici/lib/web/websocket/frame.js +133 -0
  167. package/vendor/node_modules/undici/lib/web/websocket/permessage-deflate.js +105 -0
  168. package/vendor/node_modules/undici/lib/web/websocket/receiver.js +520 -0
  169. package/vendor/node_modules/undici/lib/web/websocket/sender.js +109 -0
  170. package/vendor/node_modules/undici/lib/web/websocket/stream/websocketerror.js +104 -0
  171. package/vendor/node_modules/undici/lib/web/websocket/stream/websocketstream.js +496 -0
  172. package/vendor/node_modules/undici/lib/web/websocket/util.js +347 -0
  173. package/vendor/node_modules/undici/lib/web/websocket/websocket.js +758 -0
  174. package/vendor/node_modules/undici/package.json +152 -0
  175. package/vendor/node_modules/undici/scripts/strip-comments.js +10 -0
  176. package/vendor/node_modules/undici/types/README.md +6 -0
  177. package/vendor/node_modules/undici/types/agent.d.ts +32 -0
  178. package/vendor/node_modules/undici/types/api.d.ts +43 -0
  179. package/vendor/node_modules/undici/types/balanced-pool.d.ts +30 -0
  180. package/vendor/node_modules/undici/types/cache-interceptor.d.ts +179 -0
  181. package/vendor/node_modules/undici/types/cache.d.ts +36 -0
  182. package/vendor/node_modules/undici/types/client-stats.d.ts +15 -0
  183. package/vendor/node_modules/undici/types/client.d.ts +153 -0
  184. package/vendor/node_modules/undici/types/connector.d.ts +36 -0
  185. package/vendor/node_modules/undici/types/content-type.d.ts +21 -0
  186. package/vendor/node_modules/undici/types/cookies.d.ts +30 -0
  187. package/vendor/node_modules/undici/types/diagnostics-channel.d.ts +74 -0
  188. package/vendor/node_modules/undici/types/dispatcher.d.ts +275 -0
  189. package/vendor/node_modules/undici/types/env-http-proxy-agent.d.ts +22 -0
  190. package/vendor/node_modules/undici/types/errors.d.ts +177 -0
  191. package/vendor/node_modules/undici/types/eventsource.d.ts +66 -0
  192. package/vendor/node_modules/undici/types/fetch.d.ts +231 -0
  193. package/vendor/node_modules/undici/types/formdata.d.ts +114 -0
  194. package/vendor/node_modules/undici/types/global-dispatcher.d.ts +9 -0
  195. package/vendor/node_modules/undici/types/global-origin.d.ts +7 -0
  196. package/vendor/node_modules/undici/types/h2c-client.d.ts +73 -0
  197. package/vendor/node_modules/undici/types/handlers.d.ts +14 -0
  198. package/vendor/node_modules/undici/types/header.d.ts +160 -0
  199. package/vendor/node_modules/undici/types/index.d.ts +91 -0
  200. package/vendor/node_modules/undici/types/interceptors.d.ts +82 -0
  201. package/vendor/node_modules/undici/types/mock-agent.d.ts +68 -0
  202. package/vendor/node_modules/undici/types/mock-call-history.d.ts +111 -0
  203. package/vendor/node_modules/undici/types/mock-client.d.ts +27 -0
  204. package/vendor/node_modules/undici/types/mock-errors.d.ts +12 -0
  205. package/vendor/node_modules/undici/types/mock-interceptor.d.ts +94 -0
  206. package/vendor/node_modules/undici/types/mock-pool.d.ts +27 -0
  207. package/vendor/node_modules/undici/types/patch.d.ts +29 -0
  208. package/vendor/node_modules/undici/types/pool-stats.d.ts +19 -0
  209. package/vendor/node_modules/undici/types/pool.d.ts +41 -0
  210. package/vendor/node_modules/undici/types/proxy-agent.d.ts +29 -0
  211. package/vendor/node_modules/undici/types/readable.d.ts +68 -0
  212. package/vendor/node_modules/undici/types/retry-agent.d.ts +8 -0
  213. package/vendor/node_modules/undici/types/retry-handler.d.ts +125 -0
  214. package/vendor/node_modules/undici/types/round-robin-pool.d.ts +41 -0
  215. package/vendor/node_modules/undici/types/snapshot-agent.d.ts +109 -0
  216. package/vendor/node_modules/undici/types/socks5-proxy-agent.d.ts +25 -0
  217. package/vendor/node_modules/undici/types/util.d.ts +18 -0
  218. package/vendor/node_modules/undici/types/utility.d.ts +7 -0
  219. package/vendor/node_modules/undici/types/webidl.d.ts +347 -0
  220. package/vendor/node_modules/undici/types/websocket.d.ts +188 -0
@@ -0,0 +1,1744 @@
1
+ 'use strict'
2
+
3
+ /* global WebAssembly */
4
+
5
+ const assert = require('node:assert')
6
+ const util = require('../core/util.js')
7
+ const { channels } = require('../core/diagnostics.js')
8
+ const timers = require('../util/timers.js')
9
+ const {
10
+ RequestContentLengthMismatchError,
11
+ ResponseContentLengthMismatchError,
12
+ RequestAbortedError,
13
+ InvalidArgumentError,
14
+ HeadersTimeoutError,
15
+ HeadersOverflowError,
16
+ SocketError,
17
+ InformationalError,
18
+ BodyTimeoutError,
19
+ HTTPParserError,
20
+ ResponseExceededMaxSizeError
21
+ } = require('../core/errors.js')
22
+ const {
23
+ kUrl,
24
+ kReset,
25
+ kClient,
26
+ kParser,
27
+ kBlocking,
28
+ kRunning,
29
+ kPending,
30
+ kSize,
31
+ kWriting,
32
+ kQueue,
33
+ kNoRef,
34
+ kKeepAliveDefaultTimeout,
35
+ kHostHeader,
36
+ kPendingIdx,
37
+ kRunningIdx,
38
+ kError,
39
+ kPipelining,
40
+ kSocket,
41
+ kKeepAliveTimeoutValue,
42
+ kMaxHeadersSize,
43
+ kKeepAliveMaxTimeout,
44
+ kKeepAliveTimeoutThreshold,
45
+ kHeadersTimeout,
46
+ kBodyTimeout,
47
+ kStrictContentLength,
48
+ kMaxRequests,
49
+ kCounter,
50
+ kMaxResponseSize,
51
+ kOnError,
52
+ kResume,
53
+ kHTTPContext,
54
+ kClosed
55
+ } = require('../core/symbols.js')
56
+
57
+ const constants = require('../llhttp/constants.js')
58
+ const EMPTY_BUF = Buffer.alloc(0)
59
+ const FastBuffer = Buffer[Symbol.species]
60
+ const removeAllListeners = util.removeAllListeners
61
+ const kIdleSocketValidation = Symbol('kIdleSocketValidation')
62
+ const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
63
+ const kSocketUsed = Symbol('kSocketUsed')
64
+
65
+ let extractBody
66
+
67
+ function lazyllhttp () {
68
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined
69
+
70
+ let mod
71
+
72
+ // We disable wasm SIMD on older versions of Node.js on ppc64 that are broken on Power >=9 architectures.
73
+ let useWasmSIMD = true
74
+ if (process.arch === 'ppc64') {
75
+ const [major, minor] = process.versions.node.split('.').map(n => parseInt(n, 10))
76
+ if (major < 24 || (major === 24 && minor < 12)) {
77
+ useWasmSIMD = false
78
+ }
79
+ }
80
+ // The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior
81
+ if (process.env.UNDICI_NO_WASM_SIMD === '1') {
82
+ useWasmSIMD = false
83
+ } else if (process.env.UNDICI_NO_WASM_SIMD === '0') {
84
+ useWasmSIMD = true
85
+ }
86
+
87
+ if (useWasmSIMD) {
88
+ try {
89
+ mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js'))
90
+ } catch {
91
+ }
92
+ }
93
+
94
+ if (!mod) {
95
+ // We could check if the error was caused by the simd option not
96
+ // being enabled, but the occurring of this other error
97
+ // * https://github.com/emscripten-core/emscripten/issues/11495
98
+ // got me to remove that check to avoid breaking Node 12.
99
+ mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js'))
100
+ }
101
+
102
+ return new WebAssembly.Instance(mod, {
103
+ env: {
104
+ /**
105
+ * @param {number} p
106
+ * @param {number} at
107
+ * @param {number} len
108
+ * @returns {number}
109
+ */
110
+ wasm_on_url: (p, at, len) => {
111
+ return 0
112
+ },
113
+ /**
114
+ * @param {number} p
115
+ * @param {number} at
116
+ * @param {number} len
117
+ * @returns {number}
118
+ */
119
+ wasm_on_status: (p, at, len) => {
120
+ assert(currentParser.ptr === p)
121
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
122
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len))
123
+ },
124
+ /**
125
+ * @param {number} p
126
+ * @returns {number}
127
+ */
128
+ wasm_on_message_begin: (p) => {
129
+ assert(currentParser.ptr === p)
130
+ return currentParser.onMessageBegin()
131
+ },
132
+ /**
133
+ * @param {number} p
134
+ * @param {number} at
135
+ * @param {number} len
136
+ * @returns {number}
137
+ */
138
+ wasm_on_header_field: (p, at, len) => {
139
+ assert(currentParser.ptr === p)
140
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
141
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len))
142
+ },
143
+ /**
144
+ * @param {number} p
145
+ * @param {number} at
146
+ * @param {number} len
147
+ * @returns {number}
148
+ */
149
+ wasm_on_header_value: (p, at, len) => {
150
+ assert(currentParser.ptr === p)
151
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
152
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len))
153
+ },
154
+ /**
155
+ * @param {number} p
156
+ * @param {number} statusCode
157
+ * @param {0|1} upgrade
158
+ * @param {0|1} shouldKeepAlive
159
+ * @returns {number}
160
+ */
161
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
162
+ assert(currentParser.ptr === p)
163
+ return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1)
164
+ },
165
+ /**
166
+ * @param {number} p
167
+ * @param {number} at
168
+ * @param {number} len
169
+ * @returns {number}
170
+ */
171
+ wasm_on_body: (p, at, len) => {
172
+ assert(currentParser.ptr === p)
173
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
174
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len))
175
+ },
176
+ /**
177
+ * @param {number} p
178
+ * @returns {number}
179
+ */
180
+ wasm_on_message_complete: (p) => {
181
+ assert(currentParser.ptr === p)
182
+ return currentParser.onMessageComplete()
183
+ }
184
+
185
+ }
186
+ })
187
+ }
188
+
189
+ let llhttpInstance = null
190
+
191
+ /**
192
+ * @type {Parser|null}
193
+ */
194
+ let currentParser = null
195
+ let currentBufferRef = null
196
+ /**
197
+ * @type {number}
198
+ */
199
+ let currentBufferSize = 0
200
+ let currentBufferPtr = null
201
+
202
+ const USE_NATIVE_TIMER = 0
203
+ const USE_FAST_TIMER = 1
204
+
205
+ // Use fast timers for headers and body to take eventual event loop
206
+ // latency into account.
207
+ const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
208
+ const TIMEOUT_BODY = 4 | USE_FAST_TIMER
209
+
210
+ // Use native timers to ignore event loop latency for keep-alive
211
+ // handling.
212
+ const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
213
+
214
+ class Parser {
215
+ /**
216
+ * @param {import('./client.js')} client
217
+ * @param {import('net').Socket} socket
218
+ * @param {*} llhttp
219
+ */
220
+ constructor (client, socket, { exports }) {
221
+ this.llhttp = exports
222
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
223
+ this.client = client
224
+ /**
225
+ * @type {import('net').Socket}
226
+ */
227
+ this.socket = socket
228
+ this.timeout = null
229
+ this.timeoutWeakRef = new WeakRef(this)
230
+ this.timeoutValue = null
231
+ this.timeoutType = null
232
+ this.statusCode = 0
233
+ this.statusText = ''
234
+ this.upgrade = false
235
+ this.headers = []
236
+ this.headersSize = 0
237
+ this.headersMaxSize = client[kMaxHeadersSize]
238
+ this.shouldKeepAlive = false
239
+ this.paused = false
240
+ this.resume = this.resume.bind(this)
241
+
242
+ this.bytesRead = 0
243
+
244
+ this.keepAlive = ''
245
+ this.contentLength = ''
246
+ this.connection = ''
247
+ this.maxResponseSize = client[kMaxResponseSize]
248
+ }
249
+
250
+ setTimeout (delay, type) {
251
+ // If the existing timer and the new timer are of different timer type
252
+ // (fast or native) or have different delay, we need to clear the existing
253
+ // timer and set a new one.
254
+ if (
255
+ delay !== this.timeoutValue ||
256
+ (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
257
+ ) {
258
+ // If a timeout is already set, clear it with clearTimeout of the fast
259
+ // timer implementation, as it can clear fast and native timers.
260
+ if (this.timeout) {
261
+ timers.clearTimeout(this.timeout)
262
+ this.timeout = null
263
+ }
264
+
265
+ if (delay) {
266
+ if (type & USE_FAST_TIMER) {
267
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef)
268
+ } else {
269
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef)
270
+ this.timeout?.unref()
271
+ }
272
+ }
273
+
274
+ this.timeoutValue = delay
275
+ } else if (this.timeout) {
276
+ if (this.timeout.refresh) {
277
+ this.timeout.refresh()
278
+ }
279
+ }
280
+
281
+ this.timeoutType = type
282
+ }
283
+
284
+ resume () {
285
+ if (this.socket.destroyed || !this.paused) {
286
+ return
287
+ }
288
+
289
+ assert(this.ptr != null)
290
+ assert(currentParser === null)
291
+
292
+ this.llhttp.llhttp_resume(this.ptr)
293
+
294
+ assert(this.timeoutType === TIMEOUT_BODY)
295
+ if (this.timeout) {
296
+ if (this.timeout.refresh) {
297
+ this.timeout.refresh()
298
+ }
299
+ }
300
+
301
+ this.paused = false
302
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
303
+ this.readMore()
304
+ }
305
+
306
+ readMore () {
307
+ while (!this.paused && this.ptr) {
308
+ const chunk = this.socket.read()
309
+ if (chunk === null) {
310
+ break
311
+ }
312
+ this.execute(chunk)
313
+ }
314
+ }
315
+
316
+ /**
317
+ * @param {Buffer} chunk
318
+ */
319
+ execute (chunk) {
320
+ assert(currentParser === null)
321
+ assert(this.ptr != null)
322
+ assert(!this.paused)
323
+
324
+ const { socket, llhttp } = this
325
+
326
+ // Allocate a new buffer if the current buffer is too small.
327
+ if (chunk.length > currentBufferSize) {
328
+ if (currentBufferPtr) {
329
+ llhttp.free(currentBufferPtr)
330
+ }
331
+ // Allocate a buffer that is a multiple of 4096 bytes.
332
+ currentBufferSize = Math.ceil(chunk.length / 4096) * 4096
333
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
334
+ }
335
+
336
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk)
337
+
338
+ // Call `execute` on the wasm parser.
339
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
340
+ // and finally the length of bytes to parse.
341
+ // The return value is an error code or `constants.ERROR.OK`.
342
+ try {
343
+ let ret
344
+
345
+ try {
346
+ currentBufferRef = chunk
347
+ currentParser = this
348
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length)
349
+ } finally {
350
+ currentParser = null
351
+ currentBufferRef = null
352
+ }
353
+
354
+ if (ret !== constants.ERROR.OK) {
355
+ const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr)
356
+
357
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
358
+ this.onUpgrade(data)
359
+ } else if (ret === constants.ERROR.PAUSED) {
360
+ this.paused = true
361
+ socket.unshift(data)
362
+ } else {
363
+ throw this.createError(ret, data)
364
+ }
365
+ }
366
+ } catch (err) {
367
+ util.destroy(socket, err)
368
+ }
369
+ }
370
+
371
+ finish () {
372
+ assert(currentParser === null)
373
+ assert(this.ptr != null)
374
+ assert(!this.paused)
375
+
376
+ const { llhttp } = this
377
+
378
+ let ret
379
+
380
+ try {
381
+ currentParser = this
382
+ ret = llhttp.llhttp_finish(this.ptr)
383
+ } finally {
384
+ currentParser = null
385
+ }
386
+
387
+ if (ret === constants.ERROR.OK) {
388
+ return null
389
+ }
390
+
391
+ if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
392
+ this.paused = true
393
+ return null
394
+ }
395
+
396
+ return this.createError(ret, EMPTY_BUF)
397
+ }
398
+
399
+ createError (ret, data) {
400
+ const { llhttp, contentLength, bytesRead } = this
401
+
402
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
403
+ return new ResponseContentLengthMismatchError()
404
+ }
405
+
406
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
407
+ let message = ''
408
+ if (ptr) {
409
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
410
+ message =
411
+ 'Response does not match the HTTP/1.1 protocol (' +
412
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
413
+ ')'
414
+ }
415
+
416
+ return new HTTPParserError(message, constants.ERROR[ret], data)
417
+ }
418
+
419
+ destroy () {
420
+ assert(currentParser === null)
421
+ assert(this.ptr != null)
422
+
423
+ this.llhttp.llhttp_free(this.ptr)
424
+ this.ptr = null
425
+
426
+ this.timeout && timers.clearTimeout(this.timeout)
427
+ this.timeout = null
428
+ this.timeoutValue = null
429
+ this.timeoutType = null
430
+
431
+ this.paused = false
432
+ }
433
+
434
+ /**
435
+ * @param {Buffer} buf
436
+ * @returns {0}
437
+ */
438
+ onStatus (buf) {
439
+ this.statusText = buf.toString()
440
+ return 0
441
+ }
442
+
443
+ /**
444
+ * @returns {0|-1}
445
+ */
446
+ onMessageBegin () {
447
+ const { socket, client } = this
448
+
449
+ if (socket.destroyed) {
450
+ return -1
451
+ }
452
+
453
+ if (client[kRunning] === 0) {
454
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
455
+ return -1
456
+ }
457
+
458
+ const request = client[kQueue][client[kRunningIdx]]
459
+ if (!request) {
460
+ return -1
461
+ }
462
+ request.onResponseStarted()
463
+
464
+ return 0
465
+ }
466
+
467
+ /**
468
+ * @param {Buffer} buf
469
+ * @returns {number}
470
+ */
471
+ onHeaderField (buf) {
472
+ const len = this.headers.length
473
+
474
+ if ((len & 1) === 0) {
475
+ this.headers.push(buf)
476
+ } else {
477
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
478
+ }
479
+
480
+ this.trackHeader(buf.length)
481
+
482
+ return 0
483
+ }
484
+
485
+ /**
486
+ * @param {Buffer} buf
487
+ * @returns {number}
488
+ */
489
+ onHeaderValue (buf) {
490
+ let len = this.headers.length
491
+
492
+ if ((len & 1) === 1) {
493
+ this.headers.push(buf)
494
+ len += 1
495
+ } else {
496
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
497
+ }
498
+
499
+ const key = this.headers[len - 2]
500
+ if (key.length === 10) {
501
+ const headerName = util.bufferToLowerCasedHeaderName(key)
502
+ if (headerName === 'keep-alive') {
503
+ this.keepAlive += buf.toString()
504
+ } else if (headerName === 'connection') {
505
+ this.connection += buf.toString()
506
+ }
507
+ } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
508
+ this.contentLength += buf.toString()
509
+ }
510
+
511
+ this.trackHeader(buf.length)
512
+
513
+ return 0
514
+ }
515
+
516
+ /**
517
+ * @param {number} len
518
+ */
519
+ trackHeader (len) {
520
+ this.headersSize += len
521
+ if (this.headersSize >= this.headersMaxSize) {
522
+ util.destroy(this.socket, new HeadersOverflowError())
523
+ }
524
+ }
525
+
526
+ /**
527
+ * @param {Buffer} head
528
+ */
529
+ onUpgrade (head) {
530
+ const { upgrade, client, socket, headers, statusCode, statusText } = this
531
+
532
+ assert(upgrade)
533
+ assert(client[kSocket] === socket)
534
+ assert(!socket.destroyed)
535
+ assert(!this.paused)
536
+ assert((headers.length & 1) === 0)
537
+
538
+ const request = client[kQueue][client[kRunningIdx]]
539
+ assert(request)
540
+ assert(request.upgrade || request.method === 'CONNECT')
541
+
542
+ this.statusCode = 0
543
+ this.statusText = ''
544
+ this.shouldKeepAlive = false
545
+
546
+ this.headers = []
547
+ this.headersSize = 0
548
+
549
+ socket.unshift(head)
550
+
551
+ socket[kParser].destroy()
552
+ socket[kParser] = null
553
+
554
+ socket[kClient] = null
555
+ socket[kError] = null
556
+
557
+ removeAllListeners(socket)
558
+
559
+ client[kSocket] = null
560
+ client[kHTTPContext] = null // TODO (fix): This is hacky...
561
+ client[kQueue][client[kRunningIdx]++] = null
562
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
563
+
564
+ try {
565
+ request.onUpgrade(statusCode, headers, socket, statusText)
566
+ } catch (err) {
567
+ util.errorRequest(client, request, err)
568
+ util.destroy(socket, err)
569
+ }
570
+
571
+ client[kResume]()
572
+ }
573
+
574
+ /**
575
+ * @param {number} statusCode
576
+ * @param {boolean} upgrade
577
+ * @param {boolean} shouldKeepAlive
578
+ * @returns {number}
579
+ */
580
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
581
+ const { client, socket, headers, statusText } = this
582
+
583
+ if (socket.destroyed) {
584
+ return -1
585
+ }
586
+
587
+ if (client[kRunning] === 0) {
588
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
589
+ return -1
590
+ }
591
+
592
+ const request = client[kQueue][client[kRunningIdx]]
593
+
594
+ if (!request) {
595
+ return -1
596
+ }
597
+
598
+ assert(!this.upgrade)
599
+ assert(this.statusCode < 200)
600
+
601
+ if (statusCode === 100) {
602
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
603
+ return -1
604
+ }
605
+
606
+ /* this can only happen if server is misbehaving */
607
+ if (upgrade && !request.upgrade) {
608
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
609
+ return -1
610
+ }
611
+
612
+ assert(this.timeoutType === TIMEOUT_HEADERS)
613
+
614
+ this.statusCode = statusCode
615
+ this.shouldKeepAlive = (
616
+ shouldKeepAlive ||
617
+ // Override llhttp value which does not allow keepAlive for HEAD.
618
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
619
+ )
620
+
621
+ if (this.statusCode >= 200) {
622
+ const bodyTimeout = request.bodyTimeout != null
623
+ ? request.bodyTimeout
624
+ : client[kBodyTimeout]
625
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
626
+ } else if (this.timeout) {
627
+ if (this.timeout.refresh) {
628
+ this.timeout.refresh()
629
+ }
630
+ }
631
+
632
+ if (request.method === 'CONNECT') {
633
+ assert(client[kRunning] === 1)
634
+ this.upgrade = true
635
+ return 2
636
+ }
637
+
638
+ if (upgrade) {
639
+ assert(client[kRunning] === 1)
640
+ this.upgrade = true
641
+ return 2
642
+ }
643
+
644
+ assert((this.headers.length & 1) === 0)
645
+ this.headers = []
646
+ this.headersSize = 0
647
+
648
+ if (this.shouldKeepAlive && client[kPipelining]) {
649
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
650
+
651
+ if (keepAliveTimeout != null) {
652
+ const timeout = Math.min(
653
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
654
+ client[kKeepAliveMaxTimeout]
655
+ )
656
+ if (timeout <= 0) {
657
+ socket[kReset] = true
658
+ } else {
659
+ client[kKeepAliveTimeoutValue] = timeout
660
+ }
661
+ } else {
662
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
663
+ }
664
+ } else {
665
+ // Stop more requests from being dispatched.
666
+ socket[kReset] = true
667
+ }
668
+
669
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
670
+
671
+ if (request.aborted) {
672
+ return -1
673
+ }
674
+
675
+ if (request.method === 'HEAD') {
676
+ return 1
677
+ }
678
+
679
+ if (statusCode < 200) {
680
+ return 1
681
+ }
682
+
683
+ if (socket[kBlocking]) {
684
+ socket[kBlocking] = false
685
+ client[kResume]()
686
+ }
687
+
688
+ return pause ? constants.ERROR.PAUSED : 0
689
+ }
690
+
691
+ /**
692
+ * @param {Buffer} buf
693
+ * @returns {number}
694
+ */
695
+ onBody (buf) {
696
+ const { client, socket, statusCode, maxResponseSize } = this
697
+
698
+ if (socket.destroyed) {
699
+ return -1
700
+ }
701
+
702
+ const request = client[kQueue][client[kRunningIdx]]
703
+ assert(request)
704
+
705
+ assert(this.timeoutType === TIMEOUT_BODY)
706
+ if (this.timeout) {
707
+ if (this.timeout.refresh) {
708
+ this.timeout.refresh()
709
+ }
710
+ }
711
+
712
+ assert(statusCode >= 200)
713
+
714
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
715
+ util.destroy(socket, new ResponseExceededMaxSizeError())
716
+ return -1
717
+ }
718
+
719
+ this.bytesRead += buf.length
720
+
721
+ if (request.onData(buf) === false) {
722
+ return constants.ERROR.PAUSED
723
+ }
724
+
725
+ return 0
726
+ }
727
+
728
+ /**
729
+ * @returns {number}
730
+ */
731
+ onMessageComplete () {
732
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
733
+
734
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
735
+ return -1
736
+ }
737
+
738
+ if (upgrade) {
739
+ return 0
740
+ }
741
+
742
+ assert(statusCode >= 100)
743
+ assert((this.headers.length & 1) === 0)
744
+
745
+ const request = client[kQueue][client[kRunningIdx]]
746
+ assert(request)
747
+
748
+ this.statusCode = 0
749
+ this.statusText = ''
750
+ this.bytesRead = 0
751
+ this.contentLength = ''
752
+ this.keepAlive = ''
753
+ this.connection = ''
754
+
755
+ this.headers = []
756
+ this.headersSize = 0
757
+
758
+ if (statusCode < 200) {
759
+ return 0
760
+ }
761
+
762
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
763
+ util.destroy(socket, new ResponseContentLengthMismatchError())
764
+ return -1
765
+ }
766
+
767
+ request.onComplete(headers)
768
+
769
+ client[kQueue][client[kRunningIdx]++] = null
770
+ socket[kSocketUsed] = client[kPending] === 0
771
+
772
+ if (socket[kWriting]) {
773
+ assert(client[kRunning] === 0)
774
+ // Response completed before request.
775
+ util.destroy(socket, new InformationalError('reset'))
776
+ return constants.ERROR.PAUSED
777
+ } else if (!shouldKeepAlive) {
778
+ util.destroy(socket, new InformationalError('reset'))
779
+ return constants.ERROR.PAUSED
780
+ } else if (socket[kReset] && client[kRunning] === 0) {
781
+ // Destroy socket once all requests have completed.
782
+ // The request at the tail of the pipeline is the one
783
+ // that requested reset and no further requests should
784
+ // have been queued since then.
785
+ util.destroy(socket, new InformationalError('reset'))
786
+ return constants.ERROR.PAUSED
787
+ } else if (client[kPipelining] == null || client[kPipelining] === 1) {
788
+ // We must wait a full event loop cycle to reuse this socket to make sure
789
+ // that non-spec compliant servers are not closing the connection even if they
790
+ // said they won't.
791
+ setImmediate(client[kResume])
792
+ } else {
793
+ client[kResume]()
794
+ }
795
+
796
+ return 0
797
+ }
798
+ }
799
+
800
+ function onParserTimeout (parserWeakRef) {
801
+ const parser = parserWeakRef.deref()
802
+ if (!parser) {
803
+ return
804
+ }
805
+
806
+ const { socket, timeoutType, client, paused } = parser
807
+
808
+ if (timeoutType === TIMEOUT_HEADERS) {
809
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
810
+ assert(!paused, 'cannot be paused while waiting for headers')
811
+ util.destroy(socket, new HeadersTimeoutError())
812
+ }
813
+ } else if (timeoutType === TIMEOUT_BODY) {
814
+ if (!paused) {
815
+ util.destroy(socket, new BodyTimeoutError())
816
+ }
817
+ } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
818
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
819
+ util.destroy(socket, new InformationalError('socket idle timeout'))
820
+ }
821
+ }
822
+
823
+ /**
824
+ * @param {import ('./client.js')} client
825
+ * @param {import('net').Socket} socket
826
+ * @returns
827
+ */
828
+ function connectH1 (client, socket) {
829
+ client[kSocket] = socket
830
+
831
+ if (!llhttpInstance) {
832
+ llhttpInstance = lazyllhttp()
833
+ }
834
+
835
+ if (socket.errored) {
836
+ throw socket.errored
837
+ }
838
+
839
+ if (socket.destroyed) {
840
+ throw new SocketError('destroyed')
841
+ }
842
+
843
+ socket[kNoRef] = false
844
+ socket[kWriting] = false
845
+ socket[kReset] = false
846
+ socket[kBlocking] = false
847
+ socket[kIdleSocketValidation] = 0
848
+ socket[kIdleSocketValidationTimeout] = null
849
+ socket[kSocketUsed] = false
850
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
851
+
852
+ util.addListener(socket, 'error', onHttpSocketError)
853
+ util.addListener(socket, 'readable', onHttpSocketReadable)
854
+ util.addListener(socket, 'end', onHttpSocketEnd)
855
+ util.addListener(socket, 'close', onHttpSocketClose)
856
+
857
+ socket[kClosed] = false
858
+ socket.on('close', onSocketClose)
859
+
860
+ return {
861
+ version: 'h1',
862
+ defaultPipelining: 1,
863
+ write (request) {
864
+ return writeH1(client, request)
865
+ },
866
+ resume () {
867
+ resumeH1(client)
868
+ },
869
+ /**
870
+ * @param {Error|undefined} err
871
+ * @param {() => void} callback
872
+ */
873
+ destroy (err, callback) {
874
+ if (socket[kClosed]) {
875
+ queueMicrotask(callback)
876
+ } else {
877
+ socket.on('close', callback)
878
+ socket.destroy(err)
879
+ }
880
+ },
881
+ /**
882
+ * @returns {boolean}
883
+ */
884
+ get destroyed () {
885
+ return socket.destroyed
886
+ },
887
+ /**
888
+ * @param {import('../core/request.js')} request
889
+ * @returns {boolean}
890
+ */
891
+ busy (request) {
892
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
893
+ return true
894
+ }
895
+
896
+ if (request) {
897
+ if (client[kRunning] > 0 && !request.idempotent) {
898
+ // Non-idempotent request cannot be retried.
899
+ // Ensure that no other requests are inflight and
900
+ // could cause failure.
901
+ return true
902
+ }
903
+
904
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
905
+ // Don't dispatch an upgrade until all preceding requests have completed.
906
+ // A misbehaving server might upgrade the connection before all pipelined
907
+ // request has completed.
908
+ return true
909
+ }
910
+
911
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
912
+ (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
913
+ // Request with stream or iterator body can error while other requests
914
+ // are inflight and indirectly error those as well.
915
+ // Ensure this doesn't happen by waiting for inflight
916
+ // to complete before dispatching.
917
+
918
+ // Request with stream or iterator body cannot be retried.
919
+ // Ensure that no other requests are inflight and
920
+ // could cause failure.
921
+ return true
922
+ }
923
+ }
924
+
925
+ return false
926
+ }
927
+ }
928
+ }
929
+
930
+ function onHttpSocketError (err) {
931
+ const parser = this[kParser]
932
+
933
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
934
+ // to the user.
935
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
936
+ const parserErr = parser.finish()
937
+ if (parserErr) {
938
+ this[kError] = parserErr
939
+ this[kClient][kOnError](parserErr)
940
+ }
941
+ return
942
+ }
943
+
944
+ this[kError] = err
945
+
946
+ this[kClient][kOnError](err)
947
+ }
948
+
949
+ function onHttpSocketReadable () {
950
+ this[kParser]?.readMore()
951
+ }
952
+
953
+ function onHttpSocketEnd () {
954
+ const parser = this[kParser]
955
+
956
+ if (parser.statusCode && !parser.shouldKeepAlive) {
957
+ const parserErr = parser.finish()
958
+ if (parserErr) {
959
+ util.destroy(this, parserErr)
960
+ }
961
+ return
962
+ }
963
+
964
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
965
+ }
966
+
967
+ function onHttpSocketClose () {
968
+ const parser = this[kParser]
969
+
970
+ clearIdleSocketValidation(this)
971
+
972
+ if (parser) {
973
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
974
+ this[kError] = parser.finish() || this[kError]
975
+ }
976
+
977
+ this[kParser].destroy()
978
+ this[kParser] = null
979
+ }
980
+
981
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
982
+
983
+ const client = this[kClient]
984
+
985
+ client[kSocket] = null
986
+ client[kHTTPContext] = null // TODO (fix): This is hacky...
987
+
988
+ if (client.destroyed) {
989
+ assert(client[kPending] === 0)
990
+
991
+ // Fail entire queue.
992
+ const requests = client[kQueue].splice(client[kRunningIdx])
993
+ for (let i = 0; i < requests.length; i++) {
994
+ const request = requests[i]
995
+ util.errorRequest(client, request, err)
996
+ }
997
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
998
+ // Fail head of pipeline.
999
+ const request = client[kQueue][client[kRunningIdx]]
1000
+ client[kQueue][client[kRunningIdx]++] = null
1001
+
1002
+ util.errorRequest(client, request, err)
1003
+ }
1004
+
1005
+ client[kPendingIdx] = client[kRunningIdx]
1006
+
1007
+ assert(client[kRunning] === 0)
1008
+
1009
+ client.emit('disconnect', client[kUrl], [client], err)
1010
+
1011
+ client[kResume]()
1012
+ }
1013
+
1014
+ function onSocketClose () {
1015
+ this[kClosed] = true
1016
+ }
1017
+
1018
+ function clearIdleSocketValidation (socket) {
1019
+ if (socket[kIdleSocketValidationTimeout]) {
1020
+ clearImmediate(socket[kIdleSocketValidationTimeout])
1021
+ socket[kIdleSocketValidationTimeout] = null
1022
+ }
1023
+
1024
+ socket[kIdleSocketValidation] = 0
1025
+ }
1026
+
1027
+ function scheduleIdleSocketValidation (client, socket) {
1028
+ socket[kIdleSocketValidation] = 1
1029
+ // Yield to the check phase (after poll) so unsolicited bytes / FIN / RST
1030
+ // already pending on this idle keep-alive socket are processed before the
1031
+ // next request is written (GHSA-35p6-xmwp-9g52).
1032
+ //
1033
+ // setTimeout(0) pays Node's ~1ms timer floor on every sequential reuse
1034
+ // (#5493). setImmediate avoids that, but an *unref'd* Immediate lets poll
1035
+ // block for ~500ms when the event loop is otherwise idle (#5600 / #5606).
1036
+ // A ref'd Immediate both keeps the pending request alive and makes poll
1037
+ // return immediately — the hybrid those issues asked for.
1038
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
1039
+ socket[kIdleSocketValidationTimeout] = null
1040
+ socket[kIdleSocketValidation] = 2
1041
+
1042
+ if (client[kSocket] === socket && !socket.destroyed) {
1043
+ client[kResume]()
1044
+ }
1045
+ })
1046
+ }
1047
+
1048
+ /**
1049
+ * @param {import('./client.js')} client
1050
+ */
1051
+ function resumeH1 (client) {
1052
+ const socket = client[kSocket]
1053
+
1054
+ if (socket && !socket.destroyed) {
1055
+ if (client[kSize] === 0) {
1056
+ if (!socket[kNoRef] && socket.unref) {
1057
+ socket.unref()
1058
+ socket[kNoRef] = true
1059
+ }
1060
+ } else if (socket[kNoRef] && socket.ref) {
1061
+ socket.ref()
1062
+ socket[kNoRef] = false
1063
+ }
1064
+
1065
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
1066
+ if (socket[kIdleSocketValidation] === 0) {
1067
+ scheduleIdleSocketValidation(client, socket)
1068
+ socket[kParser].readMore()
1069
+ if (socket.destroyed) {
1070
+ return
1071
+ }
1072
+ return
1073
+ }
1074
+
1075
+ if (socket[kIdleSocketValidation] === 1) {
1076
+ socket[kParser].readMore()
1077
+ if (socket.destroyed) {
1078
+ return
1079
+ }
1080
+ return
1081
+ }
1082
+ }
1083
+
1084
+ if (client[kRunning] === 0) {
1085
+ socket[kParser].readMore()
1086
+ if (socket.destroyed) {
1087
+ return
1088
+ }
1089
+ }
1090
+
1091
+ if (client[kSize] === 0) {
1092
+ if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
1093
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
1094
+ }
1095
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
1096
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
1097
+ const request = client[kQueue][client[kRunningIdx]]
1098
+ const headersTimeout = request.headersTimeout != null
1099
+ ? request.headersTimeout
1100
+ : client[kHeadersTimeout]
1101
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
1102
+ }
1103
+ }
1104
+ }
1105
+ }
1106
+
1107
+ // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
1108
+ function shouldSendContentLength (method) {
1109
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
1110
+ }
1111
+
1112
+ /**
1113
+ * @param {import('./client.js')} client
1114
+ * @param {import('../core/request.js')} request
1115
+ * @returns
1116
+ */
1117
+ function writeH1 (client, request) {
1118
+ const { method, path, host, upgrade, blocking, reset } = request
1119
+
1120
+ let { body, headers, contentLength } = request
1121
+
1122
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
1123
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
1124
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
1125
+
1126
+ // Sending a payload body on a request that does not
1127
+ // expect it can cause undefined behavior on some
1128
+ // servers and corrupt connection state. Do not
1129
+ // re-use the connection for further requests.
1130
+
1131
+ const expectsPayload = (
1132
+ method === 'PUT' ||
1133
+ method === 'POST' ||
1134
+ method === 'PATCH' ||
1135
+ method === 'QUERY' ||
1136
+ method === 'PROPFIND' ||
1137
+ method === 'PROPPATCH'
1138
+ )
1139
+
1140
+ if (util.isFormDataLike(body)) {
1141
+ if (!extractBody) {
1142
+ extractBody = require('../web/fetch/body.js').extractBody
1143
+ }
1144
+
1145
+ const [bodyStream, contentType] = extractBody(body)
1146
+ if (request.contentType == null) {
1147
+ headers.push('content-type', contentType)
1148
+ }
1149
+ body = bodyStream.stream
1150
+ contentLength = bodyStream.length
1151
+ } else if (util.isBlobLike(body) && request.contentType == null) {
1152
+ const contentType = body.type
1153
+ if (contentType) {
1154
+ const contentTypeValue = `${contentType}`
1155
+ if (!util.isValidHeaderValue(contentTypeValue)) {
1156
+ util.errorRequest(client, request, new InvalidArgumentError('invalid content-type header'))
1157
+ return false
1158
+ }
1159
+ headers.push('content-type', contentTypeValue)
1160
+ }
1161
+ }
1162
+
1163
+ if (body && typeof body.read === 'function') {
1164
+ // Try to read EOF in order to get length.
1165
+ body.read(0)
1166
+ }
1167
+
1168
+ const bodyLength = util.bodyLength(body)
1169
+
1170
+ contentLength = bodyLength ?? contentLength
1171
+
1172
+ if (contentLength === null) {
1173
+ contentLength = request.contentLength
1174
+ }
1175
+
1176
+ if (contentLength === 0 && !expectsPayload) {
1177
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
1178
+ // A user agent SHOULD NOT send a Content-Length header field when
1179
+ // the request message does not contain a payload body and the method
1180
+ // semantics do not anticipate such a body.
1181
+
1182
+ contentLength = null
1183
+ }
1184
+
1185
+ // https://github.com/nodejs/undici/issues/2046
1186
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
1187
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
1188
+ if (client[kStrictContentLength]) {
1189
+ util.errorRequest(client, request, new RequestContentLengthMismatchError())
1190
+ return false
1191
+ }
1192
+
1193
+ process.emitWarning(new RequestContentLengthMismatchError())
1194
+ }
1195
+
1196
+ const socket = client[kSocket]
1197
+ clearIdleSocketValidation(socket)
1198
+
1199
+ /**
1200
+ * @param {Error} [err]
1201
+ * @returns {void}
1202
+ */
1203
+ const abort = (err) => {
1204
+ if (request.aborted || request.completed) {
1205
+ return
1206
+ }
1207
+
1208
+ util.errorRequest(client, request, err || new RequestAbortedError())
1209
+
1210
+ util.destroy(body)
1211
+ util.destroy(socket, new InformationalError('aborted'))
1212
+ }
1213
+
1214
+ try {
1215
+ request.onConnect(abort)
1216
+ } catch (err) {
1217
+ util.errorRequest(client, request, err)
1218
+ }
1219
+
1220
+ if (request.aborted) {
1221
+ return false
1222
+ }
1223
+
1224
+ if (method === 'HEAD') {
1225
+ // https://github.com/mcollina/undici/issues/258
1226
+ // Close after a HEAD request to interop with misbehaving servers
1227
+ // that may send a body in the response.
1228
+
1229
+ socket[kReset] = true
1230
+ }
1231
+
1232
+ if (upgrade || method === 'CONNECT') {
1233
+ // On CONNECT or upgrade, block pipeline from dispatching further
1234
+ // requests on this connection.
1235
+
1236
+ socket[kReset] = true
1237
+ }
1238
+
1239
+ if (reset != null) {
1240
+ socket[kReset] = reset
1241
+ }
1242
+
1243
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
1244
+ socket[kReset] = true
1245
+ }
1246
+
1247
+ if (blocking) {
1248
+ socket[kBlocking] = true
1249
+ }
1250
+
1251
+ if (socket.setTypeOfService) {
1252
+ socket.setTypeOfService(request.typeOfService)
1253
+ }
1254
+
1255
+ let header = `${method} ${path} HTTP/1.1\r\n`
1256
+
1257
+ if (typeof host === 'string') {
1258
+ header += `host: ${host}\r\n`
1259
+ } else {
1260
+ header += client[kHostHeader]
1261
+ }
1262
+
1263
+ if (upgrade) {
1264
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
1265
+ } else if (client[kPipelining] && !socket[kReset]) {
1266
+ header += 'connection: keep-alive\r\n'
1267
+ } else {
1268
+ header += 'connection: close\r\n'
1269
+ }
1270
+
1271
+ if (Array.isArray(headers)) {
1272
+ for (let n = 0; n < headers.length; n += 2) {
1273
+ const key = headers[n + 0]
1274
+ const val = headers[n + 1]
1275
+
1276
+ if (Array.isArray(val)) {
1277
+ for (let i = 0; i < val.length; i++) {
1278
+ header += `${key}: ${val[i]}\r\n`
1279
+ }
1280
+ } else {
1281
+ header += `${key}: ${val}\r\n`
1282
+ }
1283
+ }
1284
+ }
1285
+
1286
+ if (channels.sendHeaders.hasSubscribers) {
1287
+ channels.sendHeaders.publish({ request, headers: header, socket })
1288
+ }
1289
+
1290
+ if (!body || bodyLength === 0) {
1291
+ writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
1292
+ } else if (util.isBuffer(body)) {
1293
+ writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
1294
+ } else if (util.isBlobLike(body)) {
1295
+ if (typeof body.stream === 'function') {
1296
+ writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
1297
+ } else {
1298
+ writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
1299
+ }
1300
+ } else if (util.isStream(body)) {
1301
+ writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
1302
+ } else if (util.isIterable(body)) {
1303
+ writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
1304
+ } else {
1305
+ assert(false)
1306
+ }
1307
+
1308
+ return true
1309
+ }
1310
+
1311
+ /**
1312
+ * @param {AbortCallback} abort
1313
+ * @param {import('stream').Stream} body
1314
+ * @param {import('./client.js')} client
1315
+ * @param {import('../core/request.js')} request
1316
+ * @param {import('net').Socket} socket
1317
+ * @param {number} contentLength
1318
+ * @param {string} header
1319
+ * @param {boolean} expectsPayload
1320
+ */
1321
+ function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1322
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
1323
+
1324
+ let finished = false
1325
+
1326
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1327
+
1328
+ /**
1329
+ * @param {Buffer} chunk
1330
+ * @returns {void}
1331
+ */
1332
+ const onData = function (chunk) {
1333
+ if (finished) {
1334
+ return
1335
+ }
1336
+
1337
+ try {
1338
+ if (!writer.write(chunk) && this.pause) {
1339
+ this.pause()
1340
+ }
1341
+ } catch (err) {
1342
+ util.destroy(this, err)
1343
+ }
1344
+ }
1345
+
1346
+ /**
1347
+ * @returns {void}
1348
+ */
1349
+ const onDrain = function () {
1350
+ if (finished) {
1351
+ return
1352
+ }
1353
+
1354
+ if (body.resume) {
1355
+ body.resume()
1356
+ }
1357
+ }
1358
+
1359
+ /**
1360
+ * @returns {void}
1361
+ */
1362
+ const onClose = function () {
1363
+ // 'close' might be emitted *before* 'error' for
1364
+ // broken streams. Wait a tick to avoid this case.
1365
+ queueMicrotask(() => {
1366
+ // It's only safe to remove 'error' listener after
1367
+ // 'close'.
1368
+ body.removeListener('error', onFinished)
1369
+ })
1370
+
1371
+ if (!finished) {
1372
+ const err = new RequestAbortedError()
1373
+ queueMicrotask(() => onFinished(err))
1374
+ }
1375
+ }
1376
+
1377
+ /**
1378
+ * @param {Error} [err]
1379
+ * @returns
1380
+ */
1381
+ const onFinished = function (err) {
1382
+ if (finished) {
1383
+ return
1384
+ }
1385
+
1386
+ finished = true
1387
+
1388
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
1389
+
1390
+ socket
1391
+ .off('drain', onDrain)
1392
+ .off('error', onFinished)
1393
+
1394
+ body
1395
+ .removeListener('data', onData)
1396
+ .removeListener('end', onFinished)
1397
+ .removeListener('close', onClose)
1398
+
1399
+ if (!err) {
1400
+ try {
1401
+ writer.end()
1402
+ } catch (er) {
1403
+ err = er
1404
+ }
1405
+ }
1406
+
1407
+ writer.destroy(err)
1408
+
1409
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
1410
+ util.destroy(body, err)
1411
+ } else {
1412
+ util.destroy(body)
1413
+ }
1414
+ }
1415
+
1416
+ body
1417
+ .on('data', onData)
1418
+ .on('end', onFinished)
1419
+ .on('error', onFinished)
1420
+ .on('close', onClose)
1421
+
1422
+ if (body.resume) {
1423
+ body.resume()
1424
+ }
1425
+
1426
+ socket
1427
+ .on('drain', onDrain)
1428
+ .on('error', onFinished)
1429
+
1430
+ if (body.errorEmitted ?? body.errored) {
1431
+ setImmediate(onFinished, body.errored)
1432
+ } else if (body.endEmitted ?? body.readableEnded) {
1433
+ setImmediate(onFinished, null)
1434
+ }
1435
+
1436
+ if (body.closeEmitted ?? body.closed) {
1437
+ setImmediate(onClose)
1438
+ }
1439
+ }
1440
+
1441
+ /**
1442
+ * @typedef AbortCallback
1443
+ * @type {Function}
1444
+ * @param {Error} [err]
1445
+ * @returns {void}
1446
+ */
1447
+
1448
+ /**
1449
+ * @param {AbortCallback} abort
1450
+ * @param {Uint8Array|null} body
1451
+ * @param {import('./client.js')} client
1452
+ * @param {import('../core/request.js')} request
1453
+ * @param {import('net').Socket} socket
1454
+ * @param {number} contentLength
1455
+ * @param {string} header
1456
+ * @param {boolean} expectsPayload
1457
+ * @returns {void}
1458
+ */
1459
+ function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1460
+ try {
1461
+ if (!body) {
1462
+ if (contentLength === 0) {
1463
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1464
+ } else {
1465
+ assert(contentLength === null, 'no body must not have content length')
1466
+ socket.write(`${header}\r\n`, 'latin1')
1467
+ }
1468
+ } else if (util.isBuffer(body)) {
1469
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
1470
+
1471
+ socket.cork()
1472
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1473
+ socket.write(body)
1474
+ socket.uncork()
1475
+ request.onBodySent(body)
1476
+
1477
+ if (!expectsPayload && request.reset !== false) {
1478
+ socket[kReset] = true
1479
+ }
1480
+ }
1481
+ request.onRequestSent()
1482
+
1483
+ client[kResume]()
1484
+ } catch (err) {
1485
+ abort(err)
1486
+ }
1487
+ }
1488
+
1489
+ /**
1490
+ * @param {AbortCallback} abort
1491
+ * @param {Blob} body
1492
+ * @param {import('./client.js')} client
1493
+ * @param {import('../core/request.js')} request
1494
+ * @param {import('net').Socket} socket
1495
+ * @param {number} contentLength
1496
+ * @param {string} header
1497
+ * @param {boolean} expectsPayload
1498
+ * @returns {Promise<void>}
1499
+ */
1500
+ async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1501
+ assert(contentLength === body.size, 'blob body must have content length')
1502
+
1503
+ try {
1504
+ if (contentLength != null && contentLength !== body.size) {
1505
+ throw new RequestContentLengthMismatchError()
1506
+ }
1507
+
1508
+ const buffer = Buffer.from(await body.arrayBuffer())
1509
+
1510
+ socket.cork()
1511
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1512
+ socket.write(buffer)
1513
+ socket.uncork()
1514
+
1515
+ request.onBodySent(buffer)
1516
+ request.onRequestSent()
1517
+
1518
+ if (!expectsPayload && request.reset !== false) {
1519
+ socket[kReset] = true
1520
+ }
1521
+
1522
+ client[kResume]()
1523
+ } catch (err) {
1524
+ abort(err)
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * @param {AbortCallback} abort
1530
+ * @param {Iterable} body
1531
+ * @param {import('./client.js')} client
1532
+ * @param {import('../core/request.js')} request
1533
+ * @param {import('net').Socket} socket
1534
+ * @param {number} contentLength
1535
+ * @param {string} header
1536
+ * @param {boolean} expectsPayload
1537
+ * @returns {Promise<void>}
1538
+ */
1539
+ async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1540
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
1541
+
1542
+ let callback = null
1543
+ function onDrain () {
1544
+ if (callback) {
1545
+ const cb = callback
1546
+ callback = null
1547
+ cb()
1548
+ }
1549
+ }
1550
+
1551
+ const waitForDrain = () => new Promise((resolve, reject) => {
1552
+ assert(callback === null)
1553
+
1554
+ if (socket[kError]) {
1555
+ reject(socket[kError])
1556
+ } else {
1557
+ callback = resolve
1558
+ }
1559
+ })
1560
+
1561
+ socket
1562
+ .on('close', onDrain)
1563
+ .on('drain', onDrain)
1564
+
1565
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1566
+ try {
1567
+ // It's up to the user to somehow abort the async iterable.
1568
+ for await (const chunk of body) {
1569
+ if (socket[kError]) {
1570
+ throw socket[kError]
1571
+ }
1572
+
1573
+ if (!writer.write(chunk)) {
1574
+ await waitForDrain()
1575
+ }
1576
+ }
1577
+
1578
+ writer.end()
1579
+ } catch (err) {
1580
+ writer.destroy(err)
1581
+ } finally {
1582
+ socket
1583
+ .off('close', onDrain)
1584
+ .off('drain', onDrain)
1585
+ }
1586
+ }
1587
+
1588
+ class AsyncWriter {
1589
+ /**
1590
+ *
1591
+ * @param {object} arg
1592
+ * @param {AbortCallback} arg.abort
1593
+ * @param {import('net').Socket} arg.socket
1594
+ * @param {import('../core/request.js')} arg.request
1595
+ * @param {number} arg.contentLength
1596
+ * @param {import('./client.js')} arg.client
1597
+ * @param {boolean} arg.expectsPayload
1598
+ * @param {string} arg.header
1599
+ */
1600
+ constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
1601
+ this.socket = socket
1602
+ this.request = request
1603
+ this.contentLength = contentLength
1604
+ this.client = client
1605
+ this.bytesWritten = 0
1606
+ this.expectsPayload = expectsPayload
1607
+ this.header = header
1608
+ this.abort = abort
1609
+
1610
+ socket[kWriting] = true
1611
+ }
1612
+
1613
+ /**
1614
+ * @param {Buffer} chunk
1615
+ * @returns
1616
+ */
1617
+ write (chunk) {
1618
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
1619
+
1620
+ if (socket[kError]) {
1621
+ throw socket[kError]
1622
+ }
1623
+
1624
+ if (socket.destroyed) {
1625
+ return false
1626
+ }
1627
+
1628
+ const len = Buffer.byteLength(chunk)
1629
+ if (!len) {
1630
+ return true
1631
+ }
1632
+
1633
+ // We should defer writing chunks.
1634
+ if (contentLength !== null && bytesWritten + len > contentLength) {
1635
+ if (client[kStrictContentLength]) {
1636
+ throw new RequestContentLengthMismatchError()
1637
+ }
1638
+
1639
+ process.emitWarning(new RequestContentLengthMismatchError())
1640
+ }
1641
+
1642
+ socket.cork()
1643
+
1644
+ if (bytesWritten === 0) {
1645
+ if (!expectsPayload && request.reset !== false) {
1646
+ socket[kReset] = true
1647
+ }
1648
+
1649
+ if (contentLength === null) {
1650
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
1651
+ } else {
1652
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1653
+ }
1654
+ }
1655
+
1656
+ if (contentLength === null) {
1657
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
1658
+ }
1659
+
1660
+ this.bytesWritten += len
1661
+
1662
+ const ret = socket.write(chunk)
1663
+
1664
+ socket.uncork()
1665
+
1666
+ request.onBodySent(chunk)
1667
+
1668
+ if (!ret) {
1669
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1670
+ if (socket[kParser].timeout.refresh) {
1671
+ socket[kParser].timeout.refresh()
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ return ret
1677
+ }
1678
+
1679
+ /**
1680
+ * @returns {void}
1681
+ */
1682
+ end () {
1683
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
1684
+ request.onRequestSent()
1685
+
1686
+ socket[kWriting] = false
1687
+
1688
+ if (socket[kError]) {
1689
+ throw socket[kError]
1690
+ }
1691
+
1692
+ if (socket.destroyed) {
1693
+ return
1694
+ }
1695
+
1696
+ if (bytesWritten === 0) {
1697
+ if (expectsPayload) {
1698
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
1699
+ // A user agent SHOULD send a Content-Length in a request message when
1700
+ // no Transfer-Encoding is sent and the request method defines a meaning
1701
+ // for an enclosed payload body.
1702
+
1703
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1704
+ } else {
1705
+ socket.write(`${header}\r\n`, 'latin1')
1706
+ }
1707
+ } else if (contentLength === null) {
1708
+ socket.write('\r\n0\r\n\r\n', 'latin1')
1709
+ }
1710
+
1711
+ if (contentLength !== null && bytesWritten !== contentLength) {
1712
+ if (client[kStrictContentLength]) {
1713
+ throw new RequestContentLengthMismatchError()
1714
+ } else {
1715
+ process.emitWarning(new RequestContentLengthMismatchError())
1716
+ }
1717
+ }
1718
+
1719
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1720
+ if (socket[kParser].timeout.refresh) {
1721
+ socket[kParser].timeout.refresh()
1722
+ }
1723
+ }
1724
+
1725
+ client[kResume]()
1726
+ }
1727
+
1728
+ /**
1729
+ * @param {Error} [err]
1730
+ * @returns {void}
1731
+ */
1732
+ destroy (err) {
1733
+ const { socket, client, abort } = this
1734
+
1735
+ socket[kWriting] = false
1736
+
1737
+ if (err) {
1738
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
1739
+ abort(err)
1740
+ }
1741
+ }
1742
+ }
1743
+
1744
+ module.exports = connectH1