diff --git a/src/index.js b/src/index.js index 5a219c1..aaf869b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,3 @@ - /** TODO: * - pooling (+ load balancing by tracking # of open calls) * - queueing (worth it? sortof free via postMessage already) @@ -23,11 +22,34 @@ export default function workerize(code, options) { if (typeof code==='function') code = `(${Function.prototype.toString.call(code)})(${exportsObjName})`; code = toCjs(code, exportsObjName, exports) + `\n(${Function.prototype.toString.call(setup)})(self,${exportsObjName},{})`; let url = URL.createObjectURL(new Blob([code])), - worker = new Worker(url, options), - term = worker.terminate, callbacks = {}, counter = 0, + worker, + term, i; + + try { + worker = new Worker(url, options); + term = worker.terminate; + } catch (err) { + // TODO: How to indicate the fallback? console.warn? Property on the export? + // TODO: What's the right way to access the original exports? + const originalExports = new Function(code + `\nreturn ${exportsObjName}`)(); + // TODO: Is this the full API? Do we need to add anything else? + worker = { + kill() {}, + terminate() {}, + expose(methodName) { + worker[i] = function() { + return Promise.resolve().then(() => originalExports[i]([].slice.call(arguments))); + }; + }, + }; + // TODO: Extract to function since it's used below or fine as is? + for (i in exports) if (!(i in worker)) worker.expose(i); + return worker; + } + worker.kill = signal => { worker.postMessage({ type: 'KILL', signal }); setTimeout(worker.terminate);