Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

troika-worker-utils

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

troika-worker-utils - npm Package Compare versions

Comparing version 0.42.0 to 0.43.0

0

__tests__/_jsdom-worker.js

@@ -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')

17

CHANGELOG.md

@@ -6,2 +6,19 @@ # Change Log

# [0.43.0](https://github.com/protectwise/troika/compare/v0.42.0...v0.43.0) (2021-09-20)
### Bug Fixes
* remove warnings about many open worker module requests ([164fb8f](https://github.com/protectwise/troika/commit/164fb8fe836b95fffe7ca94fcf96d536c7281f7e)), closes [#156](https://github.com/protectwise/troika/issues/156)
### Features
* **troika-worker-utils:** add a terminateWorker function ([33b8455](https://github.com/protectwise/troika/commit/33b8455c3794e13a342a7910d6c2c4beddd295da))
# [0.42.0](https://github.com/protectwise/troika/compare/v0.41.2...v0.42.0) (2021-05-17)

@@ -8,0 +25,0 @@

39

dist/troika-worker-utils.esm.js

@@ -431,7 +431,4 @@ /**

var workers = Object.create(null);
var openRequests = /*#__PURE__*/(function () {
var obj = Object.create(null);
obj._count = 0;
return obj
})();
var registeredModules = Object.create(null); //workerId -> Set<unregisterFn>
var openRequests = Object.create(null);

@@ -497,2 +494,7 @@

registrationThenable = callWorker(workerId,'registerModule', moduleFunc.workerModuleData);
var unregister = function () {
registrationThenable = null;
registeredModules[workerId].delete(unregister);
}
;(registeredModules[workerId] || (registeredModules[workerId] = new Set())).add(unregister);
}

@@ -523,2 +525,22 @@

/**
* Terminate an active Worker by a workerId that was passed to defineWorkerModule.
* This only terminates the Worker itself; the worker module will remain available
* and if you call it again its Worker will be respawned.
* @param {string} workerId
*/
function terminateWorker(workerId) {
// Unregister all modules that were registered in that worker
if (registeredModules[workerId]) {
registeredModules[workerId].forEach(function (unregister) {
unregister();
});
}
// Terminate the Worker object
if (workers[workerId]) {
workers[workerId].terminate();
delete workers[workerId];
}
}
/**
* Stringifies a function into a form that can be deserialized in the worker

@@ -562,3 +584,2 @@ * @param fn

delete openRequests[msgId];
openRequests._count--;
callback(response);

@@ -581,6 +602,2 @@ };

};
openRequests._count++;
if (openRequests._count > 1000) { //detect leaks
console.warn('Large number of open WorkerModule requests, some may not be returning');
}
getWorker(workerId).postMessage({

@@ -607,2 +624,2 @@ messageId: messageId,

export { DefaultThenable as Thenable, ThenableWorkerModule, defineWorkerModule, stringifyFunction };
export { DefaultThenable as Thenable, ThenableWorkerModule, defineWorkerModule, stringifyFunction, terminateWorker };

@@ -437,7 +437,4 @@ (function (global, factory) {

var workers = Object.create(null);
var openRequests = /*#__PURE__*/(function () {
var obj = Object.create(null);
obj._count = 0;
return obj
})();
var registeredModules = Object.create(null); //workerId -> Set<unregisterFn>
var openRequests = Object.create(null);

@@ -503,2 +500,7 @@

registrationThenable = callWorker(workerId,'registerModule', moduleFunc.workerModuleData);
var unregister = function () {
registrationThenable = null;
registeredModules[workerId].delete(unregister);
}
;(registeredModules[workerId] || (registeredModules[workerId] = new Set())).add(unregister);
}

@@ -529,2 +531,22 @@

/**
* Terminate an active Worker by a workerId that was passed to defineWorkerModule.
* This only terminates the Worker itself; the worker module will remain available
* and if you call it again its Worker will be respawned.
* @param {string} workerId
*/
function terminateWorker(workerId) {
// Unregister all modules that were registered in that worker
if (registeredModules[workerId]) {
registeredModules[workerId].forEach(function (unregister) {
unregister();
});
}
// Terminate the Worker object
if (workers[workerId]) {
workers[workerId].terminate();
delete workers[workerId];
}
}
/**
* Stringifies a function into a form that can be deserialized in the worker

@@ -568,3 +590,2 @@ * @param fn

delete openRequests[msgId];
openRequests._count--;
callback(response);

@@ -587,6 +608,2 @@ };

};
openRequests._count++;
if (openRequests._count > 1000) { //detect leaks
console.warn('Large number of open WorkerModule requests, some may not be returning');
}
getWorker(workerId).postMessage({

@@ -617,2 +634,3 @@ messageId: messageId,

exports.stringifyFunction = stringifyFunction;
exports.terminateWorker = terminateWorker;

@@ -619,0 +637,0 @@ Object.defineProperty(exports, '__esModule', { value: true });

@@ -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="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){"undefined"!==typeof process&&"test"===process.env.NODE_ENV||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(k,q){"object"===typeof exports&&"undefined"!==typeof module?q(exports):"function"===typeof define&&define.amd?define(["exports"],q):(k="undefined"!==typeof globalThis?globalThis:k||self,q(k.troika_worker_utils={}))})(this,function(k){function q(){function b(f,c){m++;var w=0;try{c===p&&g();var v=0<f&&e(c);v?v.call(c,a(function(a){w++;b(1,a)}),a(function(a){w++;b(-1,a)})):(r=f,l=c,h||(setTimeout(d,0),h=1))}catch(E){r||w||b(-1,E)}}function d(){var a=f;h=0;f=[];a.forEach(c)}function c(a){a()}
function e(a){a=a&&(n(a)||"object"===typeof a)&&a.then;return n(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 r=0,f=[],l,h=0,m=0,v=a(function(a){m||b(1,a)}),k=a(function(a){m||b(-1,a)}),n=function(a){return"function"===typeof a},p={then:function(a,b){var c=q();f.push(function(){var f=0<r?a:b;if(n(f))try{var d=f(l);d===c&&g();var h=e(d);h?h.call(d,c.resolve,
c.reject):c.resolve(d)}catch(F){c.reject(F)}else c[0<r?"resolve":"reject"](l)});r&&!h&&(setTimeout(d,0),h=1);return c},resolve:v,reject:k};return p}function B(){var b,d,c=new Promise(function(c,a){b=c;d=a});return{then:c.then.bind(c),resolve:b,reject:d}}function G(){function b(a,g){var d=a.id,f=a.name,l=a.dependencies;void 0===l&&(l=[]);var h=a.init;void 0===h&&(h=function(){});a=a.getTransferables;void 0===a&&(a=null);if(!e[d])try{l=l.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,l):console.error("worker module init function failed to rehydrate"),e[d]={id:d,value:f,getTransferables:a},g(f)}catch(m){m&&m.noLog||console.error(m),g(m)}}function d(a,b){function c(a){try{var c=e[g].getTransferables&&e[g].getTransferables(a);c&&Array.isArray(c)&&c.length||(c=void 0);b(a,c)}catch(A){console.error(A),b(A)}}var d,g=a.id;a=a.args;e[g]&&
"function"===typeof e[g].value||b(Error("Worker module "+g+": not found or its 'init' did not return a function"));try{var h=(d=e[g]).value.apply(d,a);h&&"function"===typeof h.then?h.then(c,function(a){return b(a instanceof Error?a:Error(""+a))}):c(h)}catch(m){b(m)}}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,b){a instanceof Error?postMessage({messageId:e,success:!1,error:a.message}):postMessage({messageId:e,success:!0,result:a},
b||void 0)})}catch(f){postMessage({messageId:e,success:!1,error:f.stack})}})}function H(b){var d=function(){for(var b=[],e=arguments.length;e--;)b[e]=arguments[e];return d._getInitResult().then(function(a){if("function"===typeof a)return a.apply(void 0,b);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=n.all(c).then(function(a){return e.apply(null,a)});d._getInitResult=function(){return a};return a};return d}function x(b){function d(){for(var a=[],b=arguments.length;b--;)a[b]=arguments[b];if(!l){l=C(g,"registerModule",d.workerModuleData);var c=function(){l=null;p[g].delete(c)};(p[g]||(p[g]=new Set)).add(c)}return l.then(function(b){if(b.isCallable)return C(g,"callModule",{id:k,args:a});throw Error("Worker module function was called but `init` did not return a callable function");})}if(!(b&&
"function"===typeof b.init||y))throw Error("requires `options.init` function");var c=b.dependencies,e=b.init,a=b.getTransferables,g=b.workerId;if(!D())return H(b);null==g&&(g="#default");var k="workerModule"+ ++I,f=b.name||k,l=null;c=c&&c.map(function(a){"function"!==typeof a||a.workerModuleData||(y=!0,a=x({workerId:g,name:"<"+f+"> function dependency: "+a.name,init:"function(){return (\n"+t(a)+"\n)}"}),y=!1);a&&a.workerModuleData&&(a=a.workerModuleData);return a});d.workerModuleData={isWorkerModule:!0,
id:k,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 J(b){var d=u[b];d||(d=t(G),d=u[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=z[c];if(!a)throw Error("WorkerModule response with empty or unknown messageId");delete z[c];
a(b)});return d}function C(b,d,c){var e=n(),a=++K;z[a]=function(a){a.success?e.resolve(a.result):e.reject(Error("Error in worker "+d+" call: "+a.error))};J(b).postMessage({messageId:a,action:d,data:c});return e}q.all=B.all=function(b){var d=0,c=[],e=n();0===b.length?e.resolve([]):b.forEach(function(a,g){var k=n();k.resolve(a);k.then(function(a){d++;c[g]=a;d===b.length&&e.resolve(c)},e.reject)});return e};var n="function"===typeof Promise?B:q,D=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){"undefined"!==typeof process&&"test"===process.env.NODE_ENV||console.log("Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: ["+d.message+"]")}D=function(){return b};return b},I=0,K=0,y=!1,u=Object.create(null),p=Object.create(null),z=Object.create(null),L=x({name:"Thenable",dependencies:[n],init:function(b){return b}});
k.Thenable=n;k.ThenableWorkerModule=L;k.defineWorkerModule=x;k.stringifyFunction=t;k.terminateWorker=function(b){p[b]&&p[b].forEach(function(b){b()});u[b]&&(u[b].terminate(),delete u[b])};Object.defineProperty(k,"__esModule",{value:!0})})
{
"name": "troika-worker-utils",
"version": "0.42.0",
"version": "0.43.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": "0f7129cd43fc58f5c6a5f6f20f2d0941f9f36510"
"gitHead": "497fa534d015bc8f746c7d00ec7bfde1df92f491"
}

@@ -0,0 +0,0 @@ # `troika-worker-utils`

// Troika worker utility exports
export {defineWorkerModule, stringifyFunction} from './WorkerModules.js'
export {defineWorkerModule, terminateWorker, stringifyFunction} from './WorkerModules.js'
export {default as Thenable} from './Thenable.js'
export {default as ThenableWorkerModule} from './ThenableWorkerModule.js'

@@ -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 @@ /**

@@ -10,7 +10,4 @@ import Thenable from './Thenable.js'

const workers = Object.create(null)
const openRequests = /*#__PURE__*/(() => {
const obj = Object.create(null)
obj._count = 0
return obj
})()
const registeredModules = Object.create(null) //workerId -> Set<unregisterFn>
const openRequests = Object.create(null)

@@ -70,2 +67,7 @@

registrationThenable = callWorker(workerId,'registerModule', moduleFunc.workerModuleData)
const unregister = () => {
registrationThenable = null
registeredModules[workerId].delete(unregister)
}
;(registeredModules[workerId] || (registeredModules[workerId] = new Set())).add(unregister)
}

@@ -94,2 +96,22 @@

/**
* Terminate an active Worker by a workerId that was passed to defineWorkerModule.
* This only terminates the Worker itself; the worker module will remain available
* and if you call it again its Worker will be respawned.
* @param {string} workerId
*/
export function terminateWorker(workerId) {
// Unregister all modules that were registered in that worker
if (registeredModules[workerId]) {
registeredModules[workerId].forEach(unregister => {
unregister()
})
}
// Terminate the Worker object
if (workers[workerId]) {
workers[workerId].terminate()
delete workers[workerId]
}
}
/**
* Stringifies a function into a form that can be deserialized in the worker

@@ -133,3 +155,2 @@ * @param fn

delete openRequests[msgId]
openRequests._count--
callback(response)

@@ -152,6 +173,2 @@ }

}
openRequests._count++
if (openRequests._count > 1000) { //detect leaks
console.warn('Large number of open WorkerModule requests, some may not be returning')
}
getWorker(workerId).postMessage({

@@ -158,0 +175,0 @@ messageId,

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc