// Runs a user-written dither script off the main thread, so a slow or endless script can be // stopped (the page terminates the worker) and cannot reach the editor's DOM or state. import { scriptApi } from './dither.js'; const HEADER_LINES = 3; // "function anonymous(img,api\n) {\n"use strict";\n" precedes the source self.onmessage = (e) => { const { source, img, levels } = e.data; let fn; try { fn = new Function('img', 'api', `"use strict";\n${source}`); } catch (err) { self.postMessage({ ok: false, error: `Syntax error: ${err.message}` }); return; } try { const t0 = performance.now(); fn(img, scriptApi(img, levels)); const ms = performance.now() - t0; self.postMessage({ ok: true, data: img.data, ms }, img.data instanceof Float32Array ? [img.data.buffer] : []); } catch (err) { const m = /:(\d+):\d+/.exec(String(err?.stack || '')); const line = m ? Number(m[1]) - HEADER_LINES : 0; self.postMessage({ ok: false, error: `${err?.name || 'Error'}: ${err?.message ?? err}${line > 0 ? ` (line ${line})` : ''}` }); } };