mirror of
https://github.com/codedread/bitjs
synced 2025-10-04 01:59:15 +02:00
Add some unit tests for unarchivers. Provide a way to disconnect the impl from the host (for unit tests).
This commit is contained in:
parent
eba7042abe
commit
cf26e0a2de
17 changed files with 211 additions and 13 deletions
|
@ -10,6 +10,12 @@
|
|||
|
||||
// Requires the following JavaScript features: MessageChannel, MessagePort, and dynamic imports.
|
||||
|
||||
/**
|
||||
* @typedef Implementation
|
||||
* @property {MessagePort} hostPort The port the host uses to communicate with the implementation.
|
||||
* @property {Function} disconnectFn A function to call when the port has been disconnected.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connects a host to a compress/decompress implementation via MessagePorts. The implementation must
|
||||
* have an exported connect() function that accepts a MessagePort. If the runtime support Workers
|
||||
|
@ -17,8 +23,9 @@
|
|||
* dynamically imports the implementation inside the current JS context (node, bun).
|
||||
* @param {string} implFilename The compressor/decompressor implementation filename relative to this
|
||||
* path (e.g. './unzip.js').
|
||||
* @returns {Promise<MessagePort>} The Promise resolves to the MessagePort connected to the
|
||||
* implementation that the host should use.
|
||||
* @param {Function} disconnectFn A function to run when the port is disconnected.
|
||||
* @returns {Promise<Implementation>} The Promise resolves to the Implementation, which includes the
|
||||
* MessagePort connected to the implementation that the host should use.
|
||||
*/
|
||||
export async function getConnectedPort(implFilename) {
|
||||
const messageChannel = new MessageChannel();
|
||||
|
@ -28,13 +35,19 @@ export async function getConnectedPort(implFilename) {
|
|||
if (typeof Worker === 'undefined') {
|
||||
const implModule = await import(`${implFilename}`);
|
||||
await implModule.connect(implPort);
|
||||
return hostPort;
|
||||
return {
|
||||
hostPort,
|
||||
disconnectFn: () => implModule.disconnect(),
|
||||
};
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const workerScriptPath = new URL(`./webworker-wrapper.js`, import.meta.url).href;
|
||||
const worker = new Worker(workerScriptPath, { type: 'module' });
|
||||
worker.postMessage({ implSrc: implFilename }, [implPort]);
|
||||
resolve(hostPort);
|
||||
resolve({
|
||||
hostPort,
|
||||
disconnectFn: () => worker.postMessage({ disconnect: true }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue