UNPKG

proxied-worker

Version:

A tiny utility to asynchronously drive a namespace exposed through a Shared/Service/Worker

3 lines (2 loc) 1.11 kB
/*! (c) Andrea Giammarchi - ISC */ let t=0;export default function(e){const n=new WeakMap;async function a(e,a,i){const r=i.shift();let{length:o}=i;"get"!==r&&o--,"apply"===r&&o--;for(let t=0;t<o;t++)a=await a[i[t]];if("new"===r){const r=new a(...i.pop().map(s,e));n.get(this).set(a=String(t++),r)}else"apply"===r&&(a=await a[i[o]](...i.pop().map(s,e)));return a}async function i(t){const{source:s,data:{id:i,list:r}}=t;if(!/^proxied-worker:([^:]*?):-?\d+$/.test(i))return;const o=RegExp.$1,c=s||this;let l,g;if(n.has(this)||n.set(this,new Map),o.length){const t=n.get(this);if(!r.length)return void t.delete(o);try{l=await a.call(this,c,t.get(o),r)}catch({message:t}){g=t}}else try{l=await a.call(this,c,e,r)}catch({message:t}){g=t}c.postMessage({id:i,result:l,error:g})}addEventListener("connect",(({ports:t=[]})=>{for(const e of t)e.addEventListener("message",i.bind(e)),e.start()})),addEventListener("message",i.bind(globalThis))};const e=new Map;function s(t){return"string"==typeof t?/^proxied-worker:cb:/.test(t)?(e.has(t)||e.set(t,((...e)=>{this.postMessage({id:t,args:e})})),e.get(t)):t.slice(1):t}