From 07613a6bf26d9112d47fda9e502425395bd78105 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Tue, 9 Jul 2024 17:46:10 +0200 Subject: fix(node/http): support all `.writeHead()` signatures (#24469) Implement the missing `.writeHead()` signatures from Node's `ServerResponse` class that we didn't support. Fixes https://github.com/denoland/deno/issues/24468 --- ext/node/polyfills/http.ts | 58 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 6 deletions(-) (limited to 'ext/node') diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index 534bad908..3059da3a6 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -3,7 +3,7 @@ // TODO(petamoriken): enable prefer-primordials for node polyfills // deno-lint-ignore-file prefer-primordials -import { core } from "ext:core/mod.js"; +import { core, primordials } from "ext:core/mod.js"; import { op_fetch_response_upgrade, op_fetch_send, @@ -68,6 +68,7 @@ import { resourceForReadableStream } from "ext:deno_web/06_streams.js"; import { TcpConn } from "ext:deno_net/01_net.js"; const { internalRidSymbol } = core; +const { ArrayIsArray } = primordials; enum STATUS_CODES { /** RFC 7231, 6.2.1 */ @@ -1458,20 +1459,65 @@ export class ServerResponse extends NodeWritable { getHeaderNames() { return Object.keys(this.#headers); } - getHeaders() { + getHeaders(): Record { + // @ts-ignore Ignore null __proto__ return { __proto__: null, ...this.#headers }; } hasHeader(name: string) { return Object.hasOwn(this.#headers, name); } - writeHead(status: number, headers: Record = {}) { + writeHead( + status: number, + statusMessage?: string, + headers?: + | Record + | Array<[string, string]>, + ): this; + writeHead( + status: number, + headers?: + | Record + | Array<[string, string]>, + ): this; + writeHead( + status: number, + statusMessageOrHeaders?: + | string + | Record + | Array<[string, string]>, + maybeHeaders?: + | Record + | Array<[string, string]>, + ): this { this.statusCode = status; - for (const k in headers) { - if (Object.hasOwn(headers, k)) { - this.setHeader(k, headers[k]); + + let headers = null; + if (typeof statusMessageOrHeaders === "string") { + this.statusMessage = statusMessageOrHeaders; + if (maybeHeaders !== undefined) { + headers = maybeHeaders; } + } else if (statusMessageOrHeaders !== undefined) { + headers = statusMessageOrHeaders; } + + if (headers !== null) { + if (ArrayIsArray(headers)) { + headers = headers as Array<[string, string]>; + for (let i = 0; i < headers.length; i++) { + this.appendHeader(headers[i][0], headers[i][1]); + } + } else { + headers = headers as Record; + for (const k in headers) { + if (Object.hasOwn(headers, k)) { + this.setHeader(k, headers[k]); + } + } + } + } + return this; } -- cgit v1.2.3