diff --git a/lib/web/fetch/webidl.js b/lib/web/fetch/webidl.js index ceb7f3e8b09..d9111a85c8c 100644 --- a/lib/web/fetch/webidl.js +++ b/lib/web/fetch/webidl.js @@ -8,6 +8,7 @@ const webidl = {} webidl.converters = {} webidl.util = {} webidl.errors = {} +webidl.is = {} webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) @@ -675,6 +676,10 @@ webidl.converters['record'] = webidl.recordConverter( webidl.converters.ByteString ) +webidl.is.BufferSource = function (V) { + return ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V) +} + module.exports = { webidl } diff --git a/lib/web/websocket/stream/websocketerror.js b/lib/web/websocket/stream/websocketerror.js new file mode 100644 index 00000000000..4f14defec93 --- /dev/null +++ b/lib/web/websocket/stream/websocketerror.js @@ -0,0 +1,76 @@ +'use strict' + +const { kEnumerableProperty } = require('../../../core/util') +const { webidl } = require('../../fetch/webidl') +const { validateCloseCodeAndReason } = require('../util') + +/** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#websocketerror + */ +class WebSocketError extends DOMException { + /** @type {string} */ + #reason + /** @type {number|null} */ + #closeCode = null + + /** + * @param {string} message + * @param {import('./websocketstream').WebSocketCloseInfo} init + */ + constructor (message = '', init = {}) { + super(message, 'WebSocketError') + + message = webidl.converters.DOMString(message) + init = webidl.converters.WebSocketCloseInfo(init) + + // 1. Set this 's name to " WebSocketError ". + // 2. Set this 's message to message . + + // 3. Let code be init [" closeCode "] if it exists , or null otherwise. + let code = init.closeCode ?? null + + // 4. Let reason be init [" reason "] if it exists , or the empty string otherwise. + const reason = init.reason + + // 5. Validate close code and reason with code and reason . + validateCloseCodeAndReason(code, reason) + + // 6. If reason is non-empty, but code is not set, then set code to 1000 ("Normal Closure"). + if (reason.length) code ??= 1000 + + // 7. Set this 's closeCode to code . + this.#closeCode = code + + // 8. Set this 's reason to reason . + this.#reason = reason + } + + get closeCode () { + return this.#closeCode + } + + get reason () { + return this.#reason + } +} + +Object.defineProperties(WebSocketError.prototype, { + closeCode: kEnumerableProperty, + reason: kEnumerableProperty +}) + +webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter((V) => webidl.converters['unsigned short'](V, { enforceRange: true })), + key: 'closeCode' + }, + { + converter: webidl.converters.USVString, + key: 'reason', + defaultValue: '' + } +]) + +module.exports = { + WebSocketError +} diff --git a/lib/web/websocket/stream/websocketstream.js b/lib/web/websocket/stream/websocketstream.js new file mode 100644 index 00000000000..96acac9f190 --- /dev/null +++ b/lib/web/websocket/stream/websocketstream.js @@ -0,0 +1,357 @@ +'use strict' + +const { webidl } = require('../../fetch/webidl') +const { kEnumerableProperty } = require('../../../core/util') +const { getGlobalOrigin } = require('../../fetch/global') +const { + isValidSubprotocol, + isEstablished, + failWebsocketConnection, + closeWebSocket, + getURLRecord, + isClosing +} = require('../util') +const { kReadyState, kResponse, kByteParser, kController, kPromises } = require('../symbols') +const { states, opcodes } = require('../constants') +const { establishWebSocketConnection } = require('../connection') +const { ByteParser } = require('../receiver') +const { createDeferredPromise } = require('../../fetch/util') +const { WebSocketError } = require('./websocketerror') +const { WebsocketFrameSend } = require('../frame') + +/** + * @typedef {Object} WebSocketOpenInfo + * @property {ReadableStream} readable + * @property {WritableStream} writable + * @property {string} extensions DOMString + */ + +/** + * @typedef {Object} WebSocketCloseInfo + * @property {number} closeCode [EnforceRange] unsigned short + * @property {string} reason USVString + */ + +class WebSocketStream { + /** @type {URL} */ + #internalURL + + #handshakeAborted = false + #wasEverConnected = false + + #readableStream + #writableStream + + constructor (url, options = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocketStream constructor' }) + + url = webidl.converters.USVString(url) + options = webidl.converters.WebSocketStreamOptions(options) + + this[kReadyState] = states.CONNECTING + this[kResponse] = null + + // 1. Let baseURL be this 's relevant settings object 's API base URL . + const baseURL = getGlobalOrigin() + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL . + const urlRecord = getURLRecord(url, baseURL) + + // 3. Let protocols be options [" protocols "] if it exists , otherwise an + // empty sequence. + const protocols = options.protocols ?? [] + + // 4. If any of the values in protocols occur more than once or otherwise fail to match + // the requirements for elements that comprise the value of ` Sec-WebSocket-Protocol ` + // fields as defined by The WebSocket Protocol , then throw a " SyntaxError " + // DOMException . [WSP] + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this 's url to urlRecord . + this.#internalURL = urlRecord.toString() + + // 6. Set this 's opened promise and closed promise to new promises. + this[kPromises] = { opened: createDeferredPromise(), closed: createDeferredPromise() } + + // 7. Apply backpressure to the WebSocket. + // Note: this is done in the duplex stream for us + + // 8. If options [" signal "] exists , + if (options.signal != null) { + // 8.1. Let signal be options [" signal "]. + /** @type {AbortSignal} */ + const signal = options.signal + + // 8.2. If signal is aborted , then reject this 's opened promise and closed + // promise with signal ’s abort reason and return. + if (signal.aborted) { + this[kPromises].opened.reject(signal.reason) + this[kPromises].closed.reject(signal.reason) + return + } + + // 8.3. Add the following abort steps to signal : + signal.addEventListener('abort', () => { + // 8.3.1. If the WebSocket connection is not yet established : [WSP] + if (!isEstablished(this)) { + // 8.3.1.1. Fail the WebSocket connection . + failWebsocketConnection(this) + + // 8.3.1.2. Set this 's ready state to CLOSING . + this[kReadyState] = states.CLOSING + + // 8.3.1.3. Reject this 's opened promise and closed promise with signal ’s + // abort reason . + this[kPromises].opened.reject(signal.reason) + this[kPromises].closed.reject(signal.reason) + + // 8.3.1.4. Set this 's handshake aborted to true. + this.#handshakeAborted = true + } + }, { once: true }) + } + + // 9. Let client be this 's relevant settings object . + // 10. Run this step in parallel : + // 10.1. Establish a WebSocket connection given urlRecord , protocols , and client . [FETCH] + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + } + + /** + * @returns {string} + */ + get url () { + return this.#internalURL + } + + /** + * @returns {Promise} + */ + get opened () { + webidl.brandCheck(this, WebSocketStream) + + return this[kPromises].opened.promise + } + + /** + * @returns {Promise} + */ + get closed () { + webidl.brandCheck(this, WebSocketStream) + + return this[kPromises].closed.promise + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#dom-websocketstream-close + * @param {WebSocketCloseInfo|undefined} closeInfo + * @returns {void} + */ + close (closeInfo) { + webidl.brandCheck(this, WebSocketStream) + + closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo) + + // 1. Let code be closeInfo [" closeCode "] if present, or null otherwise. + const code = closeInfo.closeCode + + // 2. Let reason be closeInfo [" reason "]. + const reason = closeInfo.reason + + // 3. Close the WebSocket with this , code , and reason . + closeWebSocket(this, code, reason) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#the-websocketstream-interface + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Set stream ’s was ever connected to true. + this.#wasEverConnected = true + + // 3. Let extensions be the extensions in use . + const extensions = response.headersList.get('sec-websocket-extensions') ?? '' + + // 4. Let protocol be the subprotocol in use . + const protocol = response.headersList.get('sec-websocket-protocol') ?? '' + + // 5. Let pullAlgorithm be an action that pulls bytes from stream . + // 6. Let cancelAlgorithm be an action that cancels the WebSocketStream with stream and + // reason , given reason . + // 7. Let readable be a new ReadableStream . + // 8. Set up readable with pullAlgorithm and cancelAlgorithm . + const readable = new ReadableStream({ + pull (controller) { + // TODO: do we read until the queue is empty? + let chunk + while (controller.desiredSize >= 0 && (chunk = response.socket.read()) !== null) { + controller.enqueue(chunk) + } + }, + cancel: (reason) => this.#cancel(reason) + }, new ByteLengthQueuingStrategy({ highWaterMark: 4 * 1024 })) + + // 9. Let writeAlgorithm be an action that writes chunk to stream , given chunk . + // 10. Let closeAlgorithm be an action that closes stream . + // 11. Let abortAlgorithm be an action that aborts stream with reason , given reason . + // 12. Let writable be a new WritableStream . + // 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm . + const writable = new WritableStream({ + write: (chunk) => this.#write(chunk), + close: () => closeWebSocket(this), + abort: (reason) => this.#closeWithReason(reason) + }, new ByteLengthQueuingStrategy({ highWaterMark: 4 * 1024 })) + + // 14. Set stream ’s readable stream to readable . + this.#readableStream = readable + + // 15. Set stream ’s writable stream to writable . + this.#writableStream = writable + + // 16. Resolve stream ’s opened promise with WebSocketOpenInfo + // «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " + // writable " → writable ]». + this[kPromises].opened.resolve({ + extensions, + protocol, + readable, + writable + }) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#cancel + * @param {any} reason + */ + #cancel (reason) { + // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . + this.#closeWithReason(reason) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#close-using-reason + * @param {any} reason + */ + #closeWithReason (reason) { + // 1. Let code be null. + let code = null + + // 2. Let reasonString be the empty string. + let reasonString = '' + + // 3. If reason implements WebSocketError , + if (reason instanceof WebSocketError) { + // 3.1. Set code to reason ’s closeCode . + code = reason.closeCode + + // 3.2. Set reasonString to reason ’s reason . + reasonString = reason.reason + } + + // 4. Close the WebSocket with stream , code , and reasonString . If this throws an exception, + // discard code and reasonString and close the WebSocket with stream . + closeWebSocket(this, code, reasonString) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#write + * @param {any} chunk + */ + #write (chunk) { + // 1. Let promise be a new promise created in stream ’s relevant realm . + + let data + let opcode + + // 2. If chunk is a BufferSource , + if (webidl.is.BufferSource(chunk)) { + // 2.1. Let data be a copy of the bytes given chunk . + data = Buffer.from(chunk, chunk.byteOffset, chunk.byteLength) + + // 2.2. Let opcode be a binary frame opcode. + opcode = opcodes.BINARY + } else { + // 3. Otherwise, + + // 3.1. Let string be the result of converting chunk to an IDL USVString . + // If this throws an exception, return a promise rejected with the exception. + // 3.2. Let data be the result of UTF-8 encoding string . + data = new TextEncoder().encode(webidl.converters.USVString(chunk)) + + // 3.3. Let opcode be a text frame opcode. + opcode = opcodes.TEXT + } + + // 4. In parallel, + // 4.1. Wait until there is sufficient buffer space in stream to send the message. + // 4.2. If the closing handshake has not yet started , Send a WebSocket Message to + // stream comprised of data using opcode . + // 4.3. Queue a global task on the WebSocket task source given stream ’s relevant + // global object to resolve promise with undefined. + if (!isClosing(this)) { + const frame = new WebsocketFrameSend(data) + const buffer = frame.createFrame(opcode) + + this[kResponse].socket.write(buffer) + } + + // 5. Return promise . + } +} + +Object.defineProperties(WebSocketStream.prototype, { + url: kEnumerableProperty, + opened: kEnumerableProperty, + closed: kEnumerableProperty, + close: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketStream', + configurable: true + } +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.USVString +) + +webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['sequence'] + }, + { + key: 'signal', + converter: webidl.converters.AbortSignal + } +]) + +module.exports = { + WebSocketStream +} diff --git a/lib/web/websocket/symbols.js b/lib/web/websocket/symbols.js index 11d03e38a86..69da7837840 100644 --- a/lib/web/websocket/symbols.js +++ b/lib/web/websocket/symbols.js @@ -8,5 +8,6 @@ module.exports = { kBinaryType: Symbol('binary type'), kSentClose: Symbol('sent close'), kReceivedClose: Symbol('received close'), - kByteParser: Symbol('byte parser') + kByteParser: Symbol('byte parser'), + kPromises: Symbol('promises') } diff --git a/lib/web/websocket/util.js b/lib/web/websocket/util.js index 4f0e4dcf5dd..af9ee707c3a 100644 --- a/lib/web/websocket/util.js +++ b/lib/web/websocket/util.js @@ -1,8 +1,9 @@ 'use strict' -const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols') -const { states, opcodes } = require('./constants') +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL, kSentClose, kPromises } = require('./symbols') +const { states, opcodes, emptyBuffer } = require('./constants') const { MessageEvent, ErrorEvent } = require('./events') +const { WebsocketFrameSend } = require('./frame') /* globals Blob */ @@ -53,6 +54,9 @@ function isClosed (ws) { * @param {EventInit | undefined} eventInitDict */ function fireEvent (e, target, eventConstructor = Event, eventInitDict = {}) { + // TODO: remove this + if (!target.dispatchEvent) return + // 1. If eventConstructor is not given, then let eventConstructor be Event. // 2. Let event be the result of creating an event given eventConstructor, @@ -77,6 +81,9 @@ const textDecoder = new TextDecoder('utf-8', { fatal: true }) * @param {Buffer} data application data */ function websocketMessageReceived (ws, type, data) { + // TODO: remove + if (!ws.dispatchEvent) return + // 1. If ready state is not OPEN (1), then return. if (ws[kReadyState] !== states.OPEN) { return @@ -181,6 +188,9 @@ function isValidStatusCode (code) { return code >= 3000 && code <= 4999 } +/** @type {import('./stream/websocketerror').WebSocketError} */ +let WebSocketError + /** * @param {import('./websocket').WebSocket} ws * @param {string|undefined} reason @@ -200,6 +210,154 @@ function failWebsocketConnection (ws, reason) { error: new Error(reason) }) } + + if (ws[kPromises]) { + WebSocketError ??= require('./stream/websocketerror').WebSocketError + + const error = new WebSocketError('Connection closed.', { reason }) + + ws[kPromises].opened.reject(error) + ws[kPromises].closed.reject(error) + } +} + +/** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#close-the-websocket + * @param {import('./websocket').WebSocket|import('./stream/websocketstream').WebSocketStream} object + * @param {number|null} code + * @param {string} reason + */ +function closeWebSocket (object, code = null, reason = '') { + // 1. If code was not supplied, let code be null. + // 2. If reason was not supplied, let reason be the empty string. + + // 3. Validate close code and reason with code and reason . + validateCloseCodeAndReason(code, reason) + + // 4. Run the first matching steps from the following list: + // - If object ’s ready state is CLOSING (2) or CLOSED (3) + // - If the WebSocket connection is not yet established [WSP] + // - If the WebSocket closing handshake has not yet been started [WSP] + // - Otherwise + if (object[kReadyState] === states.CLOSING || object[kReadyState] === states.CLOSED) { + // Do nothing. + // I like this step. + } else if (!isEstablished(object)) { + // Fail the WebSocket connection and set object ’s ready state to CLOSING (2). [WSP] + // TODO: with reason? + failWebsocketConnection(object, reason) + object[kReadyState] = states.CLOSING + } else if (!isClosing(object)) { + // Start the WebSocket closing handshake and set object ’s ready state to CLOSING (2). [WSP] + // - If code is null and reason is the empty string, the WebSocket Close frame must not have a body. + // - if reason is non-empty but code is null, then set code to 1000 ("Normal Closure"). + // - If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code . [WSP] + // - If reason is non-empty, then reason , encoded as UTF-8 , must be provided in the Close frame after the status code. [WSP] + + if (reason.length && code === null) { + code = 1000 + } + + const frame = new WebsocketFrameSend() + + if (code !== null && reason.length === 0) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== null && reason.length) { + frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason)) + frame.frameData.writeUInt16BE(code, 0) + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = object[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + object[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + object[kReadyState] = states.CLOSING + } else { + // Set object ’s ready state to CLOSING (2). + object[kReadyState] = states.CLOSING + } +} + +/** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#validate-close-code-and-reason + * @param {number|null} code + * @param {any} reason + */ +function validateCloseCodeAndReason (code, reason) { + // 1. If code is not null, but is neither an integer equal to 1000 nor an integer in the + // range 3000 to 4999, inclusive, throw an " InvalidAccessError " DOMException . + if (code !== null && code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('Invalid code', 'InvalidAccessError') + } + + // 2. If reason is not null, then: + // TODO: reason can't be null here? + if (reason) { + // 2.1. Let reasonBytes be the result of UTF-8 encoding reason . + const reasonBytes = new TextEncoder().encode(reason) + + // 2.2. If reasonBytes is longer than 123 bytes, then throw a " SyntaxError " DOMException . + if (reasonBytes.length > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${Buffer.byteLength(reasonBytes)}`, + 'SyntaxError' + ) + } + } +} + +/** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#get-a-url-record + * @param {URL|string} url + * @param {URL|string|undefined} baseURL + */ +function getURLRecord (url, baseURL) { + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL . + /** @type {URL} */ + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 2. If urlRecord is failure, then throw a " SyntaxError " DOMException . + throw new DOMException(e, 'SyntaxError') + } + + // 3. If urlRecord ’s scheme is " http ", then set urlRecord ’s scheme to " ws ". + // 4. Otherwise, if urlRecord ’s scheme is " https ", set urlRecord ’s scheme to " wss ". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + urlRecord.protocol = 'wss:' + } + + // 5. If urlRecord ’s scheme is not " ws " or " wss ", then throw a " SyntaxError " DOMException . + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 6. If urlRecord ’s fragment is non-null, then throw a " SyntaxError " DOMException . + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 7. Return urlRecord . + return urlRecord } module.exports = { @@ -211,5 +369,8 @@ module.exports = { isValidSubprotocol, isValidStatusCode, failWebsocketConnection, - websocketMessageReceived + websocketMessageReceived, + closeWebSocket, + validateCloseCodeAndReason, + getURLRecord } diff --git a/lib/websocket/stream/websocketerror.js b/lib/websocket/stream/websocketerror.js new file mode 100644 index 00000000000..abf27cb6f74 --- /dev/null +++ b/lib/websocket/stream/websocketerror.js @@ -0,0 +1,76 @@ +'use strict' + +const { kEnumerableProperty } = require('../../core/util') +const { webidl } = require('../../fetch/webidl') +const { validateCloseCodeAndReason } = require('../util') + +/** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#websocketerror + */ +class WebSocketError extends DOMException { + /** @type {string} */ + #reason + /** @type {number|null} */ + #closeCode = null + + /** + * @param {string} message + * @param {import('./websocketstream').WebSocketCloseInfo} init + */ + constructor (message = '', init = {}) { + super(message, 'WebSocketError') + + message = webidl.converters.DOMString(message) + init = webidl.converters.WebSocketCloseInfo(init) + + // 1. Set this 's name to " WebSocketError ". + // 2. Set this 's message to message . + + // 3. Let code be init [" closeCode "] if it exists , or null otherwise. + let code = init.closeCode ?? null + + // 4. Let reason be init [" reason "] if it exists , or the empty string otherwise. + const reason = init.reason + + // 5. Validate close code and reason with code and reason . + validateCloseCodeAndReason(code, reason) + + // 6. If reason is non-empty, but code is not set, then set code to 1000 ("Normal Closure"). + if (reason.length) code ??= 1000 + + // 7. Set this 's closeCode to code . + this.#closeCode = code + + // 8. Set this 's reason to reason . + this.#reason = reason + } + + get closeCode () { + return this.#closeCode + } + + get reason () { + return this.#reason + } +} + +Object.defineProperties(WebSocketError.prototype, { + closeCode: kEnumerableProperty, + reason: kEnumerableProperty +}) + +webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter((V) => webidl.converters['unsigned short'](V, { enforceRange: true })), + key: 'closeCode' + }, + { + converter: webidl.converters.USVString, + key: 'reason', + defaultValue: '' + } +]) + +module.exports = { + WebSocketError +} diff --git a/lib/websocket/stream/websocketstream.js b/lib/websocket/stream/websocketstream.js new file mode 100644 index 00000000000..61d1ea3f1a8 --- /dev/null +++ b/lib/websocket/stream/websocketstream.js @@ -0,0 +1,359 @@ +'use strict' + +const { webidl } = require('../../fetch/webidl') +const { kEnumerableProperty } = require('../../core/util') +const { getGlobalOrigin } = require('../../fetch/global') +const { + isValidSubprotocol, + isEstablished, + failWebsocketConnection, + closeWebSocket, + getURLRecord, + isClosing +} = require('../util') +const { kReadyState, kResponse, kByteParser, kController, kPromises } = require('../symbols') +const { states, opcodes } = require('../constants') +const { establishWebSocketConnection } = require('../connection') +const { ByteParser } = require('../receiver') +const { createDeferredPromise } = require('../../fetch/util') +const { WebSocketError } = require('./websocketerror') +const { WebsocketFrameSend } = require('../frame') + +/** + * @typedef {Object} WebSocketOpenInfo + * @property {ReadableStream} readable + * @property {WritableStream} writable + * @property {string} extensions DOMString + */ + +/** + * @typedef {Object} WebSocketCloseInfo + * @property {number} closeCode [EnforceRange] unsigned short + * @property {string} reason USVString + */ + +class WebSocketStream { + /** @type {URL} */ + #internalURL + + #handshakeAborted = false + #wasEverConnected = false + + #readableStream + #writableStream + + constructor (url, options = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocketStream constructor' }) + + url = webidl.converters.USVString(url) + options = webidl.converters.WebSocketStreamOptions(options) + + this[kReadyState] = states.CONNECTING + this[kResponse] = null + + // 1. Let baseURL be this 's relevant settings object 's API base URL . + const baseURL = getGlobalOrigin() + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL . + const urlRecord = getURLRecord(url, baseURL) + + // 3. Let protocols be options [" protocols "] if it exists , otherwise an + // empty sequence. + const protocols = options.protocols ?? [] + + // 4. If any of the values in protocols occur more than once or otherwise fail to match + // the requirements for elements that comprise the value of ` Sec-WebSocket-Protocol ` + // fields as defined by The WebSocket Protocol , then throw a " SyntaxError " + // DOMException . [WSP] + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this 's url to urlRecord . + this.#internalURL = urlRecord.toString() + + // 6. Set this 's opened promise and closed promise to new promises. + this[kPromises] = { opened: createDeferredPromise(), closed: createDeferredPromise() } + + // 7. Apply backpressure to the WebSocket. + // Note: this is done in the duplex stream for us + + // 8. If options [" signal "] exists , + if (options.signal != null) { + // 8.1. Let signal be options [" signal "]. + /** @type {AbortSignal} */ + const signal = options.signal + + // 8.2. If signal is aborted , then reject this 's opened promise and closed + // promise with signal ’s abort reason and return. + if (signal.aborted) { + this[kPromises].opened.reject(signal.reason) + this[kPromises].closed.reject(signal.reason) + return + } + + // 8.3. Add the following abort steps to signal : + signal.addEventListener('abort', () => { + // 8.3.1. If the WebSocket connection is not yet established : [WSP] + if (!isEstablished(this)) { + // 8.3.1.1. Fail the WebSocket connection . + failWebsocketConnection(this) + + // 8.3.1.2. Set this 's ready state to CLOSING . + this[kReadyState] = states.CLOSING + + // 8.3.1.3. Reject this 's opened promise and closed promise with signal ’s + // abort reason . + this[kPromises].opened.reject(signal.reason) + this[kPromises].closed.reject(signal.reason) + + // 8.3.1.4. Set this 's handshake aborted to true. + this.#handshakeAborted = true + } + }, { once: true }) + } + + // 9. Let client be this 's relevant settings object . + // 10. Run this step in parallel : + // 10.1. Establish a WebSocket connection given urlRecord , protocols , and client . [FETCH] + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + } + + /** + * @returns {string} + */ + get url () { + return this.#internalURL + } + + /** + * @returns {Promise} + */ + get opened () { + webidl.brandCheck(this, WebSocketStream) + + return this[kPromises].opened.promise + } + + /** + * @returns {Promise} + */ + get closed () { + webidl.brandCheck(this, WebSocketStream) + + return this[kPromises].closed.promise + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#dom-websocketstream-close + * @param {WebSocketCloseInfo|undefined} closeInfo + * @returns {void} + */ + close (closeInfo) { + webidl.brandCheck(this, WebSocketStream) + + closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo) + + // 1. Let code be closeInfo [" closeCode "] if present, or null otherwise. + const code = closeInfo.closeCode + + // 2. Let reason be closeInfo [" reason "]. + const reason = closeInfo.reason + + // 3. Close the WebSocket with this , code , and reason . + closeWebSocket(this, code, reason) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#the-websocketstream-interface + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Set stream ’s was ever connected to true. + this.#wasEverConnected = true + + // 3. Let extensions be the extensions in use . + const extensions = response.headersList.get('sec-websocket-extensions') ?? '' + + // 4. Let protocol be the subprotocol in use . + const protocol = response.headersList.get('sec-websocket-protocol') ?? '' + + // 5. Let pullAlgorithm be an action that pulls bytes from stream . + // 6. Let cancelAlgorithm be an action that cancels the WebSocketStream with stream and + // reason , given reason . + // 7. Let readable be a new ReadableStream . + // 8. Set up readable with pullAlgorithm and cancelAlgorithm . + const readable = new ReadableStream({ + pull (controller) { + // TODO: do we read until the queue is empty? + let chunk + while ((chunk = response.socket.read()) !== null) { + controller.enqueue(chunk) + } + }, + cancel: (reason) => this.#cancel(reason) + }, new ByteLengthQueuingStrategy({ highWaterMark: 16384 })) + + // 9. Let writeAlgorithm be an action that writes chunk to stream , given chunk . + // 10. Let closeAlgorithm be an action that closes stream . + // 11. Let abortAlgorithm be an action that aborts stream with reason , given reason . + // 12. Let writable be a new WritableStream . + // 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm . + const writable = new WritableStream({ + write: (chunk) => this.#write(chunk), + close: () => closeWebSocket(this), + abort: (reason) => this.#closeWithReason(reason) + }, new ByteLengthQueuingStrategy({ highWaterMark: 16384 })) + + // 14. Set stream ’s readable stream to readable . + this.#readableStream = readable + + // 15. Set stream ’s writable stream to writable . + this.#writableStream = writable + + // 16. Resolve stream ’s opened promise with WebSocketOpenInfo + // «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " + // writable " → writable ]». + this[kPromises].opened.resolve({ + extensions, + protocol, + readable, + writable + }) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#cancel + * @param {any} reason + */ + #cancel (reason) { + // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . + this.#closeWithReason(reason) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#close-using-reason + * @param {any} reason + */ + #closeWithReason (reason) { + // 1. Let code be null. + let code = null + + // 2. Let reasonString be the empty string. + let reasonString = '' + + // 3. If reason implements WebSocketError , + if (reason instanceof WebSocketError) { + // 3.1. Set code to reason ’s closeCode . + code = reason.closeCode + + // 3.2. Set reasonString to reason ’s reason . + reasonString = reason.reason + } + + // 4. Close the WebSocket with stream , code , and reasonString . If this throws an exception, + // discard code and reasonString and close the WebSocket with stream . + closeWebSocket(this, code, reasonString) + } + + /** + * @see https://whatpr.org/websockets/48/7b748d3...7b81f79.html#write + * @param {any} chunk + */ + #write (chunk) { + // 1. Let promise be a new promise created in stream ’s relevant realm . + + let data + let opcode + + // 2. If chunk is a BufferSource , + if (webidl.is.BufferSource(chunk)) { + // 2.1. Let data be a copy of the bytes given chunk . + data = Buffer.from(chunk, chunk.byteOffset, chunk.byteLength) + + // 2.2. Let opcode be a binary frame opcode. + opcode = opcodes.BINARY + } else { + // 3. Otherwise, + + // 3.1. Let string be the result of converting chunk to an IDL USVString . + // If this throws an exception, return a promise rejected with the exception. + // 3.2. Let data be the result of UTF-8 encoding string . + data = new TextEncoder().encode(webidl.converters.USVString(chunk)) + + // 3.3. Let opcode be a text frame opcode. + opcode = opcodes.TEXT + } + + // 4. In parallel, + // 4.1. Wait until there is sufficient buffer space in stream to send the message. + // 4.2. If the closing handshake has not yet started , Send a WebSocket Message to + // stream comprised of data using opcode . + // 4.3. Queue a global task on the WebSocket task source given stream ’s relevant + // global object to resolve promise with undefined. + if (!isClosing(this)) { + const frame = new WebsocketFrameSend(data) + const buffer = frame.createFrame(opcode) + + this[kResponse].socket.write(buffer, () => { + // TODO: what if error? + }) + } + + // 5. Return promise . + } +} + +Object.defineProperties(WebSocketStream.prototype, { + url: kEnumerableProperty, + opened: kEnumerableProperty, + closed: kEnumerableProperty, + close: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketStream', + configurable: true + } +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.USVString +) + +webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['sequence'] + }, + { + key: 'signal', + converter: webidl.converters.AbortSignal + } +]) + +module.exports = { + WebSocketStream +} diff --git a/test/wpt/runner/worker.mjs b/test/wpt/runner/worker.mjs index f0f45542e97..c86bd73268f 100644 --- a/test/wpt/runner/worker.mjs +++ b/test/wpt/runner/worker.mjs @@ -5,15 +5,15 @@ import { setFlagsFromString } from 'node:v8' import { runInNewContext, runInThisContext } from 'node:vm' import { parentPort, workerData } from 'node:worker_threads' import { - fetch, File, FileReader, FormData, Headers, Request, Response, setGlobalOrigin + fetch, File, FileReader, FormData, Headers, Request, Response, setGlobalOrigin, EventSource } from '../../../index.js' import { CloseEvent } from '../../../lib/web/websocket/events.js' import { WebSocket } from '../../../lib/web/websocket/websocket.js' import { Cache } from '../../../lib/web/cache/cache.js' import { CacheStorage } from '../../../lib/web/cache/cachestorage.js' import { kConstruct } from '../../../lib/web/cache/symbols.js' -// TODO(@KhafraDev): move this import once its added to index -import { EventSource } from '../../../lib/web/eventsource/eventsource.js' +import { WebSocketStream } from '../../../lib/web/websocket/stream/websocketstream.js' +import { WebSocketError } from '../../../lib/web/websocket/stream/websocketerror.js' import { webcrypto } from 'node:crypto' const { initScripts, meta, test, url, path } = workerData @@ -96,6 +96,14 @@ Object.defineProperties(globalThis, { EventSource: { ...globalPropertyDescriptors, value: EventSource + }, + WebSocketStream: { + ...globalPropertyDescriptors, + value: WebSocketStream + }, + WebSocketError: { + ...globalPropertyDescriptors, + value: WebSocketError } }) diff --git a/test/wpt/server/websocket.mjs b/test/wpt/server/websocket.mjs index 9bb05d12612..73d042cb874 100644 --- a/test/wpt/server/websocket.mjs +++ b/test/wpt/server/websocket.mjs @@ -7,7 +7,7 @@ import { server } from './server.mjs' // event, so I'm unsure if we can stop relying on server. const wss = new WebSocketServer({ - server, + noServer: true, handleProtocols: (protocols) => protocols.values().next().value }) @@ -44,3 +44,15 @@ wss.on('connection', (ws, request) => { clearTimeout(timeout) }) }) + +server.on('upgrade', (req, socket, head) => { + if (req.url === '/404') { + socket.write('HTTP/1.1 404 Not Found\r\n\r\n') + socket.destroy() + return + } + + wss.handleUpgrade(req, socket, head, (ws, req) => { + wss.emit('connection', ws, req) + }) +}) diff --git a/test/wpt/status/websockets.status.json b/test/wpt/status/websockets.status.json index 9f5a6308a1d..e26fc226ce3 100644 --- a/test/wpt/status/websockets.status.json +++ b/test/wpt/status/websockets.status.json @@ -1,7 +1,20 @@ { "stream": { "tentative": { - "skip": true + "abort.any.js": { + "note": "investigate", + "skip": true + }, + "backpressure-send.any.js": { + "note": "The test expects us to implement our own queue, rather than relying on an external one (ie. Duplex streams). The write promise will resolve very quickly, even if the message might not have been.", + "skip": true + }, + "constructor.any.js": { + "note": "This test is either wrong, or a python server quirk where it only sends the first protocol...", + "fail": [ + "setting a protocol in the constructor should work" + ] + } } }, "interfaces": { diff --git a/test/wpt/tests/websockets/stream/tentative/close.any.js b/test/wpt/tests/websockets/stream/tentative/close.any.js index 2be9034872e..098caf31c82 100644 --- a/test/wpt/tests/websockets/stream/tentative/close.any.js +++ b/test/wpt/tests/websockets/stream/tentative/close.any.js @@ -4,12 +4,14 @@ // META: variant=?wss // META: variant=?wpt_flags=h2 +'use strict'; + promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; - wss.close({code: 3456, reason: 'pizza'}); - const { code, reason } = await wss.closed; - assert_equals(code, 3456, 'code should match'); + wss.close({ closeCode: 3456, reason: 'pizza' }); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 3456, 'code should match'); assert_equals(reason, 'pizza', 'reason should match'); }, 'close code should be sent to server and reflected back'); @@ -17,8 +19,8 @@ promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; wss.close(); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); }, 'no close argument should send empty Close frame'); @@ -26,8 +28,8 @@ promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; wss.close({}); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); }, 'unspecified close code should send empty Close frame'); @@ -35,8 +37,8 @@ promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; wss.close({reason: ''}); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); }, 'unspecified close code with empty reason should send empty Close frame'); @@ -44,8 +46,8 @@ promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; wss.close({reason: 'non-empty'}); - const { code, reason } = await wss.closed; - assert_equals(code, 1000, 'code should be set'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1000, 'code should be set'); assert_equals(reason, 'non-empty', 'reason should match'); }, 'unspecified close code with non-empty reason should set code to 1000'); @@ -61,17 +63,19 @@ promise_test(async () => { await wss.opened; const reason = '.'.repeat(124); assert_throws_dom('SyntaxError', () => wss.close({ reason }), - 'close should throw a TypeError'); + 'close should throw a SyntaxError'); }, 'close() with an overlong reason should throw'); +function IsWebSocketError(e) { + return e.constructor == WebSocketError; +} + promise_test(t => { const wss = new WebSocketStream(ECHOURL); wss.close(); return Promise.all([ - promise_rejects_dom( - t, 'NetworkError', wss.opened, 'opened promise should reject'), - promise_rejects_dom( - t, 'NetworkError', wss.closed, 'closed promise should reject'), + wss.opened.then(t.unreached_func('should have rejected')).catch(e => assert_true(IsWebSocketError(e))), + wss.closed.then(t.unreached_func('should have rejected')).catch(e => assert_true(IsWebSocketError(e))), ]); }, 'close during handshake should work'); @@ -79,8 +83,8 @@ for (const invalidCode of [999, 1001, 2999, 5000]) { promise_test(async () => { const wss = new WebSocketStream(ECHOURL); await wss.opened; - assert_throws_dom('InvalidAccessError', () => wss.close({ code: invalidCode }), - 'close should throw a TypeError'); + assert_throws_dom('InvalidAccessError', () => wss.close({ closeCode: invalidCode }), + 'close should throw an InvalidAccessError'); }, `close() with invalid code ${invalidCode} should throw`); } @@ -88,8 +92,8 @@ promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const { writable } = await wss.opened; writable.getWriter().close(); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); }, 'closing the writable should result in a clean close'); @@ -123,65 +127,57 @@ for (const { method, voweling, stream } of abortOrCancel) { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; info[stream][method](); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); }, `${voweling} the ${stream} should result in a clean close`); promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; - info[stream][method]({ code: 3333 }); - const { code, reason } = await wss.closed; - assert_equals(code, 3333, 'code should be used'); + info[stream][method]({ closeCode: 3333, reason: 'obsolete' }); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); - }, `${voweling} the ${stream} with a code should send that code`); + }, `${voweling} the ${stream} with attributes not wrapped in a WebSocketError should be ignored`); promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; - info[stream][method]({ code: 3456, reason: 'set' }); - const { code, reason } = await wss.closed; - assert_equals(code, 3456, 'code should be used'); - assert_equals(reason, 'set', 'reason should be used'); - }, `${voweling} the ${stream} with a code and reason should use them`); - - promise_test(async () => { - const wss = new WebSocketStream(ECHOURL); - const info = await wss.opened; - info[stream][method]({ reason: 'specified' }); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + info[stream][method](new WebSocketError('', { closeCode: 3333 })); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 3333, 'code should be used'); assert_equals(reason, '', 'reason should be empty'); - }, `${voweling} the ${stream} with a reason but no code should be ignored`); + }, `${voweling} the ${stream} with a code should send that code`); promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; - info[stream][method]({ code: 999 }); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); - assert_equals(reason, '', 'reason should be empty'); - }, `${voweling} the ${stream} with an invalid code should be ignored`); + info[stream][method](new WebSocketError('', { closeCode: 3456, reason: 'set' })); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 3456, 'code should be used'); + assert_equals(reason, 'set', 'reason should be used'); + }, `${voweling} the ${stream} with a code and reason should use them`); promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; - info[stream][method]({ code: 1000, reason: 'x'.repeat(128) }); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); - assert_equals(reason, '', 'reason should be empty'); - }, `${voweling} the ${stream} with an invalid reason should be ignored`); + info[stream][method](new WebSocketError('', { reason: 'specified' })); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1000, 'code should be defaulted'); + assert_equals(reason, 'specified', 'reason should be used'); + }, `${voweling} the ${stream} with a reason but no code should default the close code`); - // DOMExceptions are only ignored because the |code| attribute is too small to - // be a valid WebSocket close code. promise_test(async () => { const wss = new WebSocketStream(ECHOURL); const info = await wss.opened; - info[stream][method](new DOMException('yes', 'DataCloneError')); - const { code, reason } = await wss.closed; - assert_equals(code, 1005, 'code should be unset'); + const domException = new DOMException('yes', 'DataCloneError'); + domException.closeCode = 1000; + domException.reason = 'should be ignored'; + info[stream][method](domException); + const { closeCode, reason } = await wss.closed; + assert_equals(closeCode, 1005, 'code should be unset'); assert_equals(reason, '', 'reason should be empty'); - }, `${voweling} the ${stream} with a DOMException should be ignored`); + }, `${voweling} the ${stream} with a DOMException not set code or reason`); } diff --git a/test/wpt/tests/websockets/stream/tentative/constructor.any.js b/test/wpt/tests/websockets/stream/tentative/constructor.any.js index 4d67d81cf28..66df9743035 100644 --- a/test/wpt/tests/websockets/stream/tentative/constructor.any.js +++ b/test/wpt/tests/websockets/stream/tentative/constructor.any.js @@ -44,11 +44,15 @@ promise_test(async () => { wss.close(); }, 'setting a protocol in the constructor should work'); +function IsWebSocketError(e) { + return e.constructor == WebSocketError; +} + promise_test(t => { const wss = new WebSocketStream(`${BASEURL}/404`); return Promise.all([ - promise_rejects_dom(t, 'NetworkError', wss.opened, 'opened should reject'), - promise_rejects_dom(t, 'NetworkError', wss.closed, 'closed should reject'), + wss.opened.then(t.unreached_func('should have rejected')).catch(e => assert_true(IsWebSocketError(e))), + wss.closed.then(t.unreached_func('should have rejected')).catch(e => assert_true(IsWebSocketError(e))), ]); }, 'connection failure should reject the promises'); diff --git a/test/wpt/tests/websockets/stream/tentative/websocket-error.any.js b/test/wpt/tests/websockets/stream/tentative/websocket-error.any.js new file mode 100644 index 00000000000..b114bbb3e34 --- /dev/null +++ b/test/wpt/tests/websockets/stream/tentative/websocket-error.any.js @@ -0,0 +1,50 @@ +// META: global=window,worker + +'use strict'; + +test(() => { + const error = new WebSocketError(); + assert_equals(error.code, 0, 'DOMException code should be 0'); + assert_equals(error.name, 'WebSocketError', 'name should be correct'); + assert_equals(error.message, '', 'DOMException message should be empty'); + assert_equals(error.closeCode, null, 'closeCode should be null'); + assert_equals(error.reason, '', 'reason should be empty'); +}, 'WebSocketError defaults should be correct'); + +test(() => { + const error = new WebSocketError('message', { closeCode: 3456, reason: 'reason' }); + assert_equals(error.code, 0, 'DOMException code should be 0'); + assert_equals(error.name, 'WebSocketError', 'name should be correct'); + assert_equals(error.message, 'message', 'DOMException message should be set'); + assert_equals(error.closeCode, 3456, 'closeCode should match'); + assert_equals(error.reason, 'reason', 'reason should match'); +}, 'WebSocketError should be initialised from arguments'); + +for (const invalidCode of [999, 1001, 2999, 5000]) { + test(() => { + assert_throws_dom('InvalidAccessError', () => new WebSocketError('', { closeCode: invalidCode }), + 'invalid code should throw an InvalidAccessError'); + }, `new WebSocketError with invalid code ${invalidCode} should throw`); +} + +test(() => { + const error = new WebSocketError('', { closeCode: 3333 }); + assert_equals(error.closeCode, 3333, 'code should be used'); + assert_equals(error.reason, '', 'reason should be empty'); +}, 'passing only close code to WebSocketError should work'); + +test(() => { + const error = new WebSocketError('', { reason: 'specified' }); + assert_equals(error.closeCode, 1000, 'code should be defaulted'); + assert_equals(error.reason, 'specified', 'reason should be used'); +}, 'passing a non-empty reason should cause the close code to be set to 1000'); + +test(() => { + assert_throws_dom('SyntaxError', () => new WebSocketError('', { closeCode: 1000, reason: 'x'.repeat(124) }), + 'overlong reason should trigger SyntaxError'); +}, 'overlong reason should throw'); + +test(() => { + assert_throws_dom('SyntaxError', () => new WebSocketError('', { reason: '🔌'.repeat(32) }), + 'overlong reason should throw'); +}, 'reason should be rejected based on utf-8 bytes, not character count'); diff --git a/types/webidl.d.ts b/types/webidl.d.ts index 1e362d6f40d..df50e22920d 100644 --- a/types/webidl.d.ts +++ b/types/webidl.d.ts @@ -158,10 +158,15 @@ interface WebidlConverters { [Key: string]: (...args: any[]) => unknown } +interface WebidlIs { + BufferSource(V: any): V is NodeJS.TypedArray | DataView | ArrayBuffer +} + export interface Webidl { errors: WebidlErrors util: WebidlUtil converters: WebidlConverters + is: WebidlIs /** * @description Performs a brand-check on {@param V} to ensure it is a