import os from 'node:os';
import { Worker as NodeWorker, parentPort } from 'node:worker_threads';
/** Worker polyfill */
export class Worker extends EventTarget {
    constructor(scriptURL, options) {
        super();
        this.onmessage = null;
        this.onmessageerror = null;
        this.onerror = null;
        this._worker = new NodeWorker(scriptURL, options);
        this._worker.on('message', (data) => {
            const ev = new MessageEvent('message', { data });
            this.dispatchEvent(ev);
            if (this.onmessage) {
                this.onmessage(ev);
            }
        });
        this._worker.on('messageerror', (data) => {
            const ev = new MessageEvent('messageerror', { data });
            this.dispatchEvent(ev);
            if (this.onmessageerror) {
                this.onmessageerror(ev);
            }
        });
        this._worker.on('error', (error) => {
            const ev = new Event('error', {});
            Object.defineProperty(ev, 'error', { value: error, configurable: true });
            this.dispatchEvent(ev);
            if (this.onerror) {
                this.onerror(ev);
            }
        });
    }
    /** @inheritdoc */
    postMessage(data, transfer) {
        let t = [];
        if (!transfer) {
            //
        }
        else if (Array.isArray(transfer)) {
            t = transfer;
        }
        else if (transfer.transfer) {
            t = transfer.transfer;
        }
        this._worker.postMessage(data, t);
    }
    /** @inheritdoc */
    terminate() {
        void this._worker.terminate();
    }
}
/** add message callback */
export function onMessage(callback) {
    parentPort.on('message', callback);
}
/** post message */
export function postMessage(value, transfer) {
    parentPort.postMessage(value, transfer);
}
export const MAX_WORKERS = Math.max(os.availableParallelism?.() ?? os.cpus().length, 2) - 1;
export { TransformStream } from 'node:stream/web';
//# sourceMappingURL=node.js.map