elysia 2.0.0-beta.3 → 2.0.0-beta.31

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 (369) hide show
  1. package/README.md +1 -1
  2. package/dist/_virtual/_rolldown/runtime.mjs +1 -0
  3. package/dist/adapter/bun/index.d.ts +16 -2
  4. package/dist/adapter/bun/index.js +458 -119
  5. package/dist/adapter/bun/index.mjs +459 -121
  6. package/dist/adapter/constants.mjs +1 -0
  7. package/dist/adapter/default-headers.mjs +1 -0
  8. package/dist/adapter/index.mjs +1 -0
  9. package/dist/adapter/origin.js +0 -57
  10. package/dist/adapter/origin.mjs +1 -57
  11. package/dist/adapter/response-ownership.mjs +1 -0
  12. package/dist/adapter/skip-clone.mjs +1 -0
  13. package/dist/adapter/types.d.ts +2 -21
  14. package/dist/adapter/types.mjs +1 -0
  15. package/dist/adapter/utils.d.ts +11 -3
  16. package/dist/adapter/utils.js +147 -112
  17. package/dist/adapter/utils.mjs +149 -114
  18. package/dist/adapter/web-standard/handler.d.ts +1 -1
  19. package/dist/adapter/web-standard/handler.js +39 -36
  20. package/dist/adapter/web-standard/handler.mjs +41 -37
  21. package/dist/adapter/web-standard/index.js +2 -30
  22. package/dist/adapter/web-standard/index.mjs +3 -30
  23. package/dist/adapter/web-standard/utils.js +5 -18
  24. package/dist/adapter/web-standard/utils.mjs +6 -18
  25. package/dist/base.d.ts +387 -207
  26. package/dist/base.js +742 -676
  27. package/dist/base.mjs +747 -680
  28. package/dist/compile/aot-capture.d.ts +2 -13
  29. package/dist/compile/aot-capture.js +39 -89
  30. package/dist/compile/aot-capture.mjs +43 -88
  31. package/dist/compile/aot-emit.d.ts +9 -8
  32. package/dist/compile/aot-emit.js +36 -38
  33. package/dist/compile/aot-emit.mjs +37 -38
  34. package/dist/compile/aot-reconstruct.js +7 -30
  35. package/dist/compile/aot-reconstruct.mjs +8 -30
  36. package/dist/compile/aot.d.ts +15 -17
  37. package/dist/compile/aot.js +36 -58
  38. package/dist/compile/aot.mjs +34 -57
  39. package/dist/compile/handler/descriptor.d.ts +10 -17
  40. package/dist/compile/handler/descriptor.js +25 -58
  41. package/dist/compile/handler/descriptor.mjs +29 -58
  42. package/dist/compile/handler/frozen-validator.d.ts +7 -12
  43. package/dist/compile/handler/frozen-validator.js +57 -118
  44. package/dist/compile/handler/frozen-validator.mjs +56 -118
  45. package/dist/compile/handler/index.d.ts +8 -4
  46. package/dist/compile/handler/index.js +322 -206
  47. package/dist/compile/handler/index.mjs +324 -211
  48. package/dist/compile/handler/jit.d.ts +28 -21
  49. package/dist/compile/handler/jit.js +232 -159
  50. package/dist/compile/handler/jit.mjs +235 -165
  51. package/dist/compile/handler/params.d.ts +5 -4
  52. package/dist/compile/handler/params.js +21 -9
  53. package/dist/compile/handler/params.mjs +25 -12
  54. package/dist/compile/handler/reconstruct.d.ts +4 -4
  55. package/dist/compile/handler/reconstruct.js +8 -6
  56. package/dist/compile/handler/reconstruct.mjs +9 -6
  57. package/dist/compile/handler/static-clone-resolver.d.ts +6 -0
  58. package/dist/compile/handler/static-clone-resolver.js +8 -0
  59. package/dist/compile/handler/static-clone-resolver.mjs +8 -0
  60. package/dist/compile/handler/utils.d.ts +29 -11
  61. package/dist/compile/handler/utils.js +184 -276
  62. package/dist/compile/handler/utils.mjs +179 -275
  63. package/dist/compile/jit-probe.d.ts +2 -2
  64. package/dist/compile/jit-probe.js +2 -3
  65. package/dist/compile/jit-probe.mjs +3 -3
  66. package/dist/compile/lexer.d.ts +7 -4
  67. package/dist/compile/lexer.js +268 -6
  68. package/dist/compile/lexer.mjs +269 -4
  69. package/dist/compile/utils.d.ts +2 -1
  70. package/dist/compile/utils.js +14 -6
  71. package/dist/compile/utils.mjs +14 -6
  72. package/dist/compiled.d.ts +0 -1
  73. package/dist/compiled.js +0 -10
  74. package/dist/compiled.mjs +1 -10
  75. package/dist/constants.js +19 -4
  76. package/dist/constants.mjs +20 -4
  77. package/dist/context.d.ts +15 -5
  78. package/dist/context.js +17 -36
  79. package/dist/context.mjs +20 -38
  80. package/dist/cookie/config.d.ts +6 -2
  81. package/dist/cookie/config.js +77 -23
  82. package/dist/cookie/config.mjs +79 -25
  83. package/dist/cookie/cookie.d.ts +7 -5
  84. package/dist/cookie/cookie.js +12 -10
  85. package/dist/cookie/cookie.mjs +13 -10
  86. package/dist/cookie/crypto.d.ts +1 -1
  87. package/dist/cookie/crypto.js +19 -14
  88. package/dist/cookie/crypto.mjs +20 -14
  89. package/dist/cookie/error.d.ts +1 -2
  90. package/dist/cookie/error.js +6 -3
  91. package/dist/cookie/error.mjs +7 -3
  92. package/dist/cookie/lib.js +2 -1
  93. package/dist/cookie/lib.mjs +3 -1
  94. package/dist/cookie/serialize.mjs +1 -0
  95. package/dist/cookie/types.d.ts +1 -1
  96. package/dist/cookie/types.mjs +1 -0
  97. package/dist/cookie/utils.d.ts +5 -9
  98. package/dist/cookie/utils.js +109 -83
  99. package/dist/cookie/utils.mjs +112 -84
  100. package/dist/error.d.ts +127 -111
  101. package/dist/error.js +187 -180
  102. package/dist/error.mjs +185 -181
  103. package/dist/generation.d.ts +2 -2
  104. package/dist/generation.mjs +1 -0
  105. package/dist/handler/error.d.ts +18 -18
  106. package/dist/handler/error.js +77 -120
  107. package/dist/handler/error.mjs +80 -122
  108. package/dist/handler/fetch.js +165 -153
  109. package/dist/handler/fetch.mjs +168 -155
  110. package/dist/handler/utils.d.ts +25 -6
  111. package/dist/handler/utils.js +81 -26
  112. package/dist/handler/utils.mjs +76 -25
  113. package/dist/index.d.ts +11 -11
  114. package/dist/index.js +3 -1
  115. package/dist/index.mjs +5 -4
  116. package/dist/memory.js +2 -2
  117. package/dist/memory.mjs +3 -2
  118. package/dist/package.js +1 -1
  119. package/dist/package.mjs +2 -1
  120. package/dist/parse-query.js +76 -80
  121. package/dist/parse-query.mjs +77 -80
  122. package/dist/plugin/aot/bun.d.ts +8 -1
  123. package/dist/plugin/aot/bun.js +9 -28
  124. package/dist/plugin/aot/bun.mjs +11 -29
  125. package/dist/plugin/aot/core.d.ts +37 -66
  126. package/dist/plugin/aot/core.js +197 -153
  127. package/dist/plugin/aot/core.mjs +195 -156
  128. package/dist/plugin/aot/esbuild.js +8 -24
  129. package/dist/plugin/aot/esbuild.mjs +10 -25
  130. package/dist/plugin/aot/hooks.d.ts +6 -17
  131. package/dist/plugin/aot/hooks.js +37 -17
  132. package/dist/plugin/aot/hooks.mjs +38 -19
  133. package/dist/plugin/aot/rspack-loader.d.ts +1 -5
  134. package/dist/plugin/aot/rspack-loader.js +1 -26
  135. package/dist/plugin/aot/rspack-loader.mjs +2 -26
  136. package/dist/plugin/aot/rspack.js +2 -19
  137. package/dist/plugin/aot/rspack.mjs +4 -20
  138. package/dist/plugin/aot/source.d.ts +7 -43
  139. package/dist/plugin/aot/source.js +73 -73
  140. package/dist/plugin/aot/source.mjs +74 -74
  141. package/dist/plugin/aot/treeshake.js +2 -6
  142. package/dist/plugin/aot/treeshake.mjs +3 -6
  143. package/dist/plugin/aot/unplugin.d.ts +1 -4
  144. package/dist/plugin/aot/unplugin.js +4 -32
  145. package/dist/plugin/aot/unplugin.mjs +5 -32
  146. package/dist/plugin/aot/vite.d.ts +2 -6
  147. package/dist/plugin/aot/vite.js +0 -14
  148. package/dist/plugin/aot/vite.mjs +1 -14
  149. package/dist/plugin/aot/worker.js +2 -2
  150. package/dist/plugin/aot/worker.mjs +3 -2
  151. package/dist/plugin/auto-head.js +1 -10
  152. package/dist/plugin/auto-head.mjs +2 -10
  153. package/dist/plugin/trace.d.ts +18 -1
  154. package/dist/plugin/trace.js +0 -16
  155. package/dist/plugin/trace.mjs +1 -16
  156. package/dist/plugin/websocket.d.ts +21 -0
  157. package/dist/plugin/websocket.js +0 -21
  158. package/dist/plugin/websocket.mjs +1 -21
  159. package/dist/route-table.d.ts +3 -0
  160. package/dist/route-table.js +4 -1
  161. package/dist/route-table.mjs +5 -1
  162. package/dist/schema-snapshot.d.ts +0 -4
  163. package/dist/schema-snapshot.js +60 -56
  164. package/dist/schema-snapshot.mjs +61 -56
  165. package/dist/sucrose.d.ts +7 -56
  166. package/dist/sucrose.js +103 -735
  167. package/dist/sucrose.mjs +103 -728
  168. package/dist/trace.d.ts +16 -10
  169. package/dist/trace.js +20 -134
  170. package/dist/trace.mjs +22 -135
  171. package/dist/type/bridge-live.d.ts +5 -3
  172. package/dist/type/bridge-live.js +6 -3
  173. package/dist/type/bridge-live.mjs +6 -3
  174. package/dist/type/bridge.d.ts +7 -5
  175. package/dist/type/bridge.js +38 -28
  176. package/dist/type/bridge.mjs +27 -22
  177. package/dist/type/coerce-plan.d.ts +5 -5
  178. package/dist/type/coerce-plan.js +53 -43
  179. package/dist/type/coerce-plan.mjs +56 -44
  180. package/dist/type/coerce.d.ts +3 -7
  181. package/dist/type/coerce.js +18 -79
  182. package/dist/type/coerce.mjs +20 -80
  183. package/dist/type/compat.js +10 -19
  184. package/dist/type/compat.mjs +12 -20
  185. package/dist/type/constants.d.ts +1 -1
  186. package/dist/type/constants.mjs +1 -0
  187. package/dist/type/elysia/accelerate.mjs +1 -0
  188. package/dist/type/elysia/array-buffer.d.ts +6 -2
  189. package/dist/type/elysia/array-buffer.js +16 -15
  190. package/dist/type/elysia/array-buffer.mjs +17 -16
  191. package/dist/type/elysia/array-string.js +2 -43
  192. package/dist/type/elysia/array-string.mjs +3 -43
  193. package/dist/type/elysia/array.js +5 -9
  194. package/dist/type/elysia/array.mjs +6 -9
  195. package/dist/type/elysia/boolean-string.mjs +1 -0
  196. package/dist/type/elysia/boolean.js +3 -13
  197. package/dist/type/elysia/boolean.mjs +4 -13
  198. package/dist/type/elysia/cookie.d.ts +3 -4
  199. package/dist/type/elysia/cookie.js +3 -14
  200. package/dist/type/elysia/cookie.mjs +4 -14
  201. package/dist/type/elysia/date.d.ts +2 -1
  202. package/dist/type/elysia/date.js +7 -14
  203. package/dist/type/elysia/date.mjs +8 -14
  204. package/dist/type/elysia/file-type.d.ts +2 -2
  205. package/dist/type/elysia/file-type.js +4 -3
  206. package/dist/type/elysia/file-type.mjs +5 -3
  207. package/dist/type/elysia/file.d.ts +1 -3
  208. package/dist/type/elysia/file.js +3 -23
  209. package/dist/type/elysia/file.mjs +5 -10
  210. package/dist/type/elysia/files.js +1 -7
  211. package/dist/type/elysia/files.mjs +3 -8
  212. package/dist/type/elysia/form.mjs +1 -0
  213. package/dist/type/elysia/integer-string.d.ts +1 -1
  214. package/dist/type/elysia/integer-string.js +3 -28
  215. package/dist/type/elysia/integer-string.mjs +5 -29
  216. package/dist/type/elysia/integer.js +3 -13
  217. package/dist/type/elysia/integer.mjs +4 -13
  218. package/dist/type/elysia/intersect.js +0 -5
  219. package/dist/type/elysia/intersect.mjs +1 -5
  220. package/dist/type/elysia/json-string.d.ts +7 -0
  221. package/dist/type/elysia/json-string.js +47 -0
  222. package/dist/type/elysia/json-string.mjs +47 -0
  223. package/dist/type/elysia/keep-config.d.ts +14 -0
  224. package/dist/type/elysia/keep-config.js +62 -0
  225. package/dist/type/elysia/keep-config.mjs +54 -0
  226. package/dist/type/elysia/maybe-empty.mjs +1 -0
  227. package/dist/type/elysia/no-validate.mjs +1 -0
  228. package/dist/type/elysia/nullable.mjs +1 -0
  229. package/dist/type/elysia/number.d.ts +2 -1
  230. package/dist/type/elysia/number.js +19 -12
  231. package/dist/type/elysia/number.mjs +19 -12
  232. package/dist/type/elysia/numeric-enum.d.ts +5 -3
  233. package/dist/type/elysia/numeric-enum.js +1 -5
  234. package/dist/type/elysia/numeric-enum.mjs +2 -5
  235. package/dist/type/elysia/numeric.d.ts +4 -2
  236. package/dist/type/elysia/numeric.js +17 -14
  237. package/dist/type/elysia/numeric.mjs +17 -14
  238. package/dist/type/elysia/object-string.js +2 -40
  239. package/dist/type/elysia/object-string.mjs +3 -40
  240. package/dist/type/elysia/object.js +5 -9
  241. package/dist/type/elysia/object.mjs +6 -9
  242. package/dist/type/elysia/optional.js +8 -8
  243. package/dist/type/elysia/optional.mjs +8 -7
  244. package/dist/type/elysia/problem.d.ts +20 -0
  245. package/dist/type/elysia/problem.js +19 -0
  246. package/dist/type/elysia/problem.mjs +19 -0
  247. package/dist/type/elysia/string.mjs +1 -0
  248. package/dist/type/elysia/uint8-array.d.ts +2 -1
  249. package/dist/type/elysia/uint8-array.js +4 -18
  250. package/dist/type/elysia/uint8-array.mjs +5 -18
  251. package/dist/type/elysia/union-enum.js +5 -6
  252. package/dist/type/elysia/union-enum.mjs +6 -6
  253. package/dist/type/elysia/union.js +0 -5
  254. package/dist/type/elysia/union.mjs +1 -5
  255. package/dist/type/elysia/utils.d.ts +4 -6
  256. package/dist/type/elysia/utils.js +16 -40
  257. package/dist/type/elysia/utils.mjs +15 -36
  258. package/dist/type/exports.d.ts +4 -2
  259. package/dist/type/exports.js +13 -1
  260. package/dist/type/exports.mjs +5 -2
  261. package/dist/type/index.d.ts +1 -1
  262. package/dist/type/index.js +31 -23
  263. package/dist/type/index.mjs +33 -24
  264. package/dist/type/shared.d.ts +12 -10
  265. package/dist/type/shared.js +75 -109
  266. package/dist/type/shared.mjs +72 -108
  267. package/dist/type/sync-require.d.ts +11 -0
  268. package/dist/type/sync-require.js +7 -0
  269. package/dist/type/sync-require.mjs +6 -0
  270. package/dist/type/typebox-system-lite.d.ts +2 -0
  271. package/dist/type/typebox-system-lite.js +34 -0
  272. package/dist/type/typebox-system-lite.mjs +4 -0
  273. package/dist/type/typebox-system-require.d.ts +7 -0
  274. package/dist/type/typebox-system-require.js +24 -0
  275. package/dist/type/typebox-system-require.mjs +24 -0
  276. package/dist/type/typebox-type-live.d.ts +6 -4
  277. package/dist/type/typebox-type-live.js +23 -9
  278. package/dist/type/typebox-type-live.mjs +11 -6
  279. package/dist/type/typebox-type.d.ts +14 -4
  280. package/dist/type/typebox-type.js +85 -22
  281. package/dist/type/typebox-type.mjs +35 -21
  282. package/dist/type/typebox-value-live.d.ts +3 -1
  283. package/dist/type/typebox-value-live.js +5 -1
  284. package/dist/type/typebox-value-live.mjs +4 -1
  285. package/dist/type/typebox-value-ops.d.ts +4 -0
  286. package/dist/type/typebox-value-ops.js +90 -0
  287. package/dist/type/typebox-value-ops.mjs +6 -0
  288. package/dist/type/typebox-value-require.d.ts +8 -0
  289. package/dist/type/typebox-value-require.js +28 -0
  290. package/dist/type/typebox-value-require.mjs +25 -0
  291. package/dist/type/typebox-value.d.ts +9 -4
  292. package/dist/type/typebox-value.js +19 -8
  293. package/dist/type/typebox-value.mjs +19 -9
  294. package/dist/type/types.d.ts +1 -1
  295. package/dist/type/types.mjs +1 -0
  296. package/dist/type/utils.js +1 -10
  297. package/dist/type/utils.mjs +2 -10
  298. package/dist/type/validator/clean-safe.d.ts +2 -4
  299. package/dist/type/validator/clean-safe.js +15 -11
  300. package/dist/type/validator/clean-safe.mjs +17 -10
  301. package/dist/type/validator/custom-error.js +50 -48
  302. package/dist/type/validator/custom-error.mjs +51 -48
  303. package/dist/type/validator/default-precompute.d.ts +10 -2
  304. package/dist/type/validator/default-precompute.js +33 -77
  305. package/dist/type/validator/default-precompute.mjs +33 -77
  306. package/dist/type/validator/exact-mirror-live.d.ts +8 -0
  307. package/dist/type/validator/exact-mirror-live.js +15 -0
  308. package/dist/type/validator/exact-mirror-live.mjs +11 -0
  309. package/dist/type/validator/exact-mirror-require.d.ts +4 -0
  310. package/dist/type/validator/exact-mirror-require.js +11 -0
  311. package/dist/type/validator/exact-mirror-require.mjs +9 -0
  312. package/dist/type/validator/exact-mirror.js +15 -7
  313. package/dist/type/validator/exact-mirror.mjs +17 -7
  314. package/dist/type/validator/frozen-check.js +7 -8
  315. package/dist/type/validator/frozen-check.mjs +9 -9
  316. package/dist/type/validator/index.d.ts +2 -1
  317. package/dist/type/validator/index.js +149 -168
  318. package/dist/type/validator/index.mjs +155 -173
  319. package/dist/type/validator/string-codec-aot.d.ts +3 -2
  320. package/dist/type/validator/string-codec-aot.js +11 -7
  321. package/dist/type/validator/string-codec-aot.mjs +11 -7
  322. package/dist/type/validator/validator-cache.d.ts +5 -4
  323. package/dist/type/validator/validator-cache.js +49 -37
  324. package/dist/type/validator/validator-cache.mjs +49 -36
  325. package/dist/types.d.ts +596 -187
  326. package/dist/types.mjs +1 -0
  327. package/dist/universal/constants.mjs +1 -0
  328. package/dist/universal/env.js +2 -3
  329. package/dist/universal/env.mjs +2 -3
  330. package/dist/universal/file.d.ts +6 -4
  331. package/dist/universal/file.js +7 -19
  332. package/dist/universal/file.mjs +9 -19
  333. package/dist/universal/index.d.ts +2 -2
  334. package/dist/universal/index.mjs +1 -0
  335. package/dist/universal/is-production.d.ts +1 -2
  336. package/dist/universal/is-production.js +1 -3
  337. package/dist/universal/is-production.mjs +3 -3
  338. package/dist/universal/server.d.ts +0 -272
  339. package/dist/universal/server.mjs +1 -0
  340. package/dist/utils.d.ts +62 -22
  341. package/dist/utils.js +342 -277
  342. package/dist/utils.mjs +327 -273
  343. package/dist/validator/index.d.ts +3 -3
  344. package/dist/validator/index.js +20 -34
  345. package/dist/validator/index.mjs +23 -36
  346. package/dist/validator/route.d.ts +3 -10
  347. package/dist/validator/route.js +2 -1
  348. package/dist/validator/route.mjs +3 -1
  349. package/dist/ws/context.d.ts +4 -1
  350. package/dist/ws/context.js +41 -36
  351. package/dist/ws/context.mjs +41 -36
  352. package/dist/ws/index.mjs +1 -0
  353. package/dist/ws/parser.js +12 -22
  354. package/dist/ws/parser.mjs +13 -22
  355. package/dist/ws/route.d.ts +2 -2
  356. package/dist/ws/route.js +295 -221
  357. package/dist/ws/route.mjs +302 -227
  358. package/dist/ws/types.d.ts +6 -7
  359. package/dist/ws/types.mjs +1 -0
  360. package/package.json +22 -55
  361. package/dist/compile/analysis-cache.d.ts +0 -6
  362. package/dist/compile/analysis-cache.js +0 -12
  363. package/dist/compile/analysis-cache.mjs +0 -11
  364. package/dist/cookie/index.d.ts +0 -7
  365. package/dist/cookie/index.js +0 -13
  366. package/dist/cookie/index.mjs +0 -7
  367. package/dist/handler/index.d.ts +0 -2
  368. package/dist/handler/index.js +0 -5
  369. package/dist/handler/index.mjs +0 -3
@@ -1,3 +1,4 @@
1
+ // @bun
1
2
  //#region src/adapter/default-headers.ts
2
3
  const defaultHeaders = "\0";
3
4
 
@@ -1,3 +1,4 @@
1
+ // @bun
1
2
  //#region src/adapter/index.ts
2
3
  const createAdapter = (adapter) => adapter;
3
4
 
@@ -1,63 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  //#region src/adapter/origin.ts
4
- /**
5
- * Provenance channel for deferred abort-signal arming.
6
- *
7
- * Bun materializes `Request.signal` lazily (~214ns on the first read), so
8
- * Elysia only pays for it once the pipeline can actually observe an abort,
9
- * that is, after it suspends. Deferring that read is only sound for the exact
10
- * `Request` instance `Bun.serve` handed to `fetch`: any other request
11
- * (`app.handle`, a non-Bun adapter, or a `.wrap()` HOC that substitutes the
12
- * request) may carry a user-controlled signal that is already aborted at entry
13
- * and therefore must be observed synchronously.
14
- *
15
- * The Bun adapter publishes the untouched original here for the *synchronous*
16
- * prologue of `app.fetch` and, on the lane where `fetch` has no request hook
17
- * to run, for the compiled route's own entry probe, which is still inside that
18
- * same synchronous frame, then clears it in `finally`, so the window closes
19
- * before the first suspension and cannot leak across concurrent requests.
20
- * A `.wrap()` HOC that replaces the request or defers calling `next()` past a
21
- * microtask simply misses the window, fetch handler falls back to eager check
22
- *
23
- * ## "A single shared slot that every request writes to, so a race condition?"
24
- *
25
- * It looks like one, but it can't be. Explained like you're five:
26
- *
27
- * JavaScript only ever does ONE thing at a time. When a request comes in, the
28
- * adapter writes its name on the whiteboard (`origin.request = request`),
29
- * walks it down the hall (`fetch(request)` the synchronous part, where the
30
- * one and only identity check happens, in `fetch`'s prologue, or at the
31
- * compiled route's entry when `fetch` had no hook to run first), and erases
32
- * the whiteboard `finally`
33
- * all in one uninterruptible turn. The next request's turn CANNOT start
34
- * until this turn is completely finished, because that is how the event loop
35
- * works: run-to-completion, no preemption. So request B can never see request
36
- * A's name on the board, by the time B's turn starts, the board was already
37
- * erased at the end of A's turn.
38
- *
39
- * "But the handler is async!" the `await`s inside it run LATER, in separate
40
- * turns. That is fine, because the check already happened: the verdict was
41
- * copied onto that request's own context (`'~sig'`) during the synchronous
42
- * part, and the code that runs after an `await` only ever reads the context,
43
- * never this slot.
44
- *
45
- * And if any assumption here ever breaks, a runtime that re-enters, a wrap
46
- * that delays, a future edit that sneaks an `await` in before the check the
47
- * comparison simply MISSES and the request falls back to eager arming, which
48
- * is the exact pre-optimization behavior. Every failure mode makes a request
49
- * slightly slower, never incorrect
50
- *
51
- * Adversarial proof, not just argument: `test/core/abort-race.test.ts` storms
52
- * concurrent servers, in-process `handle()` calls, request-substituting and
53
- * `next()`-delaying wraps at this slot and asserts zero misclassification.
54
- *
55
- * Never infer the Bun runtime from `fetch`'s second argument: Cloudflare
56
- * Workers pass `env` there.
57
- *
58
- * It's insanely stupid, but it works. As Bun is single-threaded and synchronous
59
- * so the `finally` block will always run before the next request comes in.
60
- */
61
4
  const origin = { request: void 0 };
62
5
 
63
6
  //#endregion
@@ -1,61 +1,5 @@
1
+ // @bun
1
2
  //#region src/adapter/origin.ts
2
- /**
3
- * Provenance channel for deferred abort-signal arming.
4
- *
5
- * Bun materializes `Request.signal` lazily (~214ns on the first read), so
6
- * Elysia only pays for it once the pipeline can actually observe an abort,
7
- * that is, after it suspends. Deferring that read is only sound for the exact
8
- * `Request` instance `Bun.serve` handed to `fetch`: any other request
9
- * (`app.handle`, a non-Bun adapter, or a `.wrap()` HOC that substitutes the
10
- * request) may carry a user-controlled signal that is already aborted at entry
11
- * and therefore must be observed synchronously.
12
- *
13
- * The Bun adapter publishes the untouched original here for the *synchronous*
14
- * prologue of `app.fetch` and, on the lane where `fetch` has no request hook
15
- * to run, for the compiled route's own entry probe, which is still inside that
16
- * same synchronous frame, then clears it in `finally`, so the window closes
17
- * before the first suspension and cannot leak across concurrent requests.
18
- * A `.wrap()` HOC that replaces the request or defers calling `next()` past a
19
- * microtask simply misses the window, fetch handler falls back to eager check
20
- *
21
- * ## "A single shared slot that every request writes to, so a race condition?"
22
- *
23
- * It looks like one, but it can't be. Explained like you're five:
24
- *
25
- * JavaScript only ever does ONE thing at a time. When a request comes in, the
26
- * adapter writes its name on the whiteboard (`origin.request = request`),
27
- * walks it down the hall (`fetch(request)` the synchronous part, where the
28
- * one and only identity check happens, in `fetch`'s prologue, or at the
29
- * compiled route's entry when `fetch` had no hook to run first), and erases
30
- * the whiteboard `finally`
31
- * all in one uninterruptible turn. The next request's turn CANNOT start
32
- * until this turn is completely finished, because that is how the event loop
33
- * works: run-to-completion, no preemption. So request B can never see request
34
- * A's name on the board, by the time B's turn starts, the board was already
35
- * erased at the end of A's turn.
36
- *
37
- * "But the handler is async!" the `await`s inside it run LATER, in separate
38
- * turns. That is fine, because the check already happened: the verdict was
39
- * copied onto that request's own context (`'~sig'`) during the synchronous
40
- * part, and the code that runs after an `await` only ever reads the context,
41
- * never this slot.
42
- *
43
- * And if any assumption here ever breaks, a runtime that re-enters, a wrap
44
- * that delays, a future edit that sneaks an `await` in before the check the
45
- * comparison simply MISSES and the request falls back to eager arming, which
46
- * is the exact pre-optimization behavior. Every failure mode makes a request
47
- * slightly slower, never incorrect
48
- *
49
- * Adversarial proof, not just argument: `test/core/abort-race.test.ts` storms
50
- * concurrent servers, in-process `handle()` calls, request-substituting and
51
- * `next()`-delaying wraps at this slot and asserts zero misclassification.
52
- *
53
- * Never infer the Bun runtime from `fetch`'s second argument: Cloudflare
54
- * Workers pass `env` there.
55
- *
56
- * It's insanely stupid, but it works. As Bun is single-threaded and synchronous
57
- * so the `finally` block will always run before the next request comes in.
58
- */
59
3
  const origin = { request: void 0 };
60
4
 
61
5
  //#endregion
@@ -1,3 +1,4 @@
1
+ // @bun
1
2
  //#region src/adapter/response-ownership.ts
2
3
  const borrowedResponses = /* @__PURE__ */ new WeakSet();
3
4
  function borrow(response) {
@@ -1,3 +1,4 @@
1
+ // @bun
1
2
  //#region src/adapter/skip-clone.ts
2
3
  const skipClone = /* @__PURE__ */ new WeakSet();
3
4
 
@@ -1,6 +1,6 @@
1
1
  import { ListenCallback, Serve } from "../universal/server.js";
2
- import { MaybePromise } from "../types.js";
3
2
  import { Context } from "../context.js";
3
+ import { MaybePromise } from "../types.js";
4
4
  import { AnyElysia } from "../base.js";
5
5
 
6
6
  //#region src/adapter/types.d.ts
@@ -10,25 +10,6 @@ import { AnyElysia } from "../base.js";
10
10
  * @since 2.0.0
11
11
  */
12
12
  interface ElysiaAdapterOptions<App extends AnyElysia | void = void> {
13
- /**
14
- * Name of the adapter, preferably runtime
15
- */
16
- name: string;
17
- /**
18
- *
19
- * @param app
20
- */
21
- runtime: 'node' | 'deno' | 'bun' | 'cloudflare-worker' | 'browser' | 'vercel' | 'netlify' | 'lambda' | 'fastly' | 'edge' | 'unknown' | (string & {});
22
- /**
23
- * Whether this adapter is web standard
24
- */
25
- isWebStandard: boolean;
26
- /**
27
- * Whether this adapter supports WebSocket.
28
- *
29
- * `.ws()` throws on non-Bun runtimes unless this is set.
30
- */
31
- websocket?: boolean;
32
13
  listen?(app: AnyElysia, options: string | number | Partial<Serve>, callback?: ListenCallback): void;
33
14
  parse: {
34
15
  json: (context: Context) => MaybePromise<Record<keyof any, undefined> | unknown[]>;
@@ -36,7 +17,7 @@ interface ElysiaAdapterOptions<App extends AnyElysia | void = void> {
36
17
  urlencoded: (context: Context) => MaybePromise<Record<string, string | string[]>>;
37
18
  arrayBuffer: (context: Context) => MaybePromise<ArrayBuffer>;
38
19
  formData: (context: Context) => MaybePromise<Record<string, unknown>>;
39
- default: (context: Context, contentType: string, normalized?: boolean) => MaybePromise<any>;
20
+ default: (context: Context, contentType: string) => MaybePromise<any>;
40
21
  };
41
22
  response: {
42
23
  /**
@@ -1 +1,2 @@
1
+ // @bun
1
2
  export { };
@@ -1,8 +1,8 @@
1
+ import { StatusMap } from "../constants.js";
1
2
  import { BaseCookie } from "../cookie/types.js";
3
+ import { Context } from "../context.js";
2
4
  import { ElysiaFile } from "../universal/file.js";
3
- import { StatusMap } from "../constants.js";
4
5
  import { HTTPHeaders } from "../types.js";
5
- import { Context } from "../context.js";
6
6
  //#region src/adapter/utils.d.ts
7
7
  declare function materializeSetHeaders(set: Context['set']): any;
8
8
  declare function normalizeContentType(contentType: string): string;
@@ -12,6 +12,7 @@ declare function responseToSetHeaders(response: Response, set?: Context['set']):
12
12
  headers: HTTPHeaders;
13
13
  status?: number | keyof StatusMap;
14
14
  cookie?: Record<string, BaseCookie>;
15
+ redirect?: never;
15
16
  } | {
16
17
  headers: any;
17
18
  status: number | "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Enhance Your Calm" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required";
@@ -27,6 +28,13 @@ declare function createStreamHandler({
27
28
  declare function streamResponse(response: Response): AsyncGenerator<any, void, any>;
28
29
  declare function handleSet(set: Context['set']): void;
29
30
  declare function createResponseHandler(handler: CreateHandlerParameter): (response: Response, set?: Context["set"], request?: Request, owned?: boolean) => any;
31
+ /**
32
+ * Tee a returned `ReadableStream` so afterResponse, `defer()` and derive
33
+ * dispose wait for it, as for a tee'd generator. A `bytes()` stream is left
34
+ * alone (exact-stream contract), and so is a `Response`: reading its `.body`
35
+ * would move it off Bun's native send path
36
+ */
37
+ declare function observeStream(source: ReadableStream): [ReadableStream, AsyncIterable<unknown>, AsyncIterableIterator<unknown>] | undefined;
30
38
  /**
31
39
  * Split async source into `branches` independent iterators
32
40
  *
@@ -47,4 +55,4 @@ declare function createResponseHandler(handler: CreateHandlerParameter): (respon
47
55
  */
48
56
  declare function tee<T>(source: AsyncIterable<T>, branches?: number, cap?: number, capBytes?: number): AsyncIterableIterator<T>[];
49
57
  //#endregion
50
- export { createResponseHandler, createStreamHandler, handleFile, handleSet, materializeSetHeaders, normalizeContentType, parseSetCookies, responseToSetHeaders, streamResponse, tee };
58
+ export { createResponseHandler, createStreamHandler, handleFile, handleSet, materializeSetHeaders, normalizeContentType, observeStream, parseSetCookies, responseToSetHeaders, streamResponse, tee };
@@ -17,22 +17,16 @@ function materializeSetHeaders(set) {
17
17
  const sseFormat = (data) => require_utils.sseData(data) + "\n";
18
18
  const identityFormat = (data) => data;
19
19
  const textEncoder = new TextEncoder();
20
- const encodeChunk = (s) => textEncoder.encode(s);
21
20
  function normalizeContentType(contentType) {
22
21
  if (contentType === "application/json") return contentType;
23
22
  const end = contentType.indexOf(";");
24
23
  return (end === -1 ? contentType : contentType.slice(0, end)).trim().toLowerCase();
25
24
  }
26
25
  function handleFile(response, set, request, size = response.size) {
27
- if (!require_universal_constants.isBun && response instanceof Promise) return response.then((res) => handleFile(res, set, request, size));
28
26
  const rangeHeader = request?.headers.get("range");
29
27
  if (rangeHeader) {
30
28
  const match = /bytes=(\d*)-(\d*)/.exec(rangeHeader);
31
29
  if (match) {
32
- if (!match[1] && !match[2]) return new Response(null, {
33
- status: 416,
34
- headers: mergeHeaders(new Headers({ "content-range": `bytes */${size}` }), set?.headers ?? require_utils.nullObject())
35
- });
36
30
  let start;
37
31
  let end;
38
32
  if (!match[1] && match[2]) {
@@ -43,7 +37,7 @@ function handleFile(response, set, request, size = response.size) {
43
37
  start = match[1] ? parseInt(match[1]) : 0;
44
38
  end = match[2] ? Math.min(parseInt(match[2]), size - 1) : size - 1;
45
39
  }
46
- if (start >= size || start > end) return new Response(null, {
40
+ if (!match[1] && !match[2] || start >= size || start > end) return new Response(null, {
47
41
  status: 416,
48
42
  headers: mergeHeaders(new Headers({ "content-range": `bytes */${size}` }), set?.headers ?? require_utils.nullObject())
49
43
  });
@@ -61,10 +55,8 @@ function handleFile(response, set, request, size = response.size) {
61
55
  }
62
56
  const body = "value" in response ? response.value : response;
63
57
  const immutable = set && (set.status === 206 || set.status === 304 || set.status === 412 || set.status === 416);
64
- const defaultHeader = immutable ? require_utils.nullObject() : {
65
- "accept-ranges": "bytes",
66
- "content-range": size ? `bytes 0-${size - 1}/${size}` : void 0
67
- };
58
+ const defaultHeader = immutable ? require_utils.nullObject() : { "accept-ranges": "bytes" };
59
+ if (!immutable && size) defaultHeader["content-range"] = `bytes 0-${size - 1}/${size}`;
68
60
  if (!set && !size) return new Response(body);
69
61
  if (!set) return new Response(body, { headers: defaultHeader });
70
62
  if (set.headers instanceof Headers) {
@@ -75,13 +67,9 @@ function handleFile(response, set, request, size = response.size) {
75
67
  }
76
68
  return new Response(body, set);
77
69
  }
78
- if (require_utils.isNotEmpty(set.headers)) return new Response(body, {
79
- status: set.status,
80
- headers: Object.assign(defaultHeader, set.headers)
81
- });
82
70
  return new Response(body, {
83
71
  status: set.status,
84
- headers: defaultHeader
72
+ headers: Object.assign(defaultHeader, set.headers)
85
73
  });
86
74
  }
87
75
  function normalizeHeaders(set) {
@@ -124,27 +112,9 @@ function responseToSetHeaders(response, set) {
124
112
  if (set.headers["content-encoding"]) delete set.headers["content-encoding"];
125
113
  return set;
126
114
  }
127
- function enqueueBinaryChunk(controller, chunk) {
128
- if (chunk instanceof Blob) return chunk.arrayBuffer().then((buffer) => {
129
- controller.enqueue(new Uint8Array(buffer));
130
- return true;
131
- });
132
- if (chunk instanceof Uint8Array) {
133
- controller.enqueue(chunk);
134
- return true;
135
- }
136
- if (chunk instanceof ArrayBuffer) {
137
- controller.enqueue(new Uint8Array(chunk));
138
- return true;
139
- }
140
- if (ArrayBuffer.isView(chunk)) {
141
- controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
142
- return true;
143
- }
144
- return false;
145
- }
146
115
  function createStreamHandler({ mapResponse, mapCompactResponse }) {
147
116
  return async (generator, set, request, skipFormat, owned = false) => {
117
+ if (request === null) return void 0;
148
118
  if (require_utils.isByteStream(generator)) {
149
119
  if (generator.locked) throw new TypeError("Cannot transfer a locked or consumed byte stream");
150
120
  if (set) {
@@ -158,10 +128,21 @@ function createStreamHandler({ mapResponse, mapCompactResponse }) {
158
128
  return new Response(generator, { headers: { "content-type": "application/octet-stream" } });
159
129
  }
160
130
  const typedSSE = !skipFormat && "sse" in generator && generator.sse === true;
131
+ const sourceIterator = typeof generator.next === "function" ? generator : void 0;
161
132
  let init = typedSSE ? void 0 : generator.next?.();
133
+ if (init instanceof Promise || typeof init?.then === "function") init = await init;
134
+ const sign = set?.["~sign"];
135
+ if (sign) try {
136
+ await sign(set);
137
+ } catch (error) {
138
+ try {
139
+ await generator.return?.(void 0);
140
+ } catch {}
141
+ throw error;
142
+ }
162
143
  if (set) handleSet(set);
163
- if (init instanceof Promise) init = await init;
164
- if (init?.value instanceof ReadableStream) generator = init.value;
144
+ const yieldedStream = init?.value instanceof ReadableStream;
145
+ if (yieldedStream) generator = init.value;
165
146
  else if (init && (typeof init?.done === "undefined" || init?.done)) {
166
147
  if (set) return mapResponse(init.value, set, request, owned);
167
148
  return mapCompactResponse(init.value, request, owned);
@@ -195,8 +176,32 @@ function createStreamHandler({ mapResponse, mapCompactResponse }) {
195
176
  connection: "keep-alive"
196
177
  }
197
178
  };
198
- const iterator = typeof generator.next === "function" ? generator : generator[Symbol.asyncIterator]();
179
+ const sourceStream = generator instanceof ReadableStream ? generator : void 0;
180
+ let streamReader;
181
+ const iterator = sourceStream ? {
182
+ next: () => (streamReader ??= sourceStream.getReader()).read(),
183
+ async return() {
184
+ if (!streamReader) {
185
+ await sourceStream.cancel();
186
+ return {
187
+ done: true,
188
+ value: void 0
189
+ };
190
+ }
191
+ try {
192
+ await streamReader.cancel();
193
+ } finally {
194
+ streamReader.releaseLock();
195
+ }
196
+ return {
197
+ done: true,
198
+ value: void 0
199
+ };
200
+ }
201
+ } : sourceIterator ?? generator[Symbol.asyncIterator]();
202
+ const outerIterator = yieldedStream && !init.done ? sourceIterator : void 0;
199
203
  let end = false;
204
+ let finalizing;
200
205
  const signal = request?.signal;
201
206
  let onAbort;
202
207
  const cleanupAbort = () => {
@@ -205,71 +210,93 @@ function createStreamHandler({ mapResponse, mapCompactResponse }) {
205
210
  onAbort = void 0;
206
211
  }
207
212
  };
208
- const safeReturn = () => {
213
+ const safeReturn = async (target) => {
209
214
  try {
210
- const r = iterator.return?.();
211
- if (r && typeof r.then === "function") r.catch(() => {});
215
+ await target?.return?.();
212
216
  } catch {}
213
217
  };
214
- const closeSafely = (controller) => {
218
+ const finalize = (mode, controller, error) => {
219
+ if (end) return finalizing;
220
+ end = true;
221
+ cleanupAbort();
222
+ finalizing = safeReturn(iterator).then(() => safeReturn(outerIterator));
223
+ if (!controller) return finalizing;
215
224
  try {
216
- controller.close();
225
+ if (mode === "error") controller.error(error);
226
+ else controller.close();
217
227
  } catch {}
218
- cleanupAbort();
219
228
  };
220
- const enqueueValue = async (controller, value) => {
229
+ const enqueueValue = (controller, value) => {
221
230
  if (value.toSSE) {
222
- controller.enqueue(encodeChunk(value.toSSE()));
231
+ controller.enqueue(textEncoder.encode(value.toSSE()));
232
+ return;
233
+ }
234
+ if (value instanceof Blob) return value.arrayBuffer().then((buffer) => {
235
+ controller.enqueue(new Uint8Array(buffer));
236
+ });
237
+ if (value instanceof Uint8Array) {
238
+ controller.enqueue(value);
239
+ return;
240
+ }
241
+ if (value instanceof ArrayBuffer) {
242
+ controller.enqueue(new Uint8Array(value));
243
+ return;
244
+ }
245
+ if (ArrayBuffer.isView(value)) {
246
+ controller.enqueue(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
223
247
  return;
224
248
  }
225
- const p = enqueueBinaryChunk(controller, value);
226
- if (p !== false) return void await p;
227
249
  if (typeof value === "object") try {
228
- controller.enqueue(encodeChunk(format(JSON.stringify(value))));
250
+ controller.enqueue(textEncoder.encode(format(JSON.stringify(value))));
229
251
  } catch {
230
- controller.enqueue(encodeChunk(format(value.toString())));
252
+ controller.enqueue(textEncoder.encode(format(value.toString())));
231
253
  }
232
- else controller.enqueue(encodeChunk(format(value.toString())));
254
+ else controller.enqueue(textEncoder.encode(format(value.toString())));
233
255
  };
234
256
  return new Response(new ReadableStream({
235
- async start(controller) {
257
+ start(controller) {
236
258
  if (signal) {
237
- onAbort = () => {
238
- cleanupAbort();
239
- end = true;
240
- safeReturn();
241
- try {
242
- controller.close();
243
- } catch {}
244
- };
259
+ onAbort = () => finalize("close", controller);
245
260
  if (signal.aborted) onAbort();
246
261
  else signal.addEventListener("abort", onAbort, { once: true });
247
262
  }
248
263
  if (!init || init.value instanceof ReadableStream || init.value === void 0 || init.value === null) return;
249
- await enqueueValue(controller, init.value);
250
- },
251
- async pull(controller) {
252
- if (end) {
253
- closeSafely(controller);
254
- return;
255
- }
264
+ const fail = (error) => {
265
+ finalize("error", controller, error);
266
+ };
256
267
  try {
257
- const { value: chunk, done } = await iterator.next();
258
- if (done || end) {
259
- closeSafely(controller);
260
- return;
268
+ return enqueueValue(controller, init.value)?.catch(fail);
269
+ } catch (error) {
270
+ fail(error);
271
+ }
272
+ },
273
+ pull(controller) {
274
+ if (end) return;
275
+ const fail = (error) => {
276
+ finalize("error", controller, error);
277
+ };
278
+ const step = (result) => {
279
+ while (true) {
280
+ if (result.done || end) {
281
+ finalize("close", controller);
282
+ return;
283
+ }
284
+ const chunk = result.value;
285
+ if (chunk !== void 0 && chunk !== null) return enqueueValue(controller, chunk);
286
+ const next = iterator.next();
287
+ if (typeof next.then === "function") return Promise.resolve(next).then(step);
288
+ result = next;
261
289
  }
262
- if (chunk === void 0 || chunk === null) return;
263
- await enqueueValue(controller, chunk);
290
+ };
291
+ try {
292
+ const next = iterator.next();
293
+ return (typeof next.then === "function" ? Promise.resolve(next).then(step) : step(next))?.catch(fail);
264
294
  } catch (error) {
265
- cleanupAbort();
266
- controller.error(error);
295
+ fail(error);
267
296
  }
268
297
  },
269
298
  cancel() {
270
- end = true;
271
- cleanupAbort();
272
- safeReturn();
299
+ finalize("close");
273
300
  }
274
301
  }, typedSSE ? { highWaterMark: 0 } : void 0), set);
275
302
  };
@@ -292,8 +319,11 @@ function handleSet(set) {
292
319
  const cookie = require_cookie_serialize.serializeCookie(set.cookie);
293
320
  if (cookie) {
294
321
  const existing = set.headers[setCookie];
295
- if (Array.isArray(existing)) set.headers[setCookie] = existing.concat(cookie);
296
- else set.headers[setCookie] = cookie;
322
+ if (existing) {
323
+ const kept = typeof existing === "string" ? [existing] : existing;
324
+ const added = (typeof cookie === "string" ? [cookie] : cookie).filter((value) => !kept.includes(value));
325
+ set.headers[setCookie] = added.length ? kept.concat(added) : existing;
326
+ } else set.headers[setCookie] = cookie;
297
327
  }
298
328
  }
299
329
  if (set.headers[setCookie] && Array.isArray(set.headers[setCookie])) set.headers = parseSetCookies(new Headers(set.headers), set.headers[setCookie]);
@@ -326,11 +356,6 @@ function mergeHeaders(responseHeaders, setHeaders) {
326
356
  applySetHeaders(headers, setHeaders, responseHeaders);
327
357
  return headers;
328
358
  }
329
- function mergeStatus(responseStatus, setStatus) {
330
- if (typeof setStatus === "string") setStatus = require_constants.StatusMap[setStatus];
331
- if (responseStatus === 200) return setStatus;
332
- return responseStatus;
333
- }
334
359
  function cancelPropagatingBody(clonedBody, orphanedBranch, preserveOrphan = false) {
335
360
  const reader = clonedBody.getReader();
336
361
  return new ReadableStream({
@@ -349,7 +374,6 @@ function cancelPropagatingBody(clonedBody, orphanedBranch, preserveOrphan = fals
349
374
  }
350
375
  });
351
376
  }
352
- const warnedStreamBorrows = /* @__PURE__ */ new WeakSet();
353
377
  function createResponseHandler(handler) {
354
378
  const handleStream = createStreamHandler(handler);
355
379
  return (response, set, request, owned = false) => {
@@ -361,25 +385,22 @@ function createResponseHandler(handler) {
361
385
  const borrowed = !owned || explicitlyBorrowed;
362
386
  const mustClone = owned && explicitlyBorrowed;
363
387
  if (!borrowed && response.bodyUsed) throw new TypeError("Cannot reuse a consumed Response across requests");
388
+ let status;
364
389
  if (set) {
365
- const status = mergeStatus(response.status, set.status);
390
+ status = response.status === 200 ? set.status : response.status;
391
+ if (typeof status === "string") status = require_constants.StatusMap[status];
366
392
  const statusUnchanged = status === void 0 || status === response.status;
367
393
  if (!mustClone && statusUnchanged && !set.cookie && !require_utils.isNotEmpty(set.headers)) return response;
368
394
  } else if (!mustClone) return response;
369
395
  if (!borrowed && response.body?.locked) throw new TypeError("Cannot patch a Response whose body is locked");
370
396
  let body = response.body;
371
397
  if (borrowed) {
372
- const bodyBefore = body;
373
398
  const cloned = response.clone();
374
- if (explicitlyBorrowed && bodyBefore && response.body !== bodyBefore && !warnedStreamBorrows.has(response)) {
375
- warnedStreamBorrows.add(response);
376
- console.warn("[elysia] borrow() was called on a stream-backed Response");
377
- }
378
399
  body = cloned.body && response.body ? cancelPropagatingBody(cloned.body, response.body, explicitlyBorrowed) : cloned.body;
379
400
  }
380
401
  const newResponse = new Response(body, set ? {
381
402
  headers: mergeHeaders(response.headers, set.headers),
382
- status: mergeStatus(response.status, set.status),
403
+ status,
383
404
  statusText: response.statusText
384
405
  } : {
385
406
  headers: response.headers,
@@ -403,24 +424,37 @@ const doneResult = {
403
424
  done: true,
404
425
  value: void 0
405
426
  };
406
- /**
407
- * Split async source into `branches` independent iterators
408
- *
409
- * A producer drains the source ahead of consumers
410
- *
411
- * To prevent long/infinite stream, the unconsumed window is capped:
412
- * Consumed-by-every-branch entries are trimmed off the front
413
- * Producer backpressures whenever the window hits `cap` ENTRIES or
414
- * `capBytes` bytes, whichever comes first
415
- *
416
- * Streams below both caps buffer eagerly
417
- * Only streams exceeding one gate on the slowest consumer
418
- *
419
- * Branch 0 is the value consumer (response/client)
420
- * When `return()` (client abort / early exit), source is stopped
421
- * so the observer branches can still reach completion instead of spinning
422
- * an infinite source
423
- */
427
+ function observeStream(source) {
428
+ if (source.locked || require_utils.isByteStream(source)) return;
429
+ const reader = source.getReader();
430
+ const [value, observer] = tee({ [Symbol.asyncIterator]: () => ({
431
+ next: () => reader.read(),
432
+ return: (reason) => reader.cancel(reason).then(() => ({
433
+ done: true,
434
+ value: void 0
435
+ }))
436
+ }) });
437
+ const body = new ReadableStream({
438
+ async pull(controller) {
439
+ try {
440
+ const result = await value.next();
441
+ if (result.done) controller.close();
442
+ else controller.enqueue(result.value);
443
+ } catch (error) {
444
+ controller.error(error);
445
+ }
446
+ },
447
+ cancel(reason) {
448
+ return value.return?.(reason);
449
+ }
450
+ }, { highWaterMark: 0 });
451
+ if (source.sse === true) body.sse = true;
452
+ return [
453
+ body,
454
+ observer,
455
+ value
456
+ ];
457
+ }
424
458
  function tee(source, branches = 2, cap = 64, capBytes = 1 << 22) {
425
459
  const iterator = source[Symbol.asyncIterator]?.() ?? source[Symbol.iterator]();
426
460
  const buffer = [];
@@ -524,7 +558,7 @@ function tee(source, branches = 2, cap = 64, capBytes = 1 << 22) {
524
558
  wakeAll();
525
559
  }
526
560
  })();
527
- const makeBranch = (me) => ({
561
+ const makeBranch = (me) => Object.assign(Object.create(null), {
528
562
  [Symbol.asyncIterator]() {
529
563
  return this;
530
564
  },
@@ -564,6 +598,7 @@ exports.handleFile = handleFile;
564
598
  exports.handleSet = handleSet;
565
599
  exports.materializeSetHeaders = materializeSetHeaders;
566
600
  exports.normalizeContentType = normalizeContentType;
601
+ exports.observeStream = observeStream;
567
602
  exports.parseSetCookies = parseSetCookies;
568
603
  exports.responseToSetHeaders = responseToSetHeaders;
569
604
  exports.streamResponse = streamResponse;