| 141 | * @param [options.timeout] Init message timeout. Default: 10000 or set by environment variable. |
| 142 | */ |
| 143 | export async function spawn<Exposed extends WorkerFunction | WorkerModule<any> = ArbitraryWorkerInterface>( |
| 144 | worker: WorkerType, |
| 145 | options?: { timeout?: number } |
| 146 | ): Promise<ExposedToThreadType<Exposed>> { |
| 147 | debugSpawn("Initializing new thread") |
| 148 | |
| 149 | const timeout = options && options.timeout ? options.timeout : initMessageTimeout |
| 150 | const initMessage = await withTimeout(receiveInitMessage(worker), timeout, `Timeout: Did not receive an init message from worker after ${timeout}ms. Make sure the worker calls expose().`) |
| 151 | const exposed = initMessage.exposed |
| 152 | |
| 153 | const { termination, terminate } = createTerminator(worker) |
| 154 | const events = createEventObservable(worker, termination) |
| 155 | |
| 156 | if (exposed.type === "function") { |
| 157 | const proxy = createProxyFunction(worker) |
| 158 | return setPrivateThreadProps(proxy, worker, events, terminate) as ExposedToThreadType<Exposed> |
| 159 | } else if (exposed.type === "module") { |
| 160 | const proxy = createProxyModule(worker, exposed.methods) |
| 161 | return setPrivateThreadProps(proxy, worker, events, terminate) as ExposedToThreadType<Exposed> |
| 162 | } else { |
| 163 | const type = (exposed as WorkerInitMessage["exposed"]).type |
| 164 | throw Error(`Worker init message states unexpected type of expose(): ${type}`) |
| 165 | } |
| 166 | } |