|
1 |
| -import { z } from "zod"; |
| 1 | +import { deserializeError, serializeError } from "serialize-error"; |
2 | 2 | import superjson from "superjson";
|
| 3 | +import { z } from "zod"; |
3 | 4 |
|
4 | 5 | const DEFAULT_TIMEOUT = 60000;
|
5 | 6 |
|
6 | 7 | export const RequestSchema = z.object({
|
7 |
| - method: z.string(), |
8 |
| - params: z.array(z.string()).optional(), |
| 8 | + method: z.string(), |
| 9 | + params: z.array(z.string()).optional(), |
9 | 10 | });
|
10 | 11 |
|
11 | 12 | type RequestParams = z.infer<typeof RequestSchema>;
|
12 | 13 |
|
13 | 14 | export const ResponseSchema = z
|
14 |
| - .object({ |
15 |
| - id: z.string(), |
16 |
| - result: z.any().optional(), |
17 |
| - error: z.string().optional(), |
18 |
| - }) |
19 |
| - .strict(); |
| 15 | + .object({ |
| 16 | + id: z.string(), |
| 17 | + result: z.any().optional(), |
| 18 | + error: z.string().optional(), |
| 19 | + }) |
| 20 | + .strict(); |
20 | 21 |
|
21 | 22 | type Response = z.infer<typeof ResponseSchema>;
|
22 | 23 |
|
23 | 24 | export type RequestFn = (params: RequestParams) => Promise<Response>;
|
24 | 25 |
|
25 | 26 | export const createRpc = ({
|
26 |
| - worker, |
27 |
| - timeout, |
| 27 | + worker, |
| 28 | + timeout, |
28 | 29 | }: {
|
29 |
| - worker: Worker; |
30 |
| - timeout?: number; |
| 30 | + worker: Worker; |
| 31 | + timeout?: number; |
31 | 32 | }) => {
|
32 |
| - const request: RequestFn = async ({ method, params }) => { |
33 |
| - let resolved = false; |
34 |
| - return new Promise((resolve, reject) => { |
35 |
| - console.log('>>>M', method, params) |
36 |
| - setTimeout(() => { |
37 |
| - if (resolved) return; |
38 |
| - return reject(new Error("[WorkerRPC] Timeout reached.")); |
39 |
| - }, timeout ?? DEFAULT_TIMEOUT); |
40 |
| - const responseListener = (event: MessageEvent) => { |
41 |
| - resolved = true; |
42 |
| - worker.removeEventListener("message", responseListener); |
43 |
| - const data = superjson.parse(event.data); |
44 |
| - const response = ResponseSchema.parse(data); |
45 |
| - if (response.error) |
46 |
| - return reject(new Error(`[WorkerRPC] ${response.error}`)); |
47 |
| - return resolve(response); |
48 |
| - }; |
49 |
| - worker.addEventListener("message", responseListener); |
50 |
| - worker.postMessage({ method, params }); |
51 |
| - }); |
52 |
| - }; |
53 |
| - return { |
54 |
| - request, |
55 |
| - }; |
| 33 | + const request: RequestFn = async ({ method, params }) => { |
| 34 | + let resolved = false; |
| 35 | + return new Promise((resolve, reject) => { |
| 36 | + setTimeout(() => { |
| 37 | + if (resolved) return; |
| 38 | + return reject(new Error("[WorkerRPC] Timeout reached.")); |
| 39 | + }, timeout ?? DEFAULT_TIMEOUT); |
| 40 | + const responseListener = (event: MessageEvent) => { |
| 41 | + resolved = true; |
| 42 | + worker.removeEventListener("message", responseListener); |
| 43 | + const data = superjson.parse(event.data); |
| 44 | + const response = ResponseSchema.parse(data); |
| 45 | + if (response.error) { |
| 46 | + const errorObject = superjson.parse(response.error); |
| 47 | + const deserializedError = deserializeError(errorObject); |
| 48 | + return reject(deserializedError); |
| 49 | + } |
| 50 | + return resolve(response); |
| 51 | + }; |
| 52 | + worker.addEventListener("message", responseListener); |
| 53 | + worker.postMessage({ method, params }); |
| 54 | + }); |
| 55 | + }; |
| 56 | + return { |
| 57 | + request, |
| 58 | + }; |
56 | 59 | };
|
57 | 60 |
|
58 | 61 | type Method = (params: string[]) => Promise<unknown>;
|
59 | 62 | type MethodsMap = Record<string, Method>;
|
60 | 63 |
|
61 |
| -const respond = (data: unknown) => postMessage(superjson.stringify(data)) |
| 64 | +const respond = (data: unknown) => postMessage(superjson.stringify(data)); |
62 | 65 |
|
63 | 66 | export const createRpcHandler = ({ methods }: { methods: MethodsMap }) => {
|
64 |
| - const methodKeys = Object.keys(methods); |
65 |
| - if (methodKeys.length === 0) throw new Error("No methods provided."); |
66 |
| - const MethodEnum = z.enum(['error', ...methodKeys]); |
67 |
| - const ExtendedRequestSchema = RequestSchema.extend({ |
68 |
| - method: MethodEnum, |
69 |
| - }).strict(); |
70 |
| - const ExtendedResponseSchema = ResponseSchema.extend({ |
71 |
| - id: MethodEnum, |
72 |
| - }).strict(); |
73 |
| - const messageHandler = async (event: MessageEvent) => { |
74 |
| - try { |
75 |
| - const action = ExtendedRequestSchema.parse(event.data) |
76 |
| - const callable = methods[action.method] |
77 |
| - if (!callable) throw new Error(`Method "${action.method}" not found.`); |
78 |
| - const result = await callable(action.params ?? []); |
79 |
| - const parsedResult = ExtendedResponseSchema.parse({ |
80 |
| - id: action.method, |
81 |
| - result, |
82 |
| - }); |
83 |
| - return respond(parsedResult); |
84 |
| - // biome-ignore lint/suspicious/noExplicitAny: Error handling |
85 |
| - } catch (error: any) { |
86 |
| - return respond(ExtendedResponseSchema.parse({ |
87 |
| - id: 'error', |
88 |
| - error: `[WorkerRPC] ${error.message}`, |
89 |
| - })); |
90 |
| - } |
91 |
| - }; |
92 |
| - return { messageHandler }; |
| 67 | + const methodKeys = Object.keys(methods); |
| 68 | + if (methodKeys.length === 0) throw new Error("No methods provided."); |
| 69 | + const MethodEnum = z.enum(["error", ...methodKeys]); |
| 70 | + const ExtendedRequestSchema = RequestSchema.extend({ |
| 71 | + method: MethodEnum, |
| 72 | + }).strict(); |
| 73 | + const ExtendedResponseSchema = ResponseSchema.extend({ |
| 74 | + id: MethodEnum, |
| 75 | + }).strict(); |
| 76 | + const messageHandler = async (event: MessageEvent) => { |
| 77 | + try { |
| 78 | + const action = ExtendedRequestSchema.parse(event.data); |
| 79 | + const callable = methods[action.method]; |
| 80 | + if (!callable) throw new Error(`Method "${action.method}" not found.`); |
| 81 | + const result = await callable(action.params ?? []); |
| 82 | + const parsedResult = ExtendedResponseSchema.parse({ |
| 83 | + id: action.method, |
| 84 | + result, |
| 85 | + }); |
| 86 | + return respond(parsedResult); |
| 87 | + // biome-ignore lint/suspicious/noExplicitAny: Error handling |
| 88 | + } catch (error: any) { |
| 89 | + const serializedError = superjson.stringify(serializeError(error)); |
| 90 | + return respond( |
| 91 | + ExtendedResponseSchema.parse({ |
| 92 | + id: "error", |
| 93 | + error: serializedError, |
| 94 | + }), |
| 95 | + ); |
| 96 | + } |
| 97 | + }; |
| 98 | + return { messageHandler }; |
93 | 99 | };
|
0 commit comments