diff --git a/src/client.ts b/src/client.ts index 544a298..485ccae 100644 --- a/src/client.ts +++ b/src/client.ts @@ -98,8 +98,8 @@ export interface BareResponseFetch extends BareResponse { export class BareMuxConnection { worker: WorkerConnection; - constructor(workerPath: string) { - this.worker = new WorkerConnection(workerPath); + constructor(worker: string | Promise | MessagePort) { + this.worker = new WorkerConnection(worker); } async getTransport(): Promise { @@ -168,7 +168,7 @@ export class BareClient { /** * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready. */ - constructor(worker?: string | MessagePort) { + constructor(worker?: string | Promise | MessagePort) { this.worker = new WorkerConnection(worker); } diff --git a/src/connection.ts b/src/connection.ts index 57053f7..2c4b8af 100644 --- a/src/connection.ts +++ b/src/connection.ts @@ -47,10 +47,14 @@ async function searchForPort(): Promise { await testPort(port); return port; }); - const promise: Promise = Promise.race([Promise.any(promises), new Promise((_, reject) => setTimeout(reject, 1000, new TypeError("timeout")))]) as Promise; + const promise: Promise = Promise.race([ + Promise.any(promises), + new Promise((_, reject) => setTimeout(reject, 1000, new TypeError("timeout"))) + ]) as Promise; + try { return await promise; - } catch(err) { + } catch (err) { if (err instanceof AggregateError) { console.error("bare-mux: failed to get a bare-mux SharedWorker MessagePort as all clients returned an invalid MessagePort."); throw new Error("All clients returned an invalid MessagePort."); @@ -108,7 +112,7 @@ export function browserSupportsTransferringStreams(): boolean { try { chan.port1.postMessage(stream, [stream]); res = true; - } catch(err) { + } catch (err) { res = false; } browserSupportsTransferringStreamsCache = res; @@ -123,9 +127,9 @@ export class WorkerConnection { port: MessagePort | Promise; workerPath: string; - constructor(worker?: string | MessagePort) { + constructor(worker?: string | Promise | MessagePort) { this.channel = new BroadcastChannel("bare-mux"); - if (worker instanceof MessagePort) { + if (worker instanceof MessagePort || worker instanceof Promise) { this.port = worker; } else { this.createChannel(worker, true);