greatly simplify createwebsocket

This commit is contained in:
velzie 2024-09-07 16:29:32 -04:00
parent ea21f222be
commit abec64ef97
No known key found for this signature in database
GPG key ID: 048413F95F0DDE1F
3 changed files with 69 additions and 146 deletions

View file

@ -26,7 +26,6 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-inject": "^5.0.5", "@rollup/plugin-inject": "^5.0.5",
"@rollup/plugin-replace": "^5.0.5", "@rollup/plugin-replace": "^5.0.5",
"rollup": "^4.9.6", "rollup": "^4.9.6",

View file

@ -121,10 +121,9 @@ export class BareClient {
createWebSocket( createWebSocket(
remote: string | URL, remote: string | URL,
protocols: string | string[] | undefined = [], protocols: string | string[] | undefined = [],
webSocketImpl?: WebSocketImpl, __deprecated_donotuse_websocket?: any,
requestHeaders?: BareHeaders, requestHeaders?: BareHeaders,
arrayBufferImpl?: ArrayBuffer, ): BareWebSocket {
): WebSocket {
try { try {
remote = new URL(remote); remote = new URL(remote);
} catch (err) { } catch (err) {
@ -148,7 +147,6 @@ export class BareClient {
`Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.` `Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.`
); );
arrayBufferImpl = arrayBufferImpl || (webSocketImpl || WebSocket).constructor.constructor("return ArrayBuffer")().prototype;
requestHeaders = requestHeaders || {}; requestHeaders = requestHeaders || {};
requestHeaders['Host'] = (new URL(remote)).host; requestHeaders['Host'] = (new URL(remote)).host;
// requestHeaders['Origin'] = origin; // requestHeaders['Origin'] = origin;
@ -158,9 +156,9 @@ export class BareClient {
// requestHeaders['User-Agent'] = navigator.userAgent; // requestHeaders['User-Agent'] = navigator.userAgent;
requestHeaders['Connection'] = 'Upgrade'; requestHeaders['Connection'] = 'Upgrade';
const socket = new BareWebSocket(remote, protocols, this.worker, requestHeaders, arrayBufferImpl) const socket = new BareWebSocket(remote, protocols, this.worker, requestHeaders);
return socket as unknown as WebSocket; return socket;
} }
async fetch( async fetch(

View file

@ -4,82 +4,38 @@ import { BareHeaders } from "./baretypes";
export class BareWebSocket extends EventTarget { export class BareWebSocket extends EventTarget {
url: string; url: string;
protocols: string | string[] | undefined = [];
readyState: number = WebSocketFields.CONNECTING;
binaryType = "blob";
//legacy event handlers
onopen = null;
onerror = null;
onmessage = null;
onclose = null;
channel: MessageChannel; channel: MessageChannel;
constructor( constructor(
remote: string | URL, remote: string | URL,
protocols: string | string[] | undefined = [], public protocols: string | string[] | undefined = [],
worker: WorkerConnection, worker: WorkerConnection,
requestHeaders?: BareHeaders, requestHeaders?: BareHeaders,
arrayBufferImpl?: ArrayBuffer,
) { ) {
super(); super();
this.url = remote.toString(); this.url = remote.toString();
this.protocols = protocols; this.protocols = protocols;
const onopen = (protocol: string) => { const onopen = (protocol: string) => {
this.readyState = WebSocketFields.OPEN;
this.protocols = protocol; this.protocols = protocol;
(this as any).meta = {
headers: {
"sec-websocket-protocol": protocol,
}
};
const event = new Event("open") const event = new Event("open")
this.dispatchEvent(event); this.dispatchEvent(event);
if (this.onopen) {
this.onopen(event);
}
}; };
const onmessage = async (payload) => { const onmessage = async (payload) => {
if (typeof payload === "string") {
} else if ("byteLength" in payload) {
if (this.binaryType === "blob") {
payload = new Blob([payload]);
} else {
Object.setPrototypeOf(payload, arrayBufferImpl);
}
} else if ("arrayBuffer" in payload) {
if (this.binaryType === "arraybuffer") {
payload = await payload.arrayBuffer()
Object.setPrototypeOf(payload, arrayBufferImpl);
}
}
const event = new MessageEvent("message", { data: payload }); const event = new MessageEvent("message", { data: payload });
this.dispatchEvent(event); this.dispatchEvent(event);
if (this.onmessage) {
this.onmessage(event);
}
}; };
const onclose = (code: number, reason: string) => { const onclose = (code: number, reason: string) => {
this.readyState = WebSocketFields.CLOSED;
const event = new CloseEvent("close", { code, reason }) const event = new CloseEvent("close", { code, reason })
this.dispatchEvent(event); this.dispatchEvent(event);
if (this.onclose) {
this.onclose(event);
}
}; };
const onerror = () => { const onerror = () => {
this.readyState = WebSocketFields.CLOSED;
const event = new Event("error"); const event = new Event("error");
this.dispatchEvent(event); this.dispatchEvent(event);
if (this.onerror) {
this.onerror(event);
};
}; };
this.channel = new MessageChannel(); this.channel = new MessageChannel();
@ -110,12 +66,6 @@ export class BareWebSocket extends EventTarget {
} }
send(...args) { send(...args) {
if (this.readyState === WebSocketFields.CONNECTING) {
throw new DOMException(
"Failed to execute 'send' on 'WebSocket': Still in CONNECTING state."
);
}
let data = args[0]; let data = args[0];
if (data.buffer) data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); if (data.buffer) data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
@ -123,30 +73,6 @@ export class BareWebSocket extends EventTarget {
} }
close(code, reason) { close(code, reason) {
this.readyState = WebSocketFields.CLOSING;
this.channel.port1.postMessage({ type: "close", closeCode: code, closeReason: reason }); this.channel.port1.postMessage({ type: "close", closeCode: code, closeReason: reason });
} }
get bufferedAmount() {
return 0;
} }
get protocol() {
if (Array.isArray(this.protocols)) {
return this.protocols[0] || "";
} else {
return this.protocols || "";
}
}
get extensions() {
return "";
}
}
//@ts-expect-error have to do this
BareWebSocket.prototype.CONNECTING = WebSocketFields.CONNECTING;
//@ts-expect-error have to do this
BareWebSocket.prototype.OPEN = WebSocketFields.OPEN;
//@ts-expect-error have to do this
BareWebSocket.prototype.CLOSING = WebSocketFields.CLOSING;
//@ts-expect-error have to do this
BareWebSocket.prototype.CLOSED = WebSocketFields.CLOSED;