From 6e60133ef70faa65bb69e25a109ebe85e3bb8c72 Mon Sep 17 00:00:00 2001 From: Mikael Finstad Date: Tue, 6 Aug 2024 16:04:27 +0200 Subject: [PATCH] try to fix broken expressions (in production) - fixes #2059 also type and log worker error early --- src/renderer/src/worker/eval.ts | 38 ++++++++++++++++++++++----- src/renderer/src/worker/evalWorker.ts | 15 +++++++---- tsconfig.web.json | 2 ++ 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/renderer/src/worker/eval.ts b/src/renderer/src/worker/eval.ts index a14bd0ed..abbf2635 100644 --- a/src/renderer/src/worker/eval.ts +++ b/src/renderer/src/worker/eval.ts @@ -1,8 +1,28 @@ -const workerUrl = new URL('evalWorker.js', import.meta.url); +import invariant from 'tiny-invariant'; + +// https://github.com/vitejs/vite/issues/11823#issuecomment-1407277242 +// https://github.com/mifi/lossless-cut/issues/2059 +import Worker from './evalWorker?worker'; + + +export interface RequestMessageData { + code: string, + id: number, + context: string // json +} + +export type ResponseMessageData = { id: number } & ({ + error: string, +} | { + data: unknown, +}) // https://v3.vitejs.dev/guide/features.html#web-workers // todo terminate() and recreate in case of error? -const worker = new Worker(workerUrl); +const worker = new Worker(); +worker.addEventListener('error', (err) => { + console.error('evalWorker error', err); +}); let lastRequestId = 0; @@ -22,13 +42,17 @@ export default async function safeishEval(code: string, context: Record { + onmessage = (event: MessageEvent) => { // eslint-disable-next-line strict, lines-around-directive 'use strict'; @@ -130,9 +135,9 @@ myGlobal.fetch = undefined; // https://stackoverflow.com/questions/8403108/calling-eval-in-particular-context // eslint-disable-next-line unicorn/new-for-builtins, no-new-func const result = Function(`\nwith (this) { return (${code}); }`).call(context); - postMessage({ id, data: result }); + postMessage({ id, data: result } satisfies ResponseMessageData); } catch (e) { - postMessage({ id, error: `${e}` }); + postMessage({ id, error: `${e}` } satisfies ResponseMessageData); } }; })(); diff --git a/tsconfig.web.json b/tsconfig.web.json index 56a2e8c4..3eb0d857 100644 --- a/tsconfig.web.json +++ b/tsconfig.web.json @@ -5,6 +5,8 @@ "noEmit": true, "noImplicitAny": false, // todo + + "types": ["vite/client"], }, "references": [ { "path": "./tsconfig.main.json" },