Files
bare-operating-system/packages/bare-os-seeder/kernel/lib/bare/bundles/bareHttps.js
T
2026-04-03 21:39:36 -04:00

6269 lines
215 KiB
JavaScript

var __bare_os_bundle_exports__ = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../node_modules/events-universal/default.js
var require_default = __commonJS({
"../../node_modules/events-universal/default.js"(exports, module) {
module.exports = __require("events");
}
});
// ../../node_modules/fast-fifo/fixed-size.js
var require_fixed_size = __commonJS({
"../../node_modules/fast-fifo/fixed-size.js"(exports, module) {
module.exports = class FixedFIFO {
constructor(hwm) {
if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
this.buffer = new Array(hwm);
this.mask = hwm - 1;
this.top = 0;
this.btm = 0;
this.next = null;
}
clear() {
this.top = this.btm = 0;
this.next = null;
this.buffer.fill(void 0);
}
push(data) {
if (this.buffer[this.top] !== void 0) return false;
this.buffer[this.top] = data;
this.top = this.top + 1 & this.mask;
return true;
}
shift() {
const last = this.buffer[this.btm];
if (last === void 0) return void 0;
this.buffer[this.btm] = void 0;
this.btm = this.btm + 1 & this.mask;
return last;
}
peek() {
return this.buffer[this.btm];
}
isEmpty() {
return this.buffer[this.btm] === void 0;
}
};
}
});
// ../../node_modules/fast-fifo/index.js
var require_fast_fifo = __commonJS({
"../../node_modules/fast-fifo/index.js"(exports, module) {
var FixedFIFO = require_fixed_size();
module.exports = class FastFIFO {
constructor(hwm) {
this.hwm = hwm || 16;
this.head = new FixedFIFO(this.hwm);
this.tail = this.head;
this.length = 0;
}
clear() {
this.head = this.tail;
this.head.clear();
this.length = 0;
}
push(val) {
this.length++;
if (!this.head.push(val)) {
const prev = this.head;
this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
this.head.push(val);
}
}
shift() {
if (this.length !== 0) this.length--;
const val = this.tail.shift();
if (val === void 0 && this.tail.next) {
const next = this.tail.next;
this.tail.next = null;
this.tail = next;
return this.tail.shift();
}
return val;
}
peek() {
const val = this.tail.peek();
if (val === void 0 && this.tail.next) return this.tail.next.peek();
return val;
}
isEmpty() {
return this.length === 0;
}
};
}
});
// ../../node_modules/b4a/index.js
var require_b4a = __commonJS({
"../../node_modules/b4a/index.js"(exports, module) {
function isBuffer(value) {
return Buffer.isBuffer(value) || value instanceof Uint8Array;
}
function isEncoding(encoding) {
return Buffer.isEncoding(encoding);
}
function alloc(size, fill2, encoding) {
return Buffer.alloc(size, fill2, encoding);
}
function allocUnsafe(size) {
return Buffer.allocUnsafe(size);
}
function allocUnsafeSlow(size) {
return Buffer.allocUnsafeSlow(size);
}
function byteLength(string, encoding) {
return Buffer.byteLength(string, encoding);
}
function compare(a, b) {
return Buffer.compare(a, b);
}
function concat(buffers, totalLength) {
return Buffer.concat(buffers, totalLength);
}
function copy(source, target, targetStart, start, end) {
return toBuffer(source).copy(target, targetStart, start, end);
}
function equals(a, b) {
return toBuffer(a).equals(b);
}
function fill(buffer, value, offset, end, encoding) {
return toBuffer(buffer).fill(value, offset, end, encoding);
}
function from(value, encodingOrOffset, length) {
return Buffer.from(value, encodingOrOffset, length);
}
function includes(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).includes(value, byteOffset, encoding);
}
function indexOf(buffer, value, byfeOffset, encoding) {
return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
}
function lastIndexOf(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
}
function swap16(buffer) {
return toBuffer(buffer).swap16();
}
function swap32(buffer) {
return toBuffer(buffer).swap32();
}
function swap64(buffer) {
return toBuffer(buffer).swap64();
}
function toBuffer(buffer) {
if (Buffer.isBuffer(buffer)) return buffer;
return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
function toString(buffer, encoding, start, end) {
return toBuffer(buffer).toString(encoding, start, end);
}
function write(buffer, string, offset, length, encoding) {
return toBuffer(buffer).write(string, offset, length, encoding);
}
function readDoubleBE(buffer, offset) {
return toBuffer(buffer).readDoubleBE(offset);
}
function readDoubleLE(buffer, offset) {
return toBuffer(buffer).readDoubleLE(offset);
}
function readFloatBE(buffer, offset) {
return toBuffer(buffer).readFloatBE(offset);
}
function readFloatLE(buffer, offset) {
return toBuffer(buffer).readFloatLE(offset);
}
function readInt32BE(buffer, offset) {
return toBuffer(buffer).readInt32BE(offset);
}
function readInt32LE(buffer, offset) {
return toBuffer(buffer).readInt32LE(offset);
}
function readUInt32BE(buffer, offset) {
return toBuffer(buffer).readUInt32BE(offset);
}
function readUInt32LE(buffer, offset) {
return toBuffer(buffer).readUInt32LE(offset);
}
function writeDoubleBE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleBE(value, offset);
}
function writeDoubleLE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleLE(value, offset);
}
function writeFloatBE(buffer, value, offset) {
return toBuffer(buffer).writeFloatBE(value, offset);
}
function writeFloatLE(buffer, value, offset) {
return toBuffer(buffer).writeFloatLE(value, offset);
}
function writeInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeInt32BE(value, offset);
}
function writeInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeInt32LE(value, offset);
}
function writeUInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32BE(value, offset);
}
function writeUInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32LE(value, offset);
}
module.exports = {
isBuffer,
isEncoding,
alloc,
allocUnsafe,
allocUnsafeSlow,
byteLength,
compare,
concat,
copy,
equals,
fill,
from,
includes,
indexOf,
lastIndexOf,
swap16,
swap32,
swap64,
toBuffer,
toString,
write,
readDoubleBE,
readDoubleLE,
readFloatBE,
readFloatLE,
readInt32BE,
readInt32LE,
readUInt32BE,
readUInt32LE,
writeDoubleBE,
writeDoubleLE,
writeFloatBE,
writeFloatLE,
writeInt32BE,
writeInt32LE,
writeUInt32BE,
writeUInt32LE
};
}
});
// ../../node_modules/text-decoder/lib/pass-through-decoder.js
var require_pass_through_decoder = __commonJS({
"../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class PassThroughDecoder {
constructor(encoding) {
this.encoding = encoding;
}
get remaining() {
return 0;
}
decode(data) {
return b4a.toString(data, this.encoding);
}
flush() {
return "";
}
};
}
});
// ../../node_modules/text-decoder/lib/utf8-decoder.js
var require_utf8_decoder = __commonJS({
"../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class UTF8Decoder {
constructor() {
this._reset();
}
get remaining() {
return this.bytesSeen;
}
decode(data) {
if (data.byteLength === 0) return "";
if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
this.bytesSeen = trailingBytesSeen(data);
return b4a.toString(data, "utf8");
}
let result = "";
let start = 0;
if (this.bytesNeeded > 0) {
while (start < data.byteLength) {
const byte = data[start];
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
this._reset();
break;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
start++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
break;
}
}
if (this.bytesNeeded > 0) return result;
}
const trailing = trailingIncomplete(data, start);
const end = data.byteLength - trailing;
if (end > start) result += b4a.toString(data, "utf8", start, end);
for (let i = end; i < data.byteLength; i++) {
const byte = data[i];
if (this.bytesNeeded === 0) {
if (byte <= 127) {
this.bytesSeen = 0;
result += String.fromCharCode(byte);
} else if (byte >= 194 && byte <= 223) {
this.bytesNeeded = 2;
this.bytesSeen = 1;
this.codePoint = byte & 31;
} else if (byte >= 224 && byte <= 239) {
if (byte === 224) this.lowerBoundary = 160;
else if (byte === 237) this.upperBoundary = 159;
this.bytesNeeded = 3;
this.bytesSeen = 1;
this.codePoint = byte & 15;
} else if (byte >= 240 && byte <= 244) {
if (byte === 240) this.lowerBoundary = 144;
else if (byte === 244) this.upperBoundary = 143;
this.bytesNeeded = 4;
this.bytesSeen = 1;
this.codePoint = byte & 7;
} else {
this.bytesSeen = 1;
result += "\uFFFD";
}
continue;
}
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
i--;
this._reset();
continue;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
}
}
return result;
}
flush() {
const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
this._reset();
return result;
}
_reset() {
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
}
};
function trailingIncomplete(data, start) {
const len = data.byteLength;
if (len <= start) return 0;
const limit = Math.max(start, len - 4);
let i = len - 1;
while (i > limit && (data[i] & 192) === 128) i--;
if (i < start) return 0;
const byte = data[i];
let needed;
if (byte <= 127) return 0;
if (byte >= 194 && byte <= 223) needed = 2;
else if (byte >= 224 && byte <= 239) needed = 3;
else if (byte >= 240 && byte <= 244) needed = 4;
else return 0;
const available = len - i;
return available < needed ? available : 0;
}
function trailingBytesSeen(data) {
const len = data.byteLength;
if (len === 0) return 0;
const last = data[len - 1];
if (last <= 127) return 0;
if ((last & 192) !== 128) return 1;
const limit = Math.max(0, len - 4);
let i = len - 2;
while (i >= limit && (data[i] & 192) === 128) i--;
if (i < 0) return 1;
const first = data[i];
let needed;
if (first >= 194 && first <= 223) needed = 2;
else if (first >= 224 && first <= 239) needed = 3;
else if (first >= 240 && first <= 244) needed = 4;
else return 1;
if (len - i !== needed) return 1;
if (needed >= 3) {
const second = data[i + 1];
if (first === 224 && second < 160) return 1;
if (first === 237 && second > 159) return 1;
if (first === 240 && second < 144) return 1;
if (first === 244 && second > 143) return 1;
}
return 0;
}
}
});
// ../../node_modules/text-decoder/index.js
var require_text_decoder = __commonJS({
"../../node_modules/text-decoder/index.js"(exports, module) {
var PassThroughDecoder = require_pass_through_decoder();
var UTF8Decoder = require_utf8_decoder();
module.exports = class TextDecoder {
constructor(encoding = "utf8") {
this.encoding = normalizeEncoding(encoding);
switch (this.encoding) {
case "utf8":
this.decoder = new UTF8Decoder();
break;
case "utf16le":
case "base64":
throw new Error("Unsupported encoding: " + this.encoding);
default:
this.decoder = new PassThroughDecoder(this.encoding);
}
}
get remaining() {
return this.decoder.remaining;
}
push(data) {
if (typeof data === "string") return data;
return this.decoder.decode(data);
}
// For Node.js compatibility
write(data) {
return this.push(data);
}
end(data) {
let result = "";
if (data) result = this.push(data);
result += this.decoder.flush();
return result;
}
};
function normalizeEncoding(encoding) {
encoding = encoding.toLowerCase();
switch (encoding) {
case "utf8":
case "utf-8":
return "utf8";
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return "utf16le";
case "latin1":
case "binary":
return "latin1";
case "base64":
case "ascii":
case "hex":
return encoding;
default:
throw new Error("Unknown encoding: " + encoding);
}
}
}
});
// ../../node_modules/streamx/index.js
var require_streamx = __commonJS({
"../../node_modules/streamx/index.js"(exports, module) {
var { EventEmitter } = require_default();
var STREAM_DESTROYED = new Error("Stream was destroyed");
var PREMATURE_CLOSE = new Error("Premature close");
var FIFO = require_fast_fifo();
var TextDecoder = require_text_decoder();
var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
var MAX = (1 << 29) - 1;
var OPENING = 1;
var PREDESTROYING = 2;
var DESTROYING = 4;
var DESTROYED = 8;
var NOT_OPENING = MAX ^ OPENING;
var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
var READ_ACTIVE = 1 << 4;
var READ_UPDATING = 2 << 4;
var READ_PRIMARY = 4 << 4;
var READ_QUEUED = 8 << 4;
var READ_RESUMED = 16 << 4;
var READ_PIPE_DRAINED = 32 << 4;
var READ_ENDING = 64 << 4;
var READ_EMIT_DATA = 128 << 4;
var READ_EMIT_READABLE = 256 << 4;
var READ_EMITTED_READABLE = 512 << 4;
var READ_DONE = 1024 << 4;
var READ_NEXT_TICK = 2048 << 4;
var READ_NEEDS_PUSH = 4096 << 4;
var READ_READ_AHEAD = 8192 << 4;
var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
var READ_PAUSED = MAX ^ READ_RESUMED;
var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
var READ_NOT_ENDING = MAX ^ READ_ENDING;
var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
var WRITE_ACTIVE = 1 << 18;
var WRITE_UPDATING = 2 << 18;
var WRITE_PRIMARY = 4 << 18;
var WRITE_QUEUED = 8 << 18;
var WRITE_UNDRAINED = 16 << 18;
var WRITE_DONE = 32 << 18;
var WRITE_EMIT_DRAIN = 64 << 18;
var WRITE_NEXT_TICK = 128 << 18;
var WRITE_WRITING = 256 << 18;
var WRITE_FINISHING = 512 << 18;
var WRITE_CORKED = 1024 << 18;
var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
var NOT_ACTIVE = MAX ^ ACTIVE;
var DONE = READ_DONE | WRITE_DONE;
var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
var OPEN_STATUS = DESTROY_STATUS | OPENING;
var AUTO_DESTROY = DESTROY_STATUS | DONE;
var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
var IS_OPENING = OPEN_STATUS | TICKING;
var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
var WritableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark;
this.buffered = 0;
this.error = null;
this.pipeline = null;
this.drains = null;
this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
this.map = mapWritable || map;
this.afterWrite = afterWrite.bind(this);
this.afterUpdateNextTick = updateWriteNT.bind(this);
}
get ending() {
return (this.stream._duplexState & WRITE_FINISHING) !== 0;
}
get ended() {
return (this.stream._duplexState & WRITE_DONE) !== 0;
}
push(data) {
if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
if (this.map !== null) data = this.map(data);
this.buffered += this.byteLength(data);
this.queue.push(data);
if (this.buffered < this.highWaterMark) {
this.stream._duplexState |= WRITE_QUEUED;
return true;
}
this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
return false;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
return data;
}
end(data) {
if (typeof data === "function") this.stream.once("finish", data);
else if (data !== void 0 && data !== null) this.push(data);
this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
}
autoBatch(data, cb) {
const buffer = [];
const stream = this.stream;
buffer.push(data);
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
buffer.push(stream._writableState.shift());
}
if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
stream._writev(buffer, cb);
}
update() {
const stream = this.stream;
stream._duplexState |= WRITE_UPDATING;
do {
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
const data = this.shift();
stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
stream._write(data, this.afterWrite);
}
if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= WRITE_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
stream._duplexState = stream._duplexState | WRITE_ACTIVE;
stream._final(afterFinal.bind(this));
return;
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTick() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
this.stream._duplexState |= WRITE_NEXT_TICK;
if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var ReadableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
this.buffered = 0;
this.readAhead = highWaterMark > 0;
this.error = null;
this.pipeline = null;
this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
this.map = mapReadable || map;
this.pipeTo = null;
this.afterRead = afterRead.bind(this);
this.afterUpdateNextTick = updateReadNT.bind(this);
}
get ending() {
return (this.stream._duplexState & READ_ENDING) !== 0;
}
get ended() {
return (this.stream._duplexState & READ_DONE) !== 0;
}
pipe(pipeTo, cb) {
if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
if (typeof cb !== "function") cb = null;
this.stream._duplexState |= READ_PIPE_DRAINED;
this.pipeTo = pipeTo;
this.pipeline = new Pipeline(this.stream, pipeTo, cb);
if (cb) this.stream.on("error", noop);
if (isStreamx(pipeTo)) {
pipeTo._writableState.pipeline = this.pipeline;
if (cb) pipeTo.on("error", noop);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
} else {
const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
pipeTo.on("error", onerror);
pipeTo.on("close", onclose);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
}
pipeTo.on("drain", afterDrain.bind(this));
this.stream.emit("piping", pipeTo);
pipeTo.emit("pipe", this.stream);
}
push(data) {
const stream = this.stream;
if (data === null) {
this.highWaterMark = 0;
stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
return false;
}
if (this.map !== null) {
data = this.map(data);
if (data === null) {
stream._duplexState &= READ_PUSHED;
return this.buffered < this.highWaterMark;
}
}
this.buffered += this.byteLength(data);
this.queue.push(data);
stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
return this.buffered < this.highWaterMark;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
return data;
}
unshift(data) {
const pending = [this.map !== null ? this.map(data) : data];
while (this.buffered > 0) pending.push(this.shift());
for (let i = 0; i < pending.length - 1; i++) {
const data2 = pending[i];
this.buffered += this.byteLength(data2);
this.queue.push(data2);
}
this.push(pending[pending.length - 1]);
}
read() {
const stream = this.stream;
if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
return data;
}
if (this.readAhead === false) {
stream._duplexState |= READ_READ_AHEAD;
this.updateNextTick();
}
return null;
}
drain() {
const stream = this.stream;
while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
}
}
update() {
const stream = this.stream;
stream._duplexState |= READ_UPDATING;
do {
this.drain();
while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
stream._read(this.afterRead);
this.drain();
}
if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
stream._duplexState |= READ_EMITTED_READABLE;
stream.emit("readable");
}
if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= READ_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
stream.emit("end");
if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
if (this.pipeTo !== null) this.pipeTo.end();
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
this.stream._duplexState &= READ_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTickIfOpen() {
if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
updateNextTick() {
if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var TransformState = class {
constructor(stream) {
this.data = null;
this.afterTransform = afterTransform.bind(stream);
this.afterFinal = null;
}
};
var Pipeline = class {
constructor(src, dst, cb) {
this.from = src;
this.to = dst;
this.afterPipe = cb;
this.error = null;
this.pipeToFinished = false;
}
finished() {
this.pipeToFinished = true;
}
done(stream, err) {
if (err) this.error = err;
if (stream === this.to) {
this.to = null;
if (this.from !== null) {
if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
}
return;
}
}
if (stream === this.from) {
this.from = null;
if (this.to !== null) {
if ((stream._duplexState & READ_DONE) === 0) {
this.to.destroy(this.error || new Error("Readable stream closed before ending"));
}
return;
}
}
if (this.afterPipe !== null) this.afterPipe(this.error);
this.to = this.from = this.afterPipe = null;
}
};
function afterDrain() {
this.stream._duplexState |= READ_PIPE_DRAINED;
this.updateCallback();
}
function afterFinal(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROY_STATUS) === 0) {
stream._duplexState |= WRITE_DONE;
stream.emit("finish");
}
if ((stream._duplexState & AUTO_DESTROY) === DONE) {
stream._duplexState |= DESTROYING;
}
stream._duplexState &= WRITE_NOT_FINISHING;
if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
else this.updateNextTick();
}
function afterDestroy(err) {
const stream = this.stream;
if (!err && this.error !== STREAM_DESTROYED) err = this.error;
if (err) stream.emit("error", err);
stream._duplexState |= DESTROYED;
stream.emit("close");
const rs = stream._readableState;
const ws = stream._writableState;
if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
if (ws !== null) {
while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
if (ws.pipeline !== null) ws.pipeline.done(stream, err);
}
}
function afterWrite(err) {
const stream = this.stream;
if (err) stream.destroy(err);
stream._duplexState &= WRITE_NOT_ACTIVE;
if (this.drains !== null) tickDrains(this.drains);
if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
stream._duplexState &= WRITE_DRAINED;
if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
stream.emit("drain");
}
}
this.updateCallback();
}
function afterRead(err) {
if (err) this.stream.destroy(err);
this.stream._duplexState &= READ_NOT_ACTIVE;
if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
this.stream._duplexState &= READ_NO_READ_AHEAD;
this.updateCallback();
}
function updateReadNT() {
if ((this.stream._duplexState & READ_UPDATING) === 0) {
this.stream._duplexState &= READ_NOT_NEXT_TICK;
this.update();
}
}
function updateWriteNT() {
if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
this.update();
}
}
function tickDrains(drains) {
for (let i = 0; i < drains.length; i++) {
if (--drains[i].writes === 0) {
drains.shift().resolve(true);
i--;
}
}
}
function afterOpen(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROYING) === 0) {
if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
stream.emit("open");
}
stream._duplexState &= NOT_ACTIVE;
if (stream._writableState !== null) {
stream._writableState.updateCallback();
}
if (stream._readableState !== null) {
stream._readableState.updateCallback();
}
}
function afterTransform(err, data) {
if (data !== void 0 && data !== null) this.push(data);
this._writableState.afterWrite(err);
}
function newListener(name) {
if (this._readableState !== null) {
if (name === "data") {
this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
}
if (name === "readable") {
this._duplexState |= READ_EMIT_READABLE;
this._readableState.updateNextTick();
}
}
if (this._writableState !== null) {
if (name === "drain") {
this._duplexState |= WRITE_EMIT_DRAIN;
this._writableState.updateNextTick();
}
}
}
var Stream = class extends EventEmitter {
constructor(opts) {
super();
this._duplexState = 0;
this._readableState = null;
this._writableState = null;
if (opts) {
if (opts.open) this._open = opts.open;
if (opts.destroy) this._destroy = opts.destroy;
if (opts.predestroy) this._predestroy = opts.predestroy;
if (opts.signal) {
opts.signal.addEventListener("abort", abort.bind(this));
}
}
this.on("newListener", newListener);
}
_open(cb) {
cb(null);
}
_destroy(cb) {
cb(null);
}
_predestroy() {
}
get readable() {
return this._readableState !== null ? true : void 0;
}
get writable() {
return this._writableState !== null ? true : void 0;
}
get destroyed() {
return (this._duplexState & DESTROYED) !== 0;
}
get destroying() {
return (this._duplexState & DESTROY_STATUS) !== 0;
}
destroy(err) {
if ((this._duplexState & DESTROY_STATUS) === 0) {
if (!err) err = STREAM_DESTROYED;
this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
if (this._readableState !== null) {
this._readableState.highWaterMark = 0;
this._readableState.error = err;
}
if (this._writableState !== null) {
this._writableState.highWaterMark = 0;
this._writableState.error = err;
}
this._duplexState |= PREDESTROYING;
this._predestroy();
this._duplexState &= NOT_PREDESTROYING;
if (this._readableState !== null) this._readableState.updateNextTick();
if (this._writableState !== null) this._writableState.updateNextTick();
}
}
};
var Readable = class _Readable extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
this._readableState = new ReadableState(this, opts);
if (opts) {
if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
if (opts.read) this._read = opts.read;
if (opts.eagerOpen) this._readableState.updateNextTick();
if (opts.encoding) this.setEncoding(opts.encoding);
}
}
setEncoding(encoding) {
const dec = new TextDecoder(encoding);
const map = this._readableState.map || echo;
this._readableState.map = mapOrSkip;
return this;
function mapOrSkip(data) {
const next = dec.push(data);
return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
}
}
_read(cb) {
cb(null);
}
pipe(dest, cb) {
this._readableState.updateNextTick();
this._readableState.pipe(dest, cb);
return dest;
}
read() {
this._readableState.updateNextTick();
return this._readableState.read();
}
push(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.push(data);
}
unshift(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.unshift(data);
}
resume() {
this._duplexState |= READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
return this;
}
pause() {
this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
return this;
}
static _fromAsyncIterator(ite, opts) {
let destroy;
const rs = new _Readable({
...opts,
read(cb) {
ite.next().then(push).then(cb.bind(null, null)).catch(cb);
},
predestroy() {
destroy = ite.return();
},
destroy(cb) {
if (!destroy) return cb(null);
destroy.then(cb.bind(null, null)).catch(cb);
}
});
return rs;
function push(data) {
if (data.done) rs.push(null);
else rs.push(data.value);
}
}
static from(data, opts) {
if (isReadStreamx(data)) return data;
if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
let i = 0;
return new _Readable({
...opts,
read(cb) {
this.push(i === data.length ? null : data[i++]);
cb(null);
}
});
}
static isBackpressured(rs) {
return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
}
static isPaused(rs) {
return (rs._duplexState & READ_RESUMED) === 0;
}
[asyncIterator]() {
const stream = this;
let error = null;
let promiseResolve = null;
let promiseReject = null;
this.on("error", (err) => {
error = err;
});
this.on("readable", onreadable);
this.on("close", onclose);
return {
[asyncIterator]() {
return this;
},
next() {
return new Promise(function(resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
const data = stream.read();
if (data !== null) ondata(data);
else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
});
},
return() {
return destroy(null);
},
throw(err) {
return destroy(err);
}
};
function onreadable() {
if (promiseResolve !== null) ondata(stream.read());
}
function onclose() {
if (promiseResolve !== null) ondata(null);
}
function ondata(data) {
if (promiseReject === null) return;
if (error) promiseReject(error);
else if (data === null && (stream._duplexState & READ_DONE) === 0)
promiseReject(STREAM_DESTROYED);
else promiseResolve({ value: data, done: data === null });
promiseReject = promiseResolve = null;
}
function destroy(err) {
stream.destroy(err);
return new Promise((resolve, reject) => {
if (stream._duplexState & DESTROYED) return resolve({ value: void 0, done: true });
stream.once("close", function() {
if (err) reject(err);
else resolve({ value: void 0, done: true });
});
});
}
}
};
var Writable = class extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | READ_DONE;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
if (opts.eagerOpen) this._writableState.updateNextTick();
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
static isBackpressured(ws) {
return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
}
static drained(ws) {
if (ws.destroyed) return Promise.resolve(false);
const state = ws._writableState;
const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
if (writes === 0) return Promise.resolve(true);
if (state.drains === null) state.drains = [];
return new Promise((resolve) => {
state.drains.push({ writes, resolve });
});
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Duplex = class extends Readable {
// and Writable
constructor(opts) {
super(opts);
this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Transform = class extends Duplex {
constructor(opts) {
super(opts);
this._transformState = new TransformState(this);
if (opts) {
if (opts.transform) this._transform = opts.transform;
if (opts.flush) this._flush = opts.flush;
}
}
_write(data, cb) {
if (this._readableState.buffered >= this._readableState.highWaterMark) {
this._transformState.data = data;
} else {
this._transform(data, this._transformState.afterTransform);
}
}
_read(cb) {
if (this._transformState.data !== null) {
const data = this._transformState.data;
this._transformState.data = null;
cb(null);
this._transform(data, this._transformState.afterTransform);
} else {
cb(null);
}
}
destroy(err) {
super.destroy(err);
if (this._transformState.data !== null) {
this._transformState.data = null;
this._transformState.afterTransform();
}
}
_transform(data, cb) {
cb(null, data);
}
_flush(cb) {
cb(null);
}
_final(cb) {
this._transformState.afterFinal = cb;
this._flush(transformAfterFlush.bind(this));
}
};
var PassThrough = class extends Transform {
};
function transformAfterFlush(err, data) {
const cb = this._transformState.afterFinal;
if (err) return cb(err);
if (data !== null && data !== void 0) this.push(data);
this.push(null);
cb(null);
}
function pipelinePromise(...streams) {
return new Promise((resolve, reject) => {
return pipeline(...streams, (err) => {
if (err) return reject(err);
resolve();
});
});
}
function pipeline(stream, ...streams) {
const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
let src = all[0];
let dest = null;
let error = null;
for (let i = 1; i < all.length; i++) {
dest = all[i];
if (isStreamx(src)) {
src.pipe(dest, onerror);
} else {
errorHandle(src, true, i > 1, onerror);
src.pipe(dest);
}
src = dest;
}
if (done) {
let fin = false;
const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
dest.on("error", (err) => {
if (error === null) error = err;
});
dest.on("finish", () => {
fin = true;
if (!autoDestroy) done(error);
});
if (autoDestroy) {
dest.on("close", () => done(error || (fin ? null : PREMATURE_CLOSE)));
}
}
return dest;
function errorHandle(s, rd, wr, onerror2) {
s.on("error", onerror2);
s.on("close", onclose);
function onclose() {
if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
}
}
function onerror(err) {
if (!err || error) return;
error = err;
for (const s of all) {
s.destroy(err);
}
}
}
function echo(s) {
return s;
}
function isStream(stream) {
return !!stream._readableState || !!stream._writableState;
}
function isStreamx(stream) {
return typeof stream._duplexState === "number" && isStream(stream);
}
function isEnding(stream) {
return !!stream._readableState && stream._readableState.ending;
}
function isEnded(stream) {
return !!stream._readableState && stream._readableState.ended;
}
function isFinishing(stream) {
return !!stream._writableState && stream._writableState.ending;
}
function isFinished(stream) {
return !!stream._writableState && stream._writableState.ended;
}
function getStreamError(stream, opts = {}) {
const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
return !opts.all && err === STREAM_DESTROYED ? null : err;
}
function isReadStreamx(stream) {
return isStreamx(stream) && stream.readable;
}
function isDisturbed(stream) {
return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
}
function isTypedArray(data) {
return typeof data === "object" && data !== null && typeof data.byteLength === "number";
}
function defaultByteLength(data) {
return isTypedArray(data) ? data.byteLength : 1024;
}
function noop() {
}
function abort() {
this.destroy(new Error("Stream aborted."));
}
function isWritev(s) {
return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
}
module.exports = {
pipeline,
pipelinePromise,
isStream,
isStreamx,
isEnding,
isEnded,
isFinishing,
isFinished,
isDisturbed,
getStreamError,
Stream,
Writable,
Readable,
Duplex,
Transform,
// Export PassThrough for compatibility with Node.js core's stream module
PassThrough
};
}
});
// ../../node_modules/teex/index.js
var require_teex = __commonJS({
"../../node_modules/teex/index.js"(exports, module) {
var { Readable } = require_streamx();
module.exports = function(s, forks = 2) {
const streams = new Array(forks);
const status = new Array(forks).fill(true);
let ended = false;
for (let i = 0; i < forks; i++) {
streams[i] = new Readable({
read(cb) {
const check = !status[i];
status[i] = true;
if (check && allReadable()) s.resume();
cb(null);
}
});
}
s.on("end", function() {
ended = true;
for (const stream of streams) stream.push(null);
});
s.on("error", function(err) {
for (const stream of streams) stream.destroy(err);
});
s.on("close", function() {
if (ended) return;
for (const stream of streams) stream.destroy();
});
s.on("data", function(data) {
let needsPause = false;
for (let i = 0; i < streams.length; i++) {
if (!(status[i] = streams[i].push(data))) {
needsPause = true;
}
}
if (needsPause) s.pause();
});
return streams;
function allReadable() {
for (let j = 0; j < status.length; j++) {
if (!status[j]) return false;
}
return true;
}
};
}
});
// ../../node_modules/bare-stream/web.js
var require_web = __commonJS({
"../../node_modules/bare-stream/web.js"(exports) {
var { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require_streamx();
var tee = require_teex();
var readableKind = Symbol.for("bare.stream.readable.kind");
var writableKind = Symbol.for("bare.stream.writable.kind");
var transformKind = Symbol.for("bare.stream.transform.kind");
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get closed() {
return this._closed.promise;
}
read() {
const stream = this._stream._stream;
return new Promise((resolve, reject) => {
const err = getStreamError(stream);
if (err) return reject(err);
if (stream.destroyed) {
return resolve({ value: void 0, done: true });
}
const value = stream.read();
if (value !== null) {
return resolve({ value, done: false });
}
stream.once("readable", onreadable).once("close", onclose).once("error", onerror);
function onreadable() {
const value2 = stream.read();
ondone(null, value2 === null ? { value: void 0, done: true } : { value: value2, done: false });
}
function onclose() {
ondone(null, { value: void 0, done: true });
}
function onerror(err2) {
ondone(err2, null);
}
function ondone(err2, value2) {
stream.off("readable", onreadable).off("close", onclose).off("error", onerror);
if (err2) reject(err2);
else resolve(value2);
}
});
}
releaseLock() {
this._closed.reject(new TypeError("Reader was released"));
this._stream._releaseLock();
this._stream = null;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
};
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
close() {
this._stream._stream.push(null);
}
error(err) {
this._stream._stream.destroy(err);
}
};
var ReadableStream = class _ReadableStream {
static get [readableKind]() {
return 0;
}
static from(iterable) {
return new _ReadableStream(Readable.from(iterable));
}
constructor(underlyingSource = {}, queuingStrategy) {
if (isStreamx(underlyingSource)) {
this._stream = underlyingSource;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, pull, cancel } = underlyingSource;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Readable({ highWaterMark, byteLength: size });
const controller = new exports.ReadableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, controller));
}
if (pull) {
this._stream._read = this._read.bind(this, pull.bind(this, controller));
}
if (cancel) {
this._stream.once("error", cancel);
}
}
this._reader = null;
}
get [readableKind]() {
return _ReadableStream[readableKind];
}
get locked() {
return this._reader !== null;
}
getReader() {
if (this.locked) throw new TypeError("Stream is locked");
this._reader = new exports.ReadableStreamDefaultReader(this);
return this._reader;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream;
if (stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
tee() {
const [a, b] = tee(this._stream);
return [new _ReadableStream(a), new _ReadableStream(b)];
}
pipeTo(destination) {
return new Promise(
(resolve, reject) => this._stream.pipe(destination._stream, (err) => {
err ? reject(err) : resolve();
})
);
}
[Symbol.asyncIterator]() {
return this._stream[Symbol.asyncIterator]();
}
_releaseLock() {
this._reader = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _read(pull, cb) {
let err = null;
try {
await pull();
} catch (e) {
err = e;
}
cb(err);
}
};
function defaultSize() {
return 1;
}
exports.ReadableStream = ReadableStream;
exports.CountQueuingStrategy = class CountQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 1 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return 1;
}
};
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 16384 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return chunk.byteLength;
}
};
exports.isReadableStream = function isReadableStream(value) {
if (value instanceof ReadableStream) return true;
return typeof value === "object" && value !== null && value[readableKind] === ReadableStream[readableKind];
};
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
return getStreamError(stream._stream) !== null;
};
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
return isDisturbed(stream._stream);
};
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get desiredSize() {
const stream = this._stream._stream;
return stream._writableState.highWaterMark - stream._writableState.buffered;
}
get closed() {
return this._closed.promise;
}
get ready() {
const stream = this._stream._stream;
if (getStreamError(stream)) return Promise.reject();
return Writable.drained(stream).then();
}
async write(chunk) {
const stream = this._stream._stream;
let err = getStreamError(stream);
if (err) return Promise.reject(err);
stream.write(chunk);
await Writable.drained(stream);
err = getStreamError(stream);
if (err) return Promise.reject(err);
}
releaseLock() {
this._closed.reject(new TypeError("Writer was released"));
this._stream._releaseLock();
this._stream = null;
}
close() {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).end());
}
abort(reason = new TypeError("Stream was aborted")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).destroy(reason));
}
};
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
error(err) {
this._stream._stream.destroy(err);
}
};
var WritableStream = class _WritableStream {
static get [writableKind]() {
return 0;
}
constructor(underlyingSink = {}, queuingStrategy = {}) {
if (isStreamx(underlyingSink)) {
this._stream = underlyingSink;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, write, close, abort } = underlyingSink;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Writable({ highWaterMark, byteLength: size });
this._controller = new exports.WritableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (write) {
this._stream._write = this._write.bind(this, write);
}
if (close) {
this._stream._destroy = this._destroy.bind(this, close.call(this));
}
if (abort) {
this._stream.once("error", abort);
}
}
this._writer = null;
}
get [writableKind]() {
return _WritableStream[writableKind];
}
get locked() {
return this._writer !== null;
}
getWriter() {
if (this.locked) throw new TypeError("Stream is locked");
this._writer = new exports.WritableStreamDefaultWriter(this);
return this._writer;
}
abort(reason = new TypeError("Stream was aborted")) {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).destroy(reason));
}
close() {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).end());
}
_releaseLock() {
this._writer = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _write(write, data, cb) {
let err = null;
try {
await write(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _destroy(closing, cb) {
let err = null;
try {
await closing;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.WritableStream = WritableStream;
exports.isWritableStream = function isWritableStream(value) {
if (value instanceof WritableStream) return true;
return typeof value === "object" && value !== null && value[writableKind] === WritableStream[writableKind];
};
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
error(err) {
this._stream._stream.destroy(err);
}
terminate() {
const stream = this._stream._stream;
stream.push(null);
stream.destroy(new TypeError("Stream has been terminated"));
}
};
var TransformStream = class _TransformStream {
static get [transformKind]() {
return 0;
}
constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
const { start, transform, flush } = transformer;
this._stream = new Transform({ ...writableStrategy, ...readableStrategy });
this._writable = new WritableStream(this._stream);
this._readable = new ReadableStream(this._stream);
this._controller = new exports.TransformStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (transform) {
this._stream._write = this._transform.bind(this, transform);
}
if (flush) {
this._stream._flush = this._flush.bind(this, flush.call(this, this._controller));
}
}
get [transformKind]() {
return _TransformStream[transformKind];
}
get writable() {
return this._writable;
}
get readable() {
return this._readable;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _transform(transform, data, cb) {
let err = null;
try {
await transform(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _flush(flush, cb) {
let err = null;
try {
await flush;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.TransformStream = TransformStream;
exports.isTransformStream = function isTransformStream(value) {
if (value instanceof TransformStream) return true;
return typeof value === "object" && value !== null && value[transformKind] === TransformStream[transformKind];
};
function noop() {
}
}
});
// ../../node_modules/bare-stream/index.js
var require_bare_stream = __commonJS({
"../../node_modules/bare-stream/index.js"(exports, module) {
var stream = require_streamx();
var { ReadableStream, WritableStream } = require_web();
var defaultEncoding = "utf8";
module.exports = exports = stream.Stream;
exports.pipeline = stream.pipeline;
exports.isStream = stream.isStream;
exports.isEnding = stream.isEnding;
exports.isEnded = stream.isEnded;
exports.isFinishing = stream.isFinishing;
exports.isFinished = stream.isFinished;
exports.isDisturbed = stream.isDisturbed;
exports.isErrored = function isErrored(stream2) {
return exports.getStreamError(stream2) !== null;
};
exports.isReadable = function isReadable(stream2) {
return stream2.readable && !stream2.destroying && !exports.isEnded(stream2);
};
exports.isWritable = function isWritable(stream2) {
return stream2.writable && !stream2.destroying && !exports.isFinishing(stream2);
};
exports.getStreamError = stream.getStreamError;
exports.addAbortSignal = function addAbortSignal(signal, stream2) {
function onAbort() {
stream2.destroy(signal.reason);
}
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort);
return stream2;
};
exports.Stream = exports;
exports.Readable = class Readable extends stream.Readable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
map: null,
mapReadable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isReadable(this);
}
get errored() {
return stream.getStreamError(this);
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
static fromWeb(readableStream, opts = {}) {
const stream2 = readableStream._stream;
if (opts.encoding) stream2.setEncoding(opts.encoding);
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(readable, opts = {}) {
return new ReadableStream(readable, opts.strategy);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Writable = class Writable extends stream.Writable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthWritable,
map: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._write !== stream.Writable.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isWritable(this);
}
get errored() {
return stream.getStreamError(this);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding || defaultEncoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb(writableStream, opts = {}) {
const stream2 = writableStream._stream;
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(writable) {
return new WritableStream(writable);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Duplex = class Duplex extends stream.Duplex {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._write !== stream.Duplex.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
const readable = exports.Readable.fromWeb(readableStream, opts);
const writable = exports.Readable.fromWeb(writableStream, opts);
const duplex = new exports.Duplex({
write(data, encoding, cb) {
writable.write(data, encoding, cb);
}
});
readable.on("data", (data) => duplex.push(data)).on("end", () => duplex.push(null)).on("error", (err) => duplex.destroy(err));
writable.on("finish", () => duplex.end()).on("error", (err) => duplex.destroy(err));
return duplex;
}
static toWeb(duplex) {
const readableStream = exports.Readable.toWeb(duplex);
const writableStream = exports.Writable.toWeb(duplex);
return { readable: readableStream, writable: writableStream };
}
};
var DuplexSide = class extends exports.Duplex {
constructor(opts) {
super(opts);
this._otherSide = null;
this._cb = null;
}
_read() {
const cb = this._cb;
if (!cb) return;
this._cb = null;
cb();
}
_write(chunk, encoding, cb) {
this._otherSide.push(chunk, encoding);
this._otherSide._cb = cb;
}
_final(cb) {
this._otherSide.on("end", cb);
this._otherSide.push(null);
}
};
exports.duplexPair = function duplexPair(opts) {
const sideA = new DuplexSide(opts);
const sideB = new DuplexSide(opts);
sideA._otherSide = sideB;
sideB._otherSide = sideA;
return [sideA, sideB];
};
exports.Transform = class Transform extends stream.Transform {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._transform !== stream.Transform.prototype._transform) {
this._transform = transform.bind(this, this._transform);
} else {
this._transform = passthrough;
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
};
exports.PassThrough = class PassThrough extends exports.Transform {
};
exports.finished = function finished(stream2, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
const { cleanup = false } = opts;
const done = () => {
cb(exports.getStreamError(stream2, { all: true }));
if (cleanup) detach();
};
const detach = () => {
stream2.off("close", done);
stream2.off("error", noop);
};
if (stream2.destroyed) {
done();
} else {
stream2.on("close", done);
stream2.on("error", noop);
}
return detach;
};
function read(read2, cb) {
read2.call(this, 65536);
cb(null);
}
function write(write2, data, cb) {
write2.call(this, data.chunk, data.encoding, cb);
}
function transform(transform2, data, cb) {
transform2.call(this, data.chunk, data.encoding, cb);
}
function destroy(destroy2, cb) {
destroy2.call(this, exports.getStreamError(this), cb);
}
function passthrough(data, cb) {
cb(null, data.chunk);
}
function byteLengthWritable(data) {
return data.chunk.byteLength;
}
function noop() {
}
}
});
// ../../node_modules/bare-http1/lib/incoming-message.js
var require_incoming_message = __commonJS({
"../../node_modules/bare-http1/lib/incoming-message.js"(exports, module) {
var { Readable } = require_bare_stream();
module.exports = class HTTPIncomingMessage extends Readable {
constructor(socket = null, opts = {}) {
super();
this._socket = socket;
this._upgrade = false;
this._headers = opts.headers || {};
this._method = opts.method || "";
this._url = opts.url || "";
this._statusCode = opts.statusCode || 0;
this._statusMessage = opts.statusMessage || "";
}
get socket() {
return this._socket;
}
get upgrade() {
return this._upgrade;
}
get headers() {
return this._headers;
}
set headers(value) {
this._headers = value;
}
get method() {
return this._method;
}
set method(value) {
this._method = value;
}
get url() {
return this._url;
}
set url(value) {
this._url = value;
}
get statusCode() {
return this._statusCode;
}
set statusCode(value) {
this._statusCode = value;
}
get statusMessage() {
return this._statusMessage;
}
set statusMessage(value) {
this._statusMessage = value;
}
get httpVersion() {
return "1.1";
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return { ...this._headers };
}
hasHeader(name) {
return name.toLowerCase() in this._headers;
}
setTimeout(ms, ontimeout) {
if (ontimeout) this.once("timeout", ontimeout);
this._socket.setTimeout(ms);
return this;
}
_predestroy() {
if (this._upgrade === false && this._socket !== null) this._socket.destroy();
}
};
}
});
// ../../node_modules/bare-http1/lib/errors.js
var require_errors = __commonJS({
"../../node_modules/bare-http1/lib/errors.js"(exports, module) {
module.exports = class HTTPError extends Error {
constructor(msg, fn = HTTPError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "HTTPError";
}
static NOT_IMPLEMENTED(msg = "Method not implemented") {
return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED);
}
static CONNECTION_LOST(msg = "Socket hung up") {
return new HTTPError(msg, HTTPError.CONNECTION_LOST);
}
static AGENT_SUSPENDED(msg = "Agent is suspended") {
return new HTTPError(msg, HTTPError.AGENT_SUSPENDED);
}
};
}
});
// ../../node_modules/bare-http1/lib/outgoing-message.js
var require_outgoing_message = __commonJS({
"../../node_modules/bare-http1/lib/outgoing-message.js"(exports, module) {
var { Writable } = require_bare_stream();
var errors = require_errors();
module.exports = class HTTPOutgoingMessage extends Writable {
constructor(socket = null) {
super();
this._socket = socket;
this._upgrade = false;
this._headersSent = false;
this._headers = {};
}
get socket() {
return this._socket;
}
get upgrade() {
return this._upgrade;
}
get headersSent() {
return this._headersSent;
}
get headers() {
return this._headers;
}
set headers(value) {
this._headers = value;
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return { ...this._headers };
}
hasHeader(name) {
return name.toLowerCase() in this._headers;
}
setHeader(name, value) {
this._headers[name.toLowerCase()] = value;
}
flushHeaders() {
if (this._headersSent === true || this._socket === null) return;
this._socket.write(Buffer.from(this._header()));
this._headersSent = true;
}
setTimeout(ms, ontimeout) {
if (ontimeout) this.once("timeout", ontimeout);
this._socket.setTimeout(ms);
return this;
}
_header() {
throw errors.NOT_IMPLEMENTED();
}
_predestroy() {
if (this._upgrade === false && this._socket !== null) this._socket.destroy();
}
};
}
});
// ../../node_modules/bare-events/lib/errors.js
var require_errors2 = __commonJS({
"../../node_modules/bare-events/lib/errors.js"(exports, module) {
module.exports = class EventEmitterError extends Error {
constructor(msg, code, fn = EventEmitterError, opts) {
super(`${code}: ${msg}`, opts);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "EventEmitterError";
}
static OPERATION_ABORTED(cause, msg = "Operation aborted") {
return new EventEmitterError(msg, "OPERATION_ABORTED", EventEmitterError.OPERATION_ABORTED, {
cause
});
}
static UNHANDLED_ERROR(cause, msg = "Unhandled error") {
return new EventEmitterError(msg, "UNHANDLED_ERROR", EventEmitterError.UNHANDLED_ERROR, {
cause
});
}
};
}
});
// ../../node_modules/bare-events/index.js
var require_bare_events = __commonJS({
"../../node_modules/bare-events/index.js"(exports, module) {
var errors = require_errors2();
var EventListener = class {
constructor() {
this.list = [];
this.count = 0;
}
append(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.push([fn, once]);
}
prepend(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.unshift([fn, once]);
}
remove(ctx, name, fn) {
for (let i = 0, n = this.list.length; i < n; i++) {
const l = this.list[i];
if (l[0] === fn) {
this.list.splice(i, 1);
if (this.count === 1) delete ctx._events[name];
ctx.emit("removeListener", name, fn);
this.count--;
return;
}
}
}
removeAll(ctx, name) {
const list = [...this.list];
this.list = [];
if (this.count === list.length) delete ctx._events[name];
for (let i = list.length - 1; i >= 0; i--) {
ctx.emit("removeListener", name, list[i][0]);
}
this.count -= list.length;
}
emit(ctx, name, ...args) {
const list = [...this.list];
for (let i = 0, n = list.length; i < n; i++) {
const l = list[i];
if (l[1] === true) this.remove(ctx, name, l[0]);
Reflect.apply(l[0], ctx, args);
}
return list.length > 0;
}
};
function appendListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.append(ctx, name, fn, once);
return ctx;
}
function prependListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.prepend(ctx, name, fn, once);
return ctx;
}
function removeListener(ctx, name, fn) {
if (ctx._events === void 0) return ctx;
const e = ctx._events[name];
if (e !== void 0) e.remove(ctx, name, fn);
return ctx;
}
function throwUnhandledError(...args) {
let err;
if (args.length > 0) err = args[0];
if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err);
if (Error.captureStackTrace) {
Error.captureStackTrace(err, exports.prototype.emit);
}
queueMicrotask(() => {
throw err;
});
}
module.exports = exports = class EventEmitter {
constructor() {
this._events = /* @__PURE__ */ Object.create(null);
}
addListener(name, fn) {
return appendListener(this, name, fn, false);
}
addOnceListener(name, fn) {
return appendListener(this, name, fn, true);
}
prependListener(name, fn) {
return prependListener(this, name, fn, false);
}
prependOnceListener(name, fn) {
return prependListener(this, name, fn, true);
}
removeListener(name, fn) {
return removeListener(this, name, fn);
}
on(name, fn) {
return appendListener(this, name, fn, false);
}
once(name, fn) {
return appendListener(this, name, fn, true);
}
off(name, fn) {
return removeListener(this, name, fn);
}
emit(name, ...args) {
if (name === "error" && this._events !== void 0 && this._events.error === void 0) {
throwUnhandledError(...args);
}
if (this._events === void 0) return false;
const e = this._events[name];
return e === void 0 ? false : e.emit(this, name, ...args);
}
listeners(name) {
if (this._events === void 0) return [];
const e = this._events[name];
return e === void 0 ? [] : [...e.list];
}
listenerCount(name) {
if (this._events === void 0) return 0;
const e = this._events[name];
return e === void 0 ? 0 : e.list.length;
}
getMaxListeners() {
return EventEmitter.defaultMaxListeners;
}
setMaxListeners(n) {
}
removeAllListeners(name) {
if (arguments.length === 0) {
for (const key of Reflect.ownKeys(this._events)) {
if (key === "removeListener") continue;
this.removeAllListeners(key);
}
this.removeAllListeners("removeListener");
} else {
const e = this._events[name];
if (e !== void 0) e.removeAll(this, name);
}
return this;
}
};
exports.EventEmitter = exports;
exports.errors = errors;
exports.defaultMaxListeners = 10;
exports.on = function on(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
throw errors.OPERATION_ABORTED(signal.reason);
}
let error = null;
let done = false;
const events = [];
const promises = [];
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.on(name, onevent);
return {
next() {
if (events.length) {
return Promise.resolve({ value: events.shift(), done: false });
}
if (error) {
const err = error;
error = null;
return Promise.reject(err);
}
if (done) return onclose();
return new Promise((resolve, reject) => promises.push({ resolve, reject }));
},
return() {
return onclose();
},
throw(err) {
return onerror(err);
},
[Symbol.asyncIterator]() {
return this;
}
};
function onevent(...args) {
if (promises.length) {
promises.shift().resolve({ value: args, done: false });
} else {
events.push(args);
}
}
function onerror(err) {
emitter.off(name, onevent).off("error", onerror);
if (promises.length) {
promises.shift().reject(err);
} else {
error = err;
}
return Promise.resolve({ done: true });
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
function onclose() {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
done = true;
if (promises.length) promises.shift().resolve({ done: true });
return Promise.resolve({ done: true });
}
};
exports.once = function once(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
return Promise.reject(errors.OPERATION_ABORTED(signal.reason));
}
return new Promise((resolve, reject) => {
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.once(name, onevent);
function onevent(...args) {
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
resolve(args);
}
function onerror(err) {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
reject(err);
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
});
};
exports.forward = function forward(from, to, names, opts = {}) {
if (typeof names === "string") names = [names];
const { emit = to.emit.bind(to) } = opts;
const listeners = names.map(
(name) => function onevent(...args) {
emit(name, ...args);
}
);
to.on("newListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.on(name, listeners[i]);
}
}).on("removeListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.off(name, listeners[i]);
}
});
};
exports.listenerCount = function listenerCount(emitter, name) {
return emitter.listenerCount(name);
};
exports.getMaxListeners = function getMaxListeners(emitter) {
if (typeof emitter.getMaxListeners === "function") {
return emitter.getMaxListeners();
}
return exports.defaultMaxListeners;
};
exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
if (emitters.length === 0) exports.defaultMaxListeners = n;
else {
for (const emitter of emitters) {
if (typeof emitter.setMaxListeners === "function") {
emitter.setMaxListeners(n);
}
}
}
};
}
});
// ../../node_modules/bare-dns/binding.js
var require_binding = __commonJS({
"../../node_modules/bare-dns/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-dns/index.js
var require_bare_dns = __commonJS({
"../../node_modules/bare-dns/index.js"(exports) {
var binding = require_binding();
exports.Resolver = class DNSResolver {
constructor() {
this._handle = binding.initResolver();
}
resolveTxt(hostname, cb = noop) {
binding.resolveTxt(this._handle, hostname, cb, this);
}
destroy() {
binding.destroyResolver(this._handle);
this._handle = null;
}
static global = new this();
};
function onlookup(err, addresses) {
const req = this;
if (err) return req.cb(err, null, 0);
const { address, family } = addresses[0];
return req.cb(null, address, family);
}
function onlookupall(err, addresses) {
const req = this;
if (err) return req.cb(err, null);
return req.cb(null, addresses);
}
exports.lookup = function lookup(hostname, opts = {}, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
let { family = 0, all = false } = opts;
if (typeof family === "string") {
switch (family) {
case "IPv4":
family = 4;
break;
case "IPv6":
family = 6;
break;
default:
family = 0;
}
}
const req = {
cb,
handle: null
};
req.handle = binding.lookup(
hostname,
family || 0,
all,
req,
all ? onlookupall : onlookup
);
};
exports.resolveTxt = function resolveTxt(hostname, cb) {
exports.Resolver.global.resolveTxt(hostname, cb);
};
function noop() {
}
}
});
// ../../node_modules/bare-tcp/binding.js
var require_binding2 = __commonJS({
"../../node_modules/bare-tcp/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tcp/lib/constants.js
var require_constants = __commonJS({
"../../node_modules/bare-tcp/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
UNREFED: 64
}
};
}
});
// ../../node_modules/bare-tcp/lib/errors.js
var require_errors3 = __commonJS({
"../../node_modules/bare-tcp/lib/errors.js"(exports, module) {
module.exports = class TCPError extends Error {
constructor(msg, fn = TCPError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "TCPError";
}
static SOCKET_ALREADY_CONNECTED(msg) {
return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new TCPError(msg, TCPError.SERVER_IS_CLOSED);
}
static INVALID_HOST(msg = "Unrecognizable host format") {
return new TCPError(msg, TCPError.INVALID_HOST);
}
};
}
});
// ../../node_modules/bare-tcp/lib/ip.js
var require_ip = __commonJS({
"../../node_modules/bare-tcp/lib/ip.js"(exports) {
var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
var v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
var IPv4Pattern = new RegExp(`^${v4Str}$`);
var v6Seg = "(?:[0-9a-fA-F]{1,4})";
var IPv6Pattern = new RegExp(
`^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$`
);
var isIPv4 = exports.isIPv4 = function isIPv42(host) {
return IPv4Pattern.test(host);
};
var isIPv6 = exports.isIPv6 = function isIPv62(host) {
return IPv6Pattern.test(host);
};
exports.isIP = function isIP(host) {
if (isIPv4(host)) return 4;
if (isIPv6(host)) return 6;
return 0;
};
}
});
// ../../node_modules/bare-tcp/index.js
var require_bare_tcp = __commonJS({
"../../node_modules/bare-tcp/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var dns = require_bare_dns();
var binding = require_binding2();
var constants = require_constants();
var errors = require_errors3();
var ip = require_ip();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
exports.Socket = class TCPSocket extends Duplex {
constructor(opts = {}) {
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = 0;
this._keepAliveInitialDelay = 0;
this._noDelay = 0;
this._localAddress = null;
this._remoteAddress = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._timer = null;
this._timeout = 0;
this._buffer = Buffer.alloc(readBufferSize);
this._addresses = null;
this._errors = null;
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onreset,
this._onread,
this._onwrite,
this._onfinal,
this._onclose
);
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get timeout() {
return this._timeout || void 0;
}
get readyState() {
if (this._state & constants.state.CONNECTED) {
return "open";
}
return "opening";
}
get localAddress() {
if (this._localAddress) return this._localAddress.address;
}
get localFamily() {
if (this._localAddress) return `IPv${this._localAddress.family}`;
}
get localPort() {
if (this._localAddress) return this._localAddress.port;
}
get remoteAddress() {
if (this._remoteAddress) return this._remoteAddress.address;
}
get remoteFamily() {
if (this._remoteAddress) return `IPv${this._remoteAddress.family}`;
}
get remotePort() {
if (this._remoteAddress) return this._remoteAddress.port;
}
connect(port, host = "localhost", opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.SOCKET_ALREADY_CONNECTED("Socket is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
}
if (!host) host = "localhost";
const {
lookup = dns.lookup,
hints,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
timeout
} = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { all: true, family, hints }, (err, addresses) => {
if (this._state & constants.state.CLOSING) return;
this._state &= ~constants.state.CONNECTING;
if (err || addresses.length === 0) {
if (!err) {
err = new Error(`No address found for host "${host}"`);
err.code = "ENOTFOUND";
}
this.emit("lookup", err, null, 0, host);
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
for (const { address: address2, family: family3 } of addresses) {
this.emit("lookup", null, address2, family3, host);
}
const [{ address, family: family2 }, ...rest] = addresses;
if (rest.length > 0) {
this._addresses = rest.map(({ address: address2, family: family3 }) => [
port,
address2,
{ ...opts, family: family3 },
onconnect
]);
this._errors = [];
}
this.connect(port, address, { ...opts, family: family2 }, onconnect);
});
return this;
}
family = type;
try {
binding.connect(this._handle, port, host, family);
if (keepAlive) {
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
}
if (noDelay) this._noDelay = noDelay;
if (timeout) this.setTimeout(timeout);
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
setKeepAlive(enable = false, delay = 0) {
if (typeof enable === "number") {
delay = enable;
enable = false;
}
delay = Math.floor(delay / 1e3);
if (delay === 0) enable = false;
binding.keepalive(this._handle, enable, delay);
return this;
}
setNoDelay(enable = true) {
binding.nodelay(this._handle, enable);
return this;
}
setTimeout(ms, ontimeout) {
if (ms === 0) {
clearTimeout(this._timer);
this._timer = null;
} else {
if (ontimeout) this.once("timeout", ontimeout);
this._timer = setTimeout(() => this.emit("timeout"), ms);
this._timer.unref();
}
this._timeout = ms;
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
this._pendingFinal = cb;
binding.end(this._handle);
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_reset() {
this._state = 0;
this._localAddress = null;
this._remoteAddress = null;
binding.reset(this._handle);
}
_onconnect(err) {
if (err) {
if (this._addresses !== null) {
this._errors.push(err);
if (this._addresses.length > 0) return this._reset();
err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors);
}
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) this.setNoDelay();
this._localAddress = binding.address(this._handle, true);
this._remoteAddress = binding.address(this._handle, false);
this._state |= constants.state.CONNECTED;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onreset(err) {
if (err) {
this._errors.push(err);
this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors));
return;
}
this.connect(...this._addresses.shift());
}
_onread(err, read) {
if (this._timer) this._timer.refresh();
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
if (this._timer) this._timer.refresh();
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err);
}
_onclose() {
clearTimeout(this._timer);
this._continueDestroy();
}
};
exports.Server = class TCPServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
this._noDelay = noDelay;
this._pauseOnConnect = pauseOnConnect;
this._address = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
get closing() {
return (this._state & constants.state.CLOSING) !== 0;
}
get connections() {
return this._connections;
}
address() {
if ((this._state & constants.state.BOUND) === 0) return null;
const { address, family, port } = this._address;
return { address, family: `IPv${family}`, port };
}
listen(port = 0, host = "localhost", backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof port === "function") {
onlistening = port;
port = 0;
} else if (typeof host === "function") {
onlistening = host;
host = "localhost";
} else if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
backlog = opts.backlog || 511;
}
if (!host) host = "localhost";
if (!backlog) backlog = 511;
const { lookup = dns.lookup, hints } = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { family, hints }, (err, address, family2) => {
if (this._state & constants.state.CLOSING) return;
this.emit("lookup", err, address, family2, host);
this._state &= ~constants.state.BINDING;
if (err) return this.emit("error", err);
this.listen(port, address, backlog, { ...opts, family: family2 }, onlistening);
});
return this;
}
family = type;
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, port, host, backlog, family);
this._address = binding.address(this._handle, true);
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return this;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const socket = new exports.Socket({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, socket._handle);
socket._localAddress = binding.address(socket._handle, true);
socket._remoteAddress = binding.address(socket._handle, false);
socket._state |= constants.state.CONNECTED;
this._connections.add(socket);
if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) socket.setNoDelay();
socket.on("close", () => {
this._connections.delete(socket);
this._closeMaybe();
});
this.emit("connection", socket);
} catch (err2) {
socket.destroy();
this.emit("error", err2);
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
this._address = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.isIP = ip.isIP;
exports.isIPv4 = ip.isIPv4;
exports.isIPv6 = ip.isIPv6;
exports.createConnection = function createConnection(port, host, opts, onconnect) {
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
}
return new exports.Socket(opts).connect(port, host, opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../../node_modules/bare-http-parser/lib/errors.js
var require_errors4 = __commonJS({
"../../node_modules/bare-http-parser/lib/errors.js"(exports, module) {
module.exports = class HTTPParserError extends Error {
constructor(msg, fn = HTTPParserError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
}
get name() {
return "HTTPParserError";
}
static INVALID_MESSAGE(msg = "Invalid HTTP message") {
return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE);
}
static INVALID_HEADER(msg = "Invalid HTTP header") {
return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER);
}
static INVALID_CONTENT_LENGTH(msg = "Invalid HTTP Content-Length") {
return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH);
}
static INVALID_CHUNK_LENGTH(msg = "Invalid HTTP chunk length") {
return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH);
}
};
}
});
// ../../node_modules/bare-http-parser/index.js
var require_bare_http_parser = __commonJS({
"../../node_modules/bare-http-parser/index.js"(exports, module) {
var errors = require_errors4();
var constants = {
REQUEST: 1,
RESPONSE: 2,
DATA: 3,
END: 4
};
var TAB = 9;
var LF = 10;
var CR = 13;
var SP = 32;
var ZERO = 48;
var NINE = 57;
var UPPER_A = 65;
var UPPER_F = 70;
var UPPER_Z = 90;
var LOWER_A = 97;
var LOWER_F = 102;
var COLON = 58;
var MAX_CHUNK_SIZE_LENGTH = 16;
var FIRST_TOKEN = 0;
var REQUEST_URL = 1;
var REQUEST_VERSION = 2;
var STATUS_CODE = 3;
var STATUS_REASON = 4;
var FIRST_LINE_LF = 5;
var HEADER_START = 6;
var HEADER_NAME = 7;
var HEADER_VALUE_WS = 8;
var HEADER_VALUE = 9;
var HEADER_LINE_LF = 10;
var HEADER_END_LF = 11;
var BODY = 12;
var CHUNK_SIZE = 13;
var CHUNK_SIZE_LF = 14;
var CHUNK_DATA = 15;
var CHUNK_EXTENSION = 16;
var LAST_CHUNK_LF = 17;
var TRAILER_CR = 18;
var TRAILER_LF = 19;
module.exports = exports = class HTTPParser {
constructor(opts = {}) {
const { maxHeaderSize = 16384, maxHeadersCount = 2e3 } = opts;
this._maxHeaderSize = maxHeaderSize;
this._maxHeadersCount = maxHeadersCount;
this._state = FIRST_TOKEN;
this._buffer = [];
this._bufferIndex = 0;
this._byteIndex = 0;
this._buffered = 0;
this._accumulator = [];
this._isResponse = false;
this._method = "";
this._url = "";
this._version = "";
this._code = 0;
this._reason = "";
this._headerName = "";
this._headers = {};
this._headerCount = 0;
this._headerSize = 0;
this._remaining = 0;
}
*push(data, encoding) {
if (typeof data === "string") data = Buffer.from(data, encoding);
this._buffer.push(data);
this._buffered += data.byteLength;
yield* this._parse();
this._compact();
}
end() {
const buffers = this._buffer;
const bufferIndex = this._bufferIndex;
const byteIndex = this._byteIndex;
this._buffer = [];
this._bufferIndex = 0;
this._byteIndex = 0;
this._buffered = 0;
if (bufferIndex >= buffers.length) return Buffer.alloc(0);
buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex);
const remaining = buffers.slice(bufferIndex);
if (remaining.length === 0) return Buffer.alloc(0);
if (remaining.length === 1) return remaining[0];
return Buffer.concat(remaining);
}
_compact() {
if (this._bufferIndex > 0) {
this._buffer = this._buffer.slice(this._bufferIndex);
this._bufferIndex = 0;
}
if (this._byteIndex > 0 && this._buffer.length > 0) {
this._buffer[0] = this._buffer[0].subarray(this._byteIndex);
this._byteIndex = 0;
}
}
_consume(n) {
this._buffered -= n;
const current = this._buffer[this._bufferIndex];
if (this._byteIndex + n <= current.byteLength) {
const slice = current.subarray(this._byteIndex, this._byteIndex + n);
this._byteIndex += n;
if (this._byteIndex >= current.byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
return slice;
}
const result = Buffer.allocUnsafe(n);
let written = 0;
while (written < n) {
const buffer = this._buffer[this._bufferIndex];
const available = buffer.byteLength - this._byteIndex;
const take = Math.min(available, n - written);
buffer.copy(result, written, this._byteIndex, this._byteIndex + take);
written += take;
this._byteIndex += take;
if (this._byteIndex >= buffer.byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
}
return result;
}
_buildString() {
const string = String.fromCharCode.apply(null, this._accumulator);
this._accumulator = [];
return string;
}
_checkHeaderSize() {
if (++this._headerSize > this._maxHeaderSize) {
throw errors.INVALID_MESSAGE("Header exceeds limit of " + this._maxHeaderSize + " bytes");
}
}
_storeHeader(name, value) {
let end = value.length;
while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
end--;
}
if (end < value.length) value = value.substring(0, end);
this._headerCount++;
if (this._headerCount > this._maxHeadersCount) {
throw errors.INVALID_MESSAGE("Header count exceeds limit of " + this._maxHeadersCount);
}
switch (name) {
case "__proto__":
case "constructor":
case "prototype":
throw errors.INVALID_HEADER("Unsafe header name '" + name + "'");
case "host":
case "content-length":
case "transfer-encoding":
if (name in this._headers) {
throw errors.INVALID_HEADER("Duplicate header '" + name + "'");
}
this._headers[name] = value;
break;
default:
const delimiter = name === "cookie" ? "; " : ", ";
if (name in this._headers) {
this._headers[name] += delimiter + value;
} else {
this._headers[name] = value;
}
}
}
*_parse() {
while (true) {
if (this._state === BODY) {
if (this._buffered === 0) return;
const available = Math.min(this._buffered, this._remaining);
const data = this._consume(available);
this._remaining -= available;
const ended = this._remaining === 0;
if (ended) this._state = FIRST_TOKEN;
yield { type: constants.DATA, data };
if (ended) yield { type: constants.END };
continue;
}
if (this._state === CHUNK_DATA) {
if (this._buffered < this._remaining) return;
const consumed = this._consume(this._remaining);
if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
throw errors.INVALID_MESSAGE("Expected CRLF after chunk data");
}
const data = consumed.subarray(0, this._remaining - 2);
this._remaining = 0;
this._state = CHUNK_SIZE;
yield { type: constants.DATA, data };
continue;
}
if (this._buffered === 0) return;
const byte = this._buffer[this._bufferIndex][this._byteIndex++];
this._buffered--;
if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
this._bufferIndex++;
this._byteIndex = 0;
}
switch (this._state) {
case FIRST_TOKEN: {
this._checkHeaderSize();
if (byte === SP) {
const token = this._buildString();
if (token.length === 0) throw errors.INVALID_MESSAGE();
this._isResponse = token.startsWith("HTTP/");
if (this._isResponse) {
if (token !== "HTTP/1.0" && token !== "HTTP/1.1") {
throw errors.INVALID_MESSAGE();
}
this._version = token;
this._state = STATUS_CODE;
} else {
this._method = token;
this._state = REQUEST_URL;
}
} else if (byte === CR) {
throw errors.INVALID_MESSAGE();
} else if (isTokenByte(byte)) {
this._accumulator.push(byte);
} else if (byte === 47 && this._accumulator.length === 4 && this._accumulator[0] === 72 && this._accumulator[1] === 84 && this._accumulator[2] === 84 && this._accumulator[3] === 80) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case REQUEST_URL: {
this._checkHeaderSize();
if (byte === SP) {
this._url = this._buildString();
if (this._url.length === 0) throw errors.INVALID_MESSAGE();
this._state = REQUEST_VERSION;
} else if (byte === CR) {
throw errors.INVALID_MESSAGE();
} else if (byte >= 33 && byte !== 127) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case REQUEST_VERSION: {
this._checkHeaderSize();
if (byte === CR) {
this._version = this._buildString();
if (this._version !== "HTTP/1.0" && this._version !== "HTTP/1.1") {
throw errors.INVALID_MESSAGE();
}
this._state = FIRST_LINE_LF;
} else if (byte >= 33 && byte !== 127) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case STATUS_CODE: {
this._checkHeaderSize();
if (byte === SP) {
if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE();
let code = 0;
for (let i = 0, n = this._accumulator.length; i < n; i++) {
code = code * 10 + this._accumulator[i];
}
this._accumulator = [];
if (code < 100 || code > 999) throw errors.INVALID_MESSAGE();
this._code = code;
this._state = STATUS_REASON;
} else if (byte >= ZERO && byte <= NINE) {
this._accumulator.push(byte - ZERO);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case STATUS_REASON: {
this._checkHeaderSize();
if (byte === CR) {
this._reason = this._buildString();
this._state = FIRST_LINE_LF;
} else if (isFieldByte(byte)) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_MESSAGE();
}
break;
}
case FIRST_LINE_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
this._headers = {};
this._headerCount = 0;
this._state = HEADER_START;
break;
}
case HEADER_START: {
this._checkHeaderSize();
if (byte === CR) {
this._state = HEADER_END_LF;
} else if (byte !== COLON && isTokenByte(byte)) {
this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 32 : byte);
this._state = HEADER_NAME;
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_NAME: {
this._checkHeaderSize();
if (byte === COLON) {
this._headerName = this._buildString();
this._state = HEADER_VALUE_WS;
} else if (byte !== COLON && isTokenByte(byte)) {
this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 32 : byte);
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_VALUE_WS: {
this._checkHeaderSize();
if (byte === SP || byte === TAB) break;
if (byte === CR) {
this._storeHeader(this._headerName, "");
this._headerName = "";
this._state = HEADER_LINE_LF;
break;
}
if (!isFieldByte(byte)) throw errors.INVALID_HEADER();
this._accumulator.push(byte);
this._state = HEADER_VALUE;
break;
}
case HEADER_VALUE: {
this._checkHeaderSize();
if (byte === CR) {
this._storeHeader(this._headerName, this._buildString());
this._headerName = "";
this._state = HEADER_LINE_LF;
} else if (isFieldByte(byte)) {
this._accumulator.push(byte);
} else {
throw errors.INVALID_HEADER();
}
break;
}
case HEADER_LINE_LF: {
if (byte !== LF) throw errors.INVALID_HEADER();
this._state = HEADER_START;
break;
}
case HEADER_END_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
const headers = this._headers;
if (this._isResponse) {
yield {
type: constants.RESPONSE,
version: this._version,
code: this._code,
reason: this._reason,
headers
};
} else {
if (this._version === "HTTP/1.1" && !("host" in headers)) {
throw errors.INVALID_HEADER("Header 'Host' is missing");
}
yield {
type: constants.REQUEST,
version: this._version,
method: this._method,
url: this._url,
headers
};
}
const transferEncoding = headers["transfer-encoding"];
const contentLength = headers["content-length"];
const encodings = transferEncoding ? transferEncoding.split(",") : null;
const lastEncoding = encodings ? encodings[encodings.length - 1].trim().toLowerCase() : null;
if (lastEncoding === "chunked") {
if (contentLength) {
throw errors.INVALID_MESSAGE(
"Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
);
}
this._state = CHUNK_SIZE;
this._headerSize = 0;
continue;
}
if (contentLength) {
if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH();
let length = 0;
for (let i = 0, n = contentLength.length; i < n; i++) {
const c = contentLength.charCodeAt(i);
if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH();
length = length * 10 + (c - ZERO);
}
if (!Number.isSafeInteger(length) || length < 0) {
throw errors.INVALID_CONTENT_LENGTH();
}
if (length === 0) {
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
} else {
this._state = BODY;
this._remaining = length;
this._headerSize = 0;
}
} else {
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
}
break;
}
case CHUNK_SIZE: {
if (byte === CR || byte === 59) {
if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH();
let length = 0;
for (let i = 0, n = this._accumulator.length; i < n; i++) {
length = length * 16 + this._accumulator[i];
}
this._accumulator = [];
if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH();
if (byte === 59) {
this._remaining = length;
this._state = CHUNK_EXTENSION;
} else if (length === 0) {
this._state = LAST_CHUNK_LF;
} else {
this._remaining = length + 2;
this._state = CHUNK_SIZE_LF;
}
} else if (isHex(byte)) {
if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
throw errors.INVALID_CHUNK_LENGTH();
}
this._accumulator.push(hexValue(byte));
} else {
throw errors.INVALID_CHUNK_LENGTH();
}
break;
}
case CHUNK_EXTENSION: {
this._checkHeaderSize();
if (byte === CR) {
if (this._remaining === 0) {
this._state = LAST_CHUNK_LF;
} else {
this._remaining += 2;
this._state = CHUNK_SIZE_LF;
}
} else if (!isFieldByte(byte)) {
throw errors.INVALID_CHUNK_LENGTH();
}
break;
}
case CHUNK_SIZE_LF: {
if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH();
this._state = CHUNK_DATA;
break;
}
case LAST_CHUNK_LF: {
if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH();
this._state = TRAILER_CR;
break;
}
case TRAILER_CR: {
if (byte !== CR) throw errors.INVALID_MESSAGE();
this._state = TRAILER_LF;
break;
}
case TRAILER_LF: {
if (byte !== LF) throw errors.INVALID_MESSAGE();
this._state = FIRST_TOKEN;
this._headerSize = 0;
yield { type: constants.END };
break;
}
default:
throw errors.INVALID_MESSAGE();
}
}
}
};
exports.constants = constants;
var TOKEN_BYTES = Buffer.from([
// 0x00-0x1f (control characters) + 0x20 (space)
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
// 0x42-0x62: B-Z [ \ ] ^ _ ` a b
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
// 0x63-0x7f: c-z { | } ~ DEL
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0
]);
function isTokenByte(b) {
return TOKEN_BYTES[b] === 1;
}
function isFieldByte(b) {
return b === TAB || b >= 32 && b <= 126;
}
function isHex(b) {
return b >= ZERO && b <= NINE || b >= UPPER_A && b <= UPPER_F || b >= LOWER_A && b <= LOWER_F;
}
function hexValue(b) {
if (b >= ZERO && b <= NINE) return b - ZERO;
if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10;
return b - LOWER_A + 10;
}
}
});
// ../../node_modules/bare-http1/lib/client-connection.js
var require_client_connection = __commonJS({
"../../node_modules/bare-http1/lib/client-connection.js"(exports, module) {
var HTTPParser = require_bare_http_parser();
var HTTPIncomingMessage = require_incoming_message();
var errors = require_errors();
var {
constants: { RESPONSE, DATA, END }
} = HTTPParser;
var EMPTY = Buffer.alloc(0);
module.exports = class HTTPClientConnection {
static _connections = /* @__PURE__ */ new WeakMap();
static for(socket) {
return this._connections.get(socket) || null;
}
static from(socket, opts) {
return this.for(socket) || new this(socket, opts);
}
constructor(socket, opts = {}) {
const { IncomingMessage = HTTPIncomingMessage } = opts;
this._socket = socket;
this._req = null;
this._res = null;
this._IncomingMessage = IncomingMessage;
this._parser = new HTTPParser();
this._idle = true;
this._onerror = this._onerror.bind(this);
this._onclose = this._onclose.bind(this);
this._onend = this._onend.bind(this);
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._ontimeout = this._ontimeout.bind(this);
socket.on("error", this._onerror).on("close", this._onclose).on("end", this._onend).on("data", this._ondata).on("drain", this._ondrain).on("timeout", this._ontimeout);
HTTPClientConnection._connections.set(socket, this);
}
get socket() {
return this._socket;
}
get req() {
return this._req;
}
get res() {
return this._res;
}
get idle() {
return this._idle;
}
_onerror(err) {
if (this._req) this._req.destroy(err);
}
_onclose() {
if (this._req) this._req.destroy();
}
_onend() {
if (this._req) this._req.destroy(errors.CONNECTION_LOST());
}
_ondata(data) {
this._idle = false;
try {
for (const op of this._parser.push(data)) {
switch (op.type) {
case RESPONSE:
this._req.on("close", () => {
this._req = null;
});
this._res = new this._IncomingMessage(this._socket, {
headers: op.headers,
statusCode: op.code,
statusMessage: op.reason
});
this._res.on("close", () => {
this._res = null;
this._idle = true;
this._socket.emit("free");
});
if (op.headers.connection && op.headers.connection.toLowerCase() === "upgrade") {
return this._onupgrade(this._parser.end());
}
this._req.emit("response", this._res);
break;
case DATA:
this._res.push(op.data);
break;
case END:
if (this._res) {
this._res._socket = null;
this._res.push(null);
}
if (this._req) {
this._req._socket = null;
this._req.destroy();
}
break;
}
}
} catch (err) {
this._socket.destroy(err);
}
}
_onupgrade(data) {
this._detach();
const res = this._res;
const req = this._req;
res._upgrade = req._upgrade = true;
const upgraded = req.emit("upgrade", res, this._socket, data || EMPTY);
res.push(null);
req.destroy();
if (!upgraded) this._socket.destroy();
}
_ontimeout() {
if (this._req) this._req.emit("timeout");
}
_ondrain() {
if (this._req) this._req._continueWrite();
}
_detach() {
this._socket.off("error", this._onerror).off("close", this._onclose).off("end", this._onend).off("data", this._ondata).off("drain", this._ondrain).off("timeout", this._ontimeout);
HTTPClientConnection._connections.delete(this._socket);
}
};
}
});
// ../../node_modules/bare-http1/lib/agent.js
var require_agent = __commonJS({
"../../node_modules/bare-http1/lib/agent.js"(exports, module) {
var EventEmitter = require_bare_events();
var tcp = require_bare_tcp();
var HTTPClientConnection = require_client_connection();
var errors = require_errors();
var HTTPSocketSet = class {
constructor() {
this._sockets = /* @__PURE__ */ new Map();
this._size = 0;
}
get size() {
return this._size;
}
add(name, socket) {
const sockets = this._sockets.get(name);
this._size++;
if (sockets === void 0) this._sockets.set(name, [socket]);
else sockets.push(socket);
}
pop(name) {
const sockets = this._sockets.get(name);
if (sockets === void 0 || sockets.length === 0) return null;
this._size--;
const last = sockets.pop();
if (sockets.length === 0) this._sockets.delete(name);
return last;
}
delete(name, socket) {
const sockets = this._sockets.get(name);
if (sockets === void 0) return;
const i = sockets.indexOf(socket);
if (i === -1) return;
this._size--;
const last = sockets.pop();
if (last !== socket) sockets[i] = last;
if (sockets.length === 0) this._sockets.delete(name);
}
*sockets() {
for (const sockets of this._sockets.values()) {
yield* sockets;
}
}
*[Symbol.iterator]() {
for (const [name, sockets] of this._sockets) {
for (const socket of sockets) yield [name, socket];
}
}
};
var HTTPAgent = class _HTTPAgent extends EventEmitter {
constructor(opts = {}) {
super();
const { keepAlive = false, keepAliveMsecs = 1e3, defaultPort = 80 } = opts;
this._suspended = false;
this._resuming = null;
this._sockets = new HTTPSocketSet();
this._freeSockets = new HTTPSocketSet();
this._keepAlive = typeof keepAlive === "number" ? keepAlive : keepAlive ? keepAliveMsecs : -1;
this._defaultPort = defaultPort;
this._opts = { ...opts };
}
get suspended() {
return this._suspended;
}
get resumed() {
return this._resuming ? this._resuming.promise : null;
}
get sockets() {
return this._sockets.sockets();
}
get freeSockets() {
return this._freeSockets.sockets();
}
get defaultPort() {
return this._defaultPort;
}
createConnection(opts) {
if (this._suspended) throw errors.AGENT_SUSPENDED();
return tcp.createConnection(opts);
}
reuseSocket(socket, req) {
socket.ref();
}
keepSocketAlive(socket) {
if (this._keepAlive === -1) return false;
socket.setKeepAlive(true, this._keepAlive);
socket.unref();
return true;
}
getName(opts) {
return `${opts.host}:${opts.port}`;
}
addRequest(req, opts) {
opts = { ...opts, ...this._opts };
const name = this.getName(opts);
let socket = this._freeSockets.pop(name);
if (socket) this.reuseSocket(socket, req);
else {
let onfree2 = function() {
if (socket.destroyed) return;
if (agent.keepSocketAlive(socket)) {
agent._freeSockets.add(name, socket);
} else {
socket.end();
}
agent.emit("free", socket);
}, onremove2 = function() {
socket.off("free", onfree2);
agent._sockets.delete(name, socket);
agent._freeSockets.delete(name, socket);
if (agent._sockets.size === 0) _HTTPAgent._agents.delete(agent);
}, ontimeout2 = function() {
socket.destroy();
agent._freeSockets.delete(name, socket);
};
var onfree = onfree2, onremove = onremove2, ontimeout = ontimeout2;
const agent = this;
socket = this.createConnection(opts);
socket.on("free", onfree2).on("end", onremove2).on("finish", onremove2).on("close", onremove2).on("timeout", ontimeout2);
}
if (this._sockets.size === 0) _HTTPAgent._agents.add(this);
this._sockets.add(name, socket);
req._socket = socket;
const connection = HTTPClientConnection.from(socket, opts);
connection._req = req;
}
suspend() {
if (this._suspended) return;
this._resuming = Promise.withResolvers();
this._suspended = true;
this.destroy();
}
resume() {
if (this._resuming === null) return;
this._resuming.resolve();
this._resuming = null;
this._suspended = false;
}
destroy() {
for (const socket of this._sockets.sockets()) socket.destroy();
}
static _agents = /* @__PURE__ */ new Set();
static _onidle() {
for (const agent of this._agents) {
agent.destroy();
}
}
};
HTTPAgent.global = new HTTPAgent({ keepAlive: 1e3, timeout: 5e3 });
module.exports = HTTPAgent;
Bare.on("idle", HTTPAgent._onidle.bind(HTTPAgent));
}
});
// ../../node_modules/bare-http1/lib/constants.js
var require_constants2 = __commonJS({
"../../node_modules/bare-http1/lib/constants.js"(exports, module) {
module.exports = {
method: {
GET: "GET",
HEAD: "HEAD",
POST: "POST",
PUT: "PUT",
DELETE: "DELETE",
CONNECT: "CONNECT",
OPTIONS: "OPTIONS",
TRACE: "TRACE",
PATCH: "PATCH"
},
status: {
100: "Continue",
101: "Switching Protocols",
102: "Processing",
103: "Early Hints",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a Teapot",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
425: "Too Early",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required"
}
};
}
});
// ../../node_modules/bare-http1/lib/server-response.js
var require_server_response = __commonJS({
"../../node_modules/bare-http1/lib/server-response.js"(exports, module) {
var { isFinishing } = require_bare_stream();
var HTTPOutgoingMessage = require_outgoing_message();
var constants = require_constants2();
var CHUNK_DELIMITER = Buffer.from("\r\n");
var CHUNK_TERMINATOR = Buffer.from("0\r\n\r\n");
module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
constructor(socket, req) {
super(socket);
this._req = req;
this._statusCode = 200;
this._statusMessage = null;
this._chunked = true;
this._close = req.headers.connection === "close";
this._onlyHeaders = req.method === "HEAD";
this._pendingWrite = null;
}
get req() {
return this._req;
}
get statusCode() {
return this._statusCode;
}
set statusCode(value) {
this._statusCode = value;
}
get statusMessage() {
return this._statusMessage;
}
set statusMessage(value) {
this._statusMessage = value;
}
writeHead(statusCode, statusMessage = null, headers = {}) {
if (typeof statusMessage === "object" && statusMessage !== null) {
headers = statusMessage;
statusMessage = null;
}
this._statusCode = statusCode;
this._statusMessage = statusMessage || null;
if (headers) this._headers = { ...this._headers, ...headers };
}
_header() {
let h = "HTTP/1.1 " + this._statusCode + " " + (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) + "\r\n";
for (const name of Object.keys(this._headers)) {
const n = name.toLowerCase();
const v = this._headers[name];
if (n === "content-length") this._chunked = false;
if (n === "connection" && v && v.toLowerCase() === "close") this._close = true;
h += httpCase(n) + ": " + v + "\r\n";
}
if (this._chunked) h += "Transfer-Encoding: chunked\r\n";
h += "\r\n";
return h;
}
_write(data, encoding, cb) {
if (this._headersSent === false) {
if (isFinishing(this)) {
this.setHeader(
"Content-Length",
(data.byteLength + this._writableState.buffered).toString()
);
}
this.flushHeaders();
}
if (this._onlyHeaders === true) return cb(null);
if (this._chunked) {
this._socket.write(Buffer.from(data.byteLength.toString(16)));
this._socket.write(CHUNK_DELIMITER);
}
let flushed = this._socket.write(data);
if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER);
if (flushed) cb(null);
else this._pendingWrite = cb;
}
_final(cb) {
if (this._headersSent === false) {
this.setHeader("Content-Length", "0");
this.flushHeaders();
}
if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR);
if (this._close) this._socket.end();
cb(null);
}
_predestroy() {
super._predestroy();
this._req.destroy();
this._continueWrite();
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
};
function httpCase(n) {
let s = "";
for (const part of n.split("-")) {
s += (s ? "-" : "") + part.slice(0, 1).toUpperCase() + part.slice(1);
}
return s;
}
}
});
// ../../node_modules/bare-http1/lib/server-connection.js
var require_server_connection = __commonJS({
"../../node_modules/bare-http1/lib/server-connection.js"(exports, module) {
var { isEnded, isFinished, getStreamError } = require_bare_stream();
var HTTPParser = require_bare_http_parser();
var HTTPIncomingMessage = require_incoming_message();
var HTTPServerResponse = require_server_response();
var {
constants: { REQUEST, DATA, END }
} = HTTPParser;
var EMPTY = Buffer.alloc(0);
module.exports = class HTTPServerConnection {
static _connections = /* @__PURE__ */ new WeakMap();
static for(socket) {
return this._connections.get(socket) || null;
}
constructor(server, socket, opts = {}) {
const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts;
this._server = server;
this._socket = socket;
this._req = null;
this._res = null;
this._IncomingMessage = IncomingMessage;
this._ServerResponse = ServerResponse;
this._parser = new HTTPParser();
this._idle = true;
this._onclose = this._onclose.bind(this);
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._ontimeout = this._ontimeout.bind(this);
socket.on("error", noop).on("close", this._onclose).on("data", this._ondata).on("drain", this._ondrain).on("timeout", this._ontimeout);
HTTPServerConnection._connections.set(socket, this);
if (this._server.timeout) socket.setTimeout(this._server.timeout);
}
get server() {
return this._server;
}
get socket() {
return this._socket;
}
get req() {
return this._req;
}
get res() {
return this._res;
}
get idle() {
return this._idle;
}
_onclose() {
if (this._req && !isEnded(this._req)) this._req.destroy();
if (this._res && !isFinished(this._res)) this._res.destroy();
const err = getStreamError(this._socket);
if (err) this._socket.destroy(err);
}
_ondata(data) {
this._idle = false;
try {
for (const op of this._parser.push(data)) {
switch (op.type) {
case REQUEST:
this._req = new this._IncomingMessage(this._socket, {
headers: op.headers,
method: op.method,
url: op.url
});
this._req.on("close", () => {
this._req = null;
this._idle = true;
if (this._server.closing) this._socket.destroy();
});
this._req.resume();
this._req.pause();
if (op.headers.connection && op.headers.connection.toLowerCase() === "upgrade") {
return this._onupgrade(this._parser.end());
}
this._res = new this._ServerResponse(this._socket, this._req);
this._res.on("close", () => {
this._res = null;
});
this._server.emit("request", this._req, this._res);
break;
case DATA:
this._req.push(op.data);
break;
case END:
if (this._req) {
this._req._socket = null;
this._req.push(null);
}
break;
}
}
} catch (err) {
this._socket.destroy(err);
}
}
_onupgrade(data) {
this._detach();
const req = this._req;
req._upgrade = true;
const upgraded = this._server.emit("upgrade", req, this._socket, data || EMPTY);
req.push(null);
if (!upgraded) this._socket.destroy();
}
_ontimeout() {
const reqTimeout = this._req && this._req.emit("timeout");
const resTimeout = this._res && this._res.emit("timeout");
const serverTimeout = this._server.emit("timeout", this._socket);
if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy();
}
_ondrain() {
if (this._res) this._res._continueWrite();
}
_detach() {
this._socket.off("error", noop).off("close", this._onclose).off("data", this._ondata).off("drain", this._ondrain).off("timeout", this._ontimeout);
HTTPServerConnection._connections.delete(this._socket);
}
};
function noop() {
}
}
});
// ../../node_modules/bare-http1/lib/server.js
var require_server = __commonJS({
"../../node_modules/bare-http1/lib/server.js"(exports, module) {
var TCPServer = require_bare_tcp().Server;
var HTTPServerConnection = require_server_connection();
module.exports = class HTTPServer extends TCPServer {
constructor(opts = {}, onrequest) {
if (typeof opts === "function") {
onrequest = opts;
opts = {};
}
super({ allowHalfOpen: false });
this._timeout = 0;
this.on("connection", (socket) => {
new HTTPServerConnection(this, socket, opts);
});
if (onrequest) this.on("request", onrequest);
}
get timeout() {
return this._timeout || void 0;
}
setTimeout(ms = 0, ontimeout) {
if (ontimeout) this.on("timeout", ontimeout);
this._timeout = ms;
return this;
}
close(onclose) {
super.close(onclose);
for (const socket of this.connections) {
const connection = HTTPServerConnection.for(socket);
if (connection === null || connection.idle) {
socket.destroy();
}
}
return this;
}
};
}
});
// ../../node_modules/bare-http1/lib/client-request.js
var require_client_request = __commonJS({
"../../node_modules/bare-http1/lib/client-request.js"(exports, module) {
var HTTPAgent = require_agent();
var HTTPOutgoingMessage = require_outgoing_message();
var CHUNK_DELIMITER = Buffer.from("\r\n");
var CHUNK_TERMINATOR = Buffer.from("0\r\n\r\n");
module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
constructor(opts = {}, onresponse = null) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
opts = opts ? { ...opts } : {};
const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global;
const method = opts.method || "GET";
const path = opts.path || "/";
const defaultPort = opts.defaultPort || agent && agent.defaultPort || 80;
const host = opts.host = opts.host || "localhost";
const port = opts.port = opts.port || defaultPort;
const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers };
super();
agent.addRequest(this, opts);
this._headers = headers;
this._method = method;
this._path = path;
this._chunked = method !== "GET" && method !== "HEAD";
this._pendingWrite = null;
this._pendingFinal = null;
if (onresponse) this.once("response", onresponse);
}
get method() {
return this._method;
}
get path() {
return this._path;
}
// For Node.js compatibility
abort() {
return this.destroy();
}
_header() {
let h = `${this._method} ${this._path} HTTP/1.1\r
`;
let upgrade = false;
for (const name of Object.keys(this._headers)) {
const n = name.toLowerCase();
const v = this._headers[name];
if (n === "content-length") this._chunked = false;
if (n === "connection" && v && v.toLowerCase() === "upgrade") upgrade = true;
h += `${httpCase(n)}: ${v}\r
`;
}
if (upgrade) this._chunked = false;
if (this._chunked) h += "Transfer-Encoding: chunked\r\n";
h += "\r\n";
return h;
}
_write(data, encoding, cb) {
if (this._headersSent === false) this.flushHeaders();
if (this._chunked) {
this._socket.write(Buffer.from(data.byteLength.toString(16)));
this._socket.write(CHUNK_DELIMITER);
}
let flushed = this._socket.write(data);
if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER);
if (flushed) cb(null);
else this._pendingWrite = cb;
}
_final(cb) {
if (this._headersSent === false) this.flushHeaders();
if (this._chunked) this._socket.write(CHUNK_TERMINATOR);
this._pendingFinal = cb;
}
_predestroy() {
super._predestroy();
this._continueWrite();
this._continueFinal();
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_continueFinal() {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(null);
}
};
function httpCase(n) {
let s = "";
for (const part of n.split("-")) {
s += (s ? "-" : "") + part.slice(0, 1).toUpperCase() + part.slice(1);
}
return s;
}
function hostHeader(host, port, defaultPort) {
const i = host.indexOf(":");
if (i !== -1 && host.includes(":", i + 1) && host.charCodeAt(0) !== 91) {
host = `[${host}]`;
}
if (port && +port !== defaultPort) {
host += ":" + port;
}
return host;
}
}
});
// ../../node_modules/bare-http1/index.js
var require_bare_http1 = __commonJS({
"../../node_modules/bare-http1/index.js"(exports) {
exports.IncomingMessage = require_incoming_message();
exports.OutgoingMessage = require_outgoing_message();
exports.Agent = require_agent();
exports.globalAgent = exports.Agent.global;
exports.Server = require_server();
exports.ServerResponse = require_server_response();
exports.ServerConnection = require_server_connection();
exports.ClientRequest = require_client_request();
exports.ClientConnection = require_client_connection();
exports.constants = require_constants2();
exports.errors = require_errors();
exports.METHODS = Object.values(exports.constants.method);
exports.STATUS_CODES = exports.constants.status;
exports.createServer = function createServer(opts, onrequest) {
return new exports.Server(opts, onrequest);
};
exports.request = function request(url, opts, onresponse) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
if (typeof url === "string") url = new URL(url);
if (isURL(url)) {
opts = opts ? { ...url, ...opts } : { ...url };
opts.host = url.hostname;
opts.path = url.pathname + url.search;
opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url);
} else {
opts = url ? { ...url } : {};
opts.host = opts.hostname || opts.host;
opts.port = typeof opts.port === "string" ? parseInt(opts.port, 10) : opts.port;
}
return new exports.ClientRequest(opts, onresponse);
};
exports.get = function get(url, opts, onresponse) {
const req = exports.request(url, opts, onresponse);
req.end();
return req;
};
function defaultPort(url) {
switch (url.protocol) {
case "ftp:":
return 21;
case "http:":
case "ws:":
return 80;
case "https:":
case "wss:":
return 443;
}
return null;
}
function isURL(url) {
return url !== null && typeof url === "object" && typeof url.protocol === "string" && typeof url.hostname === "string" && typeof url.pathname === "string" && typeof url.search === "string";
}
}
});
// ../../node_modules/bare-tls/binding.js
var require_binding3 = __commonJS({
"../../node_modules/bare-tls/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tls/lib/constants.js
var require_constants3 = __commonJS({
"../../node_modules/bare-tls/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTED: 1,
ATTACHED: 2
}
};
}
});
// ../../node_modules/bare-tls/lib/errors.js
var require_errors5 = __commonJS({
"../../node_modules/bare-tls/lib/errors.js"(exports, module) {
module.exports = class TLSError extends Error {
constructor(msg, code, fn = TLSError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "TLSError";
}
static from(err) {
return new TLSError(err.message, err.code, TLSError.from);
}
};
}
});
// ../../node_modules/bare-pipe/binding.js
var require_binding4 = __commonJS({
"../../node_modules/bare-pipe/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-pipe/lib/constants.js
var require_constants4 = __commonJS({
"../../node_modules/bare-pipe/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
READABLE: 64,
WRITABLE: 128,
UNREFED: 256
}
};
}
});
// ../../node_modules/bare-pipe/lib/errors.js
var require_errors6 = __commonJS({
"../../node_modules/bare-pipe/lib/errors.js"(exports, module) {
module.exports = class PipeError extends Error {
constructor(msg, fn = PipeError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "PipeError";
}
static PIPE_ALREADY_CONNECTED(msg) {
return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new PipeError(msg, PipeError.SERVER_IS_CLOSED);
}
};
}
});
// ../../node_modules/bare-pipe/index.js
var require_bare_pipe = __commonJS({
"../../node_modules/bare-pipe/index.js"(exports, module) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var binding = require_binding4();
var constants = require_constants4();
var errors = require_errors6();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
module.exports = exports = class Pipe extends Duplex {
constructor(path, opts = {}) {
if (typeof path === "object" && path !== null) {
opts = path;
path = null;
}
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._fd = -1;
this._path = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._buffer = Buffer.alloc(readBufferSize);
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onwrite,
this._onfinal,
this._onread,
this._onclose
);
if (typeof path === "number") {
this.open(path);
} else if (typeof path === "string") {
this.connect(path);
}
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get readyState() {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
return "open";
}
if (this._state & constants.state.READABLE) {
return "readOnly";
}
if (this._state & constants.state.WRITABLE) {
return "writeOnly";
}
return "opening";
}
open(fd, opts = {}, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof fd === "object" && fd !== null) {
opts = fd || {};
fd = opts.fd;
}
try {
const status = binding.open(this._handle, fd);
this._state |= constants.state.CONNECTED;
this._fd = fd;
if (status & binding.READABLE) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (status & binding.WRITABLE) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
if (onconnect) this.once("connect", onconnect);
queueMicrotask(() => this.emit("connect"));
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
connect(path, opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.PIPE_ALREADY_CONNECTED("Pipe is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
try {
binding.connect(this._handle, path);
this._path = path;
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
this._pendingFinal = cb;
binding.end(this._handle);
} else {
cb(null);
}
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onconnect(err) {
if (err) {
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onread(err, read) {
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err === null || err.code === "ENOTCONN" ? null : err);
}
_onclose() {
this._continueDestroy();
}
_onspawn(readable, writable) {
this._state |= constants.state.CONNECTED;
if (readable) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (writable) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
this._continueOpen();
}
};
exports.Pipe = exports;
exports.pipe = function pipe() {
return binding.pipe();
};
exports.Server = class PipeServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._pauseOnConnect = pauseOnConnect;
this._path = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
address() {
if ((this._state & constants.state.BOUND) === 0) {
return null;
}
return this._path;
}
listen(path, backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
backlog = opts.backlog || 511;
}
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, path, backlog);
this._path = path;
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const pipe = new exports.Pipe({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, pipe._handle);
pipe._path = this._path;
pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._connections.add(pipe);
pipe.on("close", () => {
this._connections.delete(pipe);
this._closeMaybe();
});
this.emit("connection", pipe);
} catch (err2) {
pipe.destroy();
throw err2;
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.createConnection = function createConnection(path, opts, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
return new exports.Pipe(opts).connect(path, opts, onconnect);
};
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../../node_modules/bare-net/lib/constants.js
var require_constants5 = __commonJS({
"../../node_modules/bare-net/lib/constants.js"(exports, module) {
module.exports = {
type: {
TCP: 1,
IPC: 2
},
state: {
UNREFED: 1
}
};
}
});
// ../../node_modules/bare-net/index.js
var require_bare_net = __commonJS({
"../../node_modules/bare-net/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var tcp = require_bare_tcp();
var pipe = require_bare_pipe();
var constants = require_constants5();
var defaultReadBufferSize = 65536;
exports.Socket = class NetSocket extends Duplex {
constructor(opts = {}) {
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
eagerOpen = false
} = opts;
super({ eagerOpen, allowHalfOpen });
this._type = 0;
this._state = 0;
this._socket = null;
this._opts = { readBufferSize, allowHalfOpen, eagerOpen };
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
}
get connecting() {
return this._socket !== null && this._socket.connecting;
}
get pending() {
return this._socket === null || this._socket.pending;
}
get timeout() {
return this._socket === null ? void 0 : this._socket.timeout;
}
get readyState() {
return this._socket === null ? "opening" : this._socket.readyState;
}
get localAddress() {
return this._socket === null ? void 0 : this._socket.localAddress;
}
get localPort() {
return this._socket === null ? void 0 : this._socket.localPort;
}
get localFamily() {
return this._socket === null ? void 0 : this._socket.localFamily;
}
get remoteAddress() {
return this._socket === null ? void 0 : this._socket.remoteAddress;
}
get remotePort() {
return this._socket === null ? void 0 : this._socket.remotePort;
}
get remoteFamily() {
return this._socket === null ? void 0 : this._socket.remoteFamily;
}
connect(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createConnection(opts));
} else {
this._attach(constants.type.TCP, tcp.createConnection(opts));
}
if (onconnect) this.once("connect", onconnect);
return this;
}
setKeepAlive(...args) {
if (this._socket !== null) this._socket.setKeepAlive(...args);
return this;
}
setNoDelay(...args) {
if (this._socket !== null) this._socket.setNoDelay(...args);
return this;
}
setTimeout(...args) {
if (this._socket !== null) this._socket.setTimeout(...args);
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._socket !== null) this._socket.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._socket !== null) this._socket.unref();
return this;
}
_attach(type, socket) {
this._type = type;
this._socket = socket;
this._socket.on("connect", this._onconnect.bind(this)).on("timeout", this._ontimeout.bind(this)).on("error", this._onerror.bind(this)).on("data", this._ondata.bind(this)).on("end", this._onend.bind(this)).on("finish", this._onfinish.bind(this)).on("drain", this._ondrain.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._socket.unref();
this._continueOpen();
return this;
}
_open(cb) {
if (this._socket !== null) return cb(null);
this._pendingOpen = cb;
}
_write(data, encoding, cb) {
if (this._socket.write(data)) return cb(null);
this._pendingWrite = cb;
}
_final(cb) {
this._socket.end();
this._pendingFinal = cb;
}
_destroy(err, cb) {
if (this._socket === null || this._socket.destroyed) return cb(null);
this._socket.destroy(err);
this._pendingDestroy = cb;
}
_onconnect() {
this.emit("connect");
}
_ontimeout() {
this.emit("timeout");
}
_onerror(err) {
this.destroy(err);
}
_ondata(data) {
this.push(data);
}
_onend() {
this.push(null);
}
_onfinish() {
this._continueFinal();
}
_ondrain() {
this._continueWrite();
}
_onclose() {
this._continueWrite();
this._continueFinal();
if (this._pendingDestroy) this._continueDestroy();
else this.destroy();
}
_continueOpen() {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(null);
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_continueFinal() {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(null);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
};
exports.Server = class NetServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
pauseOnConnect = false
} = opts;
this._type = 0;
this._state = 0;
this._server = null;
this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect };
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server !== null && this._server.listening;
}
address() {
return this._server === null ? null : this._server.address();
}
listen(...args) {
let opts = {};
let onlistening;
if (typeof args[0] === "string") {
opts.path = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.backlog = args[1];
onlistening = args[2];
}
} else {
if (typeof args[0] === "function") {
onlistening = args[0];
} else {
opts.port = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.host = args[1];
if (typeof args[2] === "function") {
onlistening = args[2];
} else {
opts.backlog = args[2];
onlistening = args[3];
}
}
}
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createServer(opts));
} else {
this._attach(constants.type.TCP, tcp.createServer(opts));
}
this._server.listen(opts);
if (onlistening) this.once("listening", onlistening);
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
this._server.close();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._server !== null) this._server.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._server !== null) this._server.unref();
return this;
}
_attach(type, server) {
this._type = type;
this._server = server;
this._server.on("listening", this._onlistening.bind(this)).on("connection", this._onconnection.bind(this)).on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._server.unref();
return this;
}
_onlistening() {
this.emit("listening");
}
_onconnection(socket) {
this.emit("connection", new exports.Socket(this._opts)._attach(this._type, socket));
}
_onerror(err) {
this.emit("error", err);
}
_onclose() {
this.emit("close");
}
};
exports.constants = constants;
exports.isIP = tcp.isIP;
exports.isIPv4 = tcp.isIPv4;
exports.isIPv6 = tcp.isIPv6;
exports.createConnection = function createConnection(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
return new exports.Socket(opts).connect(opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
}
});
// ../../node_modules/bare-tls/net.js
var require_net = __commonJS({
"../../node_modules/bare-tls/net.js"(exports) {
var EventEmitter = require_bare_events();
var net = require_bare_net();
var tls = require_bare_tls();
var TLSNetSocket = class extends tls.Socket {
ref() {
this.socket.ref();
}
unref() {
this.socket.unref();
}
};
var TLSNetServer = class extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
const {
cert = null,
key = null,
host = null,
alpnProtocols = null,
eagerOpen = true,
allowHalfOpen = true
} = opts;
super();
this._opts = {
cert,
key,
host,
alpnProtocols,
eagerOpen,
allowHalfOpen
};
this._server = net.createServer(opts);
this._server.on("listening", this._onlistening.bind(this)).on("connection", this._onconnection.bind(this)).on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this));
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server.listening;
}
address() {
return this._server.address();
}
listen(...args) {
this._server.listen(...args);
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
this._server.close();
}
ref() {
this._server.ref();
}
unref() {
this._server.unref();
}
_onlistening() {
this.emit("listening");
}
_onconnection(socket) {
this.emit(
"connection",
new TLSNetSocket(socket, { ...this._opts, isServer: true })
);
}
_onerror(err) {
this.emit("error", err);
}
_onclose() {
this.emit("close");
}
};
exports.createConnection = function createConnection(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
return new TLSNetSocket(net.createConnection(opts, onconnect), opts);
};
exports.createServer = function createServer(opts, onconnection) {
return new TLSNetServer(opts, onconnection);
};
}
});
// ../../node_modules/bare-tls/index.js
var require_bare_tls = __commonJS({
"../../node_modules/bare-tls/index.js"(exports) {
var { Duplex, Writable } = require_bare_stream();
var binding = require_binding3();
var constants = require_constants3();
var errors = require_errors5();
var defaultReadBufferSize = 65536;
var context = binding.context();
exports.Socket = class TLSSocket extends Duplex {
constructor(socket, opts = {}) {
const {
isServer = false,
cert = null,
key = null,
host = null,
alpnProtocols = null,
eagerOpen = true,
allowHalfOpen = true,
readBufferSize = defaultReadBufferSize
} = opts;
super({ eagerOpen });
this._state = 0;
this._socket = socket;
this._key = key;
this._cert = cert;
this._allowHalfOpen = allowHalfOpen;
this._pendingOpen = null;
this._pendingWrite = null;
this._reading = Buffer.alloc(readBufferSize);
this._buffer = [];
this._buffered = 0;
let alpn = null;
if (alpnProtocols && alpnProtocols.length > 0) {
const parts = [];
for (const protocol of alpnProtocols) {
const encoded = Buffer.from(protocol);
if (encoded.byteLength === 0 || encoded.byteLength > 255) {
throw new RangeError("ALPN protocol name must be 1-255 bytes");
}
parts.push(Buffer.of(encoded.byteLength), encoded);
}
alpn = Buffer.concat(parts);
}
try {
this._handle = binding.init(
context,
isServer,
cert,
key,
host,
alpn,
this,
this._onread,
this._onwrite
);
} catch (err) {
this._handle = null;
this.destroy(err);
}
}
get socket() {
return this._socket;
}
get encrypted() {
return true;
}
get alpnProtocol() {
return binding.alpnProtocol(this._handle);
}
_onconnect() {
this._state |= constants.state.CONNECTED;
this.emit("connect");
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(null);
}
_ondata(data) {
this._buffer.push(data);
this._buffered += data.byteLength;
while (this._buffered > 0) {
if (this._state & constants.state.CONNECTED) {
let read;
try {
read = binding.read(this._handle, this._reading);
} catch (err) {
return this.destroy(errors.from(err));
}
if (read < 0) break;
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._reading.subarray(0, read));
this.push(copy);
} else {
try {
if (binding.handshake(this._handle)) this._onconnect();
else break;
} catch (err) {
if (this._pendingOpen) {
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(errors.from(err));
} else {
this.destroy(errors.from(err));
}
return;
}
}
}
}
_ondrain() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_onend() {
this.push(null);
}
_onerror(err) {
if (this._pendingOpen) {
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
} else {
this.destroy(err);
}
}
_onread(data) {
if (this._buffered < data.byteLength) return 0;
let offset = 0;
let remaining = data.byteLength;
while (remaining > 0) {
const chunk = this._buffer[0];
if (chunk.byteLength <= remaining) {
data.set(chunk, offset);
offset += chunk.byteLength;
remaining -= chunk.byteLength;
this._buffer.shift();
} else {
data.set(chunk.subarray(0, remaining), offset);
this._buffer[0] = chunk.subarray(remaining);
remaining = 0;
}
}
this._buffered -= data.byteLength;
return data.byteLength;
}
_onwrite(data) {
this._socket.write(Buffer.from(data.slice()));
return data.byteLength;
}
_attach() {
if (this._state & constants.state.ATTACHED) return;
this._state |= constants.state.ATTACHED;
this._ondata = this._ondata.bind(this);
this._ondrain = this._ondrain.bind(this);
this._onend = this._onend.bind(this);
this._onerror = this._onerror.bind(this);
this._socket.on("data", this._ondata).on("drain", this._ondrain).on("end", this._onend).on("error", this._onerror);
}
_detach() {
if (!(this._state & constants.state.ATTACHED)) return;
this._state &= ~constants.state.ATTACHED;
this._socket.off("data", this._ondata).off("drain", this._ondrain).off("end", this._onend).off("error", this._onerror);
}
_open(cb) {
this._pendingOpen = cb;
this._attach();
try {
if (binding.handshake(this._handle)) this._onconnect();
} catch (err) {
this._pendingOpen = null;
cb(errors.from(err));
}
}
_write(data, encoding, cb) {
try {
binding.write(this._handle, data);
if (Writable.isBackpressured(this._socket)) {
this._pendingWrite = cb;
} else {
cb(null);
}
} catch (err) {
this._pendingWrite = null;
cb(errors.from(err));
}
}
_final(cb) {
try {
binding.shutdown(this._handle);
cb(null);
} catch (err) {
cb(err);
}
this._socket.end();
}
_predestroy() {
if (!this._handle) return;
this._detach();
binding.destroy(this._handle);
this._handle = null;
}
_destroy(err, cb) {
if (!this._handle) return cb(err);
this._detach();
binding.destroy(this._handle);
this._handle = null;
cb(err);
}
};
exports.TLSSocket = exports.Socket;
exports.constants = constants;
exports.errors = errors;
var net = require_net();
exports.createConnection = net.createConnection;
exports.createServer = net.createServer;
exports.connect = exports.createConnection;
}
});
// ../../node_modules/bare-https/lib/socket.js
var require_socket = __commonJS({
"../../node_modules/bare-https/lib/socket.js"(exports, module) {
var TLSSocket = require_bare_tls().Socket;
module.exports = class HTTPSSocket extends TLSSocket {
setKeepAlive(...args) {
this.socket.setKeepAlive(...args);
return this;
}
setNoDelay(...args) {
this.socket.setNoDelay(...args);
return this;
}
setTimeout(...args) {
this.socket.setTimeout(...args);
return this;
}
ref() {
this.socket.ref();
return this;
}
unref() {
this.socket.unref();
return this;
}
};
}
});
// ../../node_modules/bare-https/lib/agent.js
var require_agent2 = __commonJS({
"../../node_modules/bare-https/lib/agent.js"(exports, module) {
var HTTPAgent = require_bare_http1().Agent;
var HTTPSSocket = require_socket();
var HTTPSAgent = class extends HTTPAgent {
constructor(opts = {}) {
super({ defaultPort: 443, ...opts });
}
createConnection(opts) {
return new HTTPSSocket(super.createConnection(opts), opts);
}
};
HTTPSAgent.global = new HTTPSAgent({ keepAlive: 1e3, timeout: 5e3 });
module.exports = HTTPSAgent;
}
});
// ../../node_modules/bare-https/lib/server.js
var require_server2 = __commonJS({
"../../node_modules/bare-https/lib/server.js"(exports, module) {
var TCPServer = require_bare_tcp().Server;
var HTTPServerConnection = require_bare_http1().ServerConnection;
var HTTPSSocket = require_socket();
module.exports = class HTTPSServer extends TCPServer {
constructor(opts = {}, onrequest) {
if (typeof opts === "function") {
onrequest = opts;
opts = {};
}
super({ allowHalfOpen: false });
this._timeout = 0;
this.on("connection", (socket) => {
new HTTPServerConnection(this, new HTTPSSocket(socket, { ...opts, isServer: true }), opts);
});
if (onrequest) this.on("request", onrequest);
}
get timeout() {
return this._timeout || void 0;
}
setTimeout(ms = 0, ontimeout) {
if (ontimeout) this.on("timeout", ontimeout);
this._timeout = ms;
return this;
}
close(onclose) {
super.close(onclose);
for (const socket of this.connections) {
const connection = HTTPServerConnection.for(socket);
if (connection === null || connection.idle) {
socket.destroy();
}
}
return this;
}
};
}
});
// ../../node_modules/bare-https/lib/client-request.js
var require_client_request2 = __commonJS({
"../../node_modules/bare-https/lib/client-request.js"(exports, module) {
var HTTPClientRequest = require_bare_http1().ClientRequest;
var HTTPSAgent = require_agent2();
module.exports = class HTTPSClientRequest extends HTTPClientRequest {
constructor(opts = {}, onresponse = null) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
opts = opts ? { ...opts } : {};
opts.agent = opts.agent === false ? new HTTPSAgent() : opts.agent || HTTPSAgent.global;
super(opts, onresponse);
}
};
}
});
// ../../node_modules/bare-https/index.js
var require_bare_https = __commonJS({
"../../node_modules/bare-https/index.js"(exports) {
exports.Agent = require_agent2();
exports.globalAgent = exports.Agent.global;
exports.Server = require_server2();
exports.ClientRequest = require_client_request2();
exports.createServer = function createServer(opts, onrequest) {
return new exports.Server(opts, onrequest);
};
exports.request = function request(url, opts, onresponse) {
if (typeof opts === "function") {
onresponse = opts;
opts = {};
}
if (typeof url === "string") url = new URL(url);
if (isURL(url)) {
opts = opts ? { ...url, ...opts } : { ...url };
opts.host = url.hostname;
opts.path = url.pathname + url.search;
opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url);
} else {
opts = url ? { ...url } : {};
opts.host = opts.hostname || opts.host;
opts.port = typeof opts.port === "string" ? parseInt(opts.port, 10) : opts.port;
}
return new exports.ClientRequest(opts, onresponse);
};
function defaultPort(url) {
switch (url.protocol) {
case "ftp:":
return 21;
case "http:":
case "ws:":
return 80;
case "https:":
case "wss:":
return 443;
}
return null;
}
function isURL(url) {
return url !== null && typeof url === "object" && typeof url.protocol === "string" && typeof url.hostname === "string" && typeof url.pathname === "string" && typeof url.search === "string";
}
}
});
// ../../bare-lib-entry-bareHttps.js
var bare_lib_entry_bareHttps_exports = {};
__export(bare_lib_entry_bareHttps_exports, {
default: () => bare_lib_entry_bareHttps_default
});
var import_bare_https = __toESM(require_bare_https());
var bare_lib_entry_bareHttps_default = import_bare_https.default;
return __toCommonJS(bare_lib_entry_bareHttps_exports);
})();
;(function(){var g=globalThis;var s="__bare_os_stdlib__";g[s]=g[s]||{};g[s]["bareHttps"]=typeof __bare_os_bundle_exports__!=="undefined"?__bare_os_bundle_exports__:void 0;})();