troika-worker-utils
Advanced tools
Comparing version 0.33.0 to 0.34.0
@@ -0,0 +0,0 @@ /** |
@@ -0,0 +0,0 @@ const promisesAplusTests = require('promises-aplus-tests') |
@@ -0,0 +0,0 @@ require('./_jsdom-worker.js') |
@@ -0,0 +0,0 @@ require('./_jsdom-worker.js') |
@@ -6,2 +6,11 @@ # Change Log | ||
# [0.34.0](https://github.com/protectwise/troika/compare/v0.33.1...v0.34.0) (2020-10-19) | ||
**Note:** Version bump only for package troika-worker-utils | ||
# [0.33.0](https://github.com/protectwise/troika/compare/v0.32.0...v0.33.0) (2020-10-02) | ||
@@ -8,0 +17,0 @@ |
@@ -20,20 +20,20 @@ /** | ||
function BespokeThenable() { | ||
let state = 0; // 0=pending, 1=fulfilled, -1=rejected | ||
let queue = []; | ||
let value; | ||
let scheduled = 0; | ||
let completeCalled = 0; | ||
var state = 0; // 0=pending, 1=fulfilled, -1=rejected | ||
var queue = []; | ||
var value; | ||
var scheduled = 0; | ||
var completeCalled = 0; | ||
function then(onResolve, onReject) { | ||
const nextThenable = BespokeThenable(); | ||
var nextThenable = BespokeThenable(); | ||
function handleNext() { | ||
const cb = state > 0 ? onResolve : onReject; | ||
var cb = state > 0 ? onResolve : onReject; | ||
if (isFn(cb)) { | ||
try { | ||
const result = cb(value); | ||
var result = cb(value); | ||
if (result === nextThenable) { | ||
recursiveError(); | ||
} | ||
const resultThen = getThenableThen(result); | ||
var resultThen = getThenableThen(result); | ||
if (resultThen) { | ||
@@ -59,3 +59,3 @@ resultThen.call(result, nextThenable.resolve, nextThenable.reject); | ||
const resolve = oneTime(val => { | ||
var resolve = oneTime(function (val) { | ||
if (!completeCalled) { | ||
@@ -66,3 +66,3 @@ complete(1, val); | ||
const reject = oneTime(reason => { | ||
var reject = oneTime(function (reason) { | ||
if (!completeCalled) { | ||
@@ -75,3 +75,3 @@ complete(-1, reason); | ||
completeCalled++; | ||
let ignoreThrow = 0; | ||
var ignoreThrow = 0; | ||
try { | ||
@@ -81,8 +81,8 @@ if (val === thenableObj) { | ||
} | ||
const valThen = st > 0 && getThenableThen(val); | ||
var valThen = st > 0 && getThenableThen(val); | ||
if (valThen) { | ||
valThen.call(val, oneTime(v => { | ||
valThen.call(val, oneTime(function (v) { | ||
ignoreThrow++; | ||
complete(1, v); | ||
}), oneTime(v => { | ||
}), oneTime(function (v) { | ||
ignoreThrow++; | ||
@@ -111,3 +111,3 @@ complete(-1, v); | ||
function flushQueue() { | ||
const q = queue; | ||
var q = queue; | ||
scheduled = 0; | ||
@@ -123,3 +123,3 @@ queue = []; | ||
function getThenableThen(val) { | ||
const valThen = val && (isFn(val) || typeof val === 'object') && val.then; | ||
var valThen = val && (isFn(val) || typeof val === 'object') && val.then; | ||
return isFn(valThen) && valThen | ||
@@ -129,4 +129,7 @@ } | ||
function oneTime(fn) { | ||
let called = 0; | ||
return function(...args) { | ||
var called = 0; | ||
return function() { | ||
var args = [], len = arguments.length; | ||
while ( len-- ) args[ len ] = arguments[ len ]; | ||
if (!called++) { | ||
@@ -142,8 +145,8 @@ fn.apply(this, args); | ||
const isFn = v => typeof v === 'function'; | ||
var isFn = function (v) { return typeof v === 'function'; }; | ||
const thenableObj = { | ||
then, | ||
resolve, | ||
reject | ||
var thenableObj = { | ||
then: then, | ||
resolve: resolve, | ||
reject: reject | ||
}; | ||
@@ -160,4 +163,4 @@ return thenableObj | ||
function NativePromiseThenable() { | ||
let resolve, reject; | ||
const promise = new Promise((res, rej) => { | ||
var resolve, reject; | ||
var promise = new Promise(function (res, rej) { | ||
resolve = res; | ||
@@ -168,4 +171,4 @@ reject = rej; | ||
then: promise.then.bind(promise), | ||
resolve, | ||
reject | ||
resolve: resolve, | ||
reject: reject | ||
} | ||
@@ -178,12 +181,12 @@ } | ||
BespokeThenable.all = NativePromiseThenable.all = function(items) { | ||
let resultCount = 0; | ||
let results = []; | ||
let out = DefaultThenable(); | ||
var resultCount = 0; | ||
var results = []; | ||
var out = DefaultThenable(); | ||
if (items.length === 0) { | ||
out.resolve([]); | ||
} else { | ||
items.forEach((item, i) => { | ||
let itemThenable = DefaultThenable(); | ||
items.forEach(function (item, i) { | ||
var itemThenable = DefaultThenable(); | ||
itemThenable.resolve(item); | ||
itemThenable.then(res => { | ||
itemThenable.then(function (res) { | ||
resultCount++; | ||
@@ -204,3 +207,3 @@ results[i] = res; | ||
*/ | ||
const DefaultThenable = typeof Promise === 'function' ? NativePromiseThenable : BespokeThenable; | ||
var DefaultThenable = typeof Promise === 'function' ? NativePromiseThenable : BespokeThenable; | ||
@@ -212,15 +215,21 @@ /** | ||
function workerBootstrap() { | ||
const modules = Object.create(null); | ||
var modules = Object.create(null); | ||
// Handle messages for registering a module | ||
function registerModule({id, name, dependencies=[], init=function(){}, getTransferables=null}, callback) { | ||
function registerModule(ref, callback) { | ||
var id = ref.id; | ||
var name = ref.name; | ||
var dependencies = ref.dependencies; if ( dependencies === void 0 ) dependencies = []; | ||
var init = ref.init; if ( init === void 0 ) init = function(){}; | ||
var getTransferables = ref.getTransferables; if ( getTransferables === void 0 ) getTransferables = null; | ||
// Only register once | ||
if (modules[id]) return | ||
if (modules[id]) { return } | ||
try { | ||
// If any dependencies are modules, ensure they're registered and grab their value | ||
dependencies = dependencies.map(dep => { | ||
dependencies = dependencies.map(function (dep) { | ||
if (dep && dep.isWorkerModule) { | ||
registerModule(dep, depResult => { | ||
if (depResult instanceof Error) throw depResult | ||
registerModule(dep, function (depResult) { | ||
if (depResult instanceof Error) { throw depResult } | ||
}); | ||
@@ -233,11 +242,11 @@ dep = modules[dep.id].value; | ||
// Rehydrate functions | ||
init = rehydrate(`<${name}>.init`, init); | ||
init = rehydrate(("<" + name + ">.init"), init); | ||
if (getTransferables) { | ||
getTransferables = rehydrate(`<${name}>.getTransferables`, getTransferables); | ||
getTransferables = rehydrate(("<" + name + ">.getTransferables"), getTransferables); | ||
} | ||
// Initialize the module and store its value | ||
let value = null; | ||
var value = null; | ||
if (typeof init === 'function') { | ||
value = init(...dependencies); | ||
value = init.apply(void 0, dependencies); | ||
} else { | ||
@@ -247,5 +256,5 @@ console.error('worker module init function failed to rehydrate'); | ||
modules[id] = { | ||
id, | ||
value, | ||
getTransferables | ||
id: id, | ||
value: value, | ||
getTransferables: getTransferables | ||
}; | ||
@@ -262,10 +271,14 @@ callback(value); | ||
// Handle messages for calling a registered module's result function | ||
function callModule({id, args}, callback) { | ||
function callModule(ref, callback) { | ||
var ref$1; | ||
var id = ref.id; | ||
var args = ref.args; | ||
if (!modules[id] || typeof modules[id].value !== 'function') { | ||
callback(new Error(`Worker module ${id}: not found or its 'init' did not return a function`)); | ||
callback(new Error(("Worker module " + id + ": not found or its 'init' did not return a function"))); | ||
} | ||
try { | ||
const result = modules[id].value(...args); | ||
var result = (ref$1 = modules[id]).value.apply(ref$1, args); | ||
if (result && typeof result.then === 'function') { | ||
result.then(handleResult, rej => callback(rej instanceof Error ? rej : new Error('' + rej))); | ||
result.then(handleResult, function (rej) { return callback(rej instanceof Error ? rej : new Error('' + rej)); }); | ||
} else { | ||
@@ -279,3 +292,3 @@ handleResult(result); | ||
try { | ||
let tx = modules[id].getTransferables && modules[id].getTransferables(result); | ||
var tx = modules[id].getTransferables && modules[id].getTransferables(result); | ||
if (!tx || !Array.isArray(tx) || !tx.length) { | ||
@@ -293,7 +306,7 @@ tx = undefined; //postMessage is very picky about not passing null or empty transferables | ||
function rehydrate(name, str) { | ||
let result = void 0; | ||
self.troikaDefine = r => result = r; | ||
let url = URL.createObjectURL( | ||
var result = void 0; | ||
self.troikaDefine = function (r) { return result = r; }; | ||
var url = URL.createObjectURL( | ||
new Blob( | ||
[`/** ${name.replace(/\*/g, '')} **/\n\ntroikaDefine(\n${str}\n)`], | ||
[("/** " + (name.replace(/\*/g, '')) + " **/\n\ntroikaDefine(\n" + str + "\n)")], | ||
{type: 'application/javascript'} | ||
@@ -313,11 +326,14 @@ ) | ||
// Handler for all messages within the worker | ||
self.addEventListener('message', e => { | ||
const {messageId, action, data} = e.data; | ||
self.addEventListener('message', function (e) { | ||
var ref = e.data; | ||
var messageId = ref.messageId; | ||
var action = ref.action; | ||
var data = ref.data; | ||
try { | ||
// Module registration | ||
if (action === 'registerModule') { | ||
registerModule(data, result => { | ||
registerModule(data, function (result) { | ||
if (result instanceof Error) { | ||
postMessage({ | ||
messageId, | ||
messageId: messageId, | ||
success: false, | ||
@@ -328,3 +344,3 @@ error: result.message | ||
postMessage({ | ||
messageId, | ||
messageId: messageId, | ||
success: true, | ||
@@ -338,6 +354,6 @@ result: {isCallable: typeof result === 'function'} | ||
if (action === 'callModule') { | ||
callModule(data, (result, transferables) => { | ||
callModule(data, function (result, transferables) { | ||
if (result instanceof Error) { | ||
postMessage({ | ||
messageId, | ||
messageId: messageId, | ||
success: false, | ||
@@ -348,5 +364,5 @@ error: result.message | ||
postMessage({ | ||
messageId, | ||
messageId: messageId, | ||
success: true, | ||
result | ||
result: result | ||
}, transferables || undefined); | ||
@@ -358,3 +374,3 @@ } | ||
postMessage({ | ||
messageId, | ||
messageId: messageId, | ||
success: false, | ||
@@ -373,6 +389,9 @@ error: err.stack | ||
function defineMainThreadModule(options) { | ||
let moduleFunc = function(...args) { | ||
return moduleFunc._getInitResult().then(initResult => { | ||
var moduleFunc = function() { | ||
var args = [], len = arguments.length; | ||
while ( len-- ) args[ len ] = arguments[ len ]; | ||
return moduleFunc._getInitResult().then(function (initResult) { | ||
if (typeof initResult === 'function') { | ||
return initResult(...args) | ||
return initResult.apply(void 0, args) | ||
} else { | ||
@@ -385,11 +404,11 @@ throw new Error('Worker module function was called but `init` did not return a callable function') | ||
// We can ignore getTransferables in main thread. TODO workerId? | ||
let {dependencies, init} = options; | ||
var dependencies = options.dependencies; | ||
var init = options.init; | ||
// Resolve dependencies | ||
dependencies = Array.isArray(dependencies) ? dependencies.map(dep => | ||
dep && dep._getInitResult ? dep._getInitResult() : dep | ||
dependencies = Array.isArray(dependencies) ? dependencies.map(function (dep) { return dep && dep._getInitResult ? dep._getInitResult() : dep; } | ||
) : []; | ||
// Invoke init with the resolved dependencies | ||
let initThenable = DefaultThenable.all(dependencies).then(deps => { | ||
var initThenable = DefaultThenable.all(dependencies).then(function (deps) { | ||
return init.apply(null, deps) | ||
@@ -399,3 +418,3 @@ }); | ||
// Cache the resolved promise for subsequent calls | ||
moduleFunc._getInitResult = () => initThenable; | ||
moduleFunc._getInitResult = function () { return initThenable; }; | ||
@@ -407,4 +426,4 @@ return initThenable | ||
let supportsWorkers = () => { | ||
let supported = false; | ||
var supportsWorkers = function () { | ||
var supported = false; | ||
@@ -417,3 +436,3 @@ // Only attempt worker initialization in browsers; elsewhere it would just be | ||
// Would need to be an async check. | ||
let worker = new Worker( | ||
var worker = new Worker( | ||
URL.createObjectURL( | ||
@@ -426,3 +445,3 @@ new Blob([''], { type: 'application/javascript' }) | ||
} catch (err) { | ||
console.log(`Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: [${err.message}]`); | ||
console.log(("Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: [" + (err.message) + "]")); | ||
} | ||
@@ -432,12 +451,12 @@ } | ||
// Cached result | ||
supportsWorkers = () => supported; | ||
supportsWorkers = function () { return supported; }; | ||
return supported | ||
}; | ||
let _workerModuleId = 0; | ||
let _messageId = 0; | ||
let _allowInitAsString = false; | ||
const workers = Object.create(null); | ||
const openRequests = /*#__PURE__*/(() => { | ||
const obj = Object.create(null); | ||
var _workerModuleId = 0; | ||
var _messageId = 0; | ||
var _allowInitAsString = false; | ||
var workers = Object.create(null); | ||
var openRequests = /*#__PURE__*/(function () { | ||
var obj = Object.create(null); | ||
obj._count = 0; | ||
@@ -484,3 +503,6 @@ return obj | ||
} | ||
let {dependencies, init, getTransferables, workerId} = options; | ||
var dependencies = options.dependencies; | ||
var init = options.init; | ||
var getTransferables = options.getTransferables; | ||
var workerId = options.workerId; | ||
@@ -494,7 +516,7 @@ if (!supportsWorkers()) { | ||
} | ||
const id = `workerModule${++_workerModuleId}`; | ||
const name = options.name || id; | ||
let registrationThenable = null; | ||
var id = "workerModule" + (++_workerModuleId); | ||
var name = options.name || id; | ||
var registrationThenable = null; | ||
dependencies = dependencies && dependencies.map(dep => { | ||
dependencies = dependencies && dependencies.map(function (dep) { | ||
// Wrap raw functions as worker modules with no dependencies | ||
@@ -504,5 +526,5 @@ if (typeof dep === 'function' && !dep.workerModuleData) { | ||
dep = defineWorkerModule({ | ||
workerId, | ||
name: `<${name}> function dependency: ${dep.name}`, | ||
init: `function(){return (\n${stringifyFunction(dep)}\n)}` | ||
workerId: workerId, | ||
name: ("<" + name + "> function dependency: " + (dep.name)), | ||
init: ("function(){return (\n" + (stringifyFunction(dep)) + "\n)}") | ||
}); | ||
@@ -518,3 +540,6 @@ _allowInitAsString = false; | ||
function moduleFunc(...args) { | ||
function moduleFunc() { | ||
var args = [], len = arguments.length; | ||
while ( len-- ) args[ len ] = arguments[ len ]; | ||
// Register this module if needed | ||
@@ -526,5 +551,7 @@ if (!registrationThenable) { | ||
// Invoke the module, returning a thenable | ||
return registrationThenable.then(({isCallable}) => { | ||
return registrationThenable.then(function (ref) { | ||
var isCallable = ref.isCallable; | ||
if (isCallable) { | ||
return callWorker(workerId,'callModule', {id, args}) | ||
return callWorker(workerId,'callModule', {id: id, args: args}) | ||
} else { | ||
@@ -537,5 +564,5 @@ throw new Error('Worker module function was called but `init` did not return a callable function') | ||
isWorkerModule: true, | ||
id, | ||
name, | ||
dependencies, | ||
id: id, | ||
name: name, | ||
dependencies: dependencies, | ||
init: stringifyFunction(init), | ||
@@ -552,3 +579,3 @@ getTransferables: getTransferables && stringifyFunction(getTransferables) | ||
function stringifyFunction(fn) { | ||
let str = fn.toString(); | ||
var str = fn.toString(); | ||
// If it was defined in object method/property format, it needs to be modified | ||
@@ -563,6 +590,6 @@ if (!/^function/.test(str) && /^\w+\s*\(/.test(str)) { | ||
function getWorker(workerId) { | ||
let worker = workers[workerId]; | ||
var worker = workers[workerId]; | ||
if (!worker) { | ||
// Bootstrap the worker's content | ||
const bootstrap = stringifyFunction(workerBootstrap); | ||
var bootstrap = stringifyFunction(workerBootstrap); | ||
@@ -573,3 +600,3 @@ // Create the worker from the bootstrap function content | ||
new Blob( | ||
[`/** Worker Module Bootstrap: ${workerId.replace(/\*/g, '')} **/\n\n;(${bootstrap})()`], | ||
[("/** Worker Module Bootstrap: " + (workerId.replace(/\*/g, '')) + " **/\n\n;(" + bootstrap + ")()")], | ||
{type: 'application/javascript'} | ||
@@ -581,6 +608,6 @@ ) | ||
// Single handler for response messages from the worker | ||
worker.onmessage = e => { | ||
const response = e.data; | ||
const msgId = response.messageId; | ||
const callback = openRequests[msgId]; | ||
worker.onmessage = function (e) { | ||
var response = e.data; | ||
var msgId = response.messageId; | ||
var callback = openRequests[msgId]; | ||
if (!callback) { | ||
@@ -599,9 +626,9 @@ throw new Error('WorkerModule response with empty or unknown messageId') | ||
function callWorker(workerId, action, data) { | ||
const thenable = DefaultThenable(); | ||
const messageId = ++_messageId; | ||
openRequests[messageId] = response => { | ||
var thenable = DefaultThenable(); | ||
var messageId = ++_messageId; | ||
openRequests[messageId] = function (response) { | ||
if (response.success) { | ||
thenable.resolve(response.result); | ||
} else { | ||
thenable.reject(new Error(`Error in worker ${action} call: ${response.error}`)); | ||
thenable.reject(new Error(("Error in worker " + action + " call: " + (response.error)))); | ||
} | ||
@@ -614,5 +641,5 @@ }; | ||
getWorker(workerId).postMessage({ | ||
messageId, | ||
action, | ||
data | ||
messageId: messageId, | ||
action: action, | ||
data: data | ||
}); | ||
@@ -619,0 +646,0 @@ return thenable |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | ||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | ||
(global = global || self, factory(global.troika_worker_utils = {})); | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.troika_worker_utils = {})); | ||
}(this, (function (exports) { 'use strict'; | ||
@@ -6,0 +6,0 @@ |
@@ -1,13 +0,13 @@ | ||
'use strict';(function(m,r){"object"===typeof exports&&"undefined"!==typeof module?r(exports):"function"===typeof define&&define.amd?define(["exports"],r):(m=m||self,r(m.troika_worker_utils={}))})(this,function(m){function r(){function b(f,c){n++;var v=0;try{c===q&&g();var u=0<f&&e(c);u?u.call(c,a(function(a){v++;b(1,a)}),a(function(a){v++;b(-1,a)})):(l=f,k=c,h||(setTimeout(d,0),h=1))}catch(D){l||v||b(-1,D)}}function d(){var a=f;h=0;f=[];a.forEach(c)}function c(a){a()}function e(a){a=a&&(p(a)||"object"=== | ||
typeof a)&&a.then;return p(a)&&a}function a(a){var b=0;return function(){for(var g=[],f=arguments.length;f--;)g[f]=arguments[f];b++||a.apply(this,g)}}function g(){throw new TypeError("Chaining cycle detected");}var l=0,f=[],k,h=0,n=0,u=a(function(a){n||b(1,a)}),m=a(function(a){n||b(-1,a)}),p=function(a){return"function"===typeof a},q={then:function(a,b){var c=r();f.push(function(){var f=0<l?a:b;if(p(f))try{var h=f(k);h===c&&g();var d=e(h);d?d.call(h,c.resolve,c.reject):c.resolve(h)}catch(E){c.reject(E)}else c[0< | ||
l?"resolve":"reject"](k)});l&&!h&&(setTimeout(d,0),h=1);return c},resolve:u,reject:m};return q}function z(){var b,d,c=new Promise(function(c,a){b=c;d=a});return{then:c.then.bind(c),resolve:b,reject:d}}function F(){function b(a,g){var d=a.id,f=a.name,k=a.dependencies;void 0===k&&(k=[]);var h=a.init;void 0===h&&(h=function(){});a=a.getTransferables;void 0===a&&(a=null);if(!e[d])try{k=k.map(function(a){a&&a.isWorkerModule&&(b(a,function(a){if(a instanceof Error)throw a;}),a=e[a.id].value);return a}), | ||
h=c("<"+f+">.init",h),a&&(a=c("<"+f+">.getTransferables",a)),f=null,"function"===typeof h?f=h.apply(void 0,k):console.error("worker module init function failed to rehydrate"),e[d]={id:d,value:f,getTransferables:a},g(f)}catch(n){n&&n.noLog||console.error(n),g(n)}}function d(a,b){function c(a){try{var c=e[d].getTransferables&&e[d].getTransferables(a);c&&Array.isArray(c)&&c.length||(c=void 0);b(a,c)}catch(y){console.error(y),b(y)}}var f,d=a.id;a=a.args;e[d]&&"function"===typeof e[d].value||b(Error("Worker module "+ | ||
d+": not found or its 'init' did not return a function"));try{var g=(f=e[d]).value.apply(f,a);g&&"function"===typeof g.then?g.then(c,function(a){return b(a instanceof Error?a:Error(""+a))}):c(g)}catch(n){b(n)}}function c(a,b){var c=void 0;self.troikaDefine=function(a){return c=a};a=URL.createObjectURL(new Blob(["/** "+a.replace(/\*/g,"")+" **/\n\ntroikaDefine(\n"+b+"\n)"],{type:"application/javascript"}));try{importScripts(a)}catch(f){console.error(f)}URL.revokeObjectURL(a);delete self.troikaDefine; | ||
return c}var e=Object.create(null);self.addEventListener("message",function(a){var c=a.data,e=c.messageId;a=c.action;c=c.data;try{"registerModule"===a&&b(c,function(a){a instanceof Error?postMessage({messageId:e,success:!1,error:a.message}):postMessage({messageId:e,success:!0,result:{isCallable:"function"===typeof a}})}),"callModule"===a&&d(c,function(a,c){a instanceof Error?postMessage({messageId:e,success:!1,error:a.message}):postMessage({messageId:e,success:!0,result:a},c||void 0)})}catch(f){postMessage({messageId:e, | ||
success:!1,error:f.stack})}})}function G(b){var d=function(){for(var c=[],b=arguments.length;b--;)c[b]=arguments[b];return d._getInitResult().then(function(a){if("function"===typeof a)return a.apply(void 0,c);throw Error("Worker module function was called but `init` did not return a callable function");})};d._getInitResult=function(){var c=b.dependencies,e=b.init;c=Array.isArray(c)?c.map(function(a){return a&&a._getInitResult?a._getInitResult():a}):[];var a=p.all(c).then(function(a){return e.apply(null, | ||
a)});d._getInitResult=function(){return a};return a};return d}function w(b){function d(){for(var a=[],b=arguments.length;b--;)a[b]=arguments[b];k||(k=A(g,"registerModule",d.workerModuleData));return k.then(function(b){if(b.isCallable)return A(g,"callModule",{id:l,args:a});throw Error("Worker module function was called but `init` did not return a callable function");})}if(!(b&&"function"===typeof b.init||x))throw Error("requires `options.init` function");var c=b.dependencies,e=b.init,a=b.getTransferables, | ||
g=b.workerId;if(!B())return G(b);null==g&&(g="#default");var l="workerModule"+ ++H,f=b.name||l,k=null;c=c&&c.map(function(a){"function"!==typeof a||a.workerModuleData||(x=!0,a=w({workerId:g,name:"<"+f+"> function dependency: "+a.name,init:"function(){return (\n"+t(a)+"\n)}"}),x=!1);a&&a.workerModuleData&&(a=a.workerModuleData);return a});d.workerModuleData={isWorkerModule:!0,id:l,name:f,dependencies:c,init:t(e),getTransferables:a&&t(a)};return d}function t(b){b=b.toString();!/^function/.test(b)&& | ||
/^\w+\s*\(/.test(b)&&(b="function "+b);return b}function I(b){var d=C[b];d||(d=t(F),d=C[b]=new Worker(URL.createObjectURL(new Blob(["/** Worker Module Bootstrap: "+b.replace(/\*/g,"")+" **/\n\n;("+d+")()"],{type:"application/javascript"}))),d.onmessage=function(b){b=b.data;var c=b.messageId,a=q[c];if(!a)throw Error("WorkerModule response with empty or unknown messageId");delete q[c];q.count--;a(b)});return d}function A(b,d,c){var e=p(),a=++J;q[a]=function(a){a.success?e.resolve(a.result):e.reject(Error("Error in worker "+ | ||
d+" call: "+a.error))};q._count++;1E3<q.count&&console.warn("Large number of open WorkerModule requests, some may not be returning");I(b).postMessage({messageId:a,action:d,data:c});return e}r.all=z.all=function(b){var d=0,c=[],e=p();0===b.length?e.resolve([]):b.forEach(function(a,g){var l=p();l.resolve(a);l.then(function(a){d++;c[g]=a;d===b.length&&e.resolve(c)},e.reject)});return e};var p="function"===typeof Promise?z:r,B=function(){var b=!1;if("undefined"!==typeof window&&"undefined"!==typeof window.document)try{(new Worker(URL.createObjectURL(new Blob([""], | ||
{type:"application/javascript"})))).terminate(),b=!0}catch(d){console.log("Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: ["+d.message+"]")}B=function(){return b};return b},H=0,J=0,x=!1,C=Object.create(null),q=function(){var b=Object.create(null);b._count=0;return b}(),K=w({name:"Thenable",dependencies:[p],init:function(b){return b}});m.Thenable=p;m.ThenableWorkerModule=K;m.defineWorkerModule=w;m.stringifyFunction=t;Object.defineProperty(m,"__esModule", | ||
{value:!0})}) | ||
'use strict';(function(m,r){"object"===typeof exports&&"undefined"!==typeof module?r(exports):"function"===typeof define&&define.amd?define(["exports"],r):(m="undefined"!==typeof globalThis?globalThis:m||self,r(m.troika_worker_utils={}))})(this,function(m){function r(){function b(f,c){n++;var v=0;try{c===q&&g();var u=0<f&&e(c);u?u.call(c,a(function(a){v++;b(1,a)}),a(function(a){v++;b(-1,a)})):(l=f,k=c,h||(setTimeout(d,0),h=1))}catch(D){l||v||b(-1,D)}}function d(){var a=f;h=0;f=[];a.forEach(c)}function c(a){a()} | ||
function e(a){a=a&&(p(a)||"object"===typeof a)&&a.then;return p(a)&&a}function a(a){var b=0;return function(){for(var g=[],f=arguments.length;f--;)g[f]=arguments[f];b++||a.apply(this,g)}}function g(){throw new TypeError("Chaining cycle detected");}var l=0,f=[],k,h=0,n=0,u=a(function(a){n||b(1,a)}),m=a(function(a){n||b(-1,a)}),p=function(a){return"function"===typeof a},q={then:function(a,b){var c=r();f.push(function(){var f=0<l?a:b;if(p(f))try{var h=f(k);h===c&&g();var d=e(h);d?d.call(h,c.resolve, | ||
c.reject):c.resolve(h)}catch(E){c.reject(E)}else c[0<l?"resolve":"reject"](k)});l&&!h&&(setTimeout(d,0),h=1);return c},resolve:u,reject:m};return q}function z(){var b,d,c=new Promise(function(c,a){b=c;d=a});return{then:c.then.bind(c),resolve:b,reject:d}}function F(){function b(a,g){var d=a.id,f=a.name,k=a.dependencies;void 0===k&&(k=[]);var h=a.init;void 0===h&&(h=function(){});a=a.getTransferables;void 0===a&&(a=null);if(!e[d])try{k=k.map(function(a){a&&a.isWorkerModule&&(b(a,function(a){if(a instanceof | ||
Error)throw a;}),a=e[a.id].value);return a}),h=c("<"+f+">.init",h),a&&(a=c("<"+f+">.getTransferables",a)),f=null,"function"===typeof h?f=h.apply(void 0,k):console.error("worker module init function failed to rehydrate"),e[d]={id:d,value:f,getTransferables:a},g(f)}catch(n){n&&n.noLog||console.error(n),g(n)}}function d(a,b){function c(a){try{var c=e[d].getTransferables&&e[d].getTransferables(a);c&&Array.isArray(c)&&c.length||(c=void 0);b(a,c)}catch(y){console.error(y),b(y)}}var f,d=a.id;a=a.args;e[d]&& | ||
"function"===typeof e[d].value||b(Error("Worker module "+d+": not found or its 'init' did not return a function"));try{var g=(f=e[d]).value.apply(f,a);g&&"function"===typeof g.then?g.then(c,function(a){return b(a instanceof Error?a:Error(""+a))}):c(g)}catch(n){b(n)}}function c(a,b){var c=void 0;self.troikaDefine=function(a){return c=a};a=URL.createObjectURL(new Blob(["/** "+a.replace(/\*/g,"")+" **/\n\ntroikaDefine(\n"+b+"\n)"],{type:"application/javascript"}));try{importScripts(a)}catch(f){console.error(f)}URL.revokeObjectURL(a); | ||
delete self.troikaDefine;return c}var e=Object.create(null);self.addEventListener("message",function(a){var c=a.data,e=c.messageId;a=c.action;c=c.data;try{"registerModule"===a&&b(c,function(a){a instanceof Error?postMessage({messageId:e,success:!1,error:a.message}):postMessage({messageId:e,success:!0,result:{isCallable:"function"===typeof a}})}),"callModule"===a&&d(c,function(a,c){a instanceof Error?postMessage({messageId:e,success:!1,error:a.message}):postMessage({messageId:e,success:!0,result:a}, | ||
c||void 0)})}catch(f){postMessage({messageId:e,success:!1,error:f.stack})}})}function G(b){var d=function(){for(var c=[],b=arguments.length;b--;)c[b]=arguments[b];return d._getInitResult().then(function(a){if("function"===typeof a)return a.apply(void 0,c);throw Error("Worker module function was called but `init` did not return a callable function");})};d._getInitResult=function(){var c=b.dependencies,e=b.init;c=Array.isArray(c)?c.map(function(a){return a&&a._getInitResult?a._getInitResult():a}):[]; | ||
var a=p.all(c).then(function(a){return e.apply(null,a)});d._getInitResult=function(){return a};return a};return d}function w(b){function d(){for(var a=[],b=arguments.length;b--;)a[b]=arguments[b];k||(k=A(g,"registerModule",d.workerModuleData));return k.then(function(b){if(b.isCallable)return A(g,"callModule",{id:l,args:a});throw Error("Worker module function was called but `init` did not return a callable function");})}if(!(b&&"function"===typeof b.init||x))throw Error("requires `options.init` function"); | ||
var c=b.dependencies,e=b.init,a=b.getTransferables,g=b.workerId;if(!B())return G(b);null==g&&(g="#default");var l="workerModule"+ ++H,f=b.name||l,k=null;c=c&&c.map(function(a){"function"!==typeof a||a.workerModuleData||(x=!0,a=w({workerId:g,name:"<"+f+"> function dependency: "+a.name,init:"function(){return (\n"+t(a)+"\n)}"}),x=!1);a&&a.workerModuleData&&(a=a.workerModuleData);return a});d.workerModuleData={isWorkerModule:!0,id:l,name:f,dependencies:c,init:t(e),getTransferables:a&&t(a)};return d} | ||
function t(b){b=b.toString();!/^function/.test(b)&&/^\w+\s*\(/.test(b)&&(b="function "+b);return b}function I(b){var d=C[b];d||(d=t(F),d=C[b]=new Worker(URL.createObjectURL(new Blob(["/** Worker Module Bootstrap: "+b.replace(/\*/g,"")+" **/\n\n;("+d+")()"],{type:"application/javascript"}))),d.onmessage=function(b){b=b.data;var c=b.messageId,a=q[c];if(!a)throw Error("WorkerModule response with empty or unknown messageId");delete q[c];q.count--;a(b)});return d}function A(b,d,c){var e=p(),a=++J;q[a]= | ||
function(a){a.success?e.resolve(a.result):e.reject(Error("Error in worker "+d+" call: "+a.error))};q._count++;1E3<q.count&&console.warn("Large number of open WorkerModule requests, some may not be returning");I(b).postMessage({messageId:a,action:d,data:c});return e}r.all=z.all=function(b){var d=0,c=[],e=p();0===b.length?e.resolve([]):b.forEach(function(a,g){var l=p();l.resolve(a);l.then(function(a){d++;c[g]=a;d===b.length&&e.resolve(c)},e.reject)});return e};var p="function"===typeof Promise?z:r, | ||
B=function(){var b=!1;if("undefined"!==typeof window&&"undefined"!==typeof window.document)try{(new Worker(URL.createObjectURL(new Blob([""],{type:"application/javascript"})))).terminate(),b=!0}catch(d){console.log("Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: ["+d.message+"]")}B=function(){return b};return b},H=0,J=0,x=!1,C=Object.create(null),q=function(){var b=Object.create(null);b._count=0;return b}(),K=w({name:"Thenable",dependencies:[p],init:function(b){return b}}); | ||
m.Thenable=p;m.ThenableWorkerModule=K;m.defineWorkerModule=w;m.stringifyFunction=t;Object.defineProperty(m,"__esModule",{value:!0})}) |
{ | ||
"name": "troika-worker-utils", | ||
"version": "0.33.0", | ||
"version": "0.34.0", | ||
"description": "Utilities for executing code in Web Workers", | ||
@@ -16,3 +16,3 @@ "author": "Jason Johnston <jason.johnston@protectwise.com>", | ||
"module:src": "src/index.js", | ||
"gitHead": "0c397b65aac6137ce1b4417e55d0deeb77b5ee5f" | ||
"gitHead": "b19cd3aff4b0876253d76b3fc66b7e2a1f16a7e5" | ||
} |
@@ -0,0 +0,0 @@ # `troika-worker-utils` |
@@ -0,0 +0,0 @@ // Troika worker utility exports |
@@ -0,0 +0,0 @@ import Thenable from './Thenable.js' |
@@ -0,0 +0,0 @@ let supportsWorkers = () => { |
@@ -0,0 +0,0 @@ /** |
@@ -0,0 +0,0 @@ import Thenable from './Thenable.js' |
@@ -0,0 +0,0 @@ /** |
@@ -0,0 +0,0 @@ import Thenable from './Thenable.js' |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
89781
2195