import { generateUniqueNumber } from 'fast-unique-numbers';
import { renderUnknownPortIdError } from './error-renderers';
import { isSupportingTransferables } from './is-supporting-transferables';
const DESTROY_WORKER_FUNCTIONS = new Map();
export const extendWorkerImplementation = (createWorker, partialWorkerImplementation, isSupportedFunction) => ({
    ...partialWorkerImplementation,
    connect: ({ port }) => {
        port.start();
        const destroyWorker = createWorker(port, partialWorkerImplementation);
        const portId = generateUniqueNumber(DESTROY_WORKER_FUNCTIONS);
        DESTROY_WORKER_FUNCTIONS.set(portId, () => {
            destroyWorker();
            port.close();
            DESTROY_WORKER_FUNCTIONS.delete(portId);
        });
        return { result: portId };
    },
    disconnect: ({ portId }) => {
        const destroyWorker = DESTROY_WORKER_FUNCTIONS.get(portId);
        if (destroyWorker === undefined) {
            throw renderUnknownPortIdError(portId);
        }
        destroyWorker();
        return { result: null };
    },
    isSupported: async () => {
        const isSelfSupported = await isSupportingTransferables();
        if (isSelfSupported) {
            const result = isSupportedFunction();
            const synchronousResult = result instanceof Promise ? await result : result;
            return { result: synchronousResult };
        }
        return { result: false };
    }
});
//# sourceMappingURL=extend-worker-implementation.js.map