diff --git a/.github/actions/javascript/authorChecklist/index.js b/.github/actions/javascript/authorChecklist/index.js index b06a43adc37e..f76542955ddf 100644 --- a/.github/actions/javascript/authorChecklist/index.js +++ b/.github/actions/javascript/authorChecklist/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/awaitStagingDeploys/index.js b/.github/actions/javascript/awaitStagingDeploys/index.js index 00e2f735fcb4..906a5fe20da8 100644 --- a/.github/actions/javascript/awaitStagingDeploys/index.js +++ b/.github/actions/javascript/awaitStagingDeploys/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/bumpVersion/index.js b/.github/actions/javascript/bumpVersion/index.js index c2258fb0a82d..479e50a322da 100644 --- a/.github/actions/javascript/bumpVersion/index.js +++ b/.github/actions/javascript/bumpVersion/index.js @@ -2312,66 +2312,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2438,11 +2382,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2454,9 +2394,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2566,21 +2503,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -6187,7 +6116,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -6234,9 +6162,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -6399,55 +6324,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6467,10 +6361,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6514,7 +6404,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6539,10 +6429,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request, error2); - util.destroy(socket, error2); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6551,10 +6440,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6680,7 +6565,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6724,19 +6608,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6751,10 +6628,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6762,10 +6636,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6814,7 +6687,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6832,23 +6705,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6861,29 +6717,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6914,16 +6747,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6944,18 +6769,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request, error2 || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -7311,7 +7129,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -7372,10 +7189,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7539,22 +7352,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7569,42 +7376,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error2); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -8165,10 +7948,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8674,8 +8456,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8846,6 +8628,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8866,7 +8649,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -9066,6 +8848,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -9075,7 +8858,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9516,24 +9298,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9587,7 +9351,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9597,17 +9360,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9669,9 +9421,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9720,21 +9470,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9742,7 +9480,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9750,11 +9487,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9774,7 +9506,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9802,7 +9533,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16601,48 +16332,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16725,11 +16422,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16859,14 +16552,18 @@ var require_parse2 = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17688,7 +17385,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17794,26 +17491,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17832,12 +17534,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17847,17 +17557,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17888,14 +17600,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17903,21 +17609,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17932,13 +17635,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17998,9 +17694,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -18021,9 +17714,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -18037,9 +17727,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -18050,46 +17737,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -18132,26 +17805,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -18363,6 +18016,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -18406,6 +18061,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18589,13 +18247,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18670,6 +18322,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18748,40 +18413,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18801,13 +18432,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18838,30 +18466,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18870,16 +18531,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18895,42 +18557,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18955,120 +18618,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkAndroidStatus/index.js b/.github/actions/javascript/checkAndroidStatus/index.js index de9e0e53ebc4..cf13138d08ce 100644 --- a/.github/actions/javascript/checkAndroidStatus/index.js +++ b/.github/actions/javascript/checkAndroidStatus/index.js @@ -1875,66 +1875,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2001,11 +1945,7 @@ var require_request = __commonJS({ } else if (typeof val[i2] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i2]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i2]}`); } } val = arr; @@ -2017,9 +1957,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2129,21 +2066,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5750,7 +5679,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5797,9 +5725,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5962,55 +5887,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6030,10 +5924,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6077,7 +5967,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6102,10 +5992,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6114,10 +6003,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6243,7 +6128,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6287,19 +6171,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6314,10 +6191,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6325,10 +6199,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6377,7 +6250,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6395,23 +6268,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6424,29 +6280,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6477,16 +6310,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6507,18 +6332,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6874,7 +6692,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline: pipeline2 } = __require("node:stream"); var util = require_util(); var { @@ -6935,10 +6752,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7102,22 +6915,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7132,42 +6939,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7728,10 +7511,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8237,8 +8019,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8409,6 +8191,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8429,7 +8212,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8629,6 +8411,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8638,7 +8421,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9079,24 +8861,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9150,7 +8914,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9160,17 +8923,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9232,9 +8984,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9283,21 +9033,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9305,7 +9043,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9313,11 +9050,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9337,7 +9069,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9365,7 +9096,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16164,48 +15895,14 @@ var require_util6 = __commonJS({ for (let i2 = 0; i2 < path.length; ++i2) { const code = path.charCodeAt(i2); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i2 = 0; i2 < domain.length; ++i2) { - const code = domain.charCodeAt(i2); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i2 - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16288,11 +15985,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16422,14 +16115,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17251,7 +16948,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17357,26 +17054,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17395,12 +17097,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17410,17 +17120,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17451,14 +17163,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17466,21 +17172,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17495,13 +17198,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17561,9 +17257,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17584,9 +17277,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17600,9 +17290,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower2; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17613,46 +17300,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17695,26 +17368,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17926,6 +17579,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17969,6 +17624,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18152,13 +17810,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18233,6 +17885,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18311,40 +17976,6 @@ var require_eventsource_stream = __commonJS({ var CR2 = 13; var COLON2 = 58; var SPACE2 = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] < 48 || buffer[i2] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i2 = 0; i2 < length; i2++) { - if (line[i2] !== field[i2]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18364,13 +17995,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18401,30 +18029,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF2) { + if (this.buffer[this.pos] === LF2) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18433,16 +18094,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18458,42 +18120,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE2) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18518,120 +18181,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i2 = this.lineChunkIndex; i2 <= this.chunkIndex; i2++) { - const chunk = this.chunks[i2]; - const start = i2 === this.lineChunkIndex ? this.linePos : 0; - const end = i2 === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkDeployBlockers/index.js b/.github/actions/javascript/checkDeployBlockers/index.js index c59c854097c1..2ca391c52c00 100644 --- a/.github/actions/javascript/checkDeployBlockers/index.js +++ b/.github/actions/javascript/checkDeployBlockers/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/checkSVGCompression/index.js b/.github/actions/javascript/checkSVGCompression/index.js index cad1560febba..1bd2d9dfd701 100644 --- a/.github/actions/javascript/checkSVGCompression/index.js +++ b/.github/actions/javascript/checkSVGCompression/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/failureNotifier/index.js b/.github/actions/javascript/failureNotifier/index.js index 208e6286e656..7eedc830062e 100644 --- a/.github/actions/javascript/failureNotifier/index.js +++ b/.github/actions/javascript/failureNotifier/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/formatCodeCovComment/index.js b/.github/actions/javascript/formatCodeCovComment/index.js index 9aac21e43b56..133b8de4b0d2 100644 --- a/.github/actions/javascript/formatCodeCovComment/index.js +++ b/.github/actions/javascript/formatCodeCovComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/generateHelpPreviewComment/index.js b/.github/actions/javascript/generateHelpPreviewComment/index.js index 222ea227535c..4fffa145a897 100644 --- a/.github/actions/javascript/generateHelpPreviewComment/index.js +++ b/.github/actions/javascript/generateHelpPreviewComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error) { - util.errorRequest(client, request2, error); - util.destroy(socket, error); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error = error || new RequestAbortedError(); - util.errorRequest(client, request2, error); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error); + util.destroy(stream, err); } - util.destroy(body, error); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error) { - stream.off("response", onResponse); - abort(error); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error, data) => { - if (error) { - const code = error instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.ws, error.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getAndroidRolloutPercentage/index.js b/.github/actions/javascript/getAndroidRolloutPercentage/index.js index 1abd092e27ea..e970b3649819 100644 --- a/.github/actions/javascript/getAndroidRolloutPercentage/index.js +++ b/.github/actions/javascript/getAndroidRolloutPercentage/index.js @@ -1875,66 +1875,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -2001,11 +1945,7 @@ var require_request = __commonJS({ } else if (typeof val[i2] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i2]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i2]}`); } } val = arr; @@ -2017,9 +1957,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2129,21 +2066,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5750,7 +5679,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5797,9 +5725,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5962,55 +5887,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6030,10 +5924,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6077,7 +5967,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6102,10 +5992,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error) { - util.errorRequest(client, request, error); - util.destroy(socket, error); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6114,10 +6003,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6243,7 +6128,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6287,19 +6171,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6314,10 +6191,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6325,10 +6199,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6377,7 +6250,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6395,23 +6268,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6424,29 +6280,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6477,16 +6310,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6507,18 +6332,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error) => { - if (request.aborted) { - return; - } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request.aborted || request.completed) { return; } - util.errorRequest(client, request, error || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6874,7 +6692,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline: pipeline2 } = __require("node:stream"); var util = require_util(); var { @@ -6935,10 +6752,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7102,22 +6915,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error) => { - if (request.aborted) { - return; - } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error || new RequestAbortedError()); - } + const abort = (err) => { + if (request.aborted || request.completed) { return; } - error = error || new RequestAbortedError(); - util.errorRequest(client, request, error); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error); + util.destroy(stream, err); } - util.destroy(body, error); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7132,42 +6939,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error) { - stream.off("response", onResponse); - abort(error); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7728,10 +7511,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8237,8 +8019,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8409,6 +8191,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8429,7 +8212,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8629,6 +8411,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8638,7 +8421,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9079,24 +8861,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9150,7 +8914,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9160,17 +8923,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9232,9 +8984,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9283,21 +9033,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9305,7 +9043,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9313,11 +9050,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9337,7 +9069,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9365,7 +9096,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16164,48 +15895,14 @@ var require_util6 = __commonJS({ for (let i2 = 0; i2 < path.length; ++i2) { const code = path.charCodeAt(i2); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i2 = 0; i2 < domain.length; ++i2) { - const code = domain.charCodeAt(i2); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i2 - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16288,11 +15985,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16422,14 +16115,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; + } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17251,7 +16948,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17357,26 +17054,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17395,12 +17097,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17410,17 +17120,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17451,14 +17163,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17466,21 +17172,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17495,13 +17198,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17561,9 +17257,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17584,9 +17277,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17600,9 +17290,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower2; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17613,46 +17300,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error, data) => { - if (error) { - const code = error instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.ws, error.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17695,26 +17368,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17926,6 +17579,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17969,6 +17624,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18152,13 +17810,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18233,6 +17885,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18311,40 +17976,6 @@ var require_eventsource_stream = __commonJS({ var CR2 = 13; var COLON2 = 58; var SPACE2 = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] < 48 || buffer[i2] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i2 = start; i2 < buffer.length; i2++) { - if (buffer[i2] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i2 = 0; i2 < length; i2++) { - if (line[i2] !== field[i2]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18364,13 +17995,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18401,30 +18029,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF2) { + if (this.buffer[this.pos] === LF2) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18433,16 +18094,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF2 || byte === CR2) { - if (byte === CR2) { + if (this.buffer[this.pos] === LF2 || this.buffer[this.pos] === CR2) { + if (this.buffer[this.pos] === CR2) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18458,42 +18120,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE2) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18518,120 +18181,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i2 = this.lineChunkIndex; i2 <= this.chunkIndex; i2++) { - const chunk = this.chunks[i2]; - const start = i2 === this.lineChunkIndex ? this.linePos : 0; - const end = i2 === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getArtifactInfo/index.js b/.github/actions/javascript/getArtifactInfo/index.js index b511ee174521..1d7315a4ae65 100644 --- a/.github/actions/javascript/getArtifactInfo/index.js +++ b/.github/actions/javascript/getArtifactInfo/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getDeployPullRequestList/index.js b/.github/actions/javascript/getDeployPullRequestList/index.js index c6a083ec32cf..86ebf2b747d2 100644 --- a/.github/actions/javascript/getDeployPullRequestList/index.js +++ b/.github/actions/javascript/getDeployPullRequestList/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPreviousVersion/index.js b/.github/actions/javascript/getPreviousVersion/index.js index dc48a205f79b..0343158e5a02 100644 --- a/.github/actions/javascript/getPreviousVersion/index.js +++ b/.github/actions/javascript/getPreviousVersion/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPullRequestDetails/index.js b/.github/actions/javascript/getPullRequestDetails/index.js index b7443787fc9b..78b36a004849 100644 --- a/.github/actions/javascript/getPullRequestDetails/index.js +++ b/.github/actions/javascript/getPullRequestDetails/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/getPullRequestIncrementalChanges/index.js b/.github/actions/javascript/getPullRequestIncrementalChanges/index.js index e868a069ae7e..21c54003dde2 100644 --- a/.github/actions/javascript/getPullRequestIncrementalChanges/index.js +++ b/.github/actions/javascript/getPullRequestIncrementalChanges/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error3) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error3 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error3) { - util.errorRequest(client, request2, error3); - util.destroy(socket, error3); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error3) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error3 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error3) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error3 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error3 = error3 || new RequestAbortedError(); - util.errorRequest(client, request2, error3); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error3); + util.destroy(stream, err); } - util.destroy(body, error3); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error3) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error3); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error3) { - stream.off("response", onResponse); - abort(error3); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error3, data) => { - if (error3) { - const code = error3 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error3.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error3, data) => { + if (error3) { + failWebsocketConnection(this.ws, error3.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/isAuthorizedContributor/index.js b/.github/actions/javascript/isAuthorizedContributor/index.js index d43a19fced4c..fea991ad887f 100644 --- a/.github/actions/javascript/isAuthorizedContributor/index.js +++ b/.github/actions/javascript/isAuthorizedContributor/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/isDeployChecklistLocked/index.js b/.github/actions/javascript/isDeployChecklistLocked/index.js index cfe1ac778241..ebdf2bf6961c 100644 --- a/.github/actions/javascript/isDeployChecklistLocked/index.js +++ b/.github/actions/javascript/isDeployChecklistLocked/index.js @@ -3432,7 +3432,6 @@ var require_CONST = __commonJS({ REPLACE_CARD: "replace_card", SHIP_CARD: "ship_card", REPORT_CARD_FRAUD: "report_card_fraud", - APPROVE_DIGITAL_WALLET: "approve_digital_wallet", ISSUE_CARD: "issue_card", UPDATE_CARD: "update_card", UPDATE_PERSONAL_DETAILS: "update_personal_details", @@ -22076,117 +22075,6 @@ var require_str = __commonJS({ } return parameter; } - function compare(strA, strB) { - if (strA < strB) { - return -1; - } - if (strA > strB) { - return 1; - } - return 0; - } - function caseInsensitiveCompare(strA, strB) { - const lowerCaseStrA = strA.toLocaleLowerCase(); - const lowerCaseStrB = strB.toLocaleLowerCase(); - return compare(lowerCaseStrA, lowerCaseStrB); - } - function contains(haystack, needle) { - return haystack.indexOf(needle) !== -1; - } - function cutAfter(str, substr) { - const index = str.indexOf(substr); - if (index !== -1) { - return str.substring(0, index); - } - return str; - } - function cutBefore(str, substr) { - const index = str.indexOf(substr); - if (index !== -1) { - return str.substring(index + substr.length); - } - return str; - } - function extractEmailDomain(email) { - return cutBefore(email, "@"); - } - function getExtension(url) { - var _a, _b; - if (typeof url !== "string") { - Log_1.default.warn("Str.getExtension: url is not a string", { url }); - return void 0; - } - return (_b = (_a = url.split(".").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); - } - function getRawByteSize(inputChar) { - const onlyChar = String(inputChar); - const c = onlyChar.charCodeAt(0); - if (c < 1 << 7) { - return 1; - } - if (c < 1 << 11) { - return 2; - } - if (c < 1 << 16) { - return 3; - } - if (c < 1 << 21) { - return 4; - } - if (c < 1 << 26) { - return 5; - } - if (c < 1 << 31) { - return 6; - } - return Number.NaN; - } - function htmlDecode(s) { - return HtmlEntities.decode(s); - } - function htmlEncode(s) { - return HtmlEntities.encode(s); - } - function isTypeOf(obj, type) { - return Object.prototype.toString.call(obj) === `[object ${type}]`; - } - function isNumber(obj) { - return isTypeOf(obj, "Number"); - } - function isString(obj) { - return isTypeOf(obj, "String"); - } - function isUndefined(obj) { - return obj === void 0; - } - function isValidE164Phone(phone) { - return Constants.CONST.SMS.E164_REGEX.test(phone); - } - function isValidEmail(str) { - if (!str || typeof str !== "string") { - return false; - } - const unicodeVersion = punycode_1.default.toUnicode(str); - if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { - return false; - } - return !!String(str).match(Constants.CONST.REG_EXP.EMAIL); - } - function maskFirstNCharacters(str, num, mask) { - if (!isString(str) || !isString(mask) || str.length === 0 || !isNumber(num)) { - return str; - } - return str.substring(0, num).replaceAll(/./g, mask) + str.substring(num); - } - function removeSMSDomain(text) { - return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); - } - function removeTrailingComma(str) { - return str.trim().replaceAll(/(,$)/g, ""); - } - function startsWith(haystack, needle) { - return isString(haystack) && isString(needle) && haystack.substring(0, needle.length) === needle; - } var Str2 = { /** * Return true if the string is ending with the provided suffix @@ -22244,14 +22132,18 @@ var require_str = __commonJS({ * @param s The string to decode. * @returns The decoded string. */ - htmlDecode, + htmlDecode(s) { + return HtmlEntities.decode(s); + }, /** * HTML encodes the given string. * * @param s The string to encode. * @return string @p s HTML encoded. */ - htmlEncode, + htmlEncode(s) { + return HtmlEntities.encode(s); + }, /** * Decodes the given HTML encoded string. * @@ -22293,7 +22185,7 @@ var require_str = __commonJS({ * @returns True when first === second, ignoring HTML encoding */ htmlEncodingInsensitiveEquals(first, second) { - return first === second || htmlDecode(first) === second || htmlEncode(first) === second; + return first === second || this.htmlDecode(first) === second || this.htmlEncode(first) === second; }, /** * Creates an ID that can be used as an HTML attribute from @p str. @@ -22376,14 +22268,36 @@ var require_str = __commonJS({ * one. * @returns Byte size of the character */ - getRawByteSize, + getRawByteSize(inputChar) { + const onlyChar = String(inputChar); + const c = onlyChar.charCodeAt(0); + if (c < 1 << 7) { + return 1; + } + if (c < 1 << 11) { + return 2; + } + if (c < 1 << 16) { + return 3; + } + if (c < 1 << 21) { + return 4; + } + if (c < 1 << 26) { + return 5; + } + if (c < 1 << 31) { + return 6; + } + return Number.NaN; + }, /** * Gets the length of a string in bytes, including non-ASCII characters * @returns The number of bytes used by string */ getByteLength(input) { const stringInput = String(input); - const byteLength = Array.from(stringInput).reduce((acc, char) => acc + getRawByteSize(char), 0); + const byteLength = Array.from(stringInput).reduce((acc, char) => acc + this.getRawByteSize(char), 0); return byteLength; }, /** @@ -22395,7 +22309,7 @@ var require_str = __commonJS({ const stringInput = String(input); let totalByteLength = 0; for (let i = 0; i < stringInput.length; i++) { - const charByteSize = getRawByteSize(stringInput[i]); + const charByteSize = this.getRawByteSize(stringInput[i]); if (charByteSize + totalByteLength > maxSize) { return `${stringInput.substr(0, i - 3)}...`; } @@ -22410,7 +22324,9 @@ var require_str = __commonJS({ * @param needle The case-sensitive string to search for * @returns True if the haystack starts with the needle. */ - startsWith, + startsWith(haystack, needle) { + return this.isString(haystack) && this.isString(needle) && haystack.substring(0, needle.length) === needle; + }, /** * Gets the textual value of the given string. * @@ -22418,7 +22334,7 @@ var require_str = __commonJS({ * @returns The text from within the HTML string. */ stripHTML(str) { - if (!isString(str)) { + if (!this.isString(str)) { return ""; } return str.replaceAll(/<[^>]*>?/gm, ""); @@ -22441,7 +22357,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutAfter, + cutAfter(str, substr) { + const index = str.indexOf(substr); + if (index !== -1) { + return str.substring(0, index); + } + return str; + }, /** * Returns a string containing all the characters str from after the first * occurrence of substr to the end of the string. @@ -22451,7 +22373,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutBefore, + cutBefore(str, substr) { + const index = str.indexOf(substr); + if (index !== -1) { + return str.substring(index + substr.length); + } + return str; + }, /** * Checks that the string is a domain name (e.g. example.com) * @@ -22478,7 +22406,16 @@ var require_str = __commonJS({ * * @returns True if the string is an email */ - isValidEmail, + isValidEmail(str) { + if (!str || typeof str !== "string") { + return false; + } + const unicodeVersion = punycode_1.default.toUnicode(str); + if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { + return false; + } + return !!String(str).match(Constants.CONST.REG_EXP.EMAIL); + }, /** * Checks if the string is an valid email address formed during comment markdown formation. * @@ -22496,7 +22433,9 @@ var require_str = __commonJS({ * * @returns string with the trailing comma removed */ - removeTrailingComma, + removeTrailingComma(str) { + return str.trim().replaceAll(/(,$)/g, ""); + }, /** * Checks that the string is a list of coma separated email addresss. * @@ -22505,12 +22444,12 @@ var require_str = __commonJS({ * @returns True if all emails are valid or if input is empty */ areValidEmails(str) { - const string = removeTrailingComma(str); + const string = this.removeTrailingComma(str); if (string === "") { return true; } const emails = string.split(","); - const result = emails.every((email) => isValidEmail(email.trim())); + const result = emails.every((email) => this.isValidEmail(email.trim())); return result; }, /** @@ -22527,7 +22466,9 @@ var require_str = __commonJS({ * * @returns The domain name in the email address. */ - extractEmailDomain, + extractEmailDomain(email) { + return this.cutBefore(email, "@"); + }, /** * Tries to extract the company name from the given email address * (e.g. "yelp" for "joe@yelp.co.uk"). @@ -22537,7 +22478,7 @@ var require_str = __commonJS({ * @returns The company name in the email address or null. */ extractCompanyNameFromEmailDomain(email) { - const domain = extractEmailDomain(email); + const domain = this.extractEmailDomain(email); if (!domain) { return null; } @@ -22556,7 +22497,7 @@ var require_str = __commonJS({ * @returns The local part in the email address. */ extractEmailLocalPart(email) { - return cutAfter(email, "@"); + return this.cutAfter(email, "@"); }, /** * Sanitize phone number to return only numbers. Return null if non valid phone number. @@ -22614,13 +22555,13 @@ var require_str = __commonJS({ * @returns true if the length is in the range, false otherwise */ isOfLength(str, minimumLength, maximumLength) { - if (!isString(str)) { + if (!this.isString(str)) { return false; } if (str.length < minimumLength) { return false; } - if (!isUndefined(maximumLength) && str.length > maximumLength) { + if (!this.isUndefined(maximumLength) && str.length > maximumLength) { return false; } return true; @@ -22673,7 +22614,9 @@ var require_str = __commonJS({ * * @returns Returns true if the haystack contains the needle */ - contains, + contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; + }, /** * Returns true if the haystack contains the needle, ignoring case * @@ -22683,7 +22626,7 @@ var require_str = __commonJS({ * @returns Returns true if the haystack contains the needle, ignoring case */ caseInsensitiveContains(haystack, needle) { - return contains(haystack.toLowerCase(), needle.toLowerCase()); + return this.contains(haystack.toLowerCase(), needle.toLowerCase()); }, /** * Case insensitive compare function @@ -22695,7 +22638,11 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - caseInsensitiveCompare, + caseInsensitiveCompare(strA, strB) { + const lowerCaseStrA = strA.toLocaleLowerCase(); + const lowerCaseStrB = strB.toLocaleLowerCase(); + return this.compare(lowerCaseStrA, lowerCaseStrB); + }, /** * Case insensitive equals * @@ -22704,7 +22651,7 @@ var require_str = __commonJS({ * @returns true when first == second except for case */ caseInsensitiveEquals(strA, strB) { - return caseInsensitiveCompare(strA, strB) === 0; + return this.caseInsensitiveCompare(strA, strB) === 0; }, /** * Compare function @@ -22716,7 +22663,15 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - compare, + compare(strA, strB) { + if (strA < strB) { + return -1; + } + if (strA > strB) { + return 1; + } + return 0; + }, /** * Check if a file extension is supported by SmartReports */ @@ -22735,37 +22690,45 @@ var require_str = __commonJS({ const accountNumber = String(num); const len = accountNumber.length; if (len < 6 || len > 20) { - return maskFirstNCharacters(accountNumber, len, "X"); + return this.maskFirstNCharacters(accountNumber, len, "X"); } if (len < 14) { - return maskFirstNCharacters(accountNumber, len - 4, "X"); + return this.maskFirstNCharacters(accountNumber, len - 4, "X"); } const first = accountNumber.substr(0, 6); const last = accountNumber.substr(7); - const masked = maskFirstNCharacters(last, len - 11, "X"); + const masked = this.maskFirstNCharacters(last, len - 11, "X"); return `${first}${masked}`; }, /** * Checks if something is a string * Stolen from underscore */ - isString, + isString(obj) { + return this.isTypeOf(obj, "String"); + }, /** * Checks if something is a number * Stolen from underscore * @param obj */ - isNumber, + isNumber(obj) { + return this.isTypeOf(obj, "Number"); + }, /** * Checks if something is a certain type * Stolen from underscore */ - isTypeOf, + isTypeOf(obj, type) { + return Object.prototype.toString.call(obj) === `[object ${type}]`; + }, /** * Checks to see if something is undefined * Stolen from underscore */ - isUndefined, + isUndefined(obj) { + return obj === void 0; + }, /** * Replace first N characters of the string with maskChar * eg: maskFirstNCharacters( '1234567890', 6, 'X' ) yields XXXXXX7890 @@ -22774,7 +22737,12 @@ var require_str = __commonJS({ * @param mask String we want replace the first N chars with * @returns Masked string */ - maskFirstNCharacters, + maskFirstNCharacters(str, num, mask) { + if (!this.isString(str) || !this.isString(mask) || str.length === 0 || !this.isNumber(num)) { + return str; + } + return str.substring(0, num).replaceAll(/./g, mask) + str.substring(num); + }, /** * Trim a string */ @@ -22786,7 +22754,7 @@ var require_str = __commonJS({ * @param percentageString The percentage as a string */ percentageStringToNumber(percentageString) { - return Number(cutAfter(percentageString, "%")); + return Number(this.cutAfter(percentageString, "%")); }, /** * Remove all the spaces from a string @@ -22830,7 +22798,7 @@ var require_str = __commonJS({ * Converts a value to boolean, case-insensitive. */ toBool(value) { - if (isString(value)) { + if (this.isString(value)) { return value.toLowerCase() === "true"; } return !!value; @@ -22880,7 +22848,9 @@ var require_str = __commonJS({ /** * Check for whether a phone number is valid according to E.164 standard. */ - isValidE164Phone, + isValidE164Phone(phone) { + return Constants.CONST.SMS.E164_REGEX.test(phone); + }, /** * Check for whether a phone number is valid in different formats/standards. For example: * significant: 4404589784 @@ -22906,12 +22876,14 @@ var require_str = __commonJS({ /** * Returns text without our SMS domain */ - removeSMSDomain, + removeSMSDomain(text) { + return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); + }, /** * Returns true if the text is a valid E.164 phone number with our SMS domain removed */ isSMSLogin(text) { - return isValidE164Phone(removeSMSDomain(text)); + return this.isValidE164Phone(this.removeSMSDomain(text)); }, /** * This method will return all matches of a single regex like preg_match_all() in PHP. This is not a common part of @@ -22964,7 +22936,7 @@ var require_str = __commonJS({ return url; } const website = match[3] ? match[2] : `${defaultScheme}://${match[2]}`; - return website.toLowerCase() + cutBefore(match[1], match[2]); + return website.toLowerCase() + this.cutBefore(match[1], match[2]); }, /** * Checks if parameter is a string or function @@ -22976,7 +22948,14 @@ var require_str = __commonJS({ * Get file extension for a given url with or * without query parameters */ - getExtension, + getExtension(url) { + var _a, _b; + if (typeof url !== "string") { + Log_1.default.warn("Str.getExtension: url is not a string", { url }); + return void 0; + } + return (_b = (_a = url.split(".").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); + }, /** * Takes in a URL and checks if the file extension is PDF * @@ -22984,7 +22963,7 @@ var require_str = __commonJS({ * @returns Whether file path is PDF or not */ isPDF(url) { - return getExtension(url) === "pdf"; + return this.getExtension(url) === "pdf"; }, /** * Takes in a URL and checks if the file extension is an image @@ -22995,7 +22974,7 @@ var require_str = __commonJS({ * https://reactnative.dev/docs/image#source */ isImage(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -23011,7 +22990,7 @@ var require_str = __commonJS({ * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs */ isVideo(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -23024,7 +23003,7 @@ var require_str = __commonJS({ * @returns True if is a domain account email, otherwise false. */ isDomainEmail(email) { - return startsWith(email, "+@"); + return this.startsWith(email, "+@"); }, /** * Find the minimum indentation of any line in the string, @@ -24162,17 +24141,13 @@ ${g2} }, { name: "anchor", - regex: /(\]\()?<(a)[^><]*href\s*=\s*(['"])(.*?)\3(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\2>(?![^<]*(<\/pre>|<\/code>))/gi, - replacement: (_extras, _match, g1, _g2, _g3, g4, g5) => { - const incompleteLinkStart = g1 !== null && g1 !== void 0 ? g1 : ""; - const email = g4.startsWith("mailto:") ? g4.slice(7) : ""; - if (email === g5) { - return `${incompleteLinkStart}${email}`; - } - if (incompleteLinkStart && (g4 === g5 || g4 === `https://${g5}`)) { - return `${incompleteLinkStart}${g5}`; + regex: /<(a)[^><]*href\s*=\s*(['"])(.*?)\2(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi, + replacement: (_extras, _match, _g1, _g2, g3, g4) => { + const email = g3.startsWith("mailto:") ? g3.slice(7) : ""; + if (email === g4) { + return email; } - return `${incompleteLinkStart}[${g5}](${email || g4})`; + return `[${g4}](${email || g3})`; } }, { @@ -28472,66 +28447,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -28598,11 +28517,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -28614,9 +28529,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -28726,21 +28638,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -32347,7 +32251,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -32394,9 +32297,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -32559,55 +32459,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -32627,10 +32496,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -32674,7 +32539,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -32699,10 +32564,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -32711,10 +32575,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -32840,7 +32700,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -32884,19 +32743,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -32911,10 +32763,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -32922,10 +32771,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -32974,7 +32822,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -32992,23 +32840,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -33021,29 +32852,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -33074,16 +32882,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -33104,18 +32904,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -33471,7 +33264,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -33532,10 +33324,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -33699,22 +33487,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -33729,42 +33511,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -34325,10 +34083,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -34834,8 +34591,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -35006,6 +34763,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -35026,7 +34784,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -35226,6 +34983,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -35235,7 +34993,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -35676,24 +35433,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -35747,7 +35486,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -35757,17 +35495,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -35829,9 +35556,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -35880,21 +35605,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -35902,7 +35615,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -35910,11 +35622,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -35934,7 +35641,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -35962,7 +35668,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -42761,48 +42467,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -42885,11 +42557,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -43019,14 +42687,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -43848,7 +43520,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -43954,26 +43626,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -43992,12 +43669,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -44007,17 +43692,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -44048,14 +43735,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -44063,21 +43744,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -44092,13 +43770,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -44158,9 +43829,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -44181,9 +43849,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -44197,9 +43862,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -44210,46 +43872,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -44292,26 +43940,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -44523,6 +44151,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -44566,6 +44196,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -44749,13 +44382,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -44830,6 +44457,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -44908,40 +44548,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -44961,13 +44567,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -44998,30 +44601,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -45030,16 +44666,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -45055,42 +44692,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -45115,120 +44753,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/markPullRequestsAsDeployed/index.js b/.github/actions/javascript/markPullRequestsAsDeployed/index.js index 5eca45f374da..62a50ec22616 100644 --- a/.github/actions/javascript/markPullRequestsAsDeployed/index.js +++ b/.github/actions/javascript/markPullRequestsAsDeployed/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/postOrReplaceComment/index.js b/.github/actions/javascript/postOrReplaceComment/index.js index 195707dedc9f..fb9eb8df9e7b 100644 --- a/.github/actions/javascript/postOrReplaceComment/index.js +++ b/.github/actions/javascript/postOrReplaceComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/proposalPoliceComment/index.js b/.github/actions/javascript/proposalPoliceComment/index.js index 58a12c5fb27a..126b34462df4 100644 --- a/.github/actions/javascript/proposalPoliceComment/index.js +++ b/.github/actions/javascript/proposalPoliceComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str2 = `${val[i]}`; - if (!isValidHeaderValue(str2)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str2); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); - } + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message2 = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message2 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; + } + throw new HTTPParserError(message2, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message2 = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message2 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message2, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path2.length; ++i) { const code = path2.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { @@ -24691,7 +24246,6 @@ var require_CONST = __commonJS({ REPLACE_CARD: "replace_card", SHIP_CARD: "ship_card", REPORT_CARD_FRAUD: "report_card_fraud", - APPROVE_DIGITAL_WALLET: "approve_digital_wallet", ISSUE_CARD: "issue_card", UPDATE_CARD: "update_card", UPDATE_PERSONAL_DETAILS: "update_personal_details", @@ -43335,117 +42889,6 @@ var require_str = __commonJS({ } return parameter; } - function compare(strA, strB) { - if (strA < strB) { - return -1; - } - if (strA > strB) { - return 1; - } - return 0; - } - function caseInsensitiveCompare(strA, strB) { - const lowerCaseStrA = strA.toLocaleLowerCase(); - const lowerCaseStrB = strB.toLocaleLowerCase(); - return compare(lowerCaseStrA, lowerCaseStrB); - } - function contains(haystack, needle) { - return haystack.indexOf(needle) !== -1; - } - function cutAfter(str2, substr) { - const index = str2.indexOf(substr); - if (index !== -1) { - return str2.substring(0, index); - } - return str2; - } - function cutBefore(str2, substr) { - const index = str2.indexOf(substr); - if (index !== -1) { - return str2.substring(index + substr.length); - } - return str2; - } - function extractEmailDomain(email) { - return cutBefore(email, "@"); - } - function getExtension(url) { - var _a3, _b; - if (typeof url !== "string") { - Log_1.default.warn("Str.getExtension: url is not a string", { url }); - return void 0; - } - return (_b = (_a3 = url.split(".").pop()) === null || _a3 === void 0 ? void 0 : _a3.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); - } - function getRawByteSize(inputChar) { - const onlyChar = String(inputChar); - const c = onlyChar.charCodeAt(0); - if (c < 1 << 7) { - return 1; - } - if (c < 1 << 11) { - return 2; - } - if (c < 1 << 16) { - return 3; - } - if (c < 1 << 21) { - return 4; - } - if (c < 1 << 26) { - return 5; - } - if (c < 1 << 31) { - return 6; - } - return Number.NaN; - } - function htmlDecode(s) { - return HtmlEntities.decode(s); - } - function htmlEncode(s) { - return HtmlEntities.encode(s); - } - function isTypeOf(obj, type) { - return Object.prototype.toString.call(obj) === `[object ${type}]`; - } - function isNumber(obj) { - return isTypeOf(obj, "Number"); - } - function isString(obj) { - return isTypeOf(obj, "String"); - } - function isUndefined(obj) { - return obj === void 0; - } - function isValidE164Phone(phone) { - return Constants.CONST.SMS.E164_REGEX.test(phone); - } - function isValidEmail(str2) { - if (!str2 || typeof str2 !== "string") { - return false; - } - const unicodeVersion = punycode_1.default.toUnicode(str2); - if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { - return false; - } - return !!String(str2).match(Constants.CONST.REG_EXP.EMAIL); - } - function maskFirstNCharacters(str2, num, mask) { - if (!isString(str2) || !isString(mask) || str2.length === 0 || !isNumber(num)) { - return str2; - } - return str2.substring(0, num).replaceAll(/./g, mask) + str2.substring(num); - } - function removeSMSDomain(text) { - return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); - } - function removeTrailingComma(str2) { - return str2.trim().replaceAll(/(,$)/g, ""); - } - function startsWith(haystack, needle) { - return isString(haystack) && isString(needle) && haystack.substring(0, needle.length) === needle; - } var Str6 = { /** * Return true if the string is ending with the provided suffix @@ -43503,14 +42946,18 @@ var require_str = __commonJS({ * @param s The string to decode. * @returns The decoded string. */ - htmlDecode, + htmlDecode(s) { + return HtmlEntities.decode(s); + }, /** * HTML encodes the given string. * * @param s The string to encode. * @return string @p s HTML encoded. */ - htmlEncode, + htmlEncode(s) { + return HtmlEntities.encode(s); + }, /** * Decodes the given HTML encoded string. * @@ -43552,7 +42999,7 @@ var require_str = __commonJS({ * @returns True when first === second, ignoring HTML encoding */ htmlEncodingInsensitiveEquals(first, second) { - return first === second || htmlDecode(first) === second || htmlEncode(first) === second; + return first === second || this.htmlDecode(first) === second || this.htmlEncode(first) === second; }, /** * Creates an ID that can be used as an HTML attribute from @p str. @@ -43635,14 +43082,36 @@ var require_str = __commonJS({ * one. * @returns Byte size of the character */ - getRawByteSize, + getRawByteSize(inputChar) { + const onlyChar = String(inputChar); + const c = onlyChar.charCodeAt(0); + if (c < 1 << 7) { + return 1; + } + if (c < 1 << 11) { + return 2; + } + if (c < 1 << 16) { + return 3; + } + if (c < 1 << 21) { + return 4; + } + if (c < 1 << 26) { + return 5; + } + if (c < 1 << 31) { + return 6; + } + return Number.NaN; + }, /** * Gets the length of a string in bytes, including non-ASCII characters * @returns The number of bytes used by string */ getByteLength(input) { const stringInput = String(input); - const byteLength = Array.from(stringInput).reduce((acc, char) => acc + getRawByteSize(char), 0); + const byteLength = Array.from(stringInput).reduce((acc, char) => acc + this.getRawByteSize(char), 0); return byteLength; }, /** @@ -43654,7 +43123,7 @@ var require_str = __commonJS({ const stringInput = String(input); let totalByteLength = 0; for (let i = 0; i < stringInput.length; i++) { - const charByteSize = getRawByteSize(stringInput[i]); + const charByteSize = this.getRawByteSize(stringInput[i]); if (charByteSize + totalByteLength > maxSize) { return `${stringInput.substr(0, i - 3)}...`; } @@ -43669,7 +43138,9 @@ var require_str = __commonJS({ * @param needle The case-sensitive string to search for * @returns True if the haystack starts with the needle. */ - startsWith, + startsWith(haystack, needle) { + return this.isString(haystack) && this.isString(needle) && haystack.substring(0, needle.length) === needle; + }, /** * Gets the textual value of the given string. * @@ -43677,7 +43148,7 @@ var require_str = __commonJS({ * @returns The text from within the HTML string. */ stripHTML(str2) { - if (!isString(str2)) { + if (!this.isString(str2)) { return ""; } return str2.replaceAll(/<[^>]*>?/gm, ""); @@ -43700,7 +43171,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutAfter, + cutAfter(str2, substr) { + const index = str2.indexOf(substr); + if (index !== -1) { + return str2.substring(0, index); + } + return str2; + }, /** * Returns a string containing all the characters str from after the first * occurrence of substr to the end of the string. @@ -43710,7 +43187,13 @@ var require_str = __commonJS({ * @param substr The substring to search for. * @returns The cut/trimmed string. */ - cutBefore, + cutBefore(str2, substr) { + const index = str2.indexOf(substr); + if (index !== -1) { + return str2.substring(index + substr.length); + } + return str2; + }, /** * Checks that the string is a domain name (e.g. example.com) * @@ -43737,7 +43220,16 @@ var require_str = __commonJS({ * * @returns True if the string is an email */ - isValidEmail, + isValidEmail(str2) { + if (!str2 || typeof str2 !== "string") { + return false; + } + const unicodeVersion = punycode_1.default.toUnicode(str2); + if (String(unicodeVersion).match(Constants.CONST.REG_EXP.EMOJI_RULE)) { + return false; + } + return !!String(str2).match(Constants.CONST.REG_EXP.EMAIL); + }, /** * Checks if the string is an valid email address formed during comment markdown formation. * @@ -43755,7 +43247,9 @@ var require_str = __commonJS({ * * @returns string with the trailing comma removed */ - removeTrailingComma, + removeTrailingComma(str2) { + return str2.trim().replaceAll(/(,$)/g, ""); + }, /** * Checks that the string is a list of coma separated email addresss. * @@ -43764,12 +43258,12 @@ var require_str = __commonJS({ * @returns True if all emails are valid or if input is empty */ areValidEmails(str2) { - const string = removeTrailingComma(str2); + const string = this.removeTrailingComma(str2); if (string === "") { return true; } const emails = string.split(","); - const result = emails.every((email) => isValidEmail(email.trim())); + const result = emails.every((email) => this.isValidEmail(email.trim())); return result; }, /** @@ -43786,7 +43280,9 @@ var require_str = __commonJS({ * * @returns The domain name in the email address. */ - extractEmailDomain, + extractEmailDomain(email) { + return this.cutBefore(email, "@"); + }, /** * Tries to extract the company name from the given email address * (e.g. "yelp" for "joe@yelp.co.uk"). @@ -43796,7 +43292,7 @@ var require_str = __commonJS({ * @returns The company name in the email address or null. */ extractCompanyNameFromEmailDomain(email) { - const domain = extractEmailDomain(email); + const domain = this.extractEmailDomain(email); if (!domain) { return null; } @@ -43815,7 +43311,7 @@ var require_str = __commonJS({ * @returns The local part in the email address. */ extractEmailLocalPart(email) { - return cutAfter(email, "@"); + return this.cutAfter(email, "@"); }, /** * Sanitize phone number to return only numbers. Return null if non valid phone number. @@ -43873,13 +43369,13 @@ var require_str = __commonJS({ * @returns true if the length is in the range, false otherwise */ isOfLength(str2, minimumLength, maximumLength) { - if (!isString(str2)) { + if (!this.isString(str2)) { return false; } if (str2.length < minimumLength) { return false; } - if (!isUndefined(maximumLength) && str2.length > maximumLength) { + if (!this.isUndefined(maximumLength) && str2.length > maximumLength) { return false; } return true; @@ -43932,7 +43428,9 @@ var require_str = __commonJS({ * * @returns Returns true if the haystack contains the needle */ - contains, + contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; + }, /** * Returns true if the haystack contains the needle, ignoring case * @@ -43942,7 +43440,7 @@ var require_str = __commonJS({ * @returns Returns true if the haystack contains the needle, ignoring case */ caseInsensitiveContains(haystack, needle) { - return contains(haystack.toLowerCase(), needle.toLowerCase()); + return this.contains(haystack.toLowerCase(), needle.toLowerCase()); }, /** * Case insensitive compare function @@ -43954,7 +43452,11 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - caseInsensitiveCompare, + caseInsensitiveCompare(strA, strB) { + const lowerCaseStrA = strA.toLocaleLowerCase(); + const lowerCaseStrB = strB.toLocaleLowerCase(); + return this.compare(lowerCaseStrA, lowerCaseStrB); + }, /** * Case insensitive equals * @@ -43963,7 +43465,7 @@ var require_str = __commonJS({ * @returns true when first == second except for case */ caseInsensitiveEquals(strA, strB) { - return caseInsensitiveCompare(strA, strB) === 0; + return this.caseInsensitiveCompare(strA, strB) === 0; }, /** * Compare function @@ -43975,7 +43477,15 @@ var require_str = __commonJS({ * 1 if first string > second string * 0 if first string = second string */ - compare, + compare(strA, strB) { + if (strA < strB) { + return -1; + } + if (strA > strB) { + return 1; + } + return 0; + }, /** * Check if a file extension is supported by SmartReports */ @@ -43994,37 +43504,45 @@ var require_str = __commonJS({ const accountNumber = String(num); const len = accountNumber.length; if (len < 6 || len > 20) { - return maskFirstNCharacters(accountNumber, len, "X"); + return this.maskFirstNCharacters(accountNumber, len, "X"); } if (len < 14) { - return maskFirstNCharacters(accountNumber, len - 4, "X"); + return this.maskFirstNCharacters(accountNumber, len - 4, "X"); } const first = accountNumber.substr(0, 6); const last = accountNumber.substr(7); - const masked = maskFirstNCharacters(last, len - 11, "X"); + const masked = this.maskFirstNCharacters(last, len - 11, "X"); return `${first}${masked}`; }, /** * Checks if something is a string * Stolen from underscore */ - isString, + isString(obj) { + return this.isTypeOf(obj, "String"); + }, /** * Checks if something is a number * Stolen from underscore * @param obj */ - isNumber, + isNumber(obj) { + return this.isTypeOf(obj, "Number"); + }, /** * Checks if something is a certain type * Stolen from underscore */ - isTypeOf, + isTypeOf(obj, type) { + return Object.prototype.toString.call(obj) === `[object ${type}]`; + }, /** * Checks to see if something is undefined * Stolen from underscore */ - isUndefined, + isUndefined(obj) { + return obj === void 0; + }, /** * Replace first N characters of the string with maskChar * eg: maskFirstNCharacters( '1234567890', 6, 'X' ) yields XXXXXX7890 @@ -44033,7 +43551,12 @@ var require_str = __commonJS({ * @param mask String we want replace the first N chars with * @returns Masked string */ - maskFirstNCharacters, + maskFirstNCharacters(str2, num, mask) { + if (!this.isString(str2) || !this.isString(mask) || str2.length === 0 || !this.isNumber(num)) { + return str2; + } + return str2.substring(0, num).replaceAll(/./g, mask) + str2.substring(num); + }, /** * Trim a string */ @@ -44045,7 +43568,7 @@ var require_str = __commonJS({ * @param percentageString The percentage as a string */ percentageStringToNumber(percentageString) { - return Number(cutAfter(percentageString, "%")); + return Number(this.cutAfter(percentageString, "%")); }, /** * Remove all the spaces from a string @@ -44089,7 +43612,7 @@ var require_str = __commonJS({ * Converts a value to boolean, case-insensitive. */ toBool(value) { - if (isString(value)) { + if (this.isString(value)) { return value.toLowerCase() === "true"; } return !!value; @@ -44139,7 +43662,9 @@ var require_str = __commonJS({ /** * Check for whether a phone number is valid according to E.164 standard. */ - isValidE164Phone, + isValidE164Phone(phone) { + return Constants.CONST.SMS.E164_REGEX.test(phone); + }, /** * Check for whether a phone number is valid in different formats/standards. For example: * significant: 4404589784 @@ -44165,12 +43690,14 @@ var require_str = __commonJS({ /** * Returns text without our SMS domain */ - removeSMSDomain, + removeSMSDomain(text) { + return text.replaceAll(REMOVE_SMS_DOMAIN_PATTERN, ""); + }, /** * Returns true if the text is a valid E.164 phone number with our SMS domain removed */ isSMSLogin(text) { - return isValidE164Phone(removeSMSDomain(text)); + return this.isValidE164Phone(this.removeSMSDomain(text)); }, /** * This method will return all matches of a single regex like preg_match_all() in PHP. This is not a common part of @@ -44223,7 +43750,7 @@ var require_str = __commonJS({ return url; } const website = match2[3] ? match2[2] : `${defaultScheme}://${match2[2]}`; - return website.toLowerCase() + cutBefore(match2[1], match2[2]); + return website.toLowerCase() + this.cutBefore(match2[1], match2[2]); }, /** * Checks if parameter is a string or function @@ -44235,7 +43762,14 @@ var require_str = __commonJS({ * Get file extension for a given url with or * without query parameters */ - getExtension, + getExtension(url) { + var _a3, _b; + if (typeof url !== "string") { + Log_1.default.warn("Str.getExtension: url is not a string", { url }); + return void 0; + } + return (_b = (_a3 = url.split(".").pop()) === null || _a3 === void 0 ? void 0 : _a3.split("?")[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); + }, /** * Takes in a URL and checks if the file extension is PDF * @@ -44243,7 +43777,7 @@ var require_str = __commonJS({ * @returns Whether file path is PDF or not */ isPDF(url) { - return getExtension(url) === "pdf"; + return this.getExtension(url) === "pdf"; }, /** * Takes in a URL and checks if the file extension is an image @@ -44254,7 +43788,7 @@ var require_str = __commonJS({ * https://reactnative.dev/docs/image#source */ isImage(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -44270,7 +43804,7 @@ var require_str = __commonJS({ * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs */ isVideo(url) { - const extension = getExtension(url); + const extension = this.getExtension(url); if (!extension) { return false; } @@ -44283,7 +43817,7 @@ var require_str = __commonJS({ * @returns True if is a domain account email, otherwise false. */ isDomainEmail(email) { - return startsWith(email, "+@"); + return this.startsWith(email, "+@"); }, /** * Find the minimum indentation of any line in the string, @@ -45421,17 +44955,13 @@ ${g2} }, { name: "anchor", - regex: /(\]\()?<(a)[^><]*href\s*=\s*(['"])(.*?)\3(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\2>(?![^<]*(<\/pre>|<\/code>))/gi, - replacement: (_extras, _match, g1, _g2, _g3, g4, g5) => { - const incompleteLinkStart = g1 !== null && g1 !== void 0 ? g1 : ""; - const email = g4.startsWith("mailto:") ? g4.slice(7) : ""; - if (email === g5) { - return `${incompleteLinkStart}${email}`; - } - if (incompleteLinkStart && (g4 === g5 || g4 === `https://${g5}`)) { - return `${incompleteLinkStart}${g5}`; + regex: /<(a)[^><]*href\s*=\s*(['"])(.*?)\2(?:".*?"|'.*?'|[^'"><])*>([\s\S]*?)<\/\1>(?![^<]*(<\/pre>|<\/code>))/gi, + replacement: (_extras, _match, _g1, _g2, g3, g4) => { + const email = g3.startsWith("mailto:") ? g3.slice(7) : ""; + if (email === g4) { + return email; } - return `${incompleteLinkStart}[${g5}](${email || g4})`; + return `[${g4}](${email || g3})`; } }, { diff --git a/.github/actions/javascript/reopenIssueWithComment/index.js b/.github/actions/javascript/reopenIssueWithComment/index.js index 2fe118ee3e64..f237f20694fd 100644 --- a/.github/actions/javascript/reopenIssueWithComment/index.js +++ b/.github/actions/javascript/reopenIssueWithComment/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/reviewerChecklist/index.js b/.github/actions/javascript/reviewerChecklist/index.js index 8e220a2cf59e..a9419acf5a2e 100644 --- a/.github/actions/javascript/reviewerChecklist/index.js +++ b/.github/actions/javascript/reviewerChecklist/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/validateReassureOutput/index.js b/.github/actions/javascript/validateReassureOutput/index.js index e511f56ffd08..b26522496b9c 100644 --- a/.github/actions/javascript/validateReassureOutput/index.js +++ b/.github/actions/javascript/validateReassureOutput/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request, error2); - util.destroy(socket, error2); + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request = client[kQueue][client[kRunningIdx]]; if (!request) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (request.upgrade || request.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } - return; - } - util.errorRequest(client, request, error2 || new RequestAbortedError()); + util.errorRequest(client, request, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request.aborted) { + const abort = (err) => { + if (request.aborted || request.completed) { return; } - if (request.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } - return; - } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request.onUpgradeError(error2); - }; - const onReady = () => { - try { - request.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/verifySignedCommits/index.js b/.github/actions/javascript/verifySignedCommits/index.js index d982728230d3..087b5df387fd 100644 --- a/.github/actions/javascript/verifySignedCommits/index.js +++ b/.github/actions/javascript/verifySignedCommits/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js b/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js index d5508591a07b..1e9b71a5c3e0 100644 --- a/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js +++ b/.github/actions/javascript/verifyStagingBuildsSucceeded/index.js @@ -1863,66 +1863,10 @@ var require_request = __commonJS({ return false; } } - /** - * @param {number|null} statusCode - * @param {Buffer[]|null} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); + onUpgrade(statusCode, headers, socket) { assert(!this.aborted); assert(!this.completed); - if (statusCode !== null) { - this.#publishUpgradeHeaders(statusCode, headers, statusText); - } - const result = this[kHandler].onUpgrade(statusCode, headers, socket); - if (!this.aborted) { - this.completed = true; - if (statusCode !== null) { - this.#publishUpgradeTrailers(); - } - } - return result; - } - /** - * @param {number} statusCode - * @param {import('node:http2').IncomingHttpHeaders} headers - * @param {(headers: import('node:http2').IncomingHttpHeaders) => Buffer[]} parseHeaders - * @param {string} [statusText] - */ - onUpgradeResponse(statusCode, headers, parseHeaders, statusText = "") { - assert(!this.aborted); - assert(this.completed); - if (channels.headers.hasSubscribers) { - this.#publishUpgradeHeaders(statusCode, parseHeaders(headers), statusText); - } - this.#publishUpgradeTrailers(); - } - /** - * @param {Error} error - */ - onUpgradeError(error2) { - assert(!this.aborted); - assert(this.completed); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error: error2 }); - } - } - /** - * @param {number} statusCode - * @param {Buffer[]} headers - * @param {string} statusText - */ - #publishUpgradeHeaders(statusCode, headers, statusText) { - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - } - #publishUpgradeTrailers() { - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + return this[kHandler].onUpgrade(statusCode, headers, socket); } onComplete(trailers) { this.onFinally(); @@ -1989,11 +1933,7 @@ var require_request = __commonJS({ } else if (typeof val[i] === "object") { throw new InvalidArgumentError(`invalid ${key} header`); } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + arr.push(`${val[i]}`); } } val = arr; @@ -2005,9 +1945,6 @@ var require_request = __commonJS({ val = ""; } else { val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } } if (headerName === "host") { if (request2.host !== null) { @@ -2117,21 +2054,13 @@ var require_dispatcher_base = __commonJS({ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed"); var kOnClosed = /* @__PURE__ */ Symbol("onClosed"); var kInterceptedDispatch = /* @__PURE__ */ Symbol("Intercepted Dispatch"); - var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions"); var DispatcherBase = class extends Dispatcher { - constructor(opts) { + constructor() { super(); this[kDestroyed] = false; this[kOnDestroyed] = null; this[kClosed] = false; this[kOnClosed] = []; - this[kWebSocketOptions] = opts?.webSocket ?? {}; - } - get webSocketOptions() { - return { - maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, - maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 - }; } get destroyed() { return this[kDestroyed]; @@ -5738,7 +5667,6 @@ var require_client_h1 = __commonJS({ RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, - InvalidArgumentError, HeadersTimeoutError, HeadersOverflowError, SocketError, @@ -5785,9 +5713,6 @@ var require_client_h1 = __commonJS({ var FastBuffer = Buffer[Symbol.species]; var addListener = util.addListener; var removeAllListeners = util.removeAllListeners; - var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); - var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); - var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); var extractBody; async function lazyllhttp() { const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0; @@ -5950,55 +5875,24 @@ var require_client_h1 = __commonJS({ currentBufferRef = null; } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; - if (ret !== constants3.ERROR.OK) { - const body = data.subarray(offset); - if (ret === constants3.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(body); - } else if (ret === constants3.ERROR.PAUSED) { - this.paused = true; - socket.unshift(body); - } else { - throw this.createError(ret, body); + if (ret === constants3.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants3.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants3.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ""; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; } + throw new HTTPParserError(message, constants3.ERROR[ret], data.slice(offset)); } } catch (err) { util.destroy(socket, err); } } - finish() { - assert(currentParser === null); - assert(this.ptr != null); - assert(!this.paused); - const { llhttp } = this; - let ret; - try { - currentParser = this; - ret = llhttp.llhttp_finish(this.ptr); - } finally { - currentParser = null; - } - if (ret === constants3.ERROR.OK) { - return null; - } - if (ret === constants3.ERROR.PAUSED || ret === constants3.ERROR.PAUSED_UPGRADE) { - this.paused = true; - return null; - } - return this.createError(ret, EMPTY_BUF); - } - createError(ret, data) { - const { llhttp, contentLength, bytesRead } = this; - if (contentLength && bytesRead !== parseInt(contentLength, 10)) { - return new ResponseContentLengthMismatchError(); - } - const ptr = llhttp.llhttp_get_error_reason(this.ptr); - let message = ""; - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); - message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")"; - } - return new HTTPParserError(message, constants3.ERROR[ret], data); - } destroy() { assert(this.ptr != null); assert(currentParser == null); @@ -6018,10 +5912,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6065,7 +5955,7 @@ var require_client_h1 = __commonJS({ } } onUpgrade(head) { - const { upgrade, client, socket, headers, statusCode, statusText } = this; + const { upgrade, client, socket, headers, statusCode } = this; assert(upgrade); assert(client[kSocket] === socket); assert(!socket.destroyed); @@ -6090,10 +5980,9 @@ var require_client_h1 = __commonJS({ client[kQueue][client[kRunningIdx]++] = null; client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade")); try { - request2.onUpgrade(statusCode, headers, socket, statusText); - } catch (error2) { - util.errorRequest(client, request2, error2); - util.destroy(socket, error2); + request2.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); } client[kResume](); } @@ -6102,10 +5991,6 @@ var require_client_h1 = __commonJS({ if (socket.destroyed) { return -1; } - if (client[kRunning] === 0) { - util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket))); - return -1; - } const request2 = client[kQueue][client[kRunningIdx]]; if (!request2) { return -1; @@ -6231,7 +6116,6 @@ var require_client_h1 = __commonJS({ } request2.onComplete(headers); client[kQueue][client[kRunningIdx]++] = null; - socket[kSocketUsed] = true; if (socket[kWriting]) { assert(client[kRunning] === 0); util.destroy(socket, new InformationalError("reset")); @@ -6275,19 +6159,12 @@ var require_client_h1 = __commonJS({ socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kIdleSocketValidation] = 0; - socket[kIdleSocketValidationTimeout] = null; - socket[kSocketUsed] = false; socket[kParser] = new Parser(client, socket, llhttpInstance); addListener(socket, "error", function(err) { assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); const parser = this[kParser]; if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - this[kError] = parserErr; - this[kClient][kOnError](parserErr); - } + parser.onMessageComplete(); return; } this[kError] = err; @@ -6302,10 +6179,7 @@ var require_client_h1 = __commonJS({ addListener(socket, "end", function() { const parser = this[kParser]; if (parser.statusCode && !parser.shouldKeepAlive) { - const parserErr = parser.finish(); - if (parserErr) { - util.destroy(this, parserErr); - } + parser.onMessageComplete(); return; } util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this))); @@ -6313,10 +6187,9 @@ var require_client_h1 = __commonJS({ addListener(socket, "close", function() { const client2 = this[kClient]; const parser = this[kParser]; - clearIdleSocketValidation(this); if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - this[kError] = parser.finish() || this[kError]; + parser.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -6365,7 +6238,7 @@ var require_client_h1 = __commonJS({ return socket.destroyed; }, busy(request2) { - if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true; } if (request2) { @@ -6383,23 +6256,6 @@ var require_client_h1 = __commonJS({ } }; } - function clearIdleSocketValidation(socket) { - if (socket[kIdleSocketValidationTimeout]) { - clearImmediate(socket[kIdleSocketValidationTimeout]); - socket[kIdleSocketValidationTimeout] = null; - } - socket[kIdleSocketValidation] = 0; - } - function scheduleIdleSocketValidation(client, socket) { - socket[kIdleSocketValidation] = 1; - socket[kIdleSocketValidationTimeout] = setImmediate(() => { - socket[kIdleSocketValidationTimeout] = null; - socket[kIdleSocketValidation] = 2; - if (client[kSocket] === socket && !socket.destroyed) { - client[kResume](); - } - }); - } function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -6412,29 +6268,6 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } - if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { - if (socket[kIdleSocketValidation] === 0) { - scheduleIdleSocketValidation(client, socket); - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - if (socket[kIdleSocketValidation] === 1) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - return; - } - } - if (client[kRunning] === 0) { - socket[kParser].readMore(); - if (socket.destroyed) { - return; - } - } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); @@ -6465,16 +6298,8 @@ var require_client_h1 = __commonJS({ } body = bodyStream.stream; contentLength = bodyStream.length; - } else if (util.isBlobLike(body) && request2.contentType == null) { - const contentType = body.type; - if (contentType) { - const contentTypeValue = `${contentType}`; - if (!util.isValidHeaderValue(contentTypeValue)) { - util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header")); - return false; - } - headers.push("content-type", contentTypeValue); - } + } else if (util.isBlobLike(body) && request2.contentType == null && body.type) { + headers.push("content-type", body.type); } if (body && typeof body.read === "function") { body.read(0); @@ -6495,18 +6320,11 @@ var require_client_h1 = __commonJS({ process.emitWarning(new RequestContentLengthMismatchError()); } const socket = client[kSocket]; - clearIdleSocketValidation(socket); - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (request2.upgrade || request2.method === "CONNECT") { - util.destroy(socket, new InformationalError("aborted")); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - util.errorRequest(client, request2, error2 || new RequestAbortedError()); + util.errorRequest(client, request2, err || new RequestAbortedError()); util.destroy(body); util.destroy(socket, new InformationalError("aborted")); }; @@ -6862,7 +6680,6 @@ var require_client_h2 = __commonJS({ "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) { "use strict"; var assert = __require("node:assert"); - var { errorMonitor } = __require("node:events"); var { pipeline } = __require("node:stream"); var util = require_util(); var { @@ -6923,10 +6740,6 @@ var require_client_h2 = __commonJS({ } return result; } - function parseH2ResponseHeaders(headers) { - const { [HTTP2_HEADER_STATUS]: _statusCode, ...realHeaders } = headers; - return parseH2Headers(realHeaders); - } async function connectH2(client, socket) { client[kSocket] = socket; if (!h2ExperimentalWarned) { @@ -7090,22 +6903,16 @@ var require_client_h2 = __commonJS({ const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; - const abort = (error2) => { - if (request2.aborted) { - return; - } - if (request2.completed) { - if (method === "CONNECT" && stream != null) { - util.destroy(stream, error2 || new RequestAbortedError()); - } + const abort = (err) => { + if (request2.aborted || request2.completed) { return; } - error2 = error2 || new RequestAbortedError(); - util.errorRequest(client, request2, error2); + err = err || new RequestAbortedError(); + util.errorRequest(client, request2, err); if (stream != null) { - util.destroy(stream, error2); + util.destroy(stream, err); } - util.destroy(body, error2); + util.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; client[kResume](); }; @@ -7120,42 +6927,18 @@ var require_client_h2 = __commonJS({ if (method === "CONNECT") { session.ref(); stream = session.request(headers, { endStream: false, signal }); - let upgradeResponseFinished = false; - const onResponse = (headers2) => { - upgradeResponseFinished = true; - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeResponse(Number(headers2[HTTP2_HEADER_STATUS]), headers2, parseH2ResponseHeaders); - }; - const onUpgradeError = (error2) => { - upgradeResponseFinished = true; - stream.off("response", onResponse); - request2.onUpgradeError(error2); - }; - const onReady = () => { - try { - request2.onUpgrade(null, null, stream); - } catch (error2) { - stream.off("response", onResponse); - abort(error2); - return; - } - if (request2.aborted) { - return; - } - stream.off("error", abort); - stream.once(errorMonitor, onUpgradeError); + if (stream.id && !stream.pending) { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; - }; - stream.once("response", onResponse); - stream.once("error", abort); - ++session[kOpenStreams]; - onReady(); + } else { + stream.once("ready", () => { + request2.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } stream.once("close", () => { - if (!upgradeResponseFinished && request2.completed) { - stream.off("response", onResponse); - stream.off(errorMonitor, onUpgradeError); - request2.onUpgradeError(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`)); - } session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); @@ -7716,10 +7499,9 @@ var require_client = __commonJS({ autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, - allowH2, - webSocket + allowH2 } = {}) { - super({ webSocket }); + super(); if (keepAlive !== void 0) { throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead"); } @@ -8225,8 +8007,8 @@ var require_pool_base = __commonJS({ var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); var kStats = /* @__PURE__ */ Symbol("stats"); var PoolBase = class extends DispatcherBase { - constructor(opts) { - super(opts); + constructor() { + super(); this[kQueue] = new FixedQueue(); this[kClients] = []; this[kQueued] = 0; @@ -8397,6 +8179,7 @@ var require_pool = __commonJS({ allowH2, ...options } = {}) { + super(); if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError("invalid connections"); } @@ -8417,7 +8200,6 @@ var require_pool = __commonJS({ ...connect }); } - super(options); this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : []; this[kConnections] = connections || null; this[kUrl] = util.parseOrigin(origin); @@ -8617,6 +8399,7 @@ var require_agent = __commonJS({ } var Agent = class extends DispatcherBase { constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super(); if (typeof factory !== "function") { throw new InvalidArgumentError("factory must be a function."); } @@ -8626,7 +8409,6 @@ var require_agent = __commonJS({ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError("maxRedirections must be a positive number"); } - super(options); if (connect && typeof connect !== "function") { connect = { ...connect }; } @@ -9067,24 +8849,6 @@ var require_retry_handler = __commonJS({ const current = Date.now(); return new Date(retryAfter).getTime() - current; } - function validatePartialResponseContentLength(headers, range, statusCode, retryCount) { - const contentLength = headers["content-length"]; - if (contentLength == null) { - return null; - } - if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) { - return null; - } - const length = Number(contentLength); - const expectedLength = range.end - range.start + 1; - if (!Number.isFinite(length) || length !== expectedLength) { - return new RequestRetryError("Content-Length mismatch", statusCode, { - headers, - data: { count: retryCount } - }); - } - return null; - } var RetryHandler = class _RetryHandler { constructor(opts, handlers) { const { retryOptions, ...dispatchOpts } = opts; @@ -9138,7 +8902,6 @@ var require_retry_handler = __commonJS({ this.end = null; this.etag = null; this.resume = null; - this.headersSent = false; this.handler.onConnect((reason) => { this.aborted = true; if (this.abort) { @@ -9148,17 +8911,6 @@ var require_retry_handler = __commonJS({ } }); } - checkpointResponseEnd(headers, resume) { - if (this.end == null && this.opts.method !== "HEAD") { - const contentLength = headers["content-length"]; - this.end = contentLength != null ? Number(contentLength) - 1 : null; - assert( - this.end == null || Number.isFinite(this.end), - "invalid content-length" - ); - } - this.resume = this.end != null ? resume : null; - } onRequestSent() { if (this.handler.onRequestSent) { this.handler.onRequestSent(); @@ -9220,9 +8972,7 @@ var require_retry_handler = __commonJS({ const headers = parseHeaders(rawHeaders); this.retryCount += 1; if (statusCode >= 300) { - if (!this.headersSent && this.retryOpts.statusCodes.includes(statusCode) === false) { - this.headersSent = true; - this.checkpointResponseEnd(headers, resume); + if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9271,21 +9021,9 @@ var require_retry_handler = __commonJS({ ); return false; } - const contentLengthError = validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = contentRange; - if (this.start !== start || this.end != null && this.end !== end) { - this.abort( - new RequestRetryError("Content-Range mismatch", statusCode, { - headers, - data: { count: this.retryCount } - }) - ); - return false; - } + assert(this.start === start, "content-range mismatch"); + assert(this.end == null || this.end === end, "content-range mismatch"); this.resume = resume; return true; } @@ -9293,7 +9031,6 @@ var require_retry_handler = __commonJS({ if (statusCode === 206) { const range = parseRangeHeader(headers["content-range"]); if (range == null) { - this.headersSent = true; return this.handler.onHeaders( statusCode, rawHeaders, @@ -9301,11 +9038,6 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const contentLengthError = validatePartialResponseContentLength(headers, range, statusCode, this.retryCount); - if (contentLengthError != null) { - this.abort(contentLengthError); - return false; - } const { start, size, end = size - 1 } = range; assert( start != null && Number.isFinite(start), @@ -9325,7 +9057,6 @@ var require_retry_handler = __commonJS({ "invalid content-length" ); this.resume = resume; - this.headersSent = true; this.etag = headers.etag != null ? headers.etag : null; if (this.etag != null && this.etag.startsWith("W/")) { this.etag = null; @@ -9353,7 +9084,7 @@ var require_retry_handler = __commonJS({ return this.handler.onComplete(rawTrailers); } onError(err) { - if (this.aborted || isDisturbed(this.opts.body) || this.headersSent && this.resume == null) { + if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err); } if (this.retryCount - this.retryCountCheckpoint > 0) { @@ -16152,48 +15883,14 @@ var require_util6 = __commonJS({ for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) - code > 126 || // exclude DEL and non-ascii + code === 127 || // DEL code === 59) { throw new Error("Invalid cookie path"); } } } - function isLetterOrDigit(code) { - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 90 || // A-Z - code >= 97 && code <= 122; - } function validateCookieDomain(domain) { - if (domain === " ") { - return; - } - if (domain.length > 255) { - throw new Error("Invalid cookie domain"); - } - let labelLength = 0; - for (let i = 0; i < domain.length; ++i) { - const code = domain.charCodeAt(i); - if (code === 46) { - if (labelLength === 0) { - throw new Error("Invalid cookie domain"); - } - if (domain.charCodeAt(i - 1) === 45) { - throw new Error("Invalid cookie domain"); - } - labelLength = 0; - continue; - } - if (labelLength === 0 && !isLetterOrDigit(code)) { - throw new Error("Invalid cookie domain"); - } - if (!isLetterOrDigit(code) && code !== 45) { - throw new Error("Invalid cookie domain"); - } - if (++labelLength > 63) { - throw new Error("Invalid cookie domain"); - } - } - if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) { + if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) { throw new Error("Invalid cookie domain"); } } @@ -16276,11 +15973,7 @@ var require_util6 = __commonJS({ throw new Error("Invalid unparsed"); } const [key, ...value] = part.split("="); - const trimmedKey = key.trim(); - const joinedValue = value.join("="); - validateCookieName(trimmedKey); - validateCookieValue(joinedValue); - out.push(`${trimmedKey}=${joinedValue}`); + out.push(`${key.trim()}=${value.join("=")}`); } return out.join("; "); } @@ -16410,14 +16103,18 @@ var require_parse = __commonJS({ } else if (attributeNameLowercase === "httponly") { cookieAttributeList.httpOnly = true; } else if (attributeNameLowercase === "samesite") { + let enforcement = "Default"; const attributeValueLowercase = attributeValue.toLowerCase(); - if (attributeValueLowercase === "none") { - cookieAttributeList.sameSite = "None"; - } else if (attributeValueLowercase === "strict") { - cookieAttributeList.sameSite = "Strict"; - } else if (attributeValueLowercase === "lax") { - cookieAttributeList.sameSite = "Lax"; + if (attributeValueLowercase.includes("none")) { + enforcement = "None"; + } + if (attributeValueLowercase.includes("strict")) { + enforcement = "Strict"; + } + if (attributeValueLowercase.includes("lax")) { + enforcement = "Lax"; } + cookieAttributeList.sameSite = enforcement; } else { cookieAttributeList.unparsed ??= []; cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); @@ -17239,7 +16936,7 @@ var require_connection = __commonJS({ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol"); if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList); - if (requestProtocols === null || !requestProtocols.includes(secProtocol)) { + if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); return; } @@ -17345,26 +17042,31 @@ var require_permessage_deflate = __commonJS({ var tail = Buffer.from([0, 0, 255, 255]); var kBuffer = /* @__PURE__ */ Symbol("kBuffer"); var kLength = /* @__PURE__ */ Symbol("kLength"); + var kDefaultMaxDecompressedSize = 4 * 1024 * 1024; var PerMessageDeflate = class { /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - #maxPayloadSize = 0; + /** @type {number} */ + #maxDecompressedSize; + /** @type {boolean} */ + #aborted = false; + /** @type {Function|null} */ + #currentCallback = null; /** * @param {Map} extensions + * @param {{ maxDecompressedMessageSize?: number }} [options] */ - constructor(extensions, options) { + constructor(extensions, options = {}) { this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); - this.#maxPayloadSize = options.maxPayloadSize; + this.#maxDecompressedSize = options.maxDecompressedMessageSize ?? kDefaultMaxDecompressedSize; } - /** - * Decompress a compressed payload. - * @param {Buffer} chunk Compressed data - * @param {boolean} fin Final fragment flag - * @param {Function} callback Callback function - */ decompress(chunk, fin, callback) { + if (this.#aborted) { + callback(new MessageSizeExceededError()); + return; + } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS; if (this.#options.serverMaxWindowBits) { @@ -17383,12 +17085,20 @@ var require_permessage_deflate = __commonJS({ this.#inflate[kBuffer] = []; this.#inflate[kLength] = 0; this.#inflate.on("data", (data) => { + if (this.#aborted) { + return; + } this.#inflate[kLength] += data.length; - if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { - callback(new MessageSizeExceededError()); + if (this.#inflate[kLength] > this.#maxDecompressedSize) { + this.#aborted = true; this.#inflate.removeAllListeners(); this.#inflate.destroy(); this.#inflate = null; + if (this.#currentCallback) { + const cb = this.#currentCallback; + this.#currentCallback = null; + cb(new MessageSizeExceededError()); + } return; } this.#inflate[kBuffer].push(data); @@ -17398,17 +17108,19 @@ var require_permessage_deflate = __commonJS({ callback(err); }); } + this.#currentCallback = callback; this.#inflate.write(chunk); if (fin) { this.#inflate.write(tail); } this.#inflate.flush(() => { - if (!this.#inflate) { + if (this.#aborted || !this.#inflate) { return; } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); this.#inflate[kBuffer].length = 0; this.#inflate[kLength] = 0; + this.#currentCallback = null; callback(null, full); }); } @@ -17439,14 +17151,8 @@ var require_receiver = __commonJS({ var { WebsocketFrameSend } = require_frame(); var { closeWebSocketConnection } = require_connection(); var { PerMessageDeflate } = require_permessage_deflate(); - var { MessageSizeExceededError } = require_errors(); - function failWebsocketConnectionWithCode(ws, code, reason) { - closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); - failWebsocketConnection(ws, reason); - } var ByteParser = class extends Writable { #buffers = []; - #fragmentsBytes = 0; #byteOffset = 0; #loop = false; #state = parserStates.INFO; @@ -17454,21 +17160,18 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - /** @type {number} */ - #maxFragments; - /** @type {number} */ - #maxPayloadSize; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions - * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + * @param {{ maxDecompressedMessageSize?: number }} [options] */ constructor(ws, extensions, options = {}) { super(); this.ws = ws; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; - this.#maxFragments = options.maxFragments ?? 0; - this.#maxPayloadSize = options.maxPayloadSize ?? 0; + this.#options = options; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options)); } @@ -17483,13 +17186,6 @@ var require_receiver = __commonJS({ this.#loop = true; this.run(callback); } - #validatePayloadLength() { - if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, "Payload size exceeds maximum allowed size"); - return false; - } - return true; - } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, @@ -17549,9 +17245,6 @@ var require_receiver = __commonJS({ if (payloadLength <= 125) { this.#info.payloadLength = payloadLength; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16; } else if (payloadLength === 127) { @@ -17572,9 +17265,6 @@ var require_receiver = __commonJS({ const buffer = this.consume(2); this.#info.payloadLength = buffer.readUInt16BE(0); this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback(); @@ -17588,9 +17278,6 @@ var require_receiver = __commonJS({ } this.#info.payloadLength = lower; this.#state = parserStates.READ_DATA; - if (!this.#validatePayloadLength()) { - return; - } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback(); @@ -17601,46 +17288,32 @@ var require_receiver = __commonJS({ this.#state = parserStates.INFO; } else { if (!this.#info.compressed) { - if (!this.writeFragments(body)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } + this.#fragments.push(body); if (!this.#info.fragmented && this.#info.fin) { - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + const fullMessage = Buffer.concat(this.#fragments); + websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage); + this.#fragments.length = 0; } this.#state = parserStates.INFO; } else { - this.#extensions.get("permessage-deflate").decompress( - body, - this.#info.fin, - (error2, data) => { - if (error2) { - const code = error2 instanceof MessageSizeExceededError ? 1009 : 1007; - failWebsocketConnectionWithCode(this.ws, code, error2.message); - return; - } - if (!this.writeFragments(data)) { - return; - } - if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { - failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); - return; - } - if (!this.#info.fin) { - this.#state = parserStates.INFO; - this.#loop = true; - this.run(callback); - return; - } - websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); - this.#loop = true; + this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error2, data) => { + if (error2) { + failWebsocketConnection(this.ws, error2.message); + return; + } + this.#fragments.push(data); + if (!this.#info.fin) { this.#state = parserStates.INFO; + this.#loop = true; this.run(callback); + return; } - ); + websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)); + this.#loop = true; + this.#state = parserStates.INFO; + this.#fragments.length = 0; + this.run(callback); + }); this.#loop = false; break; } @@ -17683,26 +17356,6 @@ var require_receiver = __commonJS({ this.#byteOffset -= n; return buffer; } - writeFragments(fragment) { - if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) { - failWebsocketConnectionWithCode(this.ws, 1008, "Too many message fragments"); - return false; - } - this.#fragmentsBytes += fragment.length; - this.#fragments.push(fragment); - return true; - } - consumeFragments() { - const fragments = this.#fragments; - if (fragments.length === 1) { - this.#fragmentsBytes = 0; - return fragments.shift(); - } - const output = Buffer.concat(fragments, this.#fragmentsBytes); - this.#fragments = []; - this.#fragmentsBytes = 0; - return output; - } parseCloseBody(data) { assert(data.length !== 1); let code; @@ -17914,6 +17567,8 @@ var require_websocket = __commonJS({ #extensions = ""; /** @type {SendQueue} */ #sendQueue; + /** @type {{ maxDecompressedMessageSize?: number }} */ + #options; /** * @param {string} url * @param {string|string[]} protocols @@ -17957,6 +17612,9 @@ var require_websocket = __commonJS({ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError"); } this[kWebSocketURL] = new URL(urlRecord.href); + this.#options = { + maxDecompressedMessageSize: options.maxDecompressedMessageSize + }; const client = environmentSettingsObject.settingsObject; this[kController] = establishWebSocketConnection( urlRecord, @@ -18140,13 +17798,7 @@ var require_websocket = __commonJS({ */ #onConnectionEstablished(response, parsedExtensions) { this[kResponse] = response; - const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; - const maxFragments = webSocketOptions?.maxFragments; - const maxPayloadSize = webSocketOptions?.maxPayloadSize; - const parser = new ByteParser(this, parsedExtensions, { - maxFragments, - maxPayloadSize - }); + const parser = new ByteParser(this, parsedExtensions, this.#options); parser.on("drain", onParserDrain); parser.on("error", onParserError.bind(this)); response.socket.ws = this; @@ -18221,6 +17873,19 @@ var require_websocket = __commonJS({ { key: "headers", converter: webidl.nullableConverter(webidl.converters.HeadersInit) + }, + { + key: "maxDecompressedMessageSize", + converter: webidl.nullableConverter((V) => { + V = webidl.converters["unsigned long long"](V); + if (V <= 0) { + throw webidl.errors.exception({ + header: "WebSocket constructor", + message: "maxDecompressedMessageSize must be greater than 0" + }); + } + return V; + }) } ]); webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) { @@ -18299,40 +17964,6 @@ var require_eventsource_stream = __commonJS({ var CR = 13; var COLON = 58; var SPACE = 32; - var DATA = Buffer.from("data"); - var EVENT = Buffer.from("event"); - var ID = Buffer.from("id"); - var RETRY = Buffer.from("retry"); - function isASCIINumberBytes(buffer, start) { - if (start >= buffer.length) { - return false; - } - for (let i = start; i < buffer.length; i++) { - if (buffer[i] < 48 || buffer[i] > 57) { - return false; - } - } - return true; - } - function isValidLastEventIdBytes(buffer, start) { - for (let i = start; i < buffer.length; i++) { - if (buffer[i] === 0) { - return false; - } - } - return true; - } - function isFieldName(line, length, field) { - if (length !== field.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (line[i] !== field[i]) { - return false; - } - } - return true; - } var EventSourceStream = class extends Transform { /** * @type {eventSourceSettings} @@ -18352,13 +17983,10 @@ var require_eventsource_stream = __commonJS({ */ eventEndCheck = false; /** - * @type {Buffer[]} + * @type {Buffer} */ - chunks = []; - chunkIndex = 0; + buffer = null; pos = 0; - lineChunkIndex = 0; - linePos = 0; event = { data: void 0, event: void 0, @@ -18389,30 +18017,63 @@ var require_eventsource_stream = __commonJS({ callback(); return; } - this.chunks.push(chunk); + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } if (this.checkBOM) { - if (this.handleBOM()) { - callback(); - return; + switch (this.buffer.length) { + case 1: + if (this.buffer[0] === BOM[0]) { + callback(); + return; + } + this.checkBOM = false; + callback(); + return; + case 2: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) { + callback(); + return; + } + this.checkBOM = false; + break; + case 3: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = Buffer.alloc(0); + this.checkBOM = false; + callback(); + return; + } + this.checkBOM = false; + break; + default: + if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) { + this.buffer = this.buffer.subarray(3); + } + this.checkBOM = false; + break; } } - while (this.hasCurrentByte()) { - const byte = this.currentByte(); + while (this.pos < this.buffer.length) { if (this.eventEndCheck) { if (this.crlfCheck) { - if (byte === LF) { + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.crlfCheck = false; - this.consumeCurrentByte(); continue; } this.crlfCheck = false; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.consumeCurrentByte(); - if (this.hasPendingEvent()) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if (this.event.data !== void 0 || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event); } this.clearEvent(); @@ -18421,16 +18082,17 @@ var require_eventsource_stream = __commonJS({ this.eventEndCheck = false; continue; } - if (byte === LF || byte === CR) { - if (byte === CR) { + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + if (this.buffer[this.pos] === CR) { this.crlfCheck = true; } - this.parseLine(this.readLine(), this.event); - this.consumeCurrentByte(); + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; this.eventEndCheck = true; continue; } - this.advanceCursor(); + this.pos++; } callback(); } @@ -18446,42 +18108,43 @@ var require_eventsource_stream = __commonJS({ if (colonPosition === 0) { return; } - let fieldLength = line.length; - let valueStart = line.length; + let field = ""; + let value = ""; if (colonPosition !== -1) { - fieldLength = colonPosition; - valueStart = colonPosition + 1; + field = line.subarray(0, colonPosition).toString("utf8"); + let valueStart = colonPosition + 1; if (line[valueStart] === SPACE) { ++valueStart; } + value = line.subarray(valueStart).toString("utf8"); + } else { + field = line.toString("utf8"); + value = ""; } - if (isFieldName(line, fieldLength, DATA)) { - const value = line.toString("utf8", valueStart); - if (event.data === void 0) { - event.data = value; - } else { - event.data += ` + switch (field) { + case "data": + if (event[field] === void 0) { + event[field] = value; + } else { + event[field] += ` ${value}`; - } - return; - } - if (isFieldName(line, fieldLength, RETRY)) { - if (isASCIINumberBytes(line, valueStart)) { - event.retry = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, ID)) { - if (isValidLastEventIdBytes(line, valueStart)) { - event.id = line.toString("utf8", valueStart); - } - return; - } - if (isFieldName(line, fieldLength, EVENT)) { - const value = line.toString("utf8", valueStart); - if (value.length > 0) { - event.event = value; - } + } + break; + case "retry": + if (isASCIINumber(value)) { + event[field] = value; + } + break; + case "id": + if (isValidLastEventId(value)) { + event[field] = value; + } + break; + case "event": + if (value.length > 0) { + event[field] = value; + } + break; } } /** @@ -18506,120 +18169,12 @@ ${value}`; } } clearEvent() { - this.event.data = void 0; - this.event.event = void 0; - this.event.id = void 0; - this.event.retry = void 0; - } - hasPendingEvent() { - return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0; - } - hasCurrentByte() { - return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length; - } - currentByte() { - return this.chunks[this.chunkIndex][this.pos]; - } - consumeCurrentByte() { - this.advanceCursor(); - this.syncLineStartToCursor(); - } - advanceCursor() { - this.pos++; - while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) { - this.chunkIndex++; - this.pos = 0; - } - } - syncLineStartToCursor() { - this.lineChunkIndex = this.chunkIndex; - this.linePos = this.pos; - this.dropConsumedChunks(); - } - dropConsumedChunks() { - while (this.lineChunkIndex > 0) { - this.chunks.shift(); - this.lineChunkIndex--; - this.chunkIndex--; - } - if (this.chunkIndex === this.chunks.length) { - this.chunks.length = 0; - this.chunkIndex = 0; - this.pos = 0; - this.lineChunkIndex = 0; - this.linePos = 0; - } - } - readLine() { - if (this.lineChunkIndex === this.chunkIndex) { - return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos); - } - const chunks = []; - let length = 0; - for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) { - const chunk = this.chunks[i]; - const start = i === this.lineChunkIndex ? this.linePos : 0; - const end = i === this.chunkIndex ? this.pos : chunk.length; - const slice = chunk.subarray(start, end); - length += slice.length; - chunks.push(slice); - } - return Buffer.concat(chunks, length); - } - peekBufferedByte(offset) { - let chunkIndex = this.lineChunkIndex; - let pos = this.linePos; - while (chunkIndex < this.chunks.length) { - const chunk = this.chunks[chunkIndex]; - const remaining = chunk.length - pos; - if (offset < remaining) { - return chunk[pos + offset]; - } - offset -= remaining; - chunkIndex++; - pos = 0; - } - } - discardLeadingBytes(count) { - while (count > 0 && this.lineChunkIndex < this.chunks.length) { - const chunk = this.chunks[this.lineChunkIndex]; - const remaining = chunk.length - this.linePos; - if (count < remaining) { - this.linePos += count; - count = 0; - } else { - count -= remaining; - this.lineChunkIndex++; - this.linePos = 0; - } - } - this.chunkIndex = this.lineChunkIndex; - this.pos = this.linePos; - this.dropConsumedChunks(); - } - handleBOM() { - const first = this.peekBufferedByte(0); - const second = this.peekBufferedByte(1); - const third = this.peekBufferedByte(2); - if (second === void 0) { - if (first === BOM[0]) { - return true; - } - this.checkBOM = false; - return true; - } - if (third === void 0) { - if (first === BOM[0] && second === BOM[1]) { - return true; - } - this.checkBOM = false; - return false; - } - if (first === BOM[0] && second === BOM[1] && third === BOM[2]) { - this.discardLeadingBytes(3); - } - this.checkBOM = false; - return !this.hasCurrentByte(); + this.event = { + data: void 0, + event: void 0, + id: void 0, + retry: void 0 + }; } }; module.exports = { diff --git a/__mocks__/react-native-onyx.ts b/__mocks__/react-native-onyx.ts index 6db22ac1b627..f5b09f2949da 100644 --- a/__mocks__/react-native-onyx.ts +++ b/__mocks__/react-native-onyx.ts @@ -5,7 +5,7 @@ import type {ConnectOptions, OnyxKey} from 'react-native-onyx'; // eslint-disable-next-line no-restricted-imports -import Onyx, {useOnyx} from 'react-native-onyx'; +import Onyx, {useOnyx, useOnyxState} from 'react-native-onyx'; let connectCallbackDelay = 0; function addDelayToConnectCallback(delay: number) { @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = { export default reactNativeOnyxMock; -export {useOnyx}; +export {useOnyx, useOnyxState}; diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index 60c927bec03f..4703ee160dc3 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -1984,7 +1984,6 @@ "../../tests/ui/UnreadIndicatorsTest.tsx" "@typescript-eslint/no-restricted-imports" 1 "../../tests/ui/WorkspaceMoreFeaturesPageTest.tsx" "no-restricted-imports" 1 "../../tests/unit/canEditFieldOfMoneyRequestTest.ts" "@typescript-eslint/no-deprecated/randomReportAction.originalMessage" 3 -"../../tests/unit/canEditFieldOfMoneyRequestTest.ts" "@typescript-eslint/no-restricted-imports" 1 "../../tests/unit/components/HTMLEngineProvider/VictoryChartAttributesParsers.test.ts" "rulesdir/no-raw-typography" 1 "../../tests/unit/FormulaTest.ts" "no-restricted-imports" 1 "../../tests/unit/HomePage/YourSpendSection/useYourSpendDataTest.ts" "no-restricted-imports" 1 diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 9aceaf15c17e..e78f0ba0c064 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -1435,7 +1435,6 @@ const ONYXKEYS = { DERIVED: { REPORT_ATTRIBUTES: 'reportAttributes', REPORT_TRANSACTIONS_AND_VIOLATIONS: 'reportTransactionsAndViolations', - OUTSTANDING_REPORTS_BY_POLICY_ID: 'outstandingReportsByPolicyID', VISIBLE_REPORT_ACTIONS: 'visibleReportActions', NON_PERSONAL_AND_WORKSPACE_CARD_LIST: 'nonPersonalAndWorkspaceCardList', PERSONAL_AND_WORKSPACE_CARD_LIST: 'personalAndWorkspaceCardList', @@ -2018,7 +2017,6 @@ type OnyxValuesMapping = { type OnyxDerivedValuesMapping = { [ONYXKEYS.DERIVED.REPORT_ATTRIBUTES]: OnyxTypes.ReportAttributesDerivedValue; [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]: OnyxTypes.ReportTransactionsAndViolationsDerivedValue; - [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: OnyxTypes.OutstandingReportsByPolicyIDDerivedValue; [ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS]: OnyxTypes.VisibleReportActionsDerivedValue; [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: OnyxTypes.NonPersonalAndWorkspaceCardListDerivedValue; [ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST]: OnyxTypes.PersonalAndWorkspaceCardListDerivedValue; diff --git a/src/components/MoneyReportHeaderActions/MoneyReportHeaderSecondaryActions.tsx b/src/components/MoneyReportHeaderActions/MoneyReportHeaderSecondaryActions.tsx index 941fbf534f52..bec86a53ef65 100644 --- a/src/components/MoneyReportHeaderActions/MoneyReportHeaderSecondaryActions.tsx +++ b/src/components/MoneyReportHeaderActions/MoneyReportHeaderSecondaryActions.tsx @@ -25,6 +25,7 @@ import useLifecycleActions from '@hooks/useLifecycleActions'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useOutstandingReportsByPolicyID from '@hooks/useOutstandingReportsByPolicyID'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; import useParticipantsInvoiceReport from '@hooks/useParticipantsInvoiceReport'; import usePayChatReportActions from '@hooks/usePayChatReportActions'; @@ -111,7 +112,7 @@ function MoneyReportHeaderSecondaryActionsInner({reportID, primaryAction, isRepo const [submitterLogin] = usePersonalDetail(moneyRequestReport?.ownerAccountID, loginSelector); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [reportMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${moneyRequestReport?.reportID}`); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [moveExpenseReportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, { selector: createMoveExpenseReportNVPSelector(outstandingReportsByPolicyID, moneyRequestReport?.reportID), }); diff --git a/src/components/MoneyReportHeaderActions/MoneyReportHeaderSelectionDropdown.tsx b/src/components/MoneyReportHeaderActions/MoneyReportHeaderSelectionDropdown.tsx index 80d1cb3f24a8..15e7b1a8082e 100644 --- a/src/components/MoneyReportHeaderActions/MoneyReportHeaderSelectionDropdown.tsx +++ b/src/components/MoneyReportHeaderActions/MoneyReportHeaderSelectionDropdown.tsx @@ -18,6 +18,7 @@ import useLifecycleActions from '@hooks/useLifecycleActions'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useOutstandingReportsByPolicyID from '@hooks/useOutstandingReportsByPolicyID'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; import useReportIsArchived from '@hooks/useReportIsArchived'; import useSelectedTransactionsActions from '@hooks/useSelectedTransactionsActions'; @@ -79,7 +80,7 @@ function MoneyReportHeaderSelectionDropdown({reportID, primaryAction, isReportIn const [cardList] = useOnyx(ONYXKEYS.CARD_LIST); const [reportMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${getNonEmptyStringOnyxID(moneyRequestReport?.reportID)}`); const [dismissedRejectUseExplanation] = useOnyx(ONYXKEYS.NVP_DISMISSED_REJECT_USE_EXPLANATION); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [moveExpenseReportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, { selector: createMoveExpenseReportNVPSelector(outstandingReportsByPolicyID, moneyRequestReport?.reportID), }); diff --git a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx index 941d0e3a8331..5c61e8f4d9fe 100644 --- a/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/ReportField.tsx @@ -3,6 +3,7 @@ import MenuItemFieldHTML from '@components/MenuItem/presets/MenuItemFieldHTML'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useOutstandingReports from '@hooks/useOutstandingReports'; +import {useOutstandingReportsForPolicy} from '@hooks/useOutstandingReportsByPolicyID'; import {useDerivedReportNameByReportID} from '@hooks/useReportAttributes'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; @@ -20,7 +21,6 @@ import type {Participant} from '@src/types/onyx/IOU'; import type {OnyxEntry} from 'react-native-onyx'; -import {createOutstandingReportsForPolicySelector} from '@selectors/Report'; import React from 'react'; import ExpenseFieldRow from './ExpenseFieldRow'; @@ -47,7 +47,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a const {translate, localeCompare} = useLocalize(); const policyID = selectedParticipants?.at(0)?.policyID; - const [outstandingReportsForPolicy] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID, {selector: createOutstandingReportsForPolicySelector(policyID)}); + const outstandingReportsForPolicy = useOutstandingReportsForPolicy(policyID); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); diff --git a/src/components/MoneyRequestHeaderSecondaryActions.tsx b/src/components/MoneyRequestHeaderSecondaryActions.tsx index 3b9876e6b464..e3849799bd5e 100644 --- a/src/components/MoneyRequestHeaderSecondaryActions.tsx +++ b/src/components/MoneyRequestHeaderSecondaryActions.tsx @@ -15,6 +15,7 @@ import useLocalize from '@hooks/useLocalize'; import useMoneyRequestPolicyTagsForReport from '@hooks/useMoneyRequestPolicyTagsForReport'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useOutstandingReportsByPolicyID from '@hooks/useOutstandingReportsByPolicyID'; import useParticipantsPolicyTags from '@hooks/useParticipantsPolicyTags'; import usePermissions from '@hooks/usePermissions'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; @@ -174,7 +175,7 @@ function MoneyRequestHeaderSecondaryActions({reportID, onBackButtonPress}: Money const [policyRecentlyUsedCurrencies] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES); const [dismissedRejectUseExplanation] = useOnyx(ONYXKEYS.NVP_DISMISSED_REJECT_USE_EXPLANATION); const [dismissedHoldUseExplanation] = useOnyx(ONYXKEYS.NVP_DISMISSED_HOLD_USE_EXPLANATION); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const [recentWaypoints] = useOnyx(ONYXKEYS.NVP_RECENT_WAYPOINTS); const [shouldFailAllRequests] = useOnyx(ONYXKEYS.NETWORK, {selector: shouldFailAllRequestsSelector}); diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index fb30e81b2aba..e30a553867eb 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -32,6 +32,7 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useOutstandingReportsByPolicyID from '@hooks/useOutstandingReportsByPolicyID'; import usePermissions from '@hooks/usePermissions'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; import usePersonalPolicy from '@hooks/usePersonalPolicy'; @@ -289,7 +290,7 @@ function MoneyRequestView({ const [transactionBackup] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_BACKUP}${getNonEmptyStringOnyxID(linkedTransactionID)}`); const transactionViolations = useTransactionViolations(transaction?.transactionID, false, distanceOriginalPolicy ?? policy); const allTransactionViolations = useAllTransactionViolations(transaction?.transactionID); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const delegateAccountID = useDelegateAccountID(); const personalDetailsList = usePersonalDetails(); diff --git a/src/components/Search/SearchWriteActionsProvider.tsx b/src/components/Search/SearchWriteActionsProvider.tsx index 7c282c7b0605..130a78758100 100644 --- a/src/components/Search/SearchWriteActionsProvider.tsx +++ b/src/components/Search/SearchWriteActionsProvider.tsx @@ -1,6 +1,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useOutstandingReportsByPolicyID from '@hooks/useOutstandingReportsByPolicyID'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSelfDMReport from '@hooks/useSelfDMReport'; import useShiftRangeSelection from '@hooks/useShiftRangeSelection'; @@ -21,10 +22,11 @@ import {isTransactionPendingDelete} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {OutstandingReportsByPolicyIDDerivedValue, Report, ReportNameValuePairs, SearchResults, Transaction} from '@src/types/onyx'; +import type {Report, ReportNameValuePairs, SearchResults, Transaction} from '@src/types/onyx'; import type {SearchDataTypes} from '@src/types/onyx/SearchResults'; import {getEmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject'; +import type {OutstandingReportsByPolicyID} from '@selectors/Report'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import {useIsFocused} from '@react-navigation/native'; @@ -120,8 +122,8 @@ type ReconcileSelectionParams = { /** Report name-value pairs collection, used for the change-report eligibility archived check */ reportNameValuePairs: OnyxCollection; - /** Derived outstanding reports per policy, used for the change-report eligibility check */ - outstandingReportsByPolicyID: OutstandingReportsByPolicyIDDerivedValue | undefined; + /** Outstanding reports per policy, used for the change-report eligibility check */ + outstandingReportsByPolicyID: OutstandingReportsByPolicyID | undefined; /** Whether the current snapshot is settled and can safely refresh/prune exclusions */ shouldReconcileExcludedTransactions: boolean; @@ -535,7 +537,7 @@ function SearchWriteActionsProvider({ const {accountID, email, login} = useCurrentUserPersonalDetails(); const selfDMReport = useSelfDMReport(); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); const {applySelection, getSelectedTransactions, getExcludedTransactions, getAreAllMatchingItemsSelected} = useSearchSelectionActions(); diff --git a/src/components/Search/selectionBuilders.ts b/src/components/Search/selectionBuilders.ts index 2438c60de9df..d452877dd987 100644 --- a/src/components/Search/selectionBuilders.ts +++ b/src/components/Search/selectionBuilders.ts @@ -5,9 +5,10 @@ import type {ShiftRangeBatch} from '@libs/shiftRangeSelection'; import {getOriginalTransactionWithSplitInfo, hasValidModifiedAmount, isExpenseUnreported, isOnHold, isTransactionPendingDelete} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; -import type {OutstandingReportsByPolicyIDDerivedValue, Report, ReportNameValuePairs, Rule, Transaction} from '@src/types/onyx'; +import type {Report, ReportNameValuePairs, Rule, Transaction} from '@src/types/onyx'; import type {SearchGroupBase, SearchResultDataType} from '@src/types/onyx/SearchResults'; +import type {OutstandingReportsByPolicyID} from '@selectors/Report'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import {deepEqual} from 'fast-equals'; @@ -119,8 +120,8 @@ type MapTransactionItemToSelectedEntryParams = { /** Report name-value pairs collection, used for the change-report eligibility archived check */ reportNameValuePairs: OnyxCollection; - /** Derived outstanding reports per policy, used for the change-report eligibility check */ - outstandingReportsByPolicyID: OutstandingReportsByPolicyIDDerivedValue | undefined; + /** Outstanding reports per policy, used for the change-report eligibility check */ + outstandingReportsByPolicyID: OutstandingReportsByPolicyID | undefined; /** The current user's self-DM report, used as the parent for unreported (track) expenses */ selfDMReport: OnyxEntry; @@ -272,8 +273,8 @@ type PrepareTransactionsListParams = { /** Report name-value pairs collection, used for the change-report eligibility archived check */ reportNameValuePairs: OnyxCollection; - /** Derived outstanding reports per policy, used for the change-report eligibility check */ - outstandingReportsByPolicyID: OutstandingReportsByPolicyIDDerivedValue | undefined; + /** Outstanding reports per policy, used for the change-report eligibility check */ + outstandingReportsByPolicyID: OutstandingReportsByPolicyID | undefined; /** The current user's self-DM report, used as the parent for unreported (track) expenses */ selfDMReport: OnyxEntry; diff --git a/src/components/Table/TableBody.tsx b/src/components/Table/TableBody.tsx index 9a4db2f7aead..faa96b4da20f 100644 --- a/src/components/Table/TableBody.tsx +++ b/src/components/Table/TableBody.tsx @@ -164,6 +164,7 @@ function TableBodyList({contentContainerStyle, emptyMessage, onLayout, style, .. noResultsStateElement, tableListMetadata, isEmptyResult, + isDefaultViewEmpty, scrollWidth, tableWidth, } = useTableContext(); @@ -337,8 +338,10 @@ function TableBodyList({contentContainerStyle, emptyMessage, onLayout, style, .. ); - const emptyStateContent = - tableListMetadata.hasPageHeader && isEmptyResult ? (noResultsStateElement ?? EmptyResultComponent) : (emptyStateElement ?? renderListComponent(ListEmptyComponent)); + // When the default view hides every row (e.g. all workspaces are archived), no search or filter is active, + // so show the empty state rather than "No results". + const shouldShowNoResultsState = tableListMetadata.hasPageHeader && isEmptyResult && !isDefaultViewEmpty; + const emptyStateContent = shouldShowNoResultsState ? (noResultsStateElement ?? EmptyResultComponent) : (emptyStateElement ?? renderListComponent(ListEmptyComponent)); const footerElement = renderListComponent(ListFooterComponent); // Consumer footer flex growth is useful below normal rows, but inside the combined empty-state // footer it can expand over the page header. Preserve the remaining style while disabling growth. diff --git a/src/components/Table/TableEmptyStates/TableNoResultsState.tsx b/src/components/Table/TableEmptyStates/TableNoResultsState.tsx index 60a93ca4a2c6..30c49a66fe35 100644 --- a/src/components/Table/TableEmptyStates/TableNoResultsState.tsx +++ b/src/components/Table/TableEmptyStates/TableNoResultsState.tsx @@ -21,10 +21,11 @@ type TableNoResultsStateProps = Omit) => policy?.id; export default function useOutstandingReports(selectedReportID: string | undefined, selectedPolicyID: string | undefined, ownerAccountID: number | undefined, isEditing: boolean) { - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [personalPolicyID] = useOnyx(ONYXKEYS.PERSONAL_POLICY_ID); const [allPoliciesID] = useMappedPolicies(policyIdMapper); const [selectedReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${selectedReportID}`); diff --git a/src/hooks/useOutstandingReportsByPolicyID.ts b/src/hooks/useOutstandingReportsByPolicyID.ts new file mode 100644 index 000000000000..a74ccb12efa8 --- /dev/null +++ b/src/hooks/useOutstandingReportsByPolicyID.ts @@ -0,0 +1,29 @@ +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report} from '@src/types/onyx'; + +import type {OutstandingReportsByPolicyID} from '@selectors/Report'; +import type {OnyxCollection} from 'react-native-onyx'; + +import {outstandingReportsByPolicyIDSelector} from '@selectors/Report'; +// useOnyxState reads the store directly, so Search surfaces get the live reports instead of the snapshot @hooks/useOnyx swaps in +import {useOnyxState} from 'react-native-onyx'; + +const dependencies = [ONYXKEYS.COLLECTION.REPORT]; + +function selectOutstandingReportsByPolicyID(reports: unknown): OutstandingReportsByPolicyID { + // useOnyxState's state view types a collection key as one member, but at runtime it returns the whole collection + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + return outstandingReportsByPolicyIDSelector(reports as OnyxCollection); +} + +function useOutstandingReportsByPolicyID(): OutstandingReportsByPolicyID { + return useOnyxState((state) => selectOutstandingReportsByPolicyID(state[ONYXKEYS.COLLECTION.REPORT]), {dependencies}); +} + +function useOutstandingReportsForPolicy(policyID: string | undefined): OnyxCollection { + return useOnyxState((state) => selectOutstandingReportsByPolicyID(state[ONYXKEYS.COLLECTION.REPORT])[policyID ?? CONST.DEFAULT_NUMBER_ID], {dependencies}); +} + +export {useOutstandingReportsForPolicy}; +export default useOutstandingReportsByPolicyID; diff --git a/src/hooks/useSelectedTransactionsActions.ts b/src/hooks/useSelectedTransactionsActions.ts index 904ab27f5107..6f4f93a0fabb 100644 --- a/src/hooks/useSelectedTransactionsActions.ts +++ b/src/hooks/useSelectedTransactionsActions.ts @@ -55,6 +55,7 @@ import {useMemoizedLazyExpensifyIcons} from './useLazyAsset'; import useLocalize from './useLocalize'; import useNetworkWithOfflineStatus from './useNetworkWithOfflineStatus'; import useOnyx from './useOnyx'; +import useOutstandingReportsByPolicyID from './useOutstandingReportsByPolicyID'; import usePermissions from './usePermissions'; import {useAllPersonalDetails} from './usePersonalDetails'; import usePersonalPolicy from './usePersonalPolicy'; @@ -100,7 +101,7 @@ function useSelectedTransactionsActions({ const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const [cardList] = useOnyx(ONYXKEYS.CARD_LIST); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [integrationsExportTemplates] = useOnyx(ONYXKEYS.NVP_INTEGRATION_SERVER_EXPORT_TEMPLATES); const [csvExportLayouts] = useOnyx(ONYXKEYS.NVP_CSV_EXPORT_LAYOUTS); const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); diff --git a/src/hooks/useSelectionModeReportActions.ts b/src/hooks/useSelectionModeReportActions.ts index 0d10b99dce71..772e53fb59f9 100644 --- a/src/hooks/useSelectionModeReportActions.ts +++ b/src/hooks/useSelectionModeReportActions.ts @@ -31,6 +31,7 @@ import useLifecycleActions from './useLifecycleActions'; import useLocalize from './useLocalize'; import useNetwork from './useNetwork'; import useOnyx from './useOnyx'; +import useOutstandingReportsByPolicyID from './useOutstandingReportsByPolicyID'; import {usePersonalDetail} from './usePersonalDetails'; import useReportIsArchived from './useReportIsArchived'; import useSelectionModePayment from './useSelectionModePayment'; @@ -65,7 +66,7 @@ function useSelectionModeReportActions({ const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); - const [outstandingReportsByPolicyID] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = useOutstandingReportsByPolicyID(); const [moveExpenseReportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, { selector: createMoveExpenseReportNVPSelector(outstandingReportsByPolicyID, report?.reportID), }); diff --git a/src/libs/ReportSecondaryActionUtils.ts b/src/libs/ReportSecondaryActionUtils.ts index 8bc716e0f830..52b430878cd7 100644 --- a/src/libs/ReportSecondaryActionUtils.ts +++ b/src/libs/ReportSecondaryActionUtils.ts @@ -1,19 +1,8 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type { - BankAccountList, - CardList, - OutstandingReportsByPolicyIDDerivedValue, - Policy, - Report, - ReportAction, - ReportMetadata, - ReportNameValuePairs, - Rule, - Transaction, - TransactionViolation, -} from '@src/types/onyx'; +import type {BankAccountList, CardList, Policy, Report, ReportAction, ReportMetadata, ReportNameValuePairs, Rule, Transaction, TransactionViolation} from '@src/types/onyx'; +import type {OutstandingReportsByPolicyID} from '@selectors/Report'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; @@ -1031,7 +1020,7 @@ function getSecondaryReportActions({ reportActions?: ReportAction[]; reportMetadata?: OnyxEntry; policies?: OnyxCollection; - outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue; + outstandingReportsByPolicyID?: OutstandingReportsByPolicyID; canUseNewDotSplits?: boolean; isChatReportArchived?: boolean; parentReport?: OnyxEntry; @@ -1270,7 +1259,7 @@ function getSecondaryTransactionThreadActions({ originalTransaction: OnyxEntry; policy: OnyxEntry; transactionThreadReport?: OnyxEntry; - outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue; + outstandingReportsByPolicyID?: OutstandingReportsByPolicyID; reportNameValuePairs?: OnyxCollection; isChatReportArchived: boolean; grandParentReport?: OnyxEntry; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index badb8adcf0fb..48255af8d681 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -30,7 +30,6 @@ import type { GuideAccountIDsDerivedValue, IntroSelected, OnyxInputOrEntry, - OutstandingReportsByPolicyIDDerivedValue, PersonalDetails, PersonalDetailsList, Policy, @@ -78,6 +77,7 @@ import type {EmptyObject} from '@src/types/utils/EmptyObject'; import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; import type IconAsset from '@src/types/utils/IconAsset'; +import type {OutstandingReportsByPolicyID} from '@selectors/Report'; import type {Locale as DateFnsLocale} from 'date-fns'; import type {ColorValue} from 'react-native'; import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxInputValue, OnyxUpdate} from 'react-native-onyx'; @@ -6011,7 +6011,7 @@ function canEditFieldOfMoneyRequest({ fieldToEdit: EditRequestField; isDeleteAction?: boolean; isChatReportArchived?: boolean; - outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue; + outstandingReportsByPolicyID?: OutstandingReportsByPolicyID; transaction: OnyxEntry; report?: OnyxInputOrEntry; policy?: OnyxEntry; @@ -13069,7 +13069,7 @@ function getNewestOutstandingReportForUser( * Whether the member is the approver of any of the policy's reports that are waiting for their approval. * An approver assigned through "Change approver" is only stored in the report's `managerID`, so they are not covered by `isPolicyApprover`. * @param accountID - The accountID of the member to check - * @param outstandingReportsForPolicy - The policy's outstanding reports, from the OUTSTANDING_REPORTS_BY_POLICY_ID derived value + * @param outstandingReportsForPolicy - The policy's outstanding reports, from useOutstandingReportsForPolicy * @param privateIsArchivedMap - The archived state of every report, from usePrivateIsArchivedMap */ function isApproverOfOutstandingPolicyReports( diff --git a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts index 4ea4fabd9560..28add5b7a09d 100644 --- a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts +++ b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts @@ -9,7 +9,6 @@ import guideAccountIDsConfig from './configs/guideAccountIDs'; import loginToAccountIDMapConfig from './configs/loginToAccountIDMap'; import nonPersonalAndWorkspaceCardListConfig from './configs/nonPersonalAndWorkspaceCardList'; import oneOnOneChatReportIDsConfig from './configs/oneOnOneChatReportIDs'; -import outstandingReportsByPolicyIDConfig from './configs/outstandingReportsByPolicyID'; import personalAndWorkspaceCardListConfig from './configs/personalAndWorkspaceCardList'; import reportAttributesConfig from './configs/reportAttributes'; import reportTransactionsAndViolationsConfig from './configs/reportTransactionsAndViolations'; @@ -24,7 +23,6 @@ import visibleReportActionsConfig from './configs/visibleReportActions'; const ONYX_DERIVED_VALUES = { [ONYXKEYS.DERIVED.REPORT_ATTRIBUTES]: reportAttributesConfig, [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]: reportTransactionsAndViolationsConfig, - [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: outstandingReportsByPolicyIDConfig, [ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS]: visibleReportActionsConfig, [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: nonPersonalAndWorkspaceCardListConfig, [ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST]: personalAndWorkspaceCardListConfig, diff --git a/src/libs/actions/OnyxDerived/configs/outstandingReportsByPolicyID.ts b/src/libs/actions/OnyxDerived/configs/outstandingReportsByPolicyID.ts deleted file mode 100644 index 1f6db57a3013..000000000000 --- a/src/libs/actions/OnyxDerived/configs/outstandingReportsByPolicyID.ts +++ /dev/null @@ -1,48 +0,0 @@ -import {isExpenseReport} from '@libs/ReportUtils'; - -import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDerivedValueConfig'; - -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import type {OutstandingReportsByPolicyIDDerivedValue} from '@src/types/onyx'; - -import {shallowEqual} from 'fast-equals'; - -export default createOnyxDerivedValueConfig({ - key: ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID, - dependencies: [ONYXKEYS.COLLECTION.REPORT], - compute: ([reports], {currentValue}) => { - if (!reports) { - return {}; - } - const outstandingReportsByPolicyID: OutstandingReportsByPolicyIDDerivedValue = {}; - for (const reportID of Object.keys(reports)) { - const report = reports[reportID]; - if (!report) { - continue; - } - - // Get all reports, which are the ones that are: - // - Expense reports - // - Are either open or submitted - // - Are not pending delete - // - Belong to a workspace - // This condition is similar to getOutstandingReportsForUser function - if ( - isExpenseReport(report) && - report.policyID && - report?.pendingFields?.preview !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && - (report.stateNum ?? CONST.REPORT.STATE_NUM.OPEN) <= CONST.REPORT.STATE_NUM.SUBMITTED - ) { - const reportsForPolicy = outstandingReportsByPolicyID[report.policyID] ?? {}; - reportsForPolicy[reportID] = report; - outstandingReportsByPolicyID[report.policyID] = reportsForPolicy; - } - } - - // Consumers of this key compare by reference, so handing back `currentValue` when nothing moved keeps them - // from re-rendering, and lets the engine skip the write entirely. Every `REPORT` write recomputes this, and - // for an account with no outstanding reports the result is a fresh empty object every time. - return currentValue && shallowEqual(currentValue, outstandingReportsByPolicyID) ? currentValue : outstandingReportsByPolicyID; - }, -}); diff --git a/src/pages/workspace/WorkspaceMembersPage.tsx b/src/pages/workspace/WorkspaceMembersPage.tsx index 503d07628eb1..8a0a7e587f88 100644 --- a/src/pages/workspace/WorkspaceMembersPage.tsx +++ b/src/pages/workspace/WorkspaceMembersPage.tsx @@ -21,6 +21,7 @@ import useMergeSyncResultsPage from '@hooks/useMergeSyncResultsPage'; import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import {useOutstandingReportsForPolicy} from '@hooks/useOutstandingReportsByPolicyID'; import {usePersonalDetailsByLogins} from '@hooks/usePersonalDetailByLogin'; import usePrevious from '@hooks/usePrevious'; import usePrivateIsArchivedMap from '@hooks/usePrivateIsArchivedMap'; @@ -97,7 +98,6 @@ import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; import type {ValueOf} from 'type-fest'; import {useIsFocused} from '@react-navigation/native'; -import {createOutstandingReportsForPolicySelector} from '@selectors/Report'; import React, {useCallback, useEffect, useEffectEvent, useMemo, useRef, useState} from 'react'; import {View} from 'react-native'; @@ -164,8 +164,7 @@ function WorkspaceMembersPage({personalDetails, route, policy}: WorkspaceMembers const isFocused = useIsFocused(); const policyID = route.params.policyID; const [connectionSyncProgress] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CONNECTION_SYNC_PROGRESS}${policyID}`); - const outstandingReportsForPolicySelector = useMemo(() => createOutstandingReportsForPolicySelector(policyID), [policyID]); - const [outstandingReportsForPolicy] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID, {selector: outstandingReportsForPolicySelector}); + const outstandingReportsForPolicy = useOutstandingReportsForPolicy(policyID); const privateIsArchivedMap = usePrivateIsArchivedMap(); const [invitedEmailsToAccountIDsDraft] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_INVITE_MEMBERS_DRAFT}${policyID}`); diff --git a/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx b/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx index 8a88a2ef386e..3698b348d633 100644 --- a/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx +++ b/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx @@ -22,6 +22,7 @@ import useExpensifyCardFeeds from '@hooks/useExpensifyCardFeeds'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import {useOutstandingReportsForPolicy} from '@hooks/useOutstandingReportsByPolicyID'; import usePermissions from '@hooks/usePermissions'; import usePersonalDetailByLogin from '@hooks/usePersonalDetailByLogin'; import usePrevious from '@hooks/usePrevious'; @@ -78,7 +79,6 @@ import type {CompanyCardFeed, CompanyCardFeedWithDomainID, Card as MemberCard, P import type {OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; -import {createOutstandingReportsForPolicySelector} from '@selectors/Report'; import {Str} from 'expensify-common'; import React, {useEffect} from 'react'; import {View} from 'react-native'; @@ -130,7 +130,7 @@ function WorkspaceMemberDetailsPage({personalDetails, policy, route}: WorkspaceM const [cardList] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}`); const [customCardNames] = useOnyx(ONYXKEYS.NVP_EXPENSIFY_COMPANY_CARDS_CUSTOM_NAMES); const [fundList] = useOnyx(ONYXKEYS.FUND_LIST); - const [outstandingReportsForPolicy] = useOnyx(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID, {selector: createOutstandingReportsForPolicySelector(policyID)}); + const outstandingReportsForPolicy = useOutstandingReportsForPolicy(policyID); const privateIsArchivedMap = usePrivateIsArchivedMap(); const expensifyCardSettings = useExpensifyCardFeeds(policyID); const {showConfirmModal} = useConfirmModal(); diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index 437f117c8ee3..ba5a09ed46d1 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -6,6 +6,7 @@ import { isArchivedReport, isChatRoom, isClosedReport, + isExpenseReport, isOpenExpenseReport, isPolicyExpenseChat, isThread, @@ -13,7 +14,7 @@ import { import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {OutstandingReportsByPolicyIDDerivedValue, PersonalDetailsList, Report, ReportActions, ReportNameValuePairs, Transaction} from '@src/types/onyx'; +import type {PersonalDetailsList, Report, ReportActions, ReportNameValuePairs, Transaction} from '@src/types/onyx'; import mapOnyxCollectionItems from '@src/utils/mapOnyxCollectionItems'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; @@ -23,6 +24,8 @@ import {getLastClosedReportAction} from './ReportAction'; type OpenExpenseReportIDMap = Record; +type OutstandingReportsByPolicyID = Record>; + function getArchiveReason(reportActions: OnyxEntry): ValueOf | undefined { const lastClosedReportAction = getLastClosedReportAction(reportActions); @@ -195,17 +198,77 @@ const policyChatRoomsSelector = return list; }; -/** Selects the outstanding reports that belong to the given policy. */ -const createOutstandingReportsForPolicySelector = - (policyID: string | undefined) => - (outstandingReportsByPolicyID: OnyxEntry): OnyxCollection => - outstandingReportsByPolicyID?.[policyID ?? CONST.DEFAULT_NUMBER_ID]; +const EMPTY_OUTSTANDING_REPORTS_BY_POLICY_ID: OutstandingReportsByPolicyID = {}; +const outstandingReportsByPolicyIDCache = new WeakMap>, OutstandingReportsByPolicyID>(); +let lastOutstandingReportsByPolicyID: OutstandingReportsByPolicyID = EMPTY_OUTSTANDING_REPORTS_BY_POLICY_ID; + +function hasSameReports(reportsForPolicy: NonNullable>, previousReportsForPolicy: OnyxCollection): boolean { + if (!previousReportsForPolicy) { + return false; + } + const reportKeys = Object.keys(reportsForPolicy); + if (reportKeys.length !== Object.keys(previousReportsForPolicy).length) { + return false; + } + return reportKeys.every((reportKey) => reportsForPolicy[reportKey] === previousReportsForPolicy[reportKey]); +} + +/** + * Groups the open or submitted expense reports by policy, with the same filter as getOutstandingReportsForUser. + * Cached on the collection reference so every mounted consumer shares one build per write. A policy whose reports are + * all unchanged keeps its previous object, and so does the whole map when no policy changed. + */ +function outstandingReportsByPolicyIDSelector(reports: OnyxCollection): OutstandingReportsByPolicyID { + if (!reports) { + return EMPTY_OUTSTANDING_REPORTS_BY_POLICY_ID; + } + + const cachedOutstandingReportsByPolicyID = outstandingReportsByPolicyIDCache.get(reports); + if (cachedOutstandingReportsByPolicyID) { + return cachedOutstandingReportsByPolicyID; + } + + const outstandingReportsByPolicyID: OutstandingReportsByPolicyID = {}; + for (const reportKey of Object.keys(reports)) { + const report = reports[reportKey]; + if ( + !report || + !isExpenseReport(report) || + !report.policyID || + report.pendingFields?.preview === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || + (report.stateNum ?? CONST.REPORT.STATE_NUM.OPEN) > CONST.REPORT.STATE_NUM.SUBMITTED + ) { + continue; + } + const reportsForPolicy = outstandingReportsByPolicyID[report.policyID] ?? {}; + reportsForPolicy[reportKey] = report; + outstandingReportsByPolicyID[report.policyID] = reportsForPolicy; + } + + const previousOutstandingReportsByPolicyID = lastOutstandingReportsByPolicyID; + const policyIDs = Object.keys(outstandingReportsByPolicyID); + let hasChangedPolicy = policyIDs.length !== Object.keys(previousOutstandingReportsByPolicyID).length; + for (const policyID of policyIDs) { + const reportsForPolicy = outstandingReportsByPolicyID[policyID]; + const previousReportsForPolicy = previousOutstandingReportsByPolicyID[policyID]; + if (reportsForPolicy && hasSameReports(reportsForPolicy, previousReportsForPolicy)) { + outstandingReportsByPolicyID[policyID] = previousReportsForPolicy; + } else { + hasChangedPolicy = true; + } + } + + const result = hasChangedPolicy ? outstandingReportsByPolicyID : previousOutstandingReportsByPolicyID; + outstandingReportsByPolicyIDCache.set(reports, result); + lastOutstandingReportsByPolicyID = result; + return result; +} /** * Selects archived report NVPs for the current report and possible "Move expense" destination reports. * This limits updates to data used to determine whether each destination report is archived. */ -const createMoveExpenseReportNVPSelector = (outstandingReportsByPolicyID: OnyxEntry, currentReportID: string | undefined) => { +const createMoveExpenseReportNVPSelector = (outstandingReportsByPolicyID: OnyxEntry, currentReportID: string | undefined) => { const moveExpenseReportIDs = new Set(); if (currentReportID) { moveExpenseReportIDs.add(currentReportID); @@ -433,7 +496,7 @@ export { reportPolicyFieldsSelector, roomAvatarFieldsSelector, createMoveExpenseReportNVPSelector, - createOutstandingReportsForPolicySelector, + outstandingReportsByPolicyIDSelector, openExpenseReportIDsSelector, getStableReportSelector, isDraftReportSelector, @@ -441,4 +504,4 @@ export { reportsByIDsSelector, }; -export type {ReportAvatarFields, RoomAvatarFields, StableReport}; +export type {OutstandingReportsByPolicyID, ReportAvatarFields, RoomAvatarFields, StableReport}; diff --git a/src/types/onyx/DerivedValues.ts b/src/types/onyx/DerivedValues.ts index 3f5e2a136157..3b4205786763 100644 --- a/src/types/onyx/DerivedValues.ts +++ b/src/types/onyx/DerivedValues.ts @@ -1,13 +1,11 @@ import type CONST from '@src/CONST'; -import type {OnyxCollection} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import type {Card, ReportAction} from '.'; import type {CardList} from './Card'; import type {CardFeedWithDomainID} from './CardFeeds'; import type {Errors} from './OnyxCommon'; -import type Report from './Report'; import type Transaction from './Transaction'; import type TransactionViolations from './TransactionViolation'; @@ -78,11 +76,6 @@ type ReportTransactionsAndViolations = { */ type ReportTransactionsAndViolationsDerivedValue = Record; -/** - * The derived value for report outstanding reports. - */ -type OutstandingReportsByPolicyIDDerivedValue = Record>; - /** * The derived value for visible report actions. */ @@ -249,7 +242,6 @@ export type { ReportAttributesDerivedValue, ReportTransactionsAndViolationsDerivedValue, ReportTransactionsAndViolations, - OutstandingReportsByPolicyIDDerivedValue, VisibleReportActionsDerivedValue, SortedReportActionsDerivedValue, NonPersonalAndWorkspaceCardListDerivedValue, diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index a86e9d85adb5..44507a989561 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -65,7 +65,6 @@ import type { LoginToAccountIDMapDerivedValue, NonPersonalAndWorkspaceCardListDerivedValue, OneOnOneChatReportIDsDerivedValue, - OutstandingReportsByPolicyIDDerivedValue, PersonalAndWorkspaceCardListDerivedValue, ReportAttributesDerivedValue, ReportTransactionsAndViolationsDerivedValue, @@ -495,7 +494,6 @@ export type { ReportAttributesDerivedValue, LastSearchParams, ReportTransactionsAndViolationsDerivedValue, - OutstandingReportsByPolicyIDDerivedValue, VisibleReportActionsDerivedValue, SortedReportActionsDerivedValue, NonPersonalAndWorkspaceCardListDerivedValue, diff --git a/tests/perf-test/OutstandingReportsByPolicyID.perf-test.tsx b/tests/perf-test/OutstandingReportsByPolicyID.perf-test.tsx new file mode 100644 index 000000000000..0ceab0dae7f0 --- /dev/null +++ b/tests/perf-test/OutstandingReportsByPolicyID.perf-test.tsx @@ -0,0 +1,210 @@ +import {render, screen} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import Text from '@components/Text'; + +import useIsApproverOfOutstandingPolicyReports from '@hooks/useIsApproverOfOutstandingPolicyReports'; +import useOutstandingReports from '@hooks/useOutstandingReports'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report} from '@src/types/onyx'; + +import React from 'react'; +import {View} from 'react-native'; +import Onyx from 'react-native-onyx'; +import {measureAsyncFunction, measureRenders} from 'reassure'; + +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +const CONSUMER_COUNT = 10; +const WRITES_PER_SCENARIO = 10; +const REPORT_COUNT = 5000; +const POLICY_COUNT = 50; +const CURRENT_USER_ACCOUNT_ID = 1; +const APPROVER_ACCOUNT_ID = 2; +const POLICY_ID = 'policy0'; + +// Report IDs by role in the generated collection: even IDs are chats, odd IDs are expense reports spread over the policies in turn +const CHAT_REPORT_ID = 2; +const OTHER_POLICY_OUTSTANDING_REPORT_ID = 5; +const OUTSTANDING_REPORT_ID = 101; + +function createReport(reportID: number): Report { + if (reportID % 2 === 0) { + return { + reportID: String(reportID), + type: CONST.REPORT.TYPE.CHAT, + chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, + policyID: `policy${Math.floor(reportID / 2) % POLICY_COUNT}`, + reportName: `Chat ${reportID}`, + }; + } + const isApproved = reportID % 3 === 0; + return { + reportID: String(reportID), + type: CONST.REPORT.TYPE.EXPENSE, + policyID: `policy${Math.floor(reportID / 2) % POLICY_COUNT}`, + ownerAccountID: CURRENT_USER_ACCOUNT_ID, + managerID: APPROVER_ACCOUNT_ID, + stateNum: isApproved ? CONST.REPORT.STATE_NUM.APPROVED : CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: isApproved ? CONST.REPORT.STATUS_NUM.APPROVED : CONST.REPORT.STATUS_NUM.SUBMITTED, + reportName: `Expense ${reportID}`, + }; +} + +const reports = Object.fromEntries(Array.from({length: REPORT_COUNT}, (value, index) => [`${ONYXKEYS.COLLECTION.REPORT}${index + 1}`, createReport(index + 1)])); + +/** Passed as the reassure wrapper so the providers sit outside the profiler and render counts are the consumers' own */ +function Providers({children}: {children: React.ReactNode}) { + return {children}; +} + +/** Reads every policy's outstanding reports, like the move-expense report picker and the expense header actions */ +function MoveExpenseConsumer() { + const outstandingReports = useOutstandingReports(undefined, POLICY_ID, CURRENT_USER_ACCOUNT_ID, false); + return {outstandingReports.length}; +} + +/** Reads one policy's outstanding reports, like the workspace overview and leave-workspace checks */ +function ApproverConsumer() { + const isApprover = useIsApproverOfOutstandingPolicyReports(POLICY_ID); + return {isApprover ? 'approver' : 'member'}; +} + +/** Neither consumer reads the report attributes, so their re-renders isolate outstanding reports churn */ +function AllConsumers() { + return ( + + {Array.from({length: CONSUMER_COUNT}, (value, index) => ( + + + + + ))} + + ); +} + +function SinglePolicyConsumers() { + return ( + + {Array.from({length: CONSUMER_COUNT}, (value, index) => ( + + ))} + + ); +} + +async function seed() { + await Onyx.multiSet({ + ...reports, + [ONYXKEYS.SESSION]: {accountID: APPROVER_ACCOUNT_ID, email: 'approver@test.com'}, + }); + await waitForBatchedUpdates(); +} + +async function renameChat(label: string) { + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, {reportName: `Chat ${label}-${index}`}); + await waitForBatchedUpdates(); + } +} + +describe('Outstanding reports consumers on report writes', () => { + beforeAll(async () => { + Onyx.init({keys: ONYXKEYS}); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + require('@userActions/OnyxDerived').default(); + await waitForBatchedUpdates(); + }); + + afterEach(async () => { + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + + test('[OutstandingReportsByPolicyID] should re-render consumers when a chat is renamed among 5000 reports', async () => { + // Given 10 consumers of every policy and 10 of one policy over 5000 reports + await seed(); + + // Reassure runs the scenario several times against one seeded Onyx, so every run writes a name that doesn't exist yet + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('ApproverConsumer'); + + // When a chat is renamed, which leaves every policy's outstanding reports unchanged + await renameChat(`renders ${run}`); + run++; + }; + + // Then reassure measures how many re-renders the unrelated writes cause + await measureRenders(, {scenario, wrapper: Providers}); + }); + + test('[OutstandingReportsByPolicyID] should re-render single policy consumers when another policy outstanding report changes', async () => { + // Given 10 consumers of one policy over 5000 reports + await seed(); + + let run = 0; + const scenario = async () => { + await screen.findAllByTestId('ApproverConsumer'); + + // When an outstanding report of another policy changes, which leaves this policy's outstanding reports unchanged + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${OTHER_POLICY_OUTSTANDING_REPORT_ID}`, {total: run * WRITES_PER_SCENARIO + index + 1}); + await waitForBatchedUpdates(); + } + run++; + }; + + // Then reassure measures how many re-renders the other policy's writes cause + await measureRenders(, {scenario, wrapper: Providers}); + }); + + test('[OutstandingReportsByPolicyID] should re-render consumers when a report of their policy is approved and reopened', async () => { + // Given 10 consumers of every policy and 10 of one policy over 5000 reports + await seed(); + + let isApproved = false; + const scenario = async () => { + await screen.findAllByTestId('ApproverConsumer'); + + // When an outstanding report of the consumers' policy is approved and reopened in turn, so it leaves the outstanding reports and comes back + for (let index = 0; index < WRITES_PER_SCENARIO; index++) { + isApproved = !isApproved; + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${OUTSTANDING_REPORT_ID}`, { + stateNum: isApproved ? CONST.REPORT.STATE_NUM.APPROVED : CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: isApproved ? CONST.REPORT.STATUS_NUM.APPROVED : CONST.REPORT.STATUS_NUM.SUBMITTED, + }); + await waitForBatchedUpdates(); + } + }; + + // Then reassure measures the cost of a real change, which both versions have to pay + await measureRenders(, {scenario, wrapper: Providers}); + }); + + test('[OutstandingReportsByPolicyID] should process chat renames among 5000 reports', async () => { + // Given every consumer mounted over 5000 reports + await seed(); + render( + + + , + ); + await screen.findAllByTestId('ApproverConsumer'); + + // When a chat is renamed repeatedly + let run = 0; + const writeRenames = async () => { + await renameChat(`timed ${run}`); + run++; + }; + + // Then reassure times the whole write loop, including work done outside React renders such as derived computes and their writes + await measureAsyncFunction(writeRenames); + }); +}); diff --git a/tests/ui/TableTest.tsx b/tests/ui/TableTest.tsx index 29825bdc490c..4570ad085b50 100644 --- a/tests/ui/TableTest.tsx +++ b/tests/ui/TableTest.tsx @@ -2621,6 +2621,44 @@ describe('Table', () => { expect(screen.queryByTestId('row-2')).toBeNull(); expect(screen.getByTestId('generic-empty-state')).toBeTruthy(); }); + + it('renders the empty state instead of "No results" when a page-header table hides every row by default', () => { + // Given a page-header table (like the Workspaces list) whose default filter hides every row, with both + // a no-results state and an empty state declared + const props = createDefaultProps(); + const data: TestItem[] = [ + {keyForList: '1', id: '1', name: 'Archived A', category: 'archived', value: 1}, + {keyForList: '2', id: '2', name: 'Archived B', category: 'archived', value: 2}, + ]; + + // When the table renders with no search or filter selected + render( + + data={data} + columns={props.columns} + renderItem={props.renderItem} + keyExtractor={props.keyExtractor} + filters={statusFilterConfig} + isItemInFilter={isItemInStatusFilter} + > + + Page header + + + + + + , + ); + + // Then the empty state shows inside the list with the page header still visible, because the user did + // not search or filter, so "No results found" would be misleading + expect(screen.getByTestId('flash-list')).toBeTruthy(); + expect(screen.getByTestId('table-header-component')).toBeTruthy(); + expect(screen.getAllByTestId('generic-empty-state')).toHaveLength(1); + expect(screen.getByText('No workspaces')).toBeTruthy(); + expect(screen.queryByText('common.noResultsFound')).toBeNull(); + }); }); describe('immediate filter', () => { diff --git a/tests/unit/OnyxDerivedTest.tsx b/tests/unit/OnyxDerivedTest.tsx index 629837bb5080..aba7caf09f6b 100644 --- a/tests/unit/OnyxDerivedTest.tsx +++ b/tests/unit/OnyxDerivedTest.tsx @@ -47,7 +47,7 @@ const PERSONAL_DETAILS: PersonalDetailsList = { const KEYS_READ_WITHOUT_SELECTOR = [ONYXKEYS.DERIVED.GUIDE_ACCOUNT_IDS, ONYXKEYS.DERIVED.LOGIN_TO_ACCOUNT_ID_MAP] as const; -function renderHookWithoutSelector | typeof ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID>(key: TKey) { +function renderHookWithoutSelector>(key: TKey) { let renderCount = 0; const hook = renderHook(() => { renderCount++; @@ -1225,69 +1225,4 @@ describe('OnyxDerived', () => { expect(hook.result.current[0]?.['new.member@example.com']).toBe(NEW_MEMBER_ACCOUNT_ID); }); }); - - describe('consumers without a selector on REPORT writes', () => { - const CHAT_REPORT_ID = '100'; - const EXPENSE_REPORT_ID = '200'; - const POLICY_ID = 'policy1'; - - beforeAll(async () => { - await IntlStore.load(CONST.LOCALES.EN); - }); - - beforeEach(async () => { - await act(async () => { - await Onyx.set(ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING, false); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, { - ...createRandomReport(Number(CHAT_REPORT_ID)), - type: CONST.REPORT.TYPE.CHAT, - policyID: undefined, - }); - }); - await waitForBatchedUpdatesWithAct(); - }); - - it('should keep the outstanding reports reference when a report with no outstanding expenses changes', async () => { - // Given a component that reads the derived value without a selector, the way 10 App sites do, on an - // account with no outstanding expense reports so every compute produces an equal but fresh empty object - const {hook, getRenderCount} = renderHookWithoutSelector(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); - await waitForBatchedUpdatesWithAct(); - const [valueBefore] = hook.result.current; - const rendersBefore = getRenderCount(); - - // When chat reports are written, which the derived value does not list - await act(async () => { - for (let i = 0; i < 5; i++) { - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`, {lastMessageText: `message ${i}`}); - } - }); - await waitForBatchedUpdatesWithAct(); - - // Then the engine's fresh but equal result must not reach the consumer as a new reference or a re-render - expect(hook.result.current[0]).toBe(valueBefore); - expect(getRenderCount()).toBe(rendersBefore); - }); - - it('should return new outstanding reports when an outstanding expense report arrives', async () => { - // Given a consumer of the outstanding reports - const {hook} = renderHookWithoutSelector(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); - await waitForBatchedUpdatesWithAct(); - const [valueBefore] = hook.result.current; - - // When an open expense report on a workspace arrives - await act(async () => { - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_REPORT_ID}`, { - reportID: EXPENSE_REPORT_ID, - type: CONST.REPORT.TYPE.EXPENSE, - policyID: POLICY_ID, - stateNum: CONST.REPORT.STATE_NUM.OPEN, - }); - }); - await waitForBatchedUpdatesWithAct(); - - // Then the consumer sees the change, so the stability check above is not passing on a frozen value - expect(hook.result.current[0]).not.toBe(valueBefore); - expect(hook.result.current[0]?.[POLICY_ID]?.[`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_REPORT_ID}`]).toBeTruthy(); - }); - }); }); diff --git a/tests/unit/ReportSelectorTest.ts b/tests/unit/ReportSelectorTest.ts index 004ff62647d2..2fb76988216f 100644 --- a/tests/unit/ReportSelectorTest.ts +++ b/tests/unit/ReportSelectorTest.ts @@ -1,6 +1,6 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import {createMoveExpenseReportNVPSelector, getReportHasParentAccess, getStableReportSelector, policyChatRoomsSelector} from '@src/selectors/Report'; +import {createMoveExpenseReportNVPSelector, getReportHasParentAccess, getStableReportSelector, outstandingReportsByPolicyIDSelector, policyChatRoomsSelector} from '@src/selectors/Report'; import type {Report} from '@src/types/onyx'; describe('policyChatRoomsSelector', () => { @@ -128,6 +128,130 @@ describe('createMoveExpenseReportNVPSelector', () => { }); }); +describe('outstandingReportsByPolicyIDSelector', () => { + const REPORT_KEY_PREFIX = ONYXKEYS.COLLECTION.REPORT; + const policyID = 'policy1'; + const otherPolicyID = 'policy2'; + + const openReport = {reportID: '1', policyID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.OPEN} as Report; + const submittedReport = {reportID: '2', policyID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.SUBMITTED} as Report; + const reportWithoutState = {reportID: '3', policyID, type: CONST.REPORT.TYPE.EXPENSE} as Report; + const otherPolicyReport = {reportID: '4', policyID: otherPolicyID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.OPEN} as Report; + const approvedReport = {reportID: '5', policyID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.APPROVED} as Report; + const deletingReport = { + reportID: '6', + policyID, + type: CONST.REPORT.TYPE.EXPENSE, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + pendingFields: {preview: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}, + } as Report; + const iouReport = {reportID: '7', policyID, type: CONST.REPORT.TYPE.IOU, stateNum: CONST.REPORT.STATE_NUM.OPEN} as Report; + const reportWithoutPolicy = {reportID: '8', type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.OPEN} as Report; + const chatReport = {reportID: '9', policyID, chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, reportName: 'Before'} as Report; + + const buildReports = (overrides: Record = {}) => ({ + [`${REPORT_KEY_PREFIX}1`]: openReport, + [`${REPORT_KEY_PREFIX}2`]: submittedReport, + [`${REPORT_KEY_PREFIX}3`]: reportWithoutState, + [`${REPORT_KEY_PREFIX}4`]: otherPolicyReport, + [`${REPORT_KEY_PREFIX}5`]: approvedReport, + [`${REPORT_KEY_PREFIX}6`]: deletingReport, + [`${REPORT_KEY_PREFIX}7`]: iouReport, + [`${REPORT_KEY_PREFIX}8`]: reportWithoutPolicy, + [`${REPORT_KEY_PREFIX}9`]: chatReport, + ...overrides, + }); + + it('should return an empty map when there are no reports', () => { + // Given no report collection, or an empty one + // When the outstanding reports are selected + // Then no policy has outstanding reports + expect(outstandingReportsByPolicyIDSelector(undefined)).toEqual({}); + expect(outstandingReportsByPolicyIDSelector({})).toEqual({}); + }); + + it('should group open and submitted expense reports by policy with the same filter as getOutstandingReportsForUser', () => { + // Given expense reports in every state next to reports that are not outstanding for other reasons + const reports = buildReports(); + + // When the outstanding reports are selected + // Then only open or submitted expense reports with a policy that are not being deleted are kept, keyed by their collection key under their policy + expect(outstandingReportsByPolicyIDSelector(reports)).toEqual({ + [policyID]: { + [`${REPORT_KEY_PREFIX}1`]: openReport, + [`${REPORT_KEY_PREFIX}2`]: submittedReport, + [`${REPORT_KEY_PREFIX}3`]: reportWithoutState, + }, + [otherPolicyID]: {[`${REPORT_KEY_PREFIX}4`]: otherPolicyReport}, + }); + }); + + it('should return the same map for the same report collection', () => { + // Given one report collection + const reports = buildReports(); + + // When the outstanding reports are selected twice, as two mounted consumers do after the same write + // Then both get the same object, so the map is built once per collection + expect(outstandingReportsByPolicyIDSelector(reports)).toBe(outstandingReportsByPolicyIDSelector(reports)); + }); + + it('should return the previous map when a write leaves every outstanding report unchanged', () => { + // Given the map built from a report collection + const before = outstandingReportsByPolicyIDSelector(buildReports()); + + // When a new collection only renames a chat and replaces the approved report + const after = outstandingReportsByPolicyIDSelector( + buildReports({ + [`${REPORT_KEY_PREFIX}9`]: {...chatReport, reportName: 'After'}, + [`${REPORT_KEY_PREFIX}5`]: {...approvedReport}, + }), + ); + + // Then consumers get the same object back, so they skip the re-render without a deep compare + expect(after).toBe(before); + }); + + it('should keep the reports of a policy whose outstanding reports did not change', () => { + // Given the map built from a report collection + const before = outstandingReportsByPolicyIDSelector(buildReports()); + + // When an outstanding report of the other policy changes + const changedOtherPolicyReport = {...otherPolicyReport, total: 100}; + const after = outstandingReportsByPolicyIDSelector(buildReports({[`${REPORT_KEY_PREFIX}4`]: changedOtherPolicyReport})); + + // Then only that policy gets new reports, so a consumer that reads one policy keeps its reference + expect(after).not.toBe(before); + expect(after[policyID]).toBe(before[policyID]); + expect(after[otherPolicyID]).toEqual({[`${REPORT_KEY_PREFIX}4`]: changedOtherPolicyReport}); + }); + + it('should drop a report from its policy once it is approved', () => { + // Given the map built from a report collection + const before = outstandingReportsByPolicyIDSelector(buildReports()); + + // When the submitted report is approved + const after = outstandingReportsByPolicyIDSelector(buildReports({[`${REPORT_KEY_PREFIX}2`]: {...submittedReport, stateNum: CONST.REPORT.STATE_NUM.APPROVED}})); + + // Then its policy loses it and the other policy keeps its reports + expect(after[policyID]).toEqual({ + [`${REPORT_KEY_PREFIX}1`]: openReport, + [`${REPORT_KEY_PREFIX}3`]: reportWithoutState, + }); + expect(after[otherPolicyID]).toBe(before[otherPolicyID]); + }); + + it('should remove a policy whose last outstanding report is deleted', () => { + // Given the map built from a report collection + outstandingReportsByPolicyIDSelector(buildReports()); + + // When the only outstanding report of the other policy is removed + const after = outstandingReportsByPolicyIDSelector(buildReports({[`${REPORT_KEY_PREFIX}4`]: undefined})); + + // Then that policy is gone from the map + expect(after).not.toHaveProperty(otherPolicyID); + }); +}); + describe('getStableReportSelector', () => { const {READ, WRITE, SHARE} = CONST.REPORT.PERMISSIONS; diff --git a/tests/unit/canEditFieldOfMoneyRequestTest.ts b/tests/unit/canEditFieldOfMoneyRequestTest.ts index eb187627db16..7fd74d119bcc 100644 --- a/tests/unit/canEditFieldOfMoneyRequestTest.ts +++ b/tests/unit/canEditFieldOfMoneyRequestTest.ts @@ -8,13 +8,14 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {Policy, Report, ReportAction} from '@src/types/onyx'; import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; +import {outstandingReportsByPolicyIDSelector} from '@selectors/Report'; import Onyx from 'react-native-onyx'; -import OnyxUtils from 'react-native-onyx/dist/OnyxUtils'; import createRandomPolicy from '../utils/collections/policies'; import createRandomReportAction from '../utils/collections/reportActions'; import {createExpenseReport, createInvoiceReport} from '../utils/collections/reports'; import createRandomTransaction from '../utils/collections/transaction'; +import getOnyxValue from '../utils/getOnyxValue'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; const currentUserAccountID = 5; @@ -108,7 +109,7 @@ describe('canEditFieldOfMoneyRequest', () => { }); it('should return false for invoice report action if it is not outstanding report', async () => { - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); const canEditReportField = canEditFieldOfMoneyRequest({ rules: undefined, @@ -124,7 +125,7 @@ describe('canEditFieldOfMoneyRequest', () => { it('should return true for invoice report action when there are outstanding reports', async () => { await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${IOUReportID}`, outstandingExpenseReport); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); const canEditReportField = canEditFieldOfMoneyRequest({ rules: undefined, @@ -320,7 +321,7 @@ describe('canEditFieldOfMoneyRequest', () => { }, }); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); // When the submitter tries to move an expense between reports const canEditReportField = canEditFieldOfMoneyRequest({ @@ -348,7 +349,7 @@ describe('canEditFieldOfMoneyRequest', () => { }, }); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); const canEditReportField = canEditFieldOfMoneyRequest({ rules: undefined, @@ -379,7 +380,7 @@ describe('canEditFieldOfMoneyRequest', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_1_ID}`, outstandingExpenseReport1); await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_2_ID}`, outstandingExpenseReport2); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); // When a user tries to move an expense between reports const canEditReportField = canEditFieldOfMoneyRequest({ @@ -414,7 +415,7 @@ describe('canEditFieldOfMoneyRequest', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_1_ID}`, approvedReport1); await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_2_ID}`, reimbursedReport2); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); // When trying to move an expense between reports const canEditReportField = canEditFieldOfMoneyRequest({ @@ -436,7 +437,7 @@ describe('canEditFieldOfMoneyRequest', () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_1_ID}`, outstandingExpenseReport1); await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${EXPENSE_OUTSTANDING_REPORT_2_ID}`, outstandingExpenseReport2); await waitForBatchedUpdates(); - const outstandingReportsByPolicyID = await OnyxUtils.get(ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID); + const outstandingReportsByPolicyID = outstandingReportsByPolicyIDSelector(await getOnyxValue(ONYXKEYS.COLLECTION.REPORT)); // When the submitter tries to move an expense between reports const canEditReportField = canEditFieldOfMoneyRequest({ diff --git a/tests/unit/hooks/useOutstandingReportsByPolicyIDTest.tsx b/tests/unit/hooks/useOutstandingReportsByPolicyIDTest.tsx new file mode 100644 index 000000000000..0e16dceea01b --- /dev/null +++ b/tests/unit/hooks/useOutstandingReportsByPolicyIDTest.tsx @@ -0,0 +1,167 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import useOutstandingReportsByPolicyID, {useOutstandingReportsForPolicy} from '@hooks/useOutstandingReportsByPolicyID'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report} from '@src/types/onyx'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +const POLICY_ID = 'policy1'; +const OTHER_POLICY_ID = 'policy2'; +const OPEN_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}1` as const; +const OTHER_POLICY_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}2` as const; +const CHAT_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}3` as const; +const NEW_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}4` as const; + +const openReport: Report = {reportID: '1', policyID: POLICY_ID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.OPEN}; +const otherPolicyReport: Report = {reportID: '2', policyID: OTHER_POLICY_ID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.OPEN}; +const chatReport: Report = {reportID: '3', policyID: POLICY_ID, chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM, reportName: 'Before'}; + +async function seedReports() { + await act(async () => { + await Onyx.multiSet({ + [OPEN_REPORT_KEY]: openReport, + [OTHER_POLICY_REPORT_KEY]: otherPolicyReport, + [CHAT_REPORT_KEY]: chatReport, + }); + }); +} + +describe('useOutstandingReportsByPolicyID', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + it('should follow writes to the reports', async () => { + // Given an open expense report in each of two policies + await seedReports(); + const {result} = renderHook(() => useOutstandingReportsByPolicyID()); + await waitForBatchedUpdatesWithAct(); + expect(Object.keys(result.current[POLICY_ID] ?? {})).toEqual([OPEN_REPORT_KEY]); + + // When another open expense report arrives in the first policy + await act(async () => { + await Onyx.set(NEW_REPORT_KEY, {reportID: '4', policyID: POLICY_ID, type: CONST.REPORT.TYPE.EXPENSE, stateNum: CONST.REPORT.STATE_NUM.SUBMITTED}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the hook lists it, since it reads the reports live instead of a stored derived value + expect(Object.keys(result.current[POLICY_ID] ?? {}).sort()).toEqual([OPEN_REPORT_KEY, NEW_REPORT_KEY]); + }); + + it('should not re-render when a write leaves every outstanding report unchanged', async () => { + // Given open expense reports and a chat + await seedReports(); + let renderCount = 0; + const {result} = renderHook(() => { + renderCount++; + return useOutstandingReportsByPolicyID(); + }); + await waitForBatchedUpdatesWithAct(); + const mapBeforeWrite = result.current; + const renderCountBeforeWrite = renderCount; + + // When the chat is renamed, which is not an outstanding report + await act(async () => { + await Onyx.merge(CHAT_REPORT_KEY, {reportName: 'After'}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the consumer keeps the same map and does not re-render + expect(result.current).toBe(mapBeforeWrite); + expect(renderCount).toBe(renderCountBeforeWrite); + }); + + it('should keep the same empty map when an account without outstanding reports gets report writes', async () => { + // Given an account whose only report is a chat, so every build finds no outstanding report + await act(async () => { + await Onyx.set(CHAT_REPORT_KEY, chatReport); + }); + let renderCount = 0; + const {result} = renderHook(() => { + renderCount++; + return useOutstandingReportsByPolicyID(); + }); + await waitForBatchedUpdatesWithAct(); + const mapBeforeWrites = result.current; + const renderCountBeforeWrites = renderCount; + + // When the chat is written several times + await act(async () => { + for (let i = 0; i < 5; i++) { + await Onyx.merge(CHAT_REPORT_KEY, {lastMessageText: `message ${i}`}); + } + }); + await waitForBatchedUpdatesWithAct(); + + // Then a fresh empty object never reaches the consumer as a new reference or a re-render + expect(result.current).toBe(mapBeforeWrites); + expect(renderCount).toBe(renderCountBeforeWrites); + }); + + it('should give every mounted consumer the same map', async () => { + // Given two consumers mounted over the same reports + await seedReports(); + const {result: first} = renderHook(() => useOutstandingReportsByPolicyID()); + const {result: second} = renderHook(() => useOutstandingReportsByPolicyID()); + await waitForBatchedUpdatesWithAct(); + + // When an outstanding report changes + await act(async () => { + await Onyx.merge(OPEN_REPORT_KEY, {total: 100}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then both get the same object, because the map is built once per report collection, not once per consumer + expect(second.current).toBe(first.current); + expect(first.current[POLICY_ID]?.[OPEN_REPORT_KEY]?.total).toBe(100); + }); + + it('should not re-render a single policy consumer when only another policy changes', async () => { + // Given a consumer of the first policy's outstanding reports + await seedReports(); + let renderCount = 0; + const {result} = renderHook(() => { + renderCount++; + return useOutstandingReportsForPolicy(POLICY_ID); + }); + await waitForBatchedUpdatesWithAct(); + const reportsBeforeWrite = result.current; + const renderCountBeforeWrite = renderCount; + expect(Object.keys(reportsBeforeWrite ?? {})).toEqual([OPEN_REPORT_KEY]); + + // When the other policy's outstanding report changes + await act(async () => { + await Onyx.merge(OTHER_POLICY_REPORT_KEY, {total: 100}); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the consumer keeps the same reports and does not re-render + expect(result.current).toBe(reportsBeforeWrite); + expect(renderCount).toBe(renderCountBeforeWrite); + }); + + it('should return nothing for a policy without outstanding reports', async () => { + // Given open expense reports in two policies + await seedReports(); + + // When a consumer reads a policy that has none, or no policy at all + const {result: unknownPolicy} = renderHook(() => useOutstandingReportsForPolicy('policy3')); + const {result: noPolicy} = renderHook(() => useOutstandingReportsForPolicy(undefined)); + await waitForBatchedUpdatesWithAct(); + + // Then both get undefined, as the per-policy selector on the derived value returned + expect(unknownPolicy.current).toBeUndefined(); + expect(noPolicy.current).toBeUndefined(); + }); +});