From 2b7fce1df1de40c912d635fe536531af444f4478 Mon Sep 17 00:00:00 2001 From: cirospaciari Date: Mon, 9 Oct 2023 21:20:26 -0300 Subject: [PATCH 1/2] fix abort signal and fetch error --- .../bun-usockets/src/eventing/epoll_kqueue.c | 18 +++++++--- packages/bun-usockets/src/libusockets.h | 2 +- packages/bun-usockets/src/loop.c | 2 +- packages/bun-uws/capi/examples/Broadcast.c | 4 +-- .../bun-uws/capi/examples/HelloWorldAsync.c | 4 +-- packages/bun-uws/capi/examples/UpgradeAsync.c | 4 +-- packages/bun-uws/examples/UpgradeAsync.cpp | 2 +- packages/bun-uws/src/Loop.h | 2 +- src/bun.js/api/bun.zig | 2 +- src/bun.js/event_loop.zig | 2 +- src/bun.js/node/node_fs_stat_watcher.zig | 2 +- src/bun.js/webcore/response.zig | 33 ++++++++++--------- src/bun.js/webcore/streams.zig | 6 ++++ src/deps/uws.zig | 6 ++-- src/http_client_async.zig | 21 ++++++------ test/js/web/abort/abort.test.ts | 19 +++++++++++ 16 files changed, 81 insertions(+), 48 deletions(-) diff --git a/packages/bun-usockets/src/eventing/epoll_kqueue.c b/packages/bun-usockets/src/eventing/epoll_kqueue.c index 44212d3bec7ef1..d051f5b5adc35f 100644 --- a/packages/bun-usockets/src/eventing/epoll_kqueue.c +++ b/packages/bun-usockets/src/eventing/epoll_kqueue.c @@ -414,14 +414,18 @@ struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsi #endif #ifdef LIBUS_USE_EPOLL -void us_timer_close(struct us_timer_t *timer) { +void us_timer_close(struct us_timer_t *timer, int fallthrough) { struct us_internal_callback_t *cb = (struct us_internal_callback_t *) timer; us_poll_stop(&cb->p, cb->loop); close(us_poll_fd(&cb->p)); - /* (regular) sockets are the only polls which are not freed immediately */ - us_poll_free((struct us_poll_t *) timer, cb->loop); + /* (regular) sockets are the only polls which are not freed immediately */ + if(fallthrough){ + us_free(timer); + }else { + us_poll_free((struct us_poll_t *) timer, cb->loop); + } } void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms) { @@ -438,7 +442,7 @@ void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms us_poll_start((struct us_poll_t *) t, internal_cb->loop, LIBUS_SOCKET_READABLE); } #else -void us_timer_close(struct us_timer_t *timer) { +void us_timer_close(struct us_timer_t *timer, int fallthrough) { struct us_internal_callback_t *internal_cb = (struct us_internal_callback_t *) timer; struct kevent64_s event; @@ -446,7 +450,11 @@ void us_timer_close(struct us_timer_t *timer) { kevent64(internal_cb->loop->fd, &event, 1, NULL, 0, 0, NULL); /* (regular) sockets are the only polls which are not freed immediately */ - us_poll_free((struct us_poll_t *) timer, internal_cb->loop); + if(fallthrough){ + us_free(timer); + }else { + us_poll_free((struct us_poll_t *) timer, internal_cb->loop); + } } void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms) { diff --git a/packages/bun-usockets/src/libusockets.h b/packages/bun-usockets/src/libusockets.h index c0e3fad90826e5..ea17a3622c02e5 100644 --- a/packages/bun-usockets/src/libusockets.h +++ b/packages/bun-usockets/src/libusockets.h @@ -132,7 +132,7 @@ struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsi void *us_timer_ext(struct us_timer_t *timer); /* */ -void us_timer_close(struct us_timer_t *timer); +void us_timer_close(struct us_timer_t *timer, int fallthrough); /* Arm a timer with a delay from now and eventually a repeat delay. * Specify 0 as repeat delay to disable repeating. Specify both 0 to disarm. */ diff --git a/packages/bun-usockets/src/loop.c b/packages/bun-usockets/src/loop.c index 9ad1e64bf69808..e230fa29b20c34 100644 --- a/packages/bun-usockets/src/loop.c +++ b/packages/bun-usockets/src/loop.c @@ -47,7 +47,7 @@ void us_internal_loop_data_free(struct us_loop_t *loop) { free(loop->data.recv_buf); - us_timer_close(loop->data.sweep_timer); + us_timer_close(loop->data.sweep_timer, 0); us_internal_async_close(loop->data.wakeup_async); } diff --git a/packages/bun-uws/capi/examples/Broadcast.c b/packages/bun-uws/capi/examples/Broadcast.c index dc6787349a320a..ef1b091018479a 100644 --- a/packages/bun-uws/capi/examples/Broadcast.c +++ b/packages/bun-uws/capi/examples/Broadcast.c @@ -14,7 +14,7 @@ void uws_timer_close(struct us_timer_t *timer) struct timer_handler_data *data; memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *)); free(data); - us_timer_close(t); + us_timer_close(t, 0); } //Timer create helper struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data) @@ -47,7 +47,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void if (!data->repeat) { free(data); - us_timer_close(t); + us_timer_close(t, 0); } }, ms, repeat_ms); diff --git a/packages/bun-uws/capi/examples/HelloWorldAsync.c b/packages/bun-uws/capi/examples/HelloWorldAsync.c index b8549b07ebeda8..e22dd44c1be1f5 100644 --- a/packages/bun-uws/capi/examples/HelloWorldAsync.c +++ b/packages/bun-uws/capi/examples/HelloWorldAsync.c @@ -19,7 +19,7 @@ void uws_timer_close(struct us_timer_t *timer) struct timer_handler_data *data; memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *)); free(data); - us_timer_close(t); + us_timer_close(t, 0); } //Timer create helper struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data) @@ -52,7 +52,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void if (!data->repeat) { free(data); - us_timer_close(t); + us_timer_close(t, 0); } }, ms, repeat_ms); diff --git a/packages/bun-uws/capi/examples/UpgradeAsync.c b/packages/bun-uws/capi/examples/UpgradeAsync.c index 3dacd8c8e35963..8c6e735420df75 100644 --- a/packages/bun-uws/capi/examples/UpgradeAsync.c +++ b/packages/bun-uws/capi/examples/UpgradeAsync.c @@ -62,7 +62,7 @@ void uws_timer_close(struct us_timer_t *timer) struct timer_handler_data *data; memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *)); free(data); - us_timer_close(t); + us_timer_close(t, 0); } //Timer create helper struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data) @@ -95,7 +95,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void if (!data->repeat) { free(data); - us_timer_close(t); + us_timer_close(t, 0); } }, ms, repeat_ms); diff --git a/packages/bun-uws/examples/UpgradeAsync.cpp b/packages/bun-uws/examples/UpgradeAsync.cpp index 0c5301be4db408..045605831ff2e9 100644 --- a/packages/bun-uws/examples/UpgradeAsync.cpp +++ b/packages/bun-uws/examples/UpgradeAsync.cpp @@ -90,7 +90,7 @@ int main() { delete upgradeData; - us_timer_close(t); + us_timer_close(t, 0); }, 5000, 0); }, diff --git a/packages/bun-uws/src/Loop.h b/packages/bun-uws/src/Loop.h index d3ca45b58417a3..7311dd9765e44c 100644 --- a/packages/bun-uws/src/Loop.h +++ b/packages/bun-uws/src/Loop.h @@ -126,7 +126,7 @@ struct Loop { LoopData *loopData = (LoopData *) us_loop_ext((us_loop_t *) this); /* Stop and free dateTimer first */ - us_timer_close(loopData->dateTimer); + us_timer_close(loopData->dateTimer, 1); loopData->~LoopData(); /* uSockets will track whether this loop is owned by us or a borrowed alien loop */ diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig index 0862e41ec53e40..21c2ecd0e1be36 100644 --- a/src/bun.js/api/bun.zig +++ b/src/bun.js/api/bun.zig @@ -3604,7 +3604,7 @@ pub const Timer = struct { this.poll_ref.unref(vm); - this.timer.deinit(); + this.timer.deinit(false); // balance double unreffing in doUnref vm.event_loop_handle.?.num_polls += @as(i32, @intFromBool(this.did_unref_timer)); diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index 278e62327d0f10..8bc6a771e9b5ac 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -1148,7 +1148,7 @@ pub const EventLoop = struct { pub fn callTask(timer: *uws.Timer) callconv(.C) void { var task = Task.from(timer.as(*anyopaque)); - timer.deinit(); + defer timer.deinit(true); JSC.VirtualMachine.get().enqueueTask(task); } diff --git a/src/bun.js/node/node_fs_stat_watcher.zig b/src/bun.js/node/node_fs_stat_watcher.zig index 3bf262f0754e5b..158a08ff738094 100644 --- a/src/bun.js/node/node_fs_stat_watcher.zig +++ b/src/bun.js/node/node_fs_stat_watcher.zig @@ -97,7 +97,7 @@ pub const StatWatcherScheduler = struct { prev = next; } else { if (this.head.load(.Monotonic) == null) { - this.timer.?.deinit(); + this.timer.?.deinit(false); this.timer = null; // The scheduler is not deinit here, but it will get reused. } diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index 0e80adfc4a54aa..44f6fbe56ae276 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -778,27 +778,28 @@ pub const Fetch = struct { if (!success) { const err = this.onReject(); err.ensureStillAlive(); + // if we are streaming update with error + if (this.readable_stream_ref.get()) |readable| { + readable.ptr.Bytes.onData( + .{ + .err = .{ .JSValue = err }, + }, + bun.default_allocator, + ); + return; + } + // if we are buffering resolve the promise if (this.response.get()) |response_js| { if (response_js.as(Response)) |response| { const body = response.body; - if (body.value == .Locked) { - if (body.value.Locked.readable) |readable| { - readable.ptr.Bytes.onData( - .{ - .err = .{ .JSValue = err }, - }, - bun.default_allocator, - ); - return; - } + if (body.value.Locked.promise) |promise_| { + const promise = promise_.asAnyPromise().?; + promise.reject(globalThis, err); } - + response.body.value.toErrorInstance(err, globalThis); - return; } } - - globalThis.throwValue(err); return; } @@ -1708,7 +1709,7 @@ pub const Fetch = struct { if (decompress.isBoolean()) { disable_decompression = !decompress.asBoolean(); } else if (decompress.isNumber()) { - disable_keepalive = decompress.to(i32) == 0; + disable_decompression = decompress.to(i32) == 0; } } @@ -1901,7 +1902,7 @@ pub const Fetch = struct { if (decompress.isBoolean()) { disable_decompression = !decompress.asBoolean(); } else if (decompress.isNumber()) { - disable_keepalive = decompress.to(i32) == 0; + disable_decompression = decompress.to(i32) == 0; } } diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 2e6bbdce2ac3c9..e0707436a76334 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -3596,6 +3596,9 @@ pub const ByteStream = struct { this.buffer = try std.ArrayList(u8).initCapacity(bun.default_allocator, chunk.len); this.buffer.appendSliceAssumeCapacity(chunk); }, + .err => { + this.pending.result = .{ .err = stream.err }; + }, else => unreachable, } return; @@ -3605,6 +3608,9 @@ pub const ByteStream = struct { .temporary_and_done, .temporary => { try this.buffer.appendSlice(chunk); }, + .err => { + this.pending.result = .{ .err = stream.err }; + }, // We don't support the rest of these yet else => unreachable, } diff --git a/src/deps/uws.zig b/src/deps/uws.zig index 1d6bae0c0dd029..f3138c8b98d12d 100644 --- a/src/deps/uws.zig +++ b/src/deps/uws.zig @@ -700,9 +700,9 @@ pub const Timer = opaque { @as(*@TypeOf(ptr), @ptrCast(@alignCast(value_ptr))).* = ptr; } - pub fn deinit(this: *Timer) void { + pub fn deinit(this: *Timer, comptime fallthrough: bool) void { debug("Timer.deinit()", .{}); - us_timer_close(this); + us_timer_close(this, @intFromBool(fallthrough)); } pub fn ext(this: *Timer, comptime Type: type) ?*Type { @@ -946,7 +946,7 @@ const uintmax_t = c_ulong; extern fn us_create_timer(loop: ?*Loop, fallthrough: i32, ext_size: c_uint) *Timer; extern fn us_timer_ext(timer: ?*Timer) *?*anyopaque; -extern fn us_timer_close(timer: ?*Timer) void; +extern fn us_timer_close(timer: ?*Timer, fallthrough: i32) void; extern fn us_timer_set(timer: ?*Timer, cb: ?*const fn (*Timer) callconv(.C) void, ms: i32, repeat_ms: i32) void; extern fn us_timer_loop(t: ?*Timer) ?*Loop; pub const us_socket_context_options_t = extern struct { diff --git a/src/http_client_async.zig b/src/http_client_async.zig index bbcc28252f4fd8..8c8cd6eeb7e5bc 100644 --- a/src/http_client_async.zig +++ b/src/http_client_async.zig @@ -476,11 +476,12 @@ fn NewHTTPContext(comptime ssl: bool) type { std.debug.assert(context().pending_sockets.put(pooled)); } - socket.ext(**anyopaque).?.* = bun.cast(**anyopaque, ActiveSocket.init(&dead_socket).ptr()); - socket.close(0, null); - if (comptime Environment.allow_assert) { - std.debug.assert(false); + // we can reach here if we are aborted + if (!socket.isClosed()) { + socket.ext(**anyopaque).?.* = bun.cast(**anyopaque, ActiveSocket.init(&dead_socket).ptr()); + socket.close(0, null); } + } pub fn onClose( ptr: *anyopaque, @@ -1104,7 +1105,7 @@ pub fn onClose( } if (in_progress) { - client.fail(error.ConnectionClosed); + client.closeAndFail(error.ConnectionClosed, is_ssl, socket); } } pub fn onTimeout( @@ -2900,9 +2901,7 @@ fn fail(this: *HTTPClient, err: anyerror) void { _ = socket_async_http_abort_tracker.swapRemove(this.async_http_id); } - this.state.reset(this.allocator); - this.proxy_tunneling = false; - + this.state.request_stage = .fail; this.state.response_stage = .fail; this.state.fail = err; @@ -2910,6 +2909,9 @@ fn fail(this: *HTTPClient, err: anyerror) void { const callback = this.result_callback; const result = this.toResult(); + this.state.reset(this.allocator); + this.proxy_tunneling = false; + callback.run(result); } @@ -2917,9 +2919,6 @@ fn fail(this: *HTTPClient, err: anyerror) void { fn cloneMetadata(this: *HTTPClient) void { std.debug.assert(this.state.pending_response != null); if (this.state.pending_response) |response| { - // we should never clone metadata twice - std.debug.assert(this.state.cloned_metadata == null); - // just in case we check and free if (this.state.cloned_metadata != null) { this.state.cloned_metadata.?.deinit(this.allocator); this.state.cloned_metadata = null; diff --git a/test/js/web/abort/abort.test.ts b/test/js/web/abort/abort.test.ts index 4895e0d137fc31..1a057ef7c97222 100644 --- a/test/js/web/abort/abort.test.ts +++ b/test/js/web/abort/abort.test.ts @@ -18,4 +18,23 @@ describe("AbortSignal", () => { expect(stderr?.toString()).not.toContain("✗"); }); + + test("AbortSignal.timeout(n) should not freeze the process", async () => { + + const fileName = join(import.meta.dir, "abort.signal.ts"); + + const server = Bun.spawn({ + cmd: [bunExe(), fileName], + env: bunEnv, + cwd: tmpdir(), + }); + + const exitCode = await Promise.race([server.exited, (async () => { + await Bun.sleep(5000); + server.kill(); + return 2; + })()]) + + expect(exitCode).toBe(0); + }); }); From d9f12a26bb54ef5fe764ca98343723ff867e1fe3 Mon Sep 17 00:00:00 2001 From: cirospaciari Date: Mon, 9 Oct 2023 21:46:20 -0300 Subject: [PATCH 2/2] fix fetch error and lock behavior --- src/bun.js/api/ffi.zig | 4 +- src/bun.js/bindings/ZigGlobalObject.cpp | 1 + src/bun.js/bindings/bindings.cpp | 8 ++ src/bun.js/webcore/body.zig | 11 +- src/bun.js/webcore/response.zig | 3 +- src/bun.js/webcore/streams.zig | 7 + src/http_client_async.zig | 2 - src/js/builtins/BunBuiltinNames.h | 1 + src/js/builtins/ReadableStream.ts | 9 ++ src/js/node/http.ts | 2 +- src/js/out/InternalModuleRegistryConstants.h | 6 +- src/js/out/ResolvedSourceTag.zig | 10 +- src/js/out/WebCoreJSBuiltins.cpp | 8 ++ src/js/out/WebCoreJSBuiltins.h | 11 ++ test/js/web/abort/abort.signal.ts | 24 ++++ test/js/web/abort/abort.test.ts | 14 +- test/js/web/fetch/fetch.stream.test.ts | 136 +++++++++++++++++++ 17 files changed, 233 insertions(+), 24 deletions(-) create mode 100644 test/js/web/abort/abort.signal.ts diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index 234b588887bade..a7a03e7840054f 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -317,9 +317,9 @@ pub const FFI = struct { }; }; }; - + var size = symbols.values().len; - if(size >= 63) { + if (size >= 63) { size = 0; } var obj = JSC.JSValue.createEmptyObject(global, size); diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index b9670f730186f8..777e398d38bea6 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -3717,6 +3717,7 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) putDirectBuiltinFunction(vm, this, builtinNames.createFIFOPrivateName(), streamInternalsCreateFIFOCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.createEmptyReadableStreamPrivateName(), readableStreamCreateEmptyReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); + putDirectBuiltinFunction(vm, this, builtinNames.createUsedReadableStreamPrivateName(), readableStreamCreateUsedReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.consumeReadableStreamPrivateName(), readableStreamConsumeReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.createNativeReadableStreamPrivateName(), readableStreamCreateNativeReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.requireESMPrivateName(), importMetaObjectRequireESMCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 9ba053a238ff99..2efbde7b04d182 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -2165,6 +2165,14 @@ JSC__JSValue ReadableStream__empty(Zig::GlobalObject* globalObject) return JSValue::encode(JSC::call(globalObject, function, JSC::ArgList(), "ReadableStream.create"_s)); } +JSC__JSValue ReadableStream__used(Zig::GlobalObject* globalObject) +{ + auto& vm = globalObject->vm(); + auto clientData = WebCore::clientData(vm); + auto* function = globalObject->getDirect(vm, clientData->builtinNames().createUsedReadableStreamPrivateName()).getObject(); + return JSValue::encode(JSC::call(globalObject, function, JSC::ArgList(), "ReadableStream.create"_s)); +} + JSC__JSValue JSC__JSValue__createRangeError(const ZigString* message, const ZigString* arg1, JSC__JSGlobalObject* globalObject) { diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index bbdf21d5d13572..76cda1badec6a2 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -466,7 +466,10 @@ pub const Body = struct { JSC.markBinding(@src()); switch (this.*) { - .Used, .Empty => { + .Used => { + return JSC.WebCore.ReadableStream.used(globalThis); + }, + .Empty => { return JSC.WebCore.ReadableStream.empty(globalThis); }, .Null => { @@ -493,6 +496,9 @@ pub const Body = struct { if (locked.readable) |readable| { return readable.value; } + if (locked.promise != null) { + return JSC.WebCore.ReadableStream.used(globalThis); + } var drain_result: JSC.WebCore.DrainResult = .{ .estimated_size = 0, }; @@ -1104,8 +1110,7 @@ pub fn BodyMixin(comptime Type: type) type { var body: *Body.Value = this.getBodyValue(); if (body.* == .Used) { - // TODO: make this closed - return JSC.WebCore.ReadableStream.empty(globalThis); + return JSC.WebCore.ReadableStream.used(globalThis); } return body.toReadableStream(globalThis); diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index 44f6fbe56ae276..9a2ec48ba49807 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -786,7 +786,6 @@ pub const Fetch = struct { }, bun.default_allocator, ); - return; } // if we are buffering resolve the promise if (this.response.get()) |response_js| { @@ -796,7 +795,7 @@ pub const Fetch = struct { const promise = promise_.asAnyPromise().?; promise.reject(globalThis, err); } - + response.body.value.toErrorInstance(err, globalThis); } } diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index e0707436a76334..1f95659e222340 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -225,6 +225,7 @@ pub const ReadableStream = struct { extern fn ReadableStream__isDisturbed(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool; extern fn ReadableStream__isLocked(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool; extern fn ReadableStream__empty(*JSGlobalObject) JSC.JSValue; + extern fn ReadableStream__used(*JSGlobalObject) JSC.JSValue; extern fn ReadableStream__cancel(stream: JSValue, *JSGlobalObject) void; extern fn ReadableStream__abort(stream: JSValue, *JSGlobalObject) void; extern fn ReadableStream__detach(stream: JSValue, *JSGlobalObject) void; @@ -367,6 +368,12 @@ pub const ReadableStream = struct { return ReadableStream__empty(globalThis); } + pub fn used(globalThis: *JSGlobalObject) JSC.JSValue { + JSC.markBinding(@src()); + + return ReadableStream__used(globalThis); + } + const Base = @import("../../ast/base.zig"); pub const StreamTag = enum(usize) { invalid = 0, diff --git a/src/http_client_async.zig b/src/http_client_async.zig index 8c8cd6eeb7e5bc..a8206e17d8c3a6 100644 --- a/src/http_client_async.zig +++ b/src/http_client_async.zig @@ -481,7 +481,6 @@ fn NewHTTPContext(comptime ssl: bool) type { socket.ext(**anyopaque).?.* = bun.cast(**anyopaque, ActiveSocket.init(&dead_socket).ptr()); socket.close(0, null); } - } pub fn onClose( ptr: *anyopaque, @@ -2901,7 +2900,6 @@ fn fail(this: *HTTPClient, err: anyerror) void { _ = socket_async_http_abort_tracker.swapRemove(this.async_http_id); } - this.state.request_stage = .fail; this.state.response_stage = .fail; this.state.fail = err; diff --git a/src/js/builtins/BunBuiltinNames.h b/src/js/builtins/BunBuiltinNames.h index d124a76833696b..3b29b75b2bd9d6 100644 --- a/src/js/builtins/BunBuiltinNames.h +++ b/src/js/builtins/BunBuiltinNames.h @@ -72,6 +72,7 @@ using namespace JSC; macro(createInternalModuleById) \ macro(createNativeReadableStream) \ macro(createReadableStream) \ + macro(createUsedReadableStream) \ macro(createUninitializedArrayBuffer) \ macro(createWritableStreamFromInternal) \ macro(cwd) \ diff --git a/src/js/builtins/ReadableStream.ts b/src/js/builtins/ReadableStream.ts index 419a8e696c47ea..c1d43a43059cba 100644 --- a/src/js/builtins/ReadableStream.ts +++ b/src/js/builtins/ReadableStream.ts @@ -290,6 +290,15 @@ export function createEmptyReadableStream() { return stream; } +$linkTimeConstant; +export function createUsedReadableStream() { + var stream = new ReadableStream({ + pull() {}, + } as any); + stream.getReader(); + return stream; +} + $linkTimeConstant; export function createNativeReadableStream(nativePtr, nativeType, autoAllocateChunkSize) { return new ReadableStream({ diff --git a/src/js/node/http.ts b/src/js/node/http.ts index 17dfc40404086c..5a7f1107d20b5c 100644 --- a/src/js/node/http.ts +++ b/src/js/node/http.ts @@ -662,7 +662,7 @@ class IncomingMessage extends Readable { if (this.#aborted) return; if (done) { this.push(null); - this.destroy(); + process.nextTick(destroyBodyStreamNT, this); break; } for (var v of value) { diff --git a/src/js/out/InternalModuleRegistryConstants.h b/src/js/out/InternalModuleRegistryConstants.h index 02529d8b984365..292e291504a0bd 100644 --- a/src/js/out/InternalModuleRegistryConstants.h +++ b/src/js/out/InternalModuleRegistryConstants.h @@ -98,7 +98,7 @@ static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\"; // // -static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n};\nvar getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), this.destroy();\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n}, destroyBodyStreamNT = function(bodyStream) {\n bodyStream.destroy();\n}, getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), process.nextTick(destroyBodyStreamNT, this);\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; // // @@ -347,7 +347,7 @@ static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\"; // // -static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n};\nvar getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), this.destroy();\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n}, destroyBodyStreamNT = function(bodyStream) {\n bodyStream.destroy();\n}, getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), process.nextTick(destroyBodyStreamNT, this);\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; // // @@ -597,7 +597,7 @@ static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\"; // // -static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n};\nvar getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), this.destroy();\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";// src/js/out/tmp/node/http.ts\nvar checkInvalidHeaderChar = function(val) {\n return RegExpPrototypeExec.call(headerCharRegex, val) !== null;\n}, isIPv6 = function(input) {\n return new @RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input);\n}, isValidTLSArray = function(obj) {\n if (typeof obj === \"string\" || isTypedArray(obj) || obj instanceof @ArrayBuffer || obj instanceof Blob)\n return !0;\n if (@Array.isArray(obj)) {\n for (var i = 0;i < obj.length; i++)\n if (typeof obj !== \"string\" && !isTypedArray(obj) && !(obj instanceof @ArrayBuffer) && !(obj instanceof Blob))\n return !1;\n return !0;\n }\n}, validateMsecs = function(numberlike, field) {\n if (typeof numberlike !== \"number\" || numberlike < 0)\n throw new ERR_INVALID_ARG_TYPE(field, \"number\", numberlike);\n return numberlike;\n}, validateFunction = function(callable, field) {\n if (typeof callable !== \"function\")\n throw new ERR_INVALID_ARG_TYPE(field, \"Function\", callable);\n return callable;\n}, createServer = function(options, callback) {\n return new Server(options, callback);\n}, emitListeningNextTick = function(self, onListen, err, hostname, port) {\n if (typeof onListen === \"function\")\n try {\n onListen(err, hostname, port);\n } catch (err2) {\n self.emit(\"error\", err2);\n }\n if (self.listening = !err, err)\n self.emit(\"error\", err);\n else\n self.emit(\"listening\", hostname, port);\n}, assignHeaders = function(object, req) {\n var headers = req.headers.toJSON();\n const rawHeaders = @newArrayWithSize(req.headers.count * 2);\n var i = 0;\n for (let key in headers)\n rawHeaders[i++] = key, rawHeaders[i++] = headers[key];\n object.headers = headers, object.rawHeaders = rawHeaders;\n}, destroyBodyStreamNT = function(bodyStream) {\n bodyStream.destroy();\n}, getDefaultHTTPSAgent = function() {\n return _defaultHTTPSAgent \?\?= new Agent({ defaultPort: 443, protocol: \"https:\" });\n};\nvar urlToHttpOptions = function(url) {\n var { protocol, hostname, hash, search, pathname, href, port, username, password } = url;\n return {\n protocol,\n hostname: typeof hostname === \"string\" && StringPrototypeStartsWith.call(hostname, \"[\") \? StringPrototypeSlice.call(hostname, 1, -1) : hostname,\n hash,\n search,\n pathname,\n path: `${pathname || \"\"}${search || \"\"}`,\n href,\n port: port \? Number(port) : protocol === \"https:\" \? 443 : protocol === \"http:\" \? 80 : @undefined,\n auth: username || password \? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : @undefined\n };\n}, validateHost = function(host, name) {\n if (host !== null && host !== @undefined && typeof host !== \"string\")\n throw new Error(\"Invalid arg type in options\");\n return host;\n}, checkIsHttpToken = function(val) {\n return RegExpPrototypeExec.call(tokenRegExp, val) !== null;\n};\nvar _writeHead = function(statusCode, reason, obj, response) {\n if (statusCode |= 0, statusCode < 100 || statusCode > 999)\n throw new Error(\"status code must be between 100 and 999\");\n if (typeof reason === \"string\")\n response.statusMessage = reason;\n else {\n if (!response.statusMessage)\n response.statusMessage = STATUS_CODES[statusCode] || \"unknown\";\n obj = reason;\n }\n response.statusCode = statusCode;\n {\n let k;\n if (@Array.isArray(obj)) {\n if (obj.length % 2 !== 0)\n throw new Error(\"raw headers must have an even number of elements\");\n for (let n = 0;n < obj.length; n += 2)\n if (k = obj[n + 0], k)\n response.setHeader(k, obj[n + 1]);\n } else if (obj) {\n const keys = Object.keys(obj);\n for (let i = 0;i < keys.length; i++)\n if (k = keys[i], k)\n response.setHeader(k, obj[k]);\n }\n }\n if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199)\n response._hasBody = !1;\n}, request = function(url, options, cb) {\n return new ClientRequest(url, options, cb);\n}, get = function(url, options, cb) {\n const req = request(url, options, cb);\n return req.end(), req;\n}, $, EventEmitter = @getInternalField(@internalModuleRegistry, 20) || @createInternalModuleById(20), { isTypedArray } = @requireNativeModule(\"util/types\"), { Duplex, Readable, Writable } = @getInternalField(@internalModuleRegistry, 39) || @createInternalModuleById(39), { getHeader, setHeader } = @lazy(\"http\"), headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/, validateHeaderName = (name, label) => {\n if (typeof name !== \"string\" || !name || !checkIsHttpToken(name))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN\");\n}, validateHeaderValue = (name, value) => {\n if (value === @undefined)\n throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");\n if (checkInvalidHeaderChar(value))\n throw new Error(\"ERR_INVALID_CHAR\");\n}, { URL } = globalThis, globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch;\nvar kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for(\"kOutHeaders\"), kEndCalled = Symbol.for(\"kEndCalled\"), kAbortController = Symbol.for(\"kAbortController\"), kClearTimeout = Symbol(\"kClearTimeout\"), kCorked = Symbol.for(\"kCorked\"), searchParamsSymbol = Symbol.for(\"query\"), StringPrototypeSlice = @String.prototype.slice, StringPrototypeStartsWith = @String.prototype.startsWith, StringPrototypeToUpperCase = @String.prototype.toUpperCase, ArrayIsArray = @Array.isArray, RegExpPrototypeExec = @RegExp.prototype.exec, ObjectAssign = Object.assign, INVALID_PATH_REGEX = /[^\\u0021-\\u00ff]/;\nvar _defaultHTTPSAgent, kInternalRequest = Symbol(\"kInternalRequest\"), kInternalSocketData = Symbol.for(\"::bunternal::\"), kEmptyBuffer = @Buffer.alloc(0);\n\nclass ERR_INVALID_ARG_TYPE extends TypeError {\n constructor(name, expected, actual) {\n super(`The ${name} argument must be of type ${expected}. Received type ${typeof actual}`);\n this.code = \"ERR_INVALID_ARG_TYPE\";\n }\n}\nvar FakeSocket = class Socket extends Duplex {\n [kInternalSocketData];\n bytesRead = 0;\n bytesWritten = 0;\n connecting = !1;\n timeout = 0;\n isServer = !1;\n #address;\n address() {\n var internalData;\n return this.#address \?\?= (internalData = this[kInternalSocketData])\?.[0]\?.requestIP(internalData[2]) \?\? {};\n }\n get bufferSize() {\n return this.writableLength;\n }\n connect(port, host, connectListener) {\n return this;\n }\n _destroy(err, callback) {\n }\n _final(callback) {\n }\n get localAddress() {\n return \"127.0.0.1\";\n }\n get localFamily() {\n return \"IPv4\";\n }\n get localPort() {\n return 80;\n }\n get pending() {\n return this.connecting;\n }\n _read(size) {\n }\n get readyState() {\n if (this.connecting)\n return \"opening\";\n if (this.readable)\n return this.writable \? \"open\" : \"readOnly\";\n else\n return this.writable \? \"writeOnly\" : \"closed\";\n }\n ref() {\n }\n get remoteAddress() {\n return this.address()\?.address;\n }\n set remoteAddress(val) {\n this.address().address = val;\n }\n get remotePort() {\n return this.address()\?.port;\n }\n set remotePort(val) {\n this.address().port = val;\n }\n get remoteFamily() {\n return this.address()\?.family;\n }\n set remoteFamily(val) {\n this.address().family = val;\n }\n resetAndDestroy() {\n }\n setKeepAlive(enable = !1, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n return this;\n }\n setTimeout(timeout, callback) {\n return this;\n }\n unref() {\n }\n _write(chunk, encoding, callback) {\n }\n};\n\nclass Agent extends EventEmitter {\n defaultPort = 80;\n protocol = \"http:\";\n options;\n requests;\n sockets;\n freeSockets;\n keepAliveMsecs;\n keepAlive;\n maxSockets;\n maxFreeSockets;\n scheduling;\n maxTotalSockets;\n totalSocketCount;\n #fakeSocket;\n static get globalAgent() {\n return globalAgent;\n }\n static get defaultMaxSockets() {\n return @Infinity;\n }\n constructor(options = kEmptyObject) {\n super();\n if (this.options = options = { ...options, path: null }, options.noDelay === @undefined)\n options.noDelay = !0;\n this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || \"lifo\", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || \"http:\";\n }\n createConnection() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n getName(options = kEmptyObject) {\n let name = `http:${options.host || \"localhost\"}:`;\n if (options.port)\n name += options.port;\n if (name += \":\", options.localAddress)\n name += options.localAddress;\n if (options.family === 4 || options.family === 6)\n name += `:${options.family}`;\n if (options.socketPath)\n name += `:${options.socketPath}`;\n return name;\n }\n addRequest() {\n }\n createSocket(req, options, cb) {\n cb(null, this.#fakeSocket \?\?= new FakeSocket);\n }\n removeSocket() {\n }\n keepSocketAlive() {\n return !0;\n }\n reuseSocket() {\n }\n destroy() {\n }\n}\n\nclass Server extends EventEmitter {\n #server;\n #options;\n #tls;\n #is_tls = !1;\n listening = !1;\n serverName;\n constructor(options, callback) {\n super();\n if (typeof options === \"function\")\n callback = options, options = {};\n else if (options == null || typeof options === \"object\") {\n options = { ...options }, this.#tls = null;\n let key = options.key;\n if (key) {\n if (!isValidTLSArray(key))\n @throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let cert = options.cert;\n if (cert) {\n if (!isValidTLSArray(cert))\n @throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let ca = options.ca;\n if (ca) {\n if (!isValidTLSArray(ca))\n @throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");\n this.#is_tls = !0;\n }\n let passphrase = options.passphrase;\n if (passphrase && typeof passphrase !== \"string\")\n @throwTypeError(\"passphrase argument must be an string\");\n let serverName = options.servername;\n if (serverName && typeof serverName !== \"string\")\n @throwTypeError(\"servername argument must be an string\");\n let secureOptions = options.secureOptions || 0;\n if (secureOptions && typeof secureOptions !== \"number\")\n @throwTypeError(\"secureOptions argument must be an number\");\n if (this.#is_tls)\n this.#tls = {\n serverName,\n key,\n cert,\n ca,\n passphrase,\n secureOptions\n };\n else\n this.#tls = null;\n } else\n throw new Error(\"bun-http-polyfill: invalid arguments\");\n if (this.#options = options, callback)\n this.on(\"request\", callback);\n }\n closeAllConnections() {\n const server = this.#server;\n if (!server)\n return;\n this.#server = @undefined, server.stop(!0), this.emit(\"close\");\n }\n closeIdleConnections() {\n }\n close(optionalCallback) {\n const server = this.#server;\n if (!server) {\n if (typeof optionalCallback === \"function\")\n process.nextTick(optionalCallback, new Error(\"Server is not running\"));\n return;\n }\n if (this.#server = @undefined, typeof optionalCallback === \"function\")\n this.once(\"close\", optionalCallback);\n server.stop(), this.emit(\"close\");\n }\n address() {\n if (!this.#server)\n return null;\n const address = this.#server.hostname;\n return {\n address,\n family: isIPv6(address) \? \"IPv6\" : \"IPv4\",\n port: this.#server.port\n };\n }\n listen(port, host, backlog, onListen) {\n const server = this;\n let socketPath;\n if (typeof port == \"string\" && !Number.isSafeInteger(Number(port)))\n socketPath = port;\n if (typeof host === \"function\")\n onListen = host, host = @undefined;\n if (typeof port === \"function\")\n onListen = port;\n else if (typeof port === \"object\") {\n if (port\?.signal\?.addEventListener(\"abort\", () => {\n this.close();\n }), host = port\?.host, port = port\?.port, typeof port\?.callback === \"function\")\n onListen = port\?.callback;\n }\n if (typeof backlog === \"function\")\n onListen = backlog;\n const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage;\n try {\n const tls = this.#tls;\n if (tls)\n this.serverName = tls.serverName || host || \"localhost\";\n this.#server = Bun.serve({\n tls,\n port,\n hostname: host,\n unix: socketPath,\n websocket: {\n open(ws) {\n ws.data.open(ws);\n },\n message(ws, message) {\n ws.data.message(ws, message);\n },\n close(ws, code, reason) {\n ws.data.close(ws, code, reason);\n },\n drain(ws) {\n ws.data.drain(ws);\n }\n },\n fetch(req, _server) {\n var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => {\n if (pendingError)\n return;\n if (pendingError = err, rejectFunction)\n rejectFunction(err);\n }, reply = function(resp) {\n if (pendingResponse)\n return;\n if (pendingResponse = resp, resolveFunction)\n resolveFunction(resp);\n };\n const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req });\n if (http_req.socket[kInternalSocketData] = [_server, http_res, req], http_req.once(\"error\", (err) => reject(err)), http_res.once(\"error\", (err) => reject(err)), req.headers.get(\"upgrade\"))\n server.emit(\"upgrade\", http_req, http_req.socket, kEmptyBuffer);\n else\n server.emit(\"request\", http_req, http_res);\n if (pendingError)\n throw pendingError;\n if (pendingResponse)\n return pendingResponse;\n return new @Promise((resolve, reject2) => {\n resolveFunction = resolve, rejectFunction = reject2;\n });\n }\n }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port);\n } catch (err) {\n server.emit(\"error\", err);\n }\n return this;\n }\n setTimeout(msecs, callback) {\n }\n}\nclass IncomingMessage extends Readable {\n method;\n complete;\n constructor(req, defaultIncomingOpts) {\n const method = req.method;\n super();\n const url = new URL(req.url);\n var { type = \"request\", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {};\n this.#noBody = type === \"request\" \? method === \"GET\" || method === \"HEAD\" || method === \"TRACE\" || method === \"CONNECT\" || method === \"OPTIONS\" || (parseInt(req.headers.get(\"Content-Length\") || \"\") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = @undefined;\n const socket = new FakeSocket;\n if (url.protocol === \"https:\")\n socket.encrypted = !0;\n this.#fakeSocket = socket, this.url = url.pathname + url.search, this.req = nodeReq, assignHeaders(this, req);\n }\n headers;\n rawHeaders;\n _consuming = !1;\n _dumped = !1;\n #bodyStream;\n #fakeSocket;\n #noBody = !1;\n #aborted = !1;\n #req;\n url;\n #type;\n _construct(callback) {\n if (this.#type === \"response\" || this.#noBody) {\n callback();\n return;\n }\n const contentLength = this.#req.headers.get(\"content-length\");\n if ((contentLength \? parseInt(contentLength, 10) : 0) === 0) {\n this.#noBody = !0, callback();\n return;\n }\n callback();\n }\n async#consumeStream(reader) {\n while (!0) {\n var { done, value } = await reader.readMany();\n if (this.#aborted)\n return;\n if (done) {\n this.push(null), process.nextTick(destroyBodyStreamNT, this);\n break;\n }\n for (var v of value)\n this.push(v);\n }\n }\n _read(size) {\n if (this.#noBody)\n this.push(null), this.complete = !0;\n else if (this.#bodyStream == null) {\n const reader = this.#req.body\?.getReader();\n if (!reader) {\n this.push(null);\n return;\n }\n this.#bodyStream = reader, this.#consumeStream(reader);\n }\n }\n get aborted() {\n return this.#aborted;\n }\n #abort() {\n if (this.#aborted)\n return;\n this.#aborted = !0;\n var bodyStream = this.#bodyStream;\n if (!bodyStream)\n return;\n bodyStream.cancel(), this.complete = !0, this.#bodyStream = @undefined, this.push(null);\n }\n get connection() {\n return this.#fakeSocket;\n }\n get statusCode() {\n return this.#req.status;\n }\n get statusMessage() {\n return STATUS_CODES[this.#req.status];\n }\n get httpVersion() {\n return \"1.1\";\n }\n get rawTrailers() {\n return [];\n }\n get httpVersionMajor() {\n return 1;\n }\n get httpVersionMinor() {\n return 1;\n }\n get trailers() {\n return kEmptyObject;\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n}\n\nclass OutgoingMessage extends Writable {\n constructor() {\n super(...arguments);\n }\n #headers;\n headersSent = !1;\n sendDate = !0;\n req;\n timeout;\n #finished = !1;\n [kEndCalled] = !1;\n #fakeSocket;\n #timeoutTimer;\n [kAbortController] = null;\n _implicitHeader() {\n }\n get headers() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n get socket() {\n return this.#fakeSocket \?\?= new FakeSocket;\n }\n set socket(val) {\n this.#fakeSocket = val;\n }\n get connection() {\n return this.socket;\n }\n get finished() {\n return this.#finished;\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n if (!this.#headers)\n return kEmptyObject;\n return this.#headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return headers.set(name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.removeAllListeners(\"timeout\"), this.#timeoutTimer = @undefined;\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar OriginalWriteHeadFn, OriginalImplicitHeadFn;\n\nclass ServerResponse extends Writable {\n constructor(c) {\n super();\n if (!c)\n c = {};\n var req = c.req || {}, reply = c.reply;\n if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = @undefined, this.#controller = @undefined, this.#firstWrite = @undefined, this._writableState.decodeStrings = !1, this.#deferred = @undefined, req.method === \"HEAD\")\n this._hasBody = !1;\n }\n req;\n _reply;\n sendDate;\n statusCode;\n #headers;\n headersSent = !1;\n statusMessage;\n #controller;\n #firstWrite;\n _sent100 = !1;\n _defaultKeepAlive = !1;\n _removedConnection = !1;\n _removedContLen = !1;\n _hasBody = !0;\n #deferred = @undefined;\n #finished = !1;\n _implicitHeader() {\n this.writeHead(this.statusCode);\n }\n _write(chunk, encoding, callback) {\n if (!this.#firstWrite && !this.headersSent) {\n this.#firstWrite = chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n controller.write(chunk), callback();\n });\n }\n _writev(chunks, callback) {\n if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) {\n this.#firstWrite = chunks[0].chunk, callback();\n return;\n }\n this.#ensureReadableStreamController((controller) => {\n for (let chunk of chunks)\n controller.write(chunk.chunk);\n callback();\n });\n }\n #ensureReadableStreamController(run) {\n var thisController = this.#controller;\n if (thisController)\n return run(thisController);\n this.headersSent = !0;\n var firstWrite = this.#firstWrite;\n this.#firstWrite = @undefined, this._reply(new Response(new @ReadableStream({\n type: \"direct\",\n pull: (controller) => {\n if (this.#controller = controller, firstWrite)\n controller.write(firstWrite);\n if (firstWrite = @undefined, run(controller), !this.#finished)\n return new @Promise((resolve) => {\n this.#deferred = resolve;\n });\n }\n }), {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n }));\n }\n #drainHeadersIfObservable() {\n if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn)\n return;\n this._implicitHeader();\n }\n _final(callback) {\n if (!this.headersSent) {\n var data = this.#firstWrite || \"\";\n this.#firstWrite = @undefined, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, {\n headers: this.#headers,\n status: this.statusCode,\n statusText: this.statusMessage \?\? STATUS_CODES[this.statusCode]\n })), callback && callback();\n return;\n }\n this.#finished = !0, this.#ensureReadableStreamController((controller) => {\n controller.end(), callback();\n var deferred = this.#deferred;\n if (deferred)\n this.#deferred = @undefined, deferred();\n });\n }\n writeProcessing() {\n throw new Error(\"not implemented\");\n }\n addTrailers(headers) {\n throw new Error(\"not implemented\");\n }\n assignSocket(socket) {\n throw new Error(\"not implemented\");\n }\n detachSocket(socket) {\n throw new Error(\"not implemented\");\n }\n writeContinue(callback) {\n throw new Error(\"not implemented\");\n }\n setTimeout(msecs, callback) {\n throw new Error(\"not implemented\");\n }\n get shouldKeepAlive() {\n return !0;\n }\n get chunkedEncoding() {\n return !1;\n }\n set chunkedEncoding(value) {\n }\n set shouldKeepAlive(value) {\n }\n get useChunkedEncodingByDefault() {\n return !0;\n }\n set useChunkedEncodingByDefault(value) {\n }\n appendHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n headers.append(name, value);\n }\n flushHeaders() {\n }\n getHeader(name) {\n return getHeader(this.#headers, name);\n }\n getHeaders() {\n var headers = this.#headers;\n if (!headers)\n return kEmptyObject;\n return headers.toJSON();\n }\n getHeaderNames() {\n var headers = this.#headers;\n if (!headers)\n return [];\n return @Array.from(headers.keys());\n }\n removeHeader(name) {\n if (!this.#headers)\n return;\n this.#headers.delete(name);\n }\n setHeader(name, value) {\n var headers = this.#headers \?\?= new Headers;\n return setHeader(headers, name, value), this;\n }\n hasHeader(name) {\n if (!this.#headers)\n return !1;\n return this.#headers.has(name);\n }\n writeHead(statusCode, statusMessage, headers) {\n return _writeHead(statusCode, statusMessage, headers, this), this;\n }\n}\nOriginalWriteHeadFn = ServerResponse.prototype.writeHead;\nOriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader;\n\nclass ClientRequest extends OutgoingMessage {\n #timeout;\n #res = null;\n #upgradeOrConnect = !1;\n #parser = null;\n #maxHeadersCount = null;\n #reusedSocket = !1;\n #host;\n #protocol;\n #method;\n #port;\n #useDefaultPort;\n #joinDuplicateHeaders;\n #maxHeaderSize;\n #agent = globalAgent;\n #path;\n #socketPath;\n #bodyChunks = null;\n #fetchRequest;\n #signal = null;\n [kAbortController] = null;\n #timeoutTimer = @undefined;\n #options;\n #finished;\n get path() {\n return this.#path;\n }\n get port() {\n return this.#port;\n }\n get method() {\n return this.#method;\n }\n get host() {\n return this.#host;\n }\n get protocol() {\n return this.#protocol;\n }\n _write(chunk, encoding, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = [chunk], callback();\n return;\n }\n this.#bodyChunks.push(chunk), callback();\n }\n _writev(chunks, callback) {\n if (!this.#bodyChunks) {\n this.#bodyChunks = chunks, callback();\n return;\n }\n this.#bodyChunks.push(...chunks), callback();\n }\n _final(callback) {\n if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener(\"abort\", () => {\n this[kClearTimeout]();\n }), this.#signal\?.aborted)\n this[kAbortController].abort();\n var method = this.#method, body = this.#bodyChunks\?.length === 1 \? this.#bodyChunks[0] : @Buffer.concat(this.#bodyChunks || []);\n let url, proxy;\n if (this.#path.startsWith(\"http://\") || this.#path.startsWith(\"https://\"))\n url = this.#path, proxy = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}`;\n else\n url = `${this.#protocol}//${this.#host}${this.#useDefaultPort \? \"\" : \":\" + this.#port}${this.#path}`;\n try {\n this.#fetchRequest = fetch(url, {\n method,\n headers: this.getHeaders(),\n body: body && method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" \? body : @undefined,\n redirect: \"manual\",\n verbose: !1,\n signal: this[kAbortController].signal,\n proxy,\n timeout: !1,\n decompress: !1\n }).then((response) => {\n var res = this.#res = new IncomingMessage(response, {\n type: \"response\",\n [kInternalRequest]: this\n });\n this.emit(\"response\", res);\n }).catch((err) => {\n this.emit(\"error\", err);\n }).finally(() => {\n this.#fetchRequest = null, this[kClearTimeout]();\n });\n } catch (err) {\n this.emit(\"error\", err);\n } finally {\n callback();\n }\n }\n get aborted() {\n return this.#signal\?.aborted || !!this[kAbortController]\?.signal.aborted;\n }\n abort() {\n if (this.aborted)\n return;\n this[kAbortController].abort();\n }\n constructor(input, options, cb) {\n super();\n if (typeof input === \"string\") {\n const urlStr = input;\n try {\n var urlObject = new URL(urlStr);\n } catch (e) {\n @throwTypeError(`Invalid URL: ${urlStr}`);\n }\n input = urlToHttpOptions(urlObject);\n } else if (input && typeof input === \"object\" && input instanceof URL)\n input = urlToHttpOptions(input);\n else\n cb = options, options = input, input = null;\n if (typeof options === \"function\")\n cb = options, options = input || kEmptyObject;\n else\n options = ObjectAssign(input || {}, options);\n var defaultAgent = options._defaultAgent || Agent.globalAgent;\n let protocol = options.protocol;\n if (!protocol)\n if (options.port === 443)\n protocol = \"https:\";\n else\n protocol = defaultAgent.protocol || \"http:\";\n switch (this.#protocol = protocol, this.#agent\?.protocol) {\n case @undefined:\n break;\n case \"http:\":\n if (protocol === \"https:\") {\n defaultAgent = this.#agent = getDefaultHTTPSAgent();\n break;\n }\n case \"https:\":\n if (protocol === \"https\") {\n defaultAgent = this.#agent = Agent.globalAgent;\n break;\n }\n default:\n break;\n }\n if (options.path) {\n const path = @String(options.path);\n if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null)\n throw new Error(\"Path contains unescaped characters\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\" && protocol) {\n const expectedProtocol = defaultAgent\?.protocol \?\? \"http:\";\n throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`);\n }\n const defaultPort = protocol === \"https:\" \? 443 : 80;\n this.#port = options.port || options.defaultPort || this.#agent\?.defaultPort || defaultPort, this.#useDefaultPort = this.#port === defaultPort;\n const host = this.#host = options.host = validateHost(options.hostname, \"hostname\") || validateHost(options.host, \"host\") || \"localhost\";\n this.#socketPath = options.socketPath;\n const signal = options.signal;\n if (signal)\n signal.addEventListener(\"abort\", () => {\n this[kAbortController]\?.abort();\n }), this.#signal = signal;\n let method = options.method;\n const methodIsString = typeof method === \"string\";\n if (method !== null && method !== @undefined && !methodIsString)\n throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");\n if (methodIsString && method) {\n if (!checkIsHttpToken(method))\n throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");\n method = this.#method = StringPrototypeToUpperCase.call(method);\n } else\n method = this.#method = \"GET\";\n const _maxHeaderSize = options.maxHeaderSize;\n this.#maxHeaderSize = _maxHeaderSize;\n var _joinDuplicateHeaders = options.joinDuplicateHeaders;\n if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || \"/\", cb)\n this.once(\"response\", cb);\n this.#finished = !1, this.#res = null, this.#upgradeOrConnect = !1, this.#parser = null, this.#maxHeadersCount = null, this.#reusedSocket = !1, this.#host = host, this.#protocol = protocol;\n var timeout = options.timeout;\n if (timeout !== @undefined && timeout !== 0)\n this.setTimeout(timeout, @undefined);\n if (!ArrayIsArray(headers)) {\n var headers = options.headers;\n if (headers)\n for (let key in headers)\n this.setHeader(key, headers[key]);\n var auth = options.auth;\n if (auth && !this.getHeader(\"Authorization\"))\n this.setHeader(\"Authorization\", \"Basic \" + @Buffer.from(auth).toString(\"base64\"));\n }\n var { signal: _signal, ...optsWithoutSignal } = options;\n this.#options = optsWithoutSignal;\n }\n setSocketKeepAlive(enable = !0, initialDelay = 0) {\n }\n setNoDelay(noDelay = !0) {\n }\n [kClearTimeout]() {\n if (this.#timeoutTimer)\n clearTimeout(this.#timeoutTimer), this.#timeoutTimer = @undefined, this.removeAllListeners(\"timeout\");\n }\n #onTimeout() {\n this.#timeoutTimer = @undefined, this[kAbortController]\?.abort(), this.emit(\"timeout\");\n }\n setTimeout(msecs, callback) {\n if (this.destroyed)\n return this;\n if (this.timeout = msecs = validateMsecs(msecs, \"msecs\"), clearTimeout(this.#timeoutTimer), msecs === 0) {\n if (callback !== @undefined)\n validateFunction(callback, \"callback\"), this.removeListener(\"timeout\", callback);\n this.#timeoutTimer = @undefined;\n } else if (this.#timeoutTimer = setTimeout(this.#onTimeout.bind(this), msecs).unref(), callback !== @undefined)\n validateFunction(callback, \"callback\"), this.once(\"timeout\", callback);\n return this;\n }\n}\nvar tokenRegExp = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/, METHODS = [\n \"ACL\",\n \"BIND\",\n \"CHECKOUT\",\n \"CONNECT\",\n \"COPY\",\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"LINK\",\n \"LOCK\",\n \"M-SEARCH\",\n \"MERGE\",\n \"MKACTIVITY\",\n \"MKCALENDAR\",\n \"MKCOL\",\n \"MOVE\",\n \"NOTIFY\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PROPFIND\",\n \"PROPPATCH\",\n \"PURGE\",\n \"PUT\",\n \"REBIND\",\n \"REPORT\",\n \"SEARCH\",\n \"SOURCE\",\n \"SUBSCRIBE\",\n \"TRACE\",\n \"UNBIND\",\n \"UNLINK\",\n \"UNLOCK\",\n \"UNSUBSCRIBE\"\n], STATUS_CODES = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a Teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 509: \"Bandwidth Limit Exceeded\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\"\n}, globalAgent = new Agent;\n$ = {\n Agent,\n Server,\n METHODS,\n STATUS_CODES,\n createServer,\n ServerResponse,\n IncomingMessage,\n request,\n get,\n maxHeaderSize: 16384,\n validateHeaderName,\n validateHeaderValue,\n setMaxIdleHTTPParsers(max) {\n },\n globalAgent,\n ClientRequest,\n OutgoingMessage\n};\nreturn $})\n"_s; // // diff --git a/src/js/out/ResolvedSourceTag.zig b/src/js/out/ResolvedSourceTag.zig index 4c2a99065ef3cd..d8c74e4dc9e961 100644 --- a/src/js/out/ResolvedSourceTag.zig +++ b/src/js/out/ResolvedSourceTag.zig @@ -64,16 +64,16 @@ pub const ResolvedSourceTag = enum(u32) { @"node:wasi" = 563, @"node:worker_threads" = 564, @"node:zlib" = 565, - @"depd" = 566, + depd = 566, @"detect-libc" = 567, @"detect-libc/linux" = 568, @"isomorphic-fetch" = 569, @"node-fetch" = 570, - @"undici" = 571, - @"vercel_fetch" = 572, - @"ws" = 573, + undici = 571, + vercel_fetch = 572, + ws = 573, // Native modules run through a different system using ESM registry. - @"bun" = 1024, + bun = 1024, @"bun:jsc" = 1025, @"node:buffer" = 1026, @"node:constants" = 1027, diff --git a/src/js/out/WebCoreJSBuiltins.cpp b/src/js/out/WebCoreJSBuiltins.cpp index 31246276b1eeae..74ec7565bfef20 100644 --- a/src/js/out/WebCoreJSBuiltins.cpp +++ b/src/js/out/WebCoreJSBuiltins.cpp @@ -1250,6 +1250,14 @@ const int s_readableStreamCreateNativeReadableStreamCodeLength = 215; static const JSC::Intrinsic s_readableStreamCreateNativeReadableStreamCodeIntrinsic = JSC::NoIntrinsic; const char* const s_readableStreamCreateNativeReadableStreamCode = "(function (nativePtr, nativeType, autoAllocateChunkSize) {\"use strict\";\n return new @ReadableStream({\n @lazy: !0,\n @bunNativeType: nativeType,\n @bunNativePtr: nativePtr,\n autoAllocateChunkSize\n });\n})\n"; +// createUsedReadableStream +const JSC::ConstructAbility s_readableStreamCreateUsedReadableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; +const JSC::ConstructorKind s_readableStreamCreateUsedReadableStreamCodeConstructorKind = JSC::ConstructorKind::None; +const JSC::ImplementationVisibility s_readableStreamCreateUsedReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Private; +const int s_readableStreamCreateUsedReadableStreamCodeLength = 130; +static const JSC::Intrinsic s_readableStreamCreateUsedReadableStreamCodeIntrinsic = JSC::NoIntrinsic; +const char* const s_readableStreamCreateUsedReadableStreamCode = "(function () {\"use strict\";\n var stream = new @ReadableStream({\n pull() {\n }\n });\n return stream.getReader(), stream;\n})\n"; + // getReader const JSC::ConstructAbility s_readableStreamGetReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamGetReaderCodeConstructorKind = JSC::ConstructorKind::None; diff --git a/src/js/out/WebCoreJSBuiltins.h b/src/js/out/WebCoreJSBuiltins.h index 3c6ade197be811..4d99333994f9b5 100644 --- a/src/js/out/WebCoreJSBuiltins.h +++ b/src/js/out/WebCoreJSBuiltins.h @@ -2382,6 +2382,14 @@ extern const JSC::ConstructAbility s_readableStreamCreateNativeReadableStreamCod extern const JSC::ConstructorKind s_readableStreamCreateNativeReadableStreamCodeConstructorKind; extern const JSC::ImplementationVisibility s_readableStreamCreateNativeReadableStreamCodeImplementationVisibility; +// createUsedReadableStream +#define WEBCORE_BUILTIN_READABLESTREAM_CREATEUSEDREADABLESTREAM 1 +extern const char* const s_readableStreamCreateUsedReadableStreamCode; +extern const int s_readableStreamCreateUsedReadableStreamCodeLength; +extern const JSC::ConstructAbility s_readableStreamCreateUsedReadableStreamCodeConstructAbility; +extern const JSC::ConstructorKind s_readableStreamCreateUsedReadableStreamCodeConstructorKind; +extern const JSC::ImplementationVisibility s_readableStreamCreateUsedReadableStreamCodeImplementationVisibility; + // getReader #define WEBCORE_BUILTIN_READABLESTREAM_GETREADER 1 extern const char* const s_readableStreamGetReaderCode; @@ -2499,6 +2507,7 @@ extern const JSC::ImplementationVisibility s_readableStreamValuesCodeImplementat macro(consumeReadableStream, readableStreamConsumeReadableStream, 3) \ macro(createEmptyReadableStream, readableStreamCreateEmptyReadableStream, 0) \ macro(createNativeReadableStream, readableStreamCreateNativeReadableStream, 3) \ + macro(createUsedReadableStream, readableStreamCreateUsedReadableStream, 0) \ macro(getReader, readableStreamGetReader, 1) \ macro(initializeReadableStream, readableStreamInitializeReadableStream, 3) \ macro(lazyAsyncIterator, readableStreamLazyAsyncIterator, 0) \ @@ -2519,6 +2528,7 @@ extern const JSC::ImplementationVisibility s_readableStreamValuesCodeImplementat macro(readableStreamConsumeReadableStreamCode, consumeReadableStream, ASCIILiteral(), s_readableStreamConsumeReadableStreamCodeLength) \ macro(readableStreamCreateEmptyReadableStreamCode, createEmptyReadableStream, ASCIILiteral(), s_readableStreamCreateEmptyReadableStreamCodeLength) \ macro(readableStreamCreateNativeReadableStreamCode, createNativeReadableStream, ASCIILiteral(), s_readableStreamCreateNativeReadableStreamCodeLength) \ + macro(readableStreamCreateUsedReadableStreamCode, createUsedReadableStream, ASCIILiteral(), s_readableStreamCreateUsedReadableStreamCodeLength) \ macro(readableStreamGetReaderCode, getReader, ASCIILiteral(), s_readableStreamGetReaderCodeLength) \ macro(readableStreamInitializeReadableStreamCode, initializeReadableStream, ASCIILiteral(), s_readableStreamInitializeReadableStreamCodeLength) \ macro(readableStreamLazyAsyncIteratorCode, lazyAsyncIterator, ASCIILiteral(), s_readableStreamLazyAsyncIteratorCodeLength) \ @@ -2539,6 +2549,7 @@ extern const JSC::ImplementationVisibility s_readableStreamValuesCodeImplementat macro(consumeReadableStream) \ macro(createEmptyReadableStream) \ macro(createNativeReadableStream) \ + macro(createUsedReadableStream) \ macro(getReader) \ macro(initializeReadableStream) \ macro(lazyAsyncIterator) \ diff --git a/test/js/web/abort/abort.signal.ts b/test/js/web/abort/abort.signal.ts new file mode 100644 index 00000000000000..da402f6378e2f2 --- /dev/null +++ b/test/js/web/abort/abort.signal.ts @@ -0,0 +1,24 @@ +import type { Server } from "bun"; + +const server = Bun.serve({ + port: 0, + async fetch() { + const signal = AbortSignal.timeout(1); + return await fetch("https://bun.sh", { signal }); + }, +}); + +function hostname(server: Server) { + if (server.hostname.startsWith(":")) return `[${server.hostname}]`; + return server.hostname; +} + +let url = `http://${hostname(server)}:${server.port}/`; + +const responses: Response[] = []; +for (let i = 0; i < 10; i++) { + responses.push(await fetch(url)); +} +server.stop(true); +// we fail if any of the requests succeeded +process.exit(responses.every(res => res.status === 500) ? 0 : 1); diff --git a/test/js/web/abort/abort.test.ts b/test/js/web/abort/abort.test.ts index 1a057ef7c97222..ef0b07a18d0aa8 100644 --- a/test/js/web/abort/abort.test.ts +++ b/test/js/web/abort/abort.test.ts @@ -20,7 +20,6 @@ describe("AbortSignal", () => { }); test("AbortSignal.timeout(n) should not freeze the process", async () => { - const fileName = join(import.meta.dir, "abort.signal.ts"); const server = Bun.spawn({ @@ -29,11 +28,14 @@ describe("AbortSignal", () => { cwd: tmpdir(), }); - const exitCode = await Promise.race([server.exited, (async () => { - await Bun.sleep(5000); - server.kill(); - return 2; - })()]) + const exitCode = await Promise.race([ + server.exited, + (async () => { + await Bun.sleep(5000); + server.kill(); + return 2; + })(), + ]); expect(exitCode).toBe(0); }); diff --git a/test/js/web/fetch/fetch.stream.test.ts b/test/js/web/fetch/fetch.stream.test.ts index 98271ee794cfb6..82c63ba53b53f6 100644 --- a/test/js/web/fetch/fetch.stream.test.ts +++ b/test/js/web/fetch/fetch.stream.test.ts @@ -28,6 +28,142 @@ const smallText = Buffer.from("Hello".repeat(16)); const empty = Buffer.alloc(0); describe("fetch() with streaming", () => { + it(`should be able to fail properly when reading from readable stream`, async () => { + let server: Server | null = null; + try { + server = Bun.serve({ + port: 0, + async fetch(req) { + return new Response( + new ReadableStream({ + async start(controller) { + controller.enqueue("Hello, World!"); + await Bun.sleep(1000); + controller.enqueue("Hello, World!"); + controller.close(); + }, + }), + { + status: 200, + headers: { + "Content-Type": "text/plain", + }, + }, + ); + }, + }); + + const server_url = `http://${server.hostname}:${server.port}`; + try { + const res = await fetch(server_url, { signal: AbortSignal.timeout(20) }); + const reader = res.body?.getReader(); + while (true) { + const { done } = await reader?.read(); + if (done) break; + } + expect(true).toBe("unreachable"); + } catch (err: any) { + if (err.name !== "TimeoutError") throw err; + expect(err.message).toBe("The operation timed out."); + } + } finally { + server?.stop(); + } + }); + + it(`should be locked after start buffering`, async () => { + let server: Server | null = null; + try { + server = Bun.serve({ + port: 0, + fetch(req) { + return new Response( + new ReadableStream({ + async start(controller) { + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.close(); + }, + }), + { + status: 200, + headers: { + "Content-Type": "text/plain", + }, + }, + ); + }, + }); + + const server_url = `http://${server.hostname}:${server.port}`; + const res = await fetch(server_url); + try { + const promise = res.text(); // start buffering + res.body?.getReader(); // get a reader + const result = await promise; // should throw the right error + expect(result).toBe("unreachable"); + } catch (err: any) { + if (err.name !== "TypeError") throw err; + expect(err.message).toBe("ReadableStream is locked"); + } + } finally { + server?.stop(); + } + }); + + it(`should be locked after start buffering when calling getReader`, async () => { + let server: Server | null = null; + try { + server = Bun.serve({ + port: 0, + fetch(req) { + return new Response( + new ReadableStream({ + async start(controller) { + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.enqueue("Hello, World!"); + await Bun.sleep(10); + controller.close(); + }, + }), + { + status: 200, + headers: { + "Content-Type": "text/plain", + }, + }, + ); + }, + }); + + const server_url = `http://${server.hostname}:${server.port}`; + const res = await fetch(server_url); + try { + const body = res.body as ReadableStream; + const promise = res.text(); // start buffering + body.getReader(); // get a reader + const result = await promise; // should throw the right error + expect(result).toBe("unreachable"); + } catch (err: any) { + if (err.name !== "TypeError") throw err; + expect(err.message).toBe("ReadableStream is locked"); + } + } finally { + server?.stop(); + } + }); + it("can deflate with and without headers #4478", async () => { let server: Server | null = null; try {