1 import { throwError } from '@proton/pass/utils/fp/throw';
3 import { WASM_PROCEDURE_TIMEOUT } from './constants';
4 import type { PassCoreMethod, PassCoreRPC, PassCoreResult, PassCoreService } from './types';
6 /** Creates a `PassCoreService` instance which spawns the `PassRustCore`
7 * binary in a dedicated worker. Communication occurs via postMessaging
8 * through MessageChannels (see: `core.worker.ts`) This service should
9 * be used to ensure the WASM module will not block the main UI thread */
10 export const createPassCoreWorkerService = (): PassCoreService => {
11 const worker = new Worker(
12 /* webpackChunkName: "core.worker" */
13 new URL('@proton/pass/lib/core/core.worker', import.meta.url)
16 const send = <T extends PassCoreMethod>(message: PassCoreRPC<T>) => {
17 const channel = new MessageChannel();
19 return new Promise<PassCoreResult<T>>((resolve, reject) => {
20 const timer = setTimeout(
21 () => reject(new Error(`[PassCoreWorker] Procedure timed out [${message.method}]`)),
22 WASM_PROCEDURE_TIMEOUT
25 channel.port2.onmessage = (event: MessageEvent<PassCoreResult<T>>) => {
30 worker.postMessage(message, [channel.port1]);
32 .catch((err) => throwError({ name: 'PassCoreServiceError', message: err.message }))
34 channel.port1.close();
35 channel.port2.close();
39 return { exec: (method, ...args) => send({ method, args }) };