Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / lib / core / worker.service.ts
blob6a82d416bb1a16c6c43a2b698b591bc83b5cfb5d
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)
14     );
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('PassRustCore procedure timed out')),
22                 WASM_PROCEDURE_TIMEOUT
23             );
25             channel.port2.onmessage = (event: MessageEvent<PassCoreResult<T>>) => {
26                 resolve(event.data);
27                 clearTimeout(timer);
28             };
30             worker.postMessage(message, [channel.port1]);
31         })
32             .catch((err) => throwError({ name: 'PassCoreServiceError', message: err.message }))
33             .finally(() => {
34                 channel.port1.close();
35                 channel.port2.close();
36             });
37     };
39     return { exec: (method, ...args) => send({ method, args }) };