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

@vonage/js-workerizer

Package Overview
Dependencies
Maintainers
42
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vonage/js-workerizer - npm Package Compare versions

Comparing version 1.2.2 to 1.2.3

dist/types/utils/is-emittery.d.ts

6

CHANGELOG.md
# CHANGELOG.md
## 1.2.3 (2023-06-28)
Fix:
- Fix emittery inheritance detection that could fail while bundled.
## 1.2.2 (2023-06-15)

@@ -4,0 +10,0 @@

20

dist/js-workerizer.es.js

@@ -570,17 +570,11 @@ function createGlobalThisVariable(name, defaultValue) {

});
function isExtending(tested, extended) {
let current = tested;
if (tested == extended) {
return true;
}
do {
if (current.prototype instanceof extended) {
return true;
}
} while (current = Object.getPrototypeOf(current));
return false;
function isInstanceOfEmittery(instance) {
return instance.onAny && instance.emit;
}
function isChildClassOfEmittery(input) {
return input.prototype.onAny && input.prototype.emit;
}
let nextId = 0;
async function createWorkerized(workerizedClass, worker, resolvers) {
const isEmittery = isExtending(workerizedClass, Emittery);
const isEmittery = isChildClassOfEmittery(workerizedClass);
const result = isEmittery ? new Emittery() : {};

@@ -666,3 +660,3 @@ const id = nextId++;

copy(globalsValues, globals);
if (isExtending(constructor, Emittery)) {
if (isInstanceOfEmittery(context.instance)) {
context.instance.onAny((name, data) => {

@@ -669,0 +663,0 @@ postCommand(

@@ -570,17 +570,11 @@ function createGlobalThisVariable(name, defaultValue) {

});
function isExtending(tested, extended) {
let current = tested;
if (tested == extended) {
return true;
}
do {
if (current.prototype instanceof extended) {
return true;
}
} while (current = Object.getPrototypeOf(current));
return false;
function isInstanceOfEmittery(instance) {
return instance.onAny && instance.emit;
}
function isChildClassOfEmittery(input) {
return input.prototype.onAny && input.prototype.emit;
}
let nextId = 0;
async function createWorkerized(workerizedClass, worker, resolvers) {
const isEmittery = isExtending(workerizedClass, Emittery);
const isEmittery = isChildClassOfEmittery(workerizedClass);
const result = isEmittery ? new Emittery() : {};

@@ -666,3 +660,3 @@ const id = nextId++;

copy(globalsValues, globals);
if (isExtending(constructor, Emittery)) {
if (isInstanceOfEmittery(context.instance)) {
context.instance.onAny((name, data) => {

@@ -669,0 +663,0 @@ postCommand(

@@ -1,1 +0,1 @@

function createGlobalThisVariable(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let n=globalThis.vonage.workerizer;return n[e]||(n[e]=t),n[e]}const globals=createGlobalThisVariable("globals",{});var CommandType=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(CommandType||{});function isTransferable(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let nextCommandId=0;function postCommand$1(e,t,n,r,o){const s=nextCommandId++;e.postMessage({id:s,type:t,functionName:n,args:r},r.filter((e=>isTransferable(e))));return new Promise((e=>{null==o||o.set(s,e)}))}function postCommand(e,t){const{id:n,type:r}=e,o=Array.isArray(t)?t:[t];postMessage({id:n,type:r,result:t},o.filter((e=>isTransferable(e))))}const workerized=createGlobalThisVariable("workerized",{});function isWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}async function globalsSync(){if(isWorker())postCommand({type:CommandType.GLOBALS_SYNC},globals);else{const e=[];for(const t in workerized){const{worker:n,resolvers:r}=workerized[t].workerContext;n&&e.push(postCommand$1(n,CommandType.GLOBALS_SYNC,"",[globals],r))}await Promise.all(e)}}function copy(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const n in e)Array.isArray(e[n])?(t[n]=[],copy(e[n],t[n])):"object"==typeof e[n]?(t[n]={},copy(e[n],t[n])):t[n]=e[n]}async function createWorker(e,t,n,r){const o=new t;o.addEventListener("message",(async({data:e})=>{var t,o,s,i,a,l,d;switch(e.type){case CommandType.GLOBALS_SYNC:e.id?(null==(o=n.get(null!=(t=e.id)?t:-1))||o(e.result),n.delete(null!=(s=e.id)?s:-1)):(copy(null!=(i=e.result)?i:{},globals),await globalsSync());break;case CommandType.EVENT:const{result:c}=e,u=c;if(null==(null==u?void 0:u.name))throw"Missing event name";r(u.name,u.data);break;default:null==(l=n.get(null!=(a=e.id)?a:-1))||l(e.result),n.delete(null!=(d=e.id)?d:-1)}}));if(!await postCommand$1(o,CommandType.INIT,"",[e.workerId,globals],n))throw"Failed to instantiate workerized class";return o}const anyMap=new WeakMap,eventsMap=new WeakMap,producersMap=new WeakMap,anyProducer=Symbol("anyProducer"),resolvedPromise=Promise.resolve(),listenerAdded=Symbol("listenerAdded"),listenerRemoved=Symbol("listenerRemoved");let canEmitMetaEvents=!1,isGlobalDebugEnabled=!1;function assertEventName(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function assertListener(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function getListeners(e,t){const n=eventsMap.get(e);if(n.has(t))return n.get(t)}function getEventProducers(e,t){const n="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:anyProducer,r=producersMap.get(e);if(r.has(n))return r.get(n)}function enqueueProducers(e,t,n){const r=producersMap.get(e);if(r.has(t))for(const e of r.get(t))e.enqueue(n);if(r.has(anyProducer)){const e=Promise.all([t,n]);for(const t of r.get(anyProducer))t.enqueue(e)}}function iterator(e,t){t=Array.isArray(t)?t:[t];let n=!1,flush=()=>{},r=[];const o={enqueue(e){r.push(e),flush()},finish(){n=!0,flush()}};for(const n of t){let t=getEventProducers(e,n);if(!t){t=new Set;producersMap.get(e).set(n,t)}t.add(o)}return{async next(){return r?0===r.length?n?(r=void 0,this.next()):(await new Promise((e=>{flush=e})),this.next()):{done:!1,value:await r.shift()}:{done:!0}},async return(n){r=void 0;for(const n of t){const t=getEventProducers(e,n);if(t&&(t.delete(o),0===t.size)){producersMap.get(e).delete(n)}}return flush(),arguments.length>0?{done:!0,value:await n}:{done:!0}},[Symbol.asyncIterator](){return this}}}function defaultMethodNamesOrAssert(e){if(void 0===e)return allEmitteryMethods;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!allEmitteryMethods.includes(t)){if("string"!=typeof t)throw new TypeError("`methodNames` element must be a string");throw new Error(`${t} is not Emittery method`)}return e}const isMetaEvent=e=>e===listenerAdded||e===listenerRemoved;function emitMetaEvent(e,t,n){if(isMetaEvent(t))try{canEmitMetaEvents=!0,e.emit(t,n)}finally{canEmitMetaEvents=!1}}class Emittery{static mixin(e,t){return t=defaultMethodNamesOrAssert(t),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new Emittery}),this[e]}});const emitteryMethodCaller=t=>function(...n){return this[e][t](...n)};for(const e of t)Object.defineProperty(n.prototype,e,{enumerable:!1,value:emitteryMethodCaller(e)});return n}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return isGlobalDebugEnabled;const{env:n}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===n.DEBUG||"*"===n.DEBUG||isGlobalDebugEnabled}static set isDebugEnabled(e){isGlobalDebugEnabled=e}constructor(e={}){var t;anyMap.set(this,new Set),eventsMap.set(this,new Map),producersMap.set(this,new Map),producersMap.get(this).set(anyProducer,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,n,r)=>{try{r=JSON.stringify(r)}catch{r=`Object with the following keys failed to stringify: ${Object.keys(r).join(",")}`}"symbol"!=typeof n&&"number"!=typeof n||(n=n.toString());const o=new Date,s=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${s}][emittery:${e}][${t}] Event Name: ${n}\n\tdata: ${r}`)})}logIfDebugEnabled(e,t,n){(Emittery.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);let e=getListeners(this,n);if(!e){e=new Set;eventsMap.get(this).set(n,e)}e.add(t),this.logIfDebugEnabled("subscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,listenerAdded,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);const e=getListeners(this,n);if(e&&(e.delete(t),0===e.size)){eventsMap.get(this).delete(n)}this.logIfDebugEnabled("unsubscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,listenerRemoved,{eventName:n,listener:t})}}once(e){let t;const n=new Promise((n=>{t=this.on(e,(e=>{t(),n(e)}))}));return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)assertEventName(t);return iterator(this,e)}async emit(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!canEmitMetaEvents)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),enqueueProducers(this,e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=anyMap.get(this),s=[...r],i=isMetaEvent(e)?[]:[...o];await resolvedPromise,await Promise.all([...s.map((async e=>{if(r.has(e))return e(t)})),...i.map((async n=>{if(o.has(n))return n(e,t)}))])}async emitSerial(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!canEmitMetaEvents)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=anyMap.get(this),s=[...r],i=[...o];await resolvedPromise;for(const e of s)r.has(e)&&await e(t);for(const n of i)o.has(n)&&await n(e,t)}onAny(e){return assertListener(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),anyMap.get(this).add(e),emitMetaEvent(this,listenerAdded,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return iterator(this)}offAny(e){assertListener(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),emitMetaEvent(this,listenerRemoved,{listener:e}),anyMap.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=getListeners(this,t);e&&e.clear();const n=getEventProducers(this,t);if(n){for(const e of n)e.finish();n.clear()}}else{anyMap.get(this).clear();for(const[e,t]of eventsMap.get(this).entries())t.clear(),eventsMap.get(this).delete(e);for(const[e,t]of producersMap.get(this).entries()){for(const e of t)e.finish();t.clear(),producersMap.get(this).delete(e)}}}listenerCount(e){var t,n,r,o,s,i;e=Array.isArray(e)?e:[e];let a=0;for(const l of e)if("string"!=typeof l){void 0!==l&&assertEventName(l),a+=anyMap.get(this).size;for(const e of eventsMap.get(this).values())a+=e.size;for(const e of producersMap.get(this).values())a+=e.size}else a+=anyMap.get(this).size+(null!=(n=null==(t=getListeners(this,l))?void 0:t.size)?n:0)+(null!=(o=null==(r=getEventProducers(this,l))?void 0:r.size)?o:0)+(null!=(i=null==(s=getEventProducers(this))?void 0:s.size)?i:0);return a}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=defaultMethodNamesOrAssert(t);for(const n of t){if(void 0!==e[n])throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const allEmitteryMethods=Object.getOwnPropertyNames(Emittery.prototype).filter((e=>"constructor"!==e));function isExtending(e,t){let n=e;if(e==t)return!0;do{if(n.prototype instanceof t)return!0}while(n=Object.getPrototypeOf(n));return!1}Object.defineProperty(Emittery,"listenerAdded",{value:listenerAdded,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Emittery,"listenerRemoved",{value:listenerRemoved,writable:!1,enumerable:!0,configurable:!1});let nextId=0;async function createWorkerized(e,t,n){const r=isExtending(e,Emittery)?new Emittery:{},o=nextId++;return Object.getOwnPropertyNames(e.prototype).forEach((e=>{r[e]=(...r)=>postCommand$1(t,CommandType.FORWARD,e,r,n)})),r.terminate=async(...e)=>{const s=await postCommand$1(t,CommandType.TERMINATE,"",e,n);return delete workerized[o],t.terminate(),r.workerContext.worker=void 0,s},r.workerContext={id:o,worker:t,resolvers:n},workerized[o]=r,r}async function workerize(e,t){const n=new Map;let r;const o=await createWorker(e,t,n,((e,t)=>{(null==r?void 0:r.emit)&&(null==r||r.emit(e,t))}));return r=await createWorkerized(e,o,n),r}async function handleCommandForward(e,t){const{functionName:n,args:r}=e;if(!t.instance)throw"instance not initialized";if(!n)throw"missing function name to call";if(!t.instance[n])throw`undefined function [${n}] in class ${t.instance.constructor.workerId}`;postCommand(e,await t.instance[n](...null!=r?r:[]))}const registeredWorkers=createGlobalThisVariable("registeredWorkers",{});function registerWorker(e,t){t.workerId=e,isWorker()&&(registeredWorkers[t.workerId]=t)}function handleCommandInit(e,t){if(!e.args)throw"Missing className while initializing worker";const[n,r]=e.args,o=registeredWorkers[n];if(!o)throw`unknown worker class ${n}`;t.instance=new o(e.args.slice(1)),copy(r,globals),isExtending(o,Emittery)&&t.instance.onAny(((e,t)=>{postCommand({type:CommandType.EVENT},{name:e,data:t})})),postCommand(e,void 0!==typeof t.instance)}async function handleCommandTerminate(e,t){const{args:n}=e;if(!t.instance)throw"instance not initialized";let r;t.instance.terminate&&(r=await t.instance.terminate(...null!=n?n:[])),postCommand(e,r)}function handleCommandGlobalsSync(e){if(!e.args)throw"Missing globals while syncing";copy(e.args[0],globals),postCommand(e,{})}function initWorker(){const e={};onmessage=async t=>{const n=t.data;switch(n.type){case CommandType.INIT:handleCommandInit(n,e);break;case CommandType.FORWARD:handleCommandForward(n,e);break;case CommandType.TERMINATE:handleCommandTerminate(n,e);break;case CommandType.GLOBALS_SYNC:handleCommandGlobalsSync(n)}}}function createGlobal(e,t){return globals[e]||(globals[e]=t),[()=>globals[e],async t=>{globals[e]=t,await globalsSync()}]}function registerGlobal(e,t){return createGlobal(e,t)}isWorker()&&initWorker();
function createGlobalThisVariable(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let n=globalThis.vonage.workerizer;return n[e]||(n[e]=t),n[e]}const globals=createGlobalThisVariable("globals",{});var CommandType=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(CommandType||{});function isTransferable(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let nextCommandId=0;function postCommand$1(e,t,n,r,s){const o=nextCommandId++;e.postMessage({id:o,type:t,functionName:n,args:r},r.filter((e=>isTransferable(e))));return new Promise((e=>{null==s||s.set(o,e)}))}function postCommand(e,t){const{id:n,type:r}=e,s=Array.isArray(t)?t:[t];postMessage({id:n,type:r,result:t},s.filter((e=>isTransferable(e))))}const workerized=createGlobalThisVariable("workerized",{});function isWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}async function globalsSync(){if(isWorker())postCommand({type:CommandType.GLOBALS_SYNC},globals);else{const e=[];for(const t in workerized){const{worker:n,resolvers:r}=workerized[t].workerContext;n&&e.push(postCommand$1(n,CommandType.GLOBALS_SYNC,"",[globals],r))}await Promise.all(e)}}function copy(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const e in t)delete t[e];for(const n in e)Array.isArray(e[n])?(t[n]=[],copy(e[n],t[n])):"object"==typeof e[n]?(t[n]={},copy(e[n],t[n])):t[n]=e[n]}async function createWorker(e,t,n,r){const s=new t;s.addEventListener("message",(async({data:e})=>{var t,s,o,a,i,l,d;switch(e.type){case CommandType.GLOBALS_SYNC:e.id?(null==(s=n.get(null!=(t=e.id)?t:-1))||s(e.result),n.delete(null!=(o=e.id)?o:-1)):(copy(null!=(a=e.result)?a:{},globals),await globalsSync());break;case CommandType.EVENT:const{result:c}=e,u=c;if(null==(null==u?void 0:u.name))throw"Missing event name";r(u.name,u.data);break;default:null==(l=n.get(null!=(i=e.id)?i:-1))||l(e.result),n.delete(null!=(d=e.id)?d:-1)}}));if(!await postCommand$1(s,CommandType.INIT,"",[e.workerId,globals],n))throw"Failed to instantiate workerized class";return s}const anyMap=new WeakMap,eventsMap=new WeakMap,producersMap=new WeakMap,anyProducer=Symbol("anyProducer"),resolvedPromise=Promise.resolve(),listenerAdded=Symbol("listenerAdded"),listenerRemoved=Symbol("listenerRemoved");let canEmitMetaEvents=!1,isGlobalDebugEnabled=!1;function assertEventName(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function assertListener(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function getListeners(e,t){const n=eventsMap.get(e);if(n.has(t))return n.get(t)}function getEventProducers(e,t){const n="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:anyProducer,r=producersMap.get(e);if(r.has(n))return r.get(n)}function enqueueProducers(e,t,n){const r=producersMap.get(e);if(r.has(t))for(const e of r.get(t))e.enqueue(n);if(r.has(anyProducer)){const e=Promise.all([t,n]);for(const t of r.get(anyProducer))t.enqueue(e)}}function iterator(e,t){t=Array.isArray(t)?t:[t];let n=!1,flush=()=>{},r=[];const s={enqueue(e){r.push(e),flush()},finish(){n=!0,flush()}};for(const n of t){let t=getEventProducers(e,n);if(!t){t=new Set;producersMap.get(e).set(n,t)}t.add(s)}return{async next(){return r?0===r.length?n?(r=void 0,this.next()):(await new Promise((e=>{flush=e})),this.next()):{done:!1,value:await r.shift()}:{done:!0}},async return(n){r=void 0;for(const n of t){const t=getEventProducers(e,n);if(t&&(t.delete(s),0===t.size)){producersMap.get(e).delete(n)}}return flush(),arguments.length>0?{done:!0,value:await n}:{done:!0}},[Symbol.asyncIterator](){return this}}}function defaultMethodNamesOrAssert(e){if(void 0===e)return allEmitteryMethods;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!allEmitteryMethods.includes(t)){if("string"!=typeof t)throw new TypeError("`methodNames` element must be a string");throw new Error(`${t} is not Emittery method`)}return e}const isMetaEvent=e=>e===listenerAdded||e===listenerRemoved;function emitMetaEvent(e,t,n){if(isMetaEvent(t))try{canEmitMetaEvents=!0,e.emit(t,n)}finally{canEmitMetaEvents=!1}}class Emittery{static mixin(e,t){return t=defaultMethodNamesOrAssert(t),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new Emittery}),this[e]}});const emitteryMethodCaller=t=>function(...n){return this[e][t](...n)};for(const e of t)Object.defineProperty(n.prototype,e,{enumerable:!1,value:emitteryMethodCaller(e)});return n}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return isGlobalDebugEnabled;const{env:n}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===n.DEBUG||"*"===n.DEBUG||isGlobalDebugEnabled}static set isDebugEnabled(e){isGlobalDebugEnabled=e}constructor(e={}){var t;anyMap.set(this,new Set),eventsMap.set(this,new Map),producersMap.set(this,new Map),producersMap.get(this).set(anyProducer,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,n,r)=>{try{r=JSON.stringify(r)}catch{r=`Object with the following keys failed to stringify: ${Object.keys(r).join(",")}`}"symbol"!=typeof n&&"number"!=typeof n||(n=n.toString());const s=new Date,o=`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`;console.log(`[${o}][emittery:${e}][${t}] Event Name: ${n}\n\tdata: ${r}`)})}logIfDebugEnabled(e,t,n){(Emittery.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);let e=getListeners(this,n);if(!e){e=new Set;eventsMap.get(this).set(n,e)}e.add(t),this.logIfDebugEnabled("subscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,listenerAdded,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);const e=getListeners(this,n);if(e&&(e.delete(t),0===e.size)){eventsMap.get(this).delete(n)}this.logIfDebugEnabled("unsubscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,listenerRemoved,{eventName:n,listener:t})}}once(e){let t;const n=new Promise((n=>{t=this.on(e,(e=>{t(),n(e)}))}));return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)assertEventName(t);return iterator(this,e)}async emit(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!canEmitMetaEvents)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),enqueueProducers(this,e,t);const r=null!=(n=getListeners(this,e))?n:new Set,s=anyMap.get(this),o=[...r],a=isMetaEvent(e)?[]:[...s];await resolvedPromise,await Promise.all([...o.map((async e=>{if(r.has(e))return e(t)})),...a.map((async n=>{if(s.has(n))return n(e,t)}))])}async emitSerial(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!canEmitMetaEvents)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=null!=(n=getListeners(this,e))?n:new Set,s=anyMap.get(this),o=[...r],a=[...s];await resolvedPromise;for(const e of o)r.has(e)&&await e(t);for(const n of a)s.has(n)&&await n(e,t)}onAny(e){return assertListener(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),anyMap.get(this).add(e),emitMetaEvent(this,listenerAdded,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return iterator(this)}offAny(e){assertListener(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),emitMetaEvent(this,listenerRemoved,{listener:e}),anyMap.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=getListeners(this,t);e&&e.clear();const n=getEventProducers(this,t);if(n){for(const e of n)e.finish();n.clear()}}else{anyMap.get(this).clear();for(const[e,t]of eventsMap.get(this).entries())t.clear(),eventsMap.get(this).delete(e);for(const[e,t]of producersMap.get(this).entries()){for(const e of t)e.finish();t.clear(),producersMap.get(this).delete(e)}}}listenerCount(e){var t,n,r,s,o,a;e=Array.isArray(e)?e:[e];let i=0;for(const l of e)if("string"!=typeof l){void 0!==l&&assertEventName(l),i+=anyMap.get(this).size;for(const e of eventsMap.get(this).values())i+=e.size;for(const e of producersMap.get(this).values())i+=e.size}else i+=anyMap.get(this).size+(null!=(n=null==(t=getListeners(this,l))?void 0:t.size)?n:0)+(null!=(s=null==(r=getEventProducers(this,l))?void 0:r.size)?s:0)+(null!=(a=null==(o=getEventProducers(this))?void 0:o.size)?a:0);return i}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=defaultMethodNamesOrAssert(t);for(const n of t){if(void 0!==e[n])throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const allEmitteryMethods=Object.getOwnPropertyNames(Emittery.prototype).filter((e=>"constructor"!==e));function isInstanceOfEmittery(e){return e.onAny&&e.emit}function isChildClassOfEmittery(e){return e.prototype.onAny&&e.prototype.emit}Object.defineProperty(Emittery,"listenerAdded",{value:listenerAdded,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Emittery,"listenerRemoved",{value:listenerRemoved,writable:!1,enumerable:!0,configurable:!1});let nextId=0;async function createWorkerized(e,t,n){const r=isChildClassOfEmittery(e)?new Emittery:{},s=nextId++;return Object.getOwnPropertyNames(e.prototype).forEach((e=>{r[e]=(...r)=>postCommand$1(t,CommandType.FORWARD,e,r,n)})),r.terminate=async(...e)=>{const o=await postCommand$1(t,CommandType.TERMINATE,"",e,n);return delete workerized[s],t.terminate(),r.workerContext.worker=void 0,o},r.workerContext={id:s,worker:t,resolvers:n},workerized[s]=r,r}async function workerize(e,t){const n=new Map;let r;const s=await createWorker(e,t,n,((e,t)=>{(null==r?void 0:r.emit)&&(null==r||r.emit(e,t))}));return r=await createWorkerized(e,s,n),r}async function handleCommandForward(e,t){const{functionName:n,args:r}=e;if(!t.instance)throw"instance not initialized";if(!n)throw"missing function name to call";if(!t.instance[n])throw`undefined function [${n}] in class ${t.instance.constructor.workerId}`;postCommand(e,await t.instance[n](...null!=r?r:[]))}const registeredWorkers=createGlobalThisVariable("registeredWorkers",{});function registerWorker(e,t){t.workerId=e,isWorker()&&(registeredWorkers[t.workerId]=t)}function handleCommandInit(e,t){if(!e.args)throw"Missing className while initializing worker";const[n,r]=e.args,s=registeredWorkers[n];if(!s)throw`unknown worker class ${n}`;t.instance=new s(e.args.slice(1)),copy(r,globals),isInstanceOfEmittery(t.instance)&&t.instance.onAny(((e,t)=>{postCommand({type:CommandType.EVENT},{name:e,data:t})})),postCommand(e,void 0!==typeof t.instance)}async function handleCommandTerminate(e,t){const{args:n}=e;if(!t.instance)throw"instance not initialized";let r;t.instance.terminate&&(r=await t.instance.terminate(...null!=n?n:[])),postCommand(e,r)}function handleCommandGlobalsSync(e){if(!e.args)throw"Missing globals while syncing";copy(e.args[0],globals),postCommand(e,{})}function initWorker(){const e={};onmessage=async t=>{const n=t.data;switch(n.type){case CommandType.INIT:handleCommandInit(n,e);break;case CommandType.FORWARD:handleCommandForward(n,e);break;case CommandType.TERMINATE:handleCommandTerminate(n,e);break;case CommandType.GLOBALS_SYNC:handleCommandGlobalsSync(n)}}}function createGlobal(e,t){return globals[e]||(globals[e]=t),[()=>globals[e],async t=>{globals[e]=t,await globalsSync()}]}function registerGlobal(e,t){return createGlobal(e,t)}isWorker()&&initWorker();

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["js-workerizer"]={})}(this,(function(e){"use strict";function createGlobalThisVariable(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let n=globalThis.vonage.workerizer;return n[e]||(n[e]=t),n[e]}const t=createGlobalThisVariable("globals",{});var n=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(n||{});function isTransferable(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let r=0;function postCommand$1(e,t,n,o,s){const i=r++;e.postMessage({id:i,type:t,functionName:n,args:o},o.filter((e=>isTransferable(e))));return new Promise((e=>{null==s||s.set(i,e)}))}function postCommand(e,t){const{id:n,type:r}=e,o=Array.isArray(t)?t:[t];postMessage({id:n,type:r,result:t},o.filter((e=>isTransferable(e))))}const o=createGlobalThisVariable("workerized",{});function isWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}async function globalsSync(){if(isWorker())postCommand({type:n.GLOBALS_SYNC},t);else{const e=[];for(const r in o){const{worker:s,resolvers:i}=o[r].workerContext;s&&e.push(postCommand$1(s,n.GLOBALS_SYNC,"",[t],i))}await Promise.all(e)}}function copy(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const n in t)delete t[n];for(const n in e)Array.isArray(e[n])?(t[n]=[],copy(e[n],t[n])):"object"==typeof e[n]?(t[n]={},copy(e[n],t[n])):t[n]=e[n]}const s=new WeakMap,i=new WeakMap,a=new WeakMap,l=Symbol("anyProducer"),c=Promise.resolve(),f=Symbol("listenerAdded"),u=Symbol("listenerRemoved");let d=!1,g=!1;function assertEventName(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function assertListener(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function getListeners(e,t){const n=i.get(e);if(n.has(t))return n.get(t)}function getEventProducers(e,t){const n="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:l,r=a.get(e);if(r.has(n))return r.get(n)}function iterator(e,t){t=Array.isArray(t)?t:[t];let n=!1,flush=()=>{},r=[];const o={enqueue(e){r.push(e),flush()},finish(){n=!0,flush()}};for(const s of t){let t=getEventProducers(e,s);if(!t){t=new Set;a.get(e).set(s,t)}t.add(o)}return{async next(){return r?0===r.length?n?(r=void 0,this.next()):(await new Promise((e=>{flush=e})),this.next()):{done:!1,value:await r.shift()}:{done:!0}},async return(n){r=void 0;for(const r of t){const t=getEventProducers(e,r);if(t&&(t.delete(o),0===t.size)){a.get(e).delete(r)}}return flush(),arguments.length>0?{done:!0,value:await n}:{done:!0}},[Symbol.asyncIterator](){return this}}}function defaultMethodNamesOrAssert(e){if(void 0===e)return m;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!m.includes(t)){if("string"!=typeof t)throw new TypeError("`methodNames` element must be a string");throw new Error(`${t} is not Emittery method`)}return e}const isMetaEvent=e=>e===f||e===u;function emitMetaEvent(e,t,n){if(isMetaEvent(t))try{d=!0,e.emit(t,n)}finally{d=!1}}class Emittery{static mixin(e,t){return t=defaultMethodNamesOrAssert(t),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,e,{enumerable:!1,get:function getEmitteryProperty(){return Object.defineProperty(this,e,{enumerable:!1,value:new Emittery}),this[e]}});const emitteryMethodCaller=t=>function(...n){return this[e][t](...n)};for(const e of t)Object.defineProperty(n.prototype,e,{enumerable:!1,value:emitteryMethodCaller(e)});return n}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return g;const{env:n}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===n.DEBUG||"*"===n.DEBUG||g}static set isDebugEnabled(e){g=e}constructor(e={}){var t;s.set(this,new Set),i.set(this,new Map),a.set(this,new Map),a.get(this).set(l,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,n,r)=>{try{r=JSON.stringify(r)}catch{r=`Object with the following keys failed to stringify: ${Object.keys(r).join(",")}`}"symbol"!=typeof n&&"number"!=typeof n||(n=n.toString());const o=new Date,s=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${s}][emittery:${e}][${t}] Event Name: ${n}\n\tdata: ${r}`)})}logIfDebugEnabled(e,t,n){(Emittery.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);let e=getListeners(this,n);if(!e){e=new Set;i.get(this).set(n,e)}e.add(t),this.logIfDebugEnabled("subscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,f,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);const e=getListeners(this,n);if(e&&(e.delete(t),0===e.size)){i.get(this).delete(n)}this.logIfDebugEnabled("unsubscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,u,{eventName:n,listener:t})}}once(e){let t;const n=new Promise((n=>{t=this.on(e,(e=>{t(),n(e)}))}));return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)assertEventName(t);return iterator(this,e)}async emit(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!d)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),function enqueueProducers(e,t,n){const r=a.get(e);if(r.has(t))for(const o of r.get(t))o.enqueue(n);if(r.has(l)){const e=Promise.all([t,n]);for(const t of r.get(l))t.enqueue(e)}}(this,e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=s.get(this),i=[...r],f=isMetaEvent(e)?[]:[...o];await c,await Promise.all([...i.map((async e=>{if(r.has(e))return e(t)})),...f.map((async n=>{if(o.has(n))return n(e,t)}))])}async emitSerial(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!d)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=s.get(this),i=[...r],a=[...o];await c;for(const s of i)r.has(s)&&await s(t);for(const s of a)o.has(s)&&await s(e,t)}onAny(e){return assertListener(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),s.get(this).add(e),emitMetaEvent(this,f,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return iterator(this)}offAny(e){assertListener(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),emitMetaEvent(this,u,{listener:e}),s.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=getListeners(this,t);e&&e.clear();const n=getEventProducers(this,t);if(n){for(const e of n)e.finish();n.clear()}}else{s.get(this).clear();for(const[e,t]of i.get(this).entries())t.clear(),i.get(this).delete(e);for(const[e,t]of a.get(this).entries()){for(const e of t)e.finish();t.clear(),a.get(this).delete(e)}}}listenerCount(e){var t,n,r,o,l,c;e=Array.isArray(e)?e:[e];let f=0;for(const u of e)if("string"!=typeof u){void 0!==u&&assertEventName(u),f+=s.get(this).size;for(const e of i.get(this).values())f+=e.size;for(const e of a.get(this).values())f+=e.size}else f+=s.get(this).size+(null!=(n=null==(t=getListeners(this,u))?void 0:t.size)?n:0)+(null!=(o=null==(r=getEventProducers(this,u))?void 0:r.size)?o:0)+(null!=(c=null==(l=getEventProducers(this))?void 0:l.size)?c:0);return f}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=defaultMethodNamesOrAssert(t);for(const n of t){if(void 0!==e[n])throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const m=Object.getOwnPropertyNames(Emittery.prototype).filter((e=>"constructor"!==e));function isExtending(e,t){let n=e;if(e==t)return!0;do{if(n.prototype instanceof t)return!0}while(n=Object.getPrototypeOf(n));return!1}Object.defineProperty(Emittery,"listenerAdded",{value:f,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Emittery,"listenerRemoved",{value:u,writable:!1,enumerable:!0,configurable:!1});let y=0;const h=createGlobalThisVariable("registeredWorkers",{});function initWorker(){const e={};onmessage=async r=>{const o=r.data;switch(o.type){case n.INIT:!function handleCommandInit(e,r){if(!e.args)throw"Missing className while initializing worker";const[o,s]=e.args,i=h[o];if(!i)throw`unknown worker class ${o}`;r.instance=new i(e.args.slice(1)),copy(s,t),isExtending(i,Emittery)&&r.instance.onAny(((e,t)=>{postCommand({type:n.EVENT},{name:e,data:t})})),postCommand(e,void 0!==typeof r.instance)}(o,e);break;case n.FORWARD:!async function handleCommandForward(e,t){const{functionName:n,args:r}=e;if(!t.instance)throw"instance not initialized";if(!n)throw"missing function name to call";if(!t.instance[n])throw`undefined function [${n}] in class ${t.instance.constructor.workerId}`;postCommand(e,await t.instance[n](...null!=r?r:[]))}(o,e);break;case n.TERMINATE:!async function handleCommandTerminate(e,t){const{args:n}=e;if(!t.instance)throw"instance not initialized";let r;t.instance.terminate&&(r=await t.instance.terminate(...null!=n?n:[])),postCommand(e,r)}(o,e);break;case n.GLOBALS_SYNC:!function handleCommandGlobalsSync(e){if(!e.args)throw"Missing globals while syncing";copy(e.args[0],t),postCommand(e,{})}(o)}}}isWorker()&&initWorker(),e.CommandType=n,e.initWorker=initWorker,e.registerGlobal=function registerGlobal(e,n){return function createGlobal(e,n){return t[e]||(t[e]=n),[()=>t[e],async n=>{t[e]=n,await globalsSync()}]}(e,n)},e.registerWorker=function registerWorker(e,t){t.workerId=e,isWorker()&&(h[t.workerId]=t)},e.registeredWorkers=h,e.workerize=async function workerize(e,r){const s=new Map;let i;const a=await async function createWorker(e,r,o,s){const i=new r;if(i.addEventListener("message",(async({data:e})=>{var r,i,a,l,c,f,u;switch(e.type){case n.GLOBALS_SYNC:e.id?(null==(i=o.get(null!=(r=e.id)?r:-1))||i(e.result),o.delete(null!=(a=e.id)?a:-1)):(copy(null!=(l=e.result)?l:{},t),await globalsSync());break;case n.EVENT:const{result:d}=e,g=d;if(null==(null==g?void 0:g.name))throw"Missing event name";s(g.name,g.data);break;default:null==(f=o.get(null!=(c=e.id)?c:-1))||f(e.result),o.delete(null!=(u=e.id)?u:-1)}})),!(await postCommand$1(i,n.INIT,"",[e.workerId,t],o)))throw"Failed to instantiate workerized class";return i}(e,r,s,((e,t)=>{(null==i?void 0:i.emit)&&(null==i||i.emit(e,t))}));return i=await async function createWorkerized(e,t,r){const s=isExtending(e,Emittery)?new Emittery:{},i=y++;return Object.getOwnPropertyNames(e.prototype).forEach((e=>{s[e]=(...o)=>postCommand$1(t,n.FORWARD,e,o,r)})),s.terminate=async(...e)=>{const a=await postCommand$1(t,n.TERMINATE,"",e,r);return delete o[i],t.terminate(),s.workerContext.worker=void 0,a},s.workerContext={id:i,worker:t,resolvers:r},o[i]=s,s}(e,a,s),i},Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["js-workerizer"]={})}(this,(function(e){"use strict";function createGlobalThisVariable(e,t){globalThis.vonage||(globalThis.vonage={}),globalThis.vonage.workerizer||(globalThis.vonage.workerizer={});let n=globalThis.vonage.workerizer;return n[e]||(n[e]=t),n[e]}const t=createGlobalThisVariable("globals",{});var n=(e=>(e.INIT="INIT",e.FORWARD="FORWARD",e.TERMINATE="TERMINATE",e.GLOBALS_SYNC="GLOBALS_SYNC",e.EVENT="EVENT",e))(n||{});function isTransferable(e){return[ImageBitmap,ReadableStream,WritableStream].some((t=>e instanceof t))}let r=0;function postCommand$1(e,t,n,o,s){const i=r++;e.postMessage({id:i,type:t,functionName:n,args:o},o.filter((e=>isTransferable(e))));return new Promise((e=>{null==s||s.set(i,e)}))}function postCommand(e,t){const{id:n,type:r}=e,o=Array.isArray(t)?t:[t];postMessage({id:n,type:r,result:t},o.filter((e=>isTransferable(e))))}const o=createGlobalThisVariable("workerized",{});function isWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}async function globalsSync(){if(isWorker())postCommand({type:n.GLOBALS_SYNC},t);else{const e=[];for(const r in o){const{worker:s,resolvers:i}=o[r].workerContext;s&&e.push(postCommand$1(s,n.GLOBALS_SYNC,"",[t],i))}await Promise.all(e)}}function copy(e,t){if(Array.isArray(t))t.splice(0,t.length);else if("object"==typeof t)for(const n in t)delete t[n];for(const n in e)Array.isArray(e[n])?(t[n]=[],copy(e[n],t[n])):"object"==typeof e[n]?(t[n]={},copy(e[n],t[n])):t[n]=e[n]}const s=new WeakMap,i=new WeakMap,a=new WeakMap,l=Symbol("anyProducer"),c=Promise.resolve(),f=Symbol("listenerAdded"),u=Symbol("listenerRemoved");let d=!1,m=!1;function assertEventName(e){if("string"!=typeof e&&"symbol"!=typeof e&&"number"!=typeof e)throw new TypeError("`eventName` must be a string, symbol, or number")}function assertListener(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function getListeners(e,t){const n=i.get(e);if(n.has(t))return n.get(t)}function getEventProducers(e,t){const n="string"==typeof t||"symbol"==typeof t||"number"==typeof t?t:l,r=a.get(e);if(r.has(n))return r.get(n)}function iterator(e,t){t=Array.isArray(t)?t:[t];let n=!1,flush=()=>{},r=[];const o={enqueue(e){r.push(e),flush()},finish(){n=!0,flush()}};for(const s of t){let t=getEventProducers(e,s);if(!t){t=new Set;a.get(e).set(s,t)}t.add(o)}return{async next(){return r?0===r.length?n?(r=void 0,this.next()):(await new Promise((e=>{flush=e})),this.next()):{done:!1,value:await r.shift()}:{done:!0}},async return(n){r=void 0;for(const r of t){const t=getEventProducers(e,r);if(t&&(t.delete(o),0===t.size)){a.get(e).delete(r)}}return flush(),arguments.length>0?{done:!0,value:await n}:{done:!0}},[Symbol.asyncIterator](){return this}}}function defaultMethodNamesOrAssert(e){if(void 0===e)return g;if(!Array.isArray(e))throw new TypeError("`methodNames` must be an array of strings");for(const t of e)if(!g.includes(t)){if("string"!=typeof t)throw new TypeError("`methodNames` element must be a string");throw new Error(`${t} is not Emittery method`)}return e}const isMetaEvent=e=>e===f||e===u;function emitMetaEvent(e,t,n){if(isMetaEvent(t))try{d=!0,e.emit(t,n)}finally{d=!1}}class Emittery{static mixin(e,t){return t=defaultMethodNamesOrAssert(t),n=>{if("function"!=typeof n)throw new TypeError("`target` must be function");for(const e of t)if(void 0!==n.prototype[e])throw new Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(n.prototype,e,{enumerable:!1,get:function getEmitteryProperty(){return Object.defineProperty(this,e,{enumerable:!1,value:new Emittery}),this[e]}});const emitteryMethodCaller=t=>function(...n){return this[e][t](...n)};for(const e of t)Object.defineProperty(n.prototype,e,{enumerable:!1,value:emitteryMethodCaller(e)});return n}}static get isDebugEnabled(){var e,t;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return m;const{env:n}=null!=(t=globalThis.process)?t:{env:{}};return"emittery"===n.DEBUG||"*"===n.DEBUG||m}static set isDebugEnabled(e){m=e}constructor(e={}){var t;s.set(this,new Set),i.set(this,new Map),a.set(this,new Map),a.get(this).set(l,new Set),this.debug=null!=(t=e.debug)?t:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,t,n,r)=>{try{r=JSON.stringify(r)}catch{r=`Object with the following keys failed to stringify: ${Object.keys(r).join(",")}`}"symbol"!=typeof n&&"number"!=typeof n||(n=n.toString());const o=new Date,s=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${s}][emittery:${e}][${t}] Event Name: ${n}\n\tdata: ${r}`)})}logIfDebugEnabled(e,t,n){(Emittery.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,t,n)}on(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);let e=getListeners(this,n);if(!e){e=new Set;i.get(this).set(n,e)}e.add(t),this.logIfDebugEnabled("subscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,f,{eventName:n,listener:t})}return this.off.bind(this,e,t)}off(e,t){assertListener(t),e=Array.isArray(e)?e:[e];for(const n of e){assertEventName(n);const e=getListeners(this,n);if(e&&(e.delete(t),0===e.size)){i.get(this).delete(n)}this.logIfDebugEnabled("unsubscribe",n,void 0),isMetaEvent(n)||emitMetaEvent(this,u,{eventName:n,listener:t})}}once(e){let t;const n=new Promise((n=>{t=this.on(e,(e=>{t(),n(e)}))}));return n.off=t,n}events(e){e=Array.isArray(e)?e:[e];for(const t of e)assertEventName(t);return iterator(this,e)}async emit(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!d)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,t),function enqueueProducers(e,t,n){const r=a.get(e);if(r.has(t))for(const o of r.get(t))o.enqueue(n);if(r.has(l)){const e=Promise.all([t,n]);for(const t of r.get(l))t.enqueue(e)}}(this,e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=s.get(this),i=[...r],f=isMetaEvent(e)?[]:[...o];await c,await Promise.all([...i.map((async e=>{if(r.has(e))return e(t)})),...f.map((async n=>{if(o.has(n))return n(e,t)}))])}async emitSerial(e,t){var n;if(assertEventName(e),isMetaEvent(e)&&!d)throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,t);const r=null!=(n=getListeners(this,e))?n:new Set,o=s.get(this),i=[...r],a=[...o];await c;for(const s of i)r.has(s)&&await s(t);for(const s of a)o.has(s)&&await s(e,t)}onAny(e){return assertListener(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),s.get(this).add(e),emitMetaEvent(this,f,{listener:e}),this.offAny.bind(this,e)}anyEvent(){return iterator(this)}offAny(e){assertListener(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),emitMetaEvent(this,u,{listener:e}),s.get(this).delete(e)}clearListeners(e){e=Array.isArray(e)?e:[e];for(const t of e)if(this.logIfDebugEnabled("clear",t,void 0),"string"==typeof t||"symbol"==typeof t||"number"==typeof t){const e=getListeners(this,t);e&&e.clear();const n=getEventProducers(this,t);if(n){for(const e of n)e.finish();n.clear()}}else{s.get(this).clear();for(const[e,t]of i.get(this).entries())t.clear(),i.get(this).delete(e);for(const[e,t]of a.get(this).entries()){for(const e of t)e.finish();t.clear(),a.get(this).delete(e)}}}listenerCount(e){var t,n,r,o,l,c;e=Array.isArray(e)?e:[e];let f=0;for(const u of e)if("string"!=typeof u){void 0!==u&&assertEventName(u),f+=s.get(this).size;for(const e of i.get(this).values())f+=e.size;for(const e of a.get(this).values())f+=e.size}else f+=s.get(this).size+(null!=(n=null==(t=getListeners(this,u))?void 0:t.size)?n:0)+(null!=(o=null==(r=getEventProducers(this,u))?void 0:r.size)?o:0)+(null!=(c=null==(l=getEventProducers(this))?void 0:l.size)?c:0);return f}bindMethods(e,t){if("object"!=typeof e||null===e)throw new TypeError("`target` must be an object");t=defaultMethodNamesOrAssert(t);for(const n of t){if(void 0!==e[n])throw new Error(`The property \`${n}\` already exists on \`target\``);Object.defineProperty(e,n,{enumerable:!1,value:this[n].bind(this)})}}}const g=Object.getOwnPropertyNames(Emittery.prototype).filter((e=>"constructor"!==e));Object.defineProperty(Emittery,"listenerAdded",{value:f,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Emittery,"listenerRemoved",{value:u,writable:!1,enumerable:!0,configurable:!1});let y=0;const h=createGlobalThisVariable("registeredWorkers",{});function initWorker(){const e={};onmessage=async r=>{const o=r.data;switch(o.type){case n.INIT:!function handleCommandInit(e,r){if(!e.args)throw"Missing className while initializing worker";const[o,s]=e.args,i=h[o];if(!i)throw`unknown worker class ${o}`;r.instance=new i(e.args.slice(1)),copy(s,t),function isInstanceOfEmittery(e){return e.onAny&&e.emit}(r.instance)&&r.instance.onAny(((e,t)=>{postCommand({type:n.EVENT},{name:e,data:t})})),postCommand(e,void 0!==typeof r.instance)}(o,e);break;case n.FORWARD:!async function handleCommandForward(e,t){const{functionName:n,args:r}=e;if(!t.instance)throw"instance not initialized";if(!n)throw"missing function name to call";if(!t.instance[n])throw`undefined function [${n}] in class ${t.instance.constructor.workerId}`;postCommand(e,await t.instance[n](...null!=r?r:[]))}(o,e);break;case n.TERMINATE:!async function handleCommandTerminate(e,t){const{args:n}=e;if(!t.instance)throw"instance not initialized";let r;t.instance.terminate&&(r=await t.instance.terminate(...null!=n?n:[])),postCommand(e,r)}(o,e);break;case n.GLOBALS_SYNC:!function handleCommandGlobalsSync(e){if(!e.args)throw"Missing globals while syncing";copy(e.args[0],t),postCommand(e,{})}(o)}}}isWorker()&&initWorker(),e.CommandType=n,e.initWorker=initWorker,e.registerGlobal=function registerGlobal(e,n){return function createGlobal(e,n){return t[e]||(t[e]=n),[()=>t[e],async n=>{t[e]=n,await globalsSync()}]}(e,n)},e.registerWorker=function registerWorker(e,t){t.workerId=e,isWorker()&&(h[t.workerId]=t)},e.registeredWorkers=h,e.workerize=async function workerize(e,r){const s=new Map;let i;const a=await async function createWorker(e,r,o,s){const i=new r;if(i.addEventListener("message",(async({data:e})=>{var r,i,a,l,c,f,u;switch(e.type){case n.GLOBALS_SYNC:e.id?(null==(i=o.get(null!=(r=e.id)?r:-1))||i(e.result),o.delete(null!=(a=e.id)?a:-1)):(copy(null!=(l=e.result)?l:{},t),await globalsSync());break;case n.EVENT:const{result:d}=e,m=d;if(null==(null==m?void 0:m.name))throw"Missing event name";s(m.name,m.data);break;default:null==(f=o.get(null!=(c=e.id)?c:-1))||f(e.result),o.delete(null!=(u=e.id)?u:-1)}})),!(await postCommand$1(i,n.INIT,"",[e.workerId,t],o)))throw"Failed to instantiate workerized class";return i}(e,r,s,((e,t)=>{(null==i?void 0:i.emit)&&(null==i||i.emit(e,t))}));return i=await async function createWorkerized(e,t,r){const s=function isChildClassOfEmittery(e){return e.prototype.onAny&&e.prototype.emit}(e)?new Emittery:{},i=y++;return Object.getOwnPropertyNames(e.prototype).forEach((e=>{s[e]=(...o)=>postCommand$1(t,n.FORWARD,e,o,r)})),s.terminate=async(...e)=>{const a=await postCommand$1(t,n.TERMINATE,"",e,r);return delete o[i],t.terminate(),s.workerContext.worker=void 0,a},s.workerContext={id:i,worker:t,resolvers:r},o[i]=s,s}(e,a,s),i},Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
{
"name": "@vonage/js-workerizer",
"version": "1.2.2",
"version": "1.2.3",
"description": "Library providing a simple way to run a class instance on its dedicated worker.",

@@ -5,0 +5,0 @@ "types": "./dist/types/index.d.ts",

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