Skip to content

Commit 5a91a3d

Browse files
committed
Prepend ws protocol if none is present
1 parent 9f37702 commit 5a91a3d

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/Socket.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ export const debug = debugLib('obs-websocket-js:Socket');
1111

1212
export type ConnectArgs = {
1313
address: string;
14-
secure: boolean;
1514
password: string;
1615
};
1716

@@ -26,9 +25,8 @@ export abstract class Socket extends EventEmitter<EventHandlersDataMap> {
2625

2726
async connect(args: Partial<ConnectArgs> = {}): Promise<void> {
2827
const parsedArgs = {
29-
address: 'localhost:4444',
28+
address: 'ws://localhost:4444',
3029
password: '',
31-
secure: false,
3230
...args,
3331
};
3432

@@ -45,7 +43,7 @@ export abstract class Socket extends EventEmitter<EventHandlersDataMap> {
4543
}
4644

4745
try {
48-
await this.connect0(parsedArgs.address, parsedArgs.secure);
46+
await this.connect0(parsedArgs.address);
4947
await this.authenticate(parsedArgs.password);
5048
} catch (e: unknown) {
5149
this.socket.close();
@@ -82,19 +80,21 @@ export abstract class Socket extends EventEmitter<EventHandlersDataMap> {
8280
/**
8381
* Opens a WebSocket connection to an obs-websocket server, but does not attempt any authentication.
8482
*
85-
* @param {String} address url without ws:// or wss:// prefix.
86-
* @param {Boolean} secure whether to us ws:// or wss://
83+
* @param {String} address url with or without ws:// or wss:// prefix.
8784
* @returns {Promise}
8885
* @private
8986
* @return {Promise} on attempted creation of WebSocket connection.
9087
*/
91-
private async connect0(address: string, secure: boolean): Promise<void> {
88+
private async connect0(address: string): Promise<void> {
9289
// We need to wrap this in a promise so we can resolve only when connected
9390
return new Promise<void>((resolve, reject): void => {
9491
let settled = false;
92+
// Check if the address starts with a prefix and prepend if needed
93+
const regex = /^wss?:\/\//i;
94+
const parsedAddress = `${regex.test(address) ? '' : 'ws://'}${address}`;
9595

96-
debug('Attempting to connect to: %s (secure: %s)', address, secure);
97-
this.socket = new WebSocket((secure ? 'wss://' : 'ws://') + address);
96+
debug('Attempting to connect to: %s', parsedAddress);
97+
this.socket = new WebSocket(parsedAddress);
9898

9999
// We only handle the initial connection error.
100100
// Beyond that, the consumer is responsible for adding their own generic `error` event listener.

0 commit comments

Comments
 (0)