From 0a2a93a2093421534714487d65131f56f722e859 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 15 May 2023 23:36:36 -0700 Subject: [PATCH] adding worker thread messaging (try) --- src/esmockCache.js | 2 ++ src/esmockLoader.js | 10 +++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/esmockCache.js b/src/esmockCache.js index c092086a..67452496 100644 --- a/src/esmockCache.js +++ b/src/esmockCache.js @@ -7,6 +7,8 @@ const esmockCache = { } const esmockTreeIdSet = (key, keylong) => ( + (typeof global.postMessageEsmk === 'function') + && global.postMessageEsmk({ key, keylong }), global.mockKeys[String(key)] = keylong) const esmockTreeIdGet = key => ( diff --git a/src/esmockLoader.js b/src/esmockLoader.js index 6b5c3d74..1c0d1f97 100644 --- a/src/esmockLoader.js +++ b/src/esmockLoader.js @@ -1,4 +1,5 @@ import process from 'process' +import { isMainThread } from 'node:worker_threads' import urlDummy from './esmockDummy.js' import esmockErr from './esmockErr.js' @@ -16,6 +17,13 @@ const withHashRe = /.*#-#/ const isesmRe = /isesm=true/ const isnotfoundRe = /isfound=false/ +const globalPreload = isMainThread && (({ port }) => ( + port.addEventListener('message', ev => ( + global.mockKeys[ev.data.key] = ev.data.keylong)), + port.unref(), + 'global.postMessageEsmk = d => port.postMessage(d)' +)) + // new versions of node: when multiple loaders are used and context // is passed to nextResolve, the process crashes in a recursive call // see: /esmock/issues/#48 @@ -123,4 +131,4 @@ const load = async (url, context, nextLoad) => { // node lt 16.12 require getSource, node gte 16.12 warn remove getSource const getSource = isLT1612 && load -export {load, resolve, getSource, loaderIsVerified} +export {load, resolve, getSource, loaderIsVerified, globalPreload}