From: Chris Duncan Date: Thu, 5 Dec 2024 13:24:11 +0000 (-0800) Subject: Testing fixes to worker polyfill. X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=1701644ce372c8a7645828bcde5f2821699b604e;p=libnemo.git Testing fixes to worker polyfill. --- diff --git a/src/lib/bip44-ckd.ts b/src/lib/bip44-ckd.ts index b6ed3a5..00a6dce 100644 --- a/src/lib/bip44-ckd.ts +++ b/src/lib/bip44-ckd.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: 2024 Chris Duncan // SPDX-License-Identifier: GPL-3.0-or-later +import { isMainThread, parentPort } from 'node:worker_threads' + type ExtendedKey = { privateKey: DataView chainCode: DataView @@ -10,17 +12,23 @@ const b = () => { /** * Polyfill for window methods which do not exist when executing Node.js tests. */ + console.log(`isMainThread: ${isMainThread}`) + console.log(`parentPort: ${parentPort}`) if (typeof window === 'undefined' && typeof self === 'undefined') { + console.log(`in one`) try { - import('node:worker_threads').then(worker_threads => { - const { isMainThread, parentPort } = worker_threads - if (!isMainThread && parentPort) { - var addEventListener = Object.getPrototypeOf(parentPort).addListener.bind(parentPort) - var postMessage = Object.getPrototypeOf(parentPort).postMessage.bind(parentPort) - } - }) + if (!isMainThread && parentPort) { + console.log(`in two`) + //@ts-expect-error + var addEventListener = addEventListener || Object.getPrototypeOf(parentPort).addListener.bind(parentPort) + //@ts-expect-error + var postMessage = postMessage || Object.getPrototypeOf(parentPort).postMessage.bind(parentPort) + } } catch { } } + console.log(`typeof addEventListener: ${typeof addEventListener}`) + console.log(`typeof postMessage: ${typeof postMessage}`) + console.log(' ') const BIP44_COIN_NANO = 165 const BIP44_PURPOSE = 44 @@ -32,10 +40,10 @@ const b = () => { */ if (typeof addEventListener === 'function') { addEventListener('message', (message: any): void => { + console.log(`bip44 worker`) const data = JSON.parse(new TextDecoder().decode(message.data ?? message)) calculate(data).then(results => { const buf = new TextEncoder().encode(JSON.stringify(results)).buffer - //@ts-expect-error postMessage(buf, [buf]) }) }) @@ -135,4 +143,8 @@ export const Bip44Ckd = b() const start = b.toString().indexOf('{') + 1 const end = b.toString().lastIndexOf('return') -export const worker = b.toString().substring(start, end) +let worker_threads = '' +if (typeof window === 'undefined' && typeof self === 'undefined') { + worker_threads += `import { isMainThread, parentPort } from 'node:worker_threads'\n` +} +export const worker = worker_threads + b.toString().substring(start, end)