| 420 | const buffer: Array<[I, ReadonlyArray<unknown> | undefined]> = [] |
| 421 | |
| 422 | const run = <A, E, R>( |
| 423 | handler: (_: Worker.BackingWorker.Message<O>) => Effect.Effect<A, E, R> |
| 424 | ): Effect.Effect<never, WorkerError | E, R> => |
| 425 | Effect.uninterruptibleMask((restore) => |
| 426 | Effect.gen(function*() { |
| 427 | const scope = yield* Effect.scope |
| 428 | const port = yield* options.setup({ worker: spawn(id), scope }) |
| 429 | currentPort = port |
| 430 | yield* Scope.addFinalizer( |
| 431 | scope, |
| 432 | Effect.sync(() => { |
| 433 | currentPort = undefined |
| 434 | }) |
| 435 | ) |
| 436 | const runtime = (yield* Effect.runtime<R | Scope.Scope>()).pipe( |
| 437 | Runtime.updateContext(Context.omit(Scope.Scope)) |
| 438 | ) as Runtime.Runtime<R> |
| 439 | const fiberSet = yield* FiberSet.make<any, WorkerError | E>() |
| 440 | const runFork = Runtime.runFork(runtime) |
| 441 | yield* options.listen({ |
| 442 | port, |
| 443 | scope, |
| 444 | emit(data) { |
| 445 | FiberSet.unsafeAdd(fiberSet, runFork(handler(data))) |
| 446 | }, |
| 447 | deferred: fiberSet.deferred as any |
| 448 | }) |
| 449 | if (buffer.length > 0) { |
| 450 | for (const [message, transfers] of buffer) { |
| 451 | port.postMessage([0, message], transfers as any) |
| 452 | } |
| 453 | buffer.length = 0 |
| 454 | } |
| 455 | return (yield* restore(FiberSet.join(fiberSet))) as never |
| 456 | }).pipe(Effect.scoped) |
| 457 | ) |
| 458 | |
| 459 | const send = (message: I, transfers?: ReadonlyArray<unknown>) => |
| 460 | Effect.try({ |