UNPKG

reactive-channel

Version:

A simple yet powerful abstraction that enables communication between asynchronous tasks.

38 lines (37 loc) 13.1 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var D=Object.defineProperty,F=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable,H=(e,r,c)=>r in e?D(e,r,{enumerable:!0,configurable:!0,writable:!0,value:c}):e[r]=c,G=(e,r)=>{for(var c in r||(r={}))L.call(r,c)&&H(e,c,r[c]);if(F)for(var c of F(r))B.call(r,c)&&H(e,c,r[c]);return e};function J(){const e=[];function r(n){if(e.length!==0)for(const i of e.slice())i(n)}function c(n){const i=e.indexOf(n);i!==-1&&e.splice(i,1)}function t(n){return e.indexOf(n)===-1&&e.push(n),()=>c(n)}function s(n){const i=t(u=>{i(),n(u)});return i}return{emit:r,subscribe:t,subscribeOnce:s,nOfSubscriptions(){return e.length}}}/** * @license * Copyright (c) 2016-22 [these people](https://github.com/sveltejs/svelte/graphs/contributors) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function j(e,r,c){const t=Array.isArray(e),s=!t&&"subscribe"in e&&"nOfSubscriptions"in e&&"content"in e,n=s?1:t?e.length:Object.keys(e).length;return K(void 0,{comparator:c==null?void 0:c.comparator,start:n===0?u=>{u(r(t?[]:{}))}:s?u=>e.subscribe(f=>u(r(f))):t?u=>{let d=new Array(e.length),f=0;const $=e.map((h,a)=>h.subscribe(v=>{if(f<n&&(d[a]=v,f++),f===n){const p=[...d];p[a]=v,u(r(p)),d=p}}));return()=>{for(const h of $)h();f=0}}:u=>{let d={},f=0;const $=Object.entries(e).map(([h,a])=>a.subscribe(v=>{if(f<n&&(d[h]=v,f++),f===n){const p=G({},d);p[h]=v,u(r(p)),d=p}}));return()=>{for(const h of $)h();f=0}}})}/** * @license * Copyright (c) 2016-22 [these people](https://github.com/sveltejs/svelte/graphs/contributors) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function T(e,r){var c;let t=e;const s=J();let n;const i=typeof r=="function"?r:r==null?void 0:r.start,u=(c=typeof r=="function"||r==null?void 0:r.comparator)!=null?c:(a,v)=>a===v,d=()=>{if(s.nOfSubscriptions()>0)return t;let a;return $(p=>a=p)(),a},f=a=>{t!==void 0&&u(t,a)||(t=a,s.emit(t))},$=a=>{s.nOfSubscriptions()===0&&(n=i==null?void 0:i(f));const v=s.subscribe(a);return a(t),()=>{v(),s.nOfSubscriptions()===0&&(n==null||n(),n=void 0)}};return{content:d,set:f,subscribe:$,update:a=>{f(a(d()))},nOfSubscriptions:s.nOfSubscriptions}}function K(e,r){const{content:c,nOfSubscriptions:t,subscribe:s}=T(e,r);return{content:c,nOfSubscriptions:t,subscribe:s}}class k extends Error{constructor(r,c){super(`queue doesn't contain enough elements, requested ${r}, filled slots ${c}`),this.requestedItems=r,this.filledSlots=c}}class Q extends Error{constructor(r,c){super(`queue doesn't have enough space, requested ${r}, available slots ${c}`),this.requestedItems=r,this.availableSlots=c}}function C(e,r){const c=Array.isArray(e),t=c?r!=null?r:e.length:e;let s=new Array(t),n=0,i=0;const u=T(0),d=j(u,o=>o===t),f=j(u,o=>o===0),$=j(u,o=>t-o);if(c){const o=Math.min(e.length,t);for(let l=0;l<o;l++)s[i]=e[l],i=(i+1)%t;u.update(l=>l+o)}const h=o=>{if(d.content())throw new Q(1,0);s[i]=o,i=(i+1)%t,u.update(l=>l+1)},a=o=>{const l=$.content();if(l<o.length)throw new Q(o.length,l);for(let b=0;b<o.length;b++)s[i]=o[b],i=(i+1)%t;u.update(b=>b+o.length)},v=()=>{n=0,i=0,s=new Array(t),u.set(0)};function p(o){const l=u.content();if(typeof o=="undefined"){if(l===0)throw new k(1,0);const b=s[n];return s[n]=void 0,n=(n+1)%t,u.update(E=>E-1),b}else{if(o>l)throw new k(o,l);const b=new Array(o);for(let E=0;E<b.length;E++)b[E]=s[(n+E)%t],s[(n+E)%t]=void 0;return n=(n+o)%t,u.set(l-o),b}}const O=()=>p(u.content());function*m(){for(;u.content()>0;)yield p()}return{enqueue:h,enqueueMulti:a,dequeue:p,dequeueAll:O,toArray:()=>{const o=new Array(u.content());for(let l=0;l<o.length;l++)o[l]=s[(n+l)%t];return o},at:o=>{const l=u.content();if(!(o>=l||o<-l))return o>=0?s[(n+o)%t]:s[(n+l+o)%t]},indexOf:o=>{const l=u.content();for(let b=0;b<l;b++)if(s[(n+b)%t]===o)return b;return-1},replace:(o,l)=>{const b=u.content();if(o>=b||o<-b)throw new RangeError(`${o} is not a valid positive nor negative index. The number of filled slots is ${b}`);const E=o>=0?o:b+o,R=(n+E)%t,_=s[R];return s[R]=l,_},remove:o=>{const l=u.content();if(o>=l||o<-l)throw new RangeError(`${o} is not a valid positive nor negative index. The number of filled slots is ${l}`);const b=o>=0?o:l+o,E=(n+b)%t,R=s[E];if(l-b<b){for(let _=n;_<n+l-b-1;_++)s[_%t]=s[(_+1)%t];i=(i+t-1)%t}else{for(let _=n+b-1;_>=n;_--)s[(_+1)%t]=s[_%t];n=(n+1)%t}return u.set(l-1),R},availableSlots$:$,filledSlots$:u,capacity:t,iter:m,[Symbol.iterator]:m,full$:d,empty$:f,clear:v}}var U=Object.defineProperty,M=Object.getOwnPropertySymbols,X=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,N=(e,r,c)=>r in e?U(e,r,{enumerable:!0,configurable:!0,writable:!0,value:c}):e[r]=c,Z=(e,r)=>{for(var c in r||(r={}))X.call(r,c)&&N(e,c,r[c]);if(M)for(var c of M(r))Y.call(r,c)&&N(e,c,r[c]);return e};function V(){const e=[];function r(n){if(e.length!==0)for(const i of e.slice())i(n)}function c(n){const i=e.indexOf(n);i!==-1&&e.splice(i,1)}function t(n){return e.indexOf(n)===-1&&e.push(n),()=>c(n)}function s(n){const i=t(u=>{i(),n(u)});return i}return{emit:r,subscribe:t,subscribeOnce:s,nOfSubscriptions(){return e.length}}}/** * @license * Copyright (c) 2016-22 [these people](https://github.com/sveltejs/svelte/graphs/contributors) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function S(e,r,c){const t=Array.isArray(e),s=!t&&"subscribe"in e&&"nOfSubscriptions"in e&&"content"in e,n=s?1:t?e.length:Object.keys(e).length;return ee(void 0,{comparator:c==null?void 0:c.comparator,start:n===0?u=>{u(r(t?[]:{}))}:s?u=>e.subscribe(f=>u(r(f))):t?u=>{let d=new Array(e.length),f=0;const $=e.map((h,a)=>h.subscribe(v=>{if(f<n&&(d[a]=v,f++),f===n){const p=[...d];p[a]=v,u(r(p)),d=p}}));return()=>{for(const h of $)h();f=0}}:u=>{let d={},f=0;const $=Object.entries(e).map(([h,a])=>a.subscribe(v=>{if(f<n&&(d[h]=v,f++),f===n){const p=Z({},d);p[h]=v,u(r(p)),d=p}}));return()=>{for(const h of $)h();f=0}}})}/** * @license * Copyright (c) 2016-22 [these people](https://github.com/sveltejs/svelte/graphs/contributors) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function W(e,r){var c;let t=e;const s=V();let n;const i=typeof r=="function"?r:r==null?void 0:r.start,u=(c=typeof r=="function"||r==null?void 0:r.comparator)!=null?c:(a,v)=>a===v,d=()=>{if(s.nOfSubscriptions()>0)return t;let a;return $(p=>a=p)(),a},f=a=>{t!==void 0&&u(t,a)||(t=a,s.emit(t))},$=a=>{s.nOfSubscriptions()===0&&(n=i==null?void 0:i(f));const v=s.subscribe(a);return a(t),()=>{v(),s.nOfSubscriptions()===0&&(n==null||n(),n=void 0)}};return{content:d,set:f,subscribe:$,update:a=>{f(a(d()))},nOfSubscriptions:s.nOfSubscriptions}}function ee(e,r){const{content:c,nOfSubscriptions:t,subscribe:s}=W(e,r);return{content:c,nOfSubscriptions:t,subscribe:s}}const A=()=>{};class I extends Error{constructor(){super("channel full, cannot enqueue data")}}class q extends Error{constructor(){super("channel closed")}}class z extends Error{constructor(){super("channel has already too many pending recv")}}function ne(e){const{capacity:r=1024,maxConcurrentPendingRecv:c=1024}=e||{},t=C(r),s=C(r),n=C(c),i=W(!1),u=S([i,t.availableSlots$],([m,g])=>m?0:g),d=S([i,t.filledSlots$],([m,g])=>m?0:g),f=S(u,m=>m>0),$=S([d,n.full$],([m,g])=>m>0&&!g);async function h(m,g){if(i.content())throw new q;if(t.full$.content())throw new I;let P=A,x=A;const w=new Promise((o,l)=>{P=o,x=l});let y;n.empty$.content()?(y={promise:w,resolveSend:P,rejectSend:x},t.enqueue(y),s.enqueue(m)):n.dequeue().resolveRecv({promise:w,resolveSend:P,rejectSend:x,value:m});try{if(!(g!=null&&g.signal))await w;else{const o=g.signal;o.throwIfAborted(),await Promise.race([w,new Promise((l,b)=>{o.addEventListener("abort",()=>{Promise.resolve().then(()=>b(o.reason)).catch(A)})})])}}catch(o){if(y){const l=t.indexOf(y);l!==-1&&(t.remove(l),s.remove(l))}throw o}}function a(m){if(i.content())throw new q;if(t.full$.content())throw new I;h(m).catch(A)}async function v(m){if(i.content())throw new q;let g;if(!t.empty$.content())g={...t.dequeue(),value:s.dequeue()};else{if(n.full$.content())throw new z;const P={resolveRecv:A,rejectRecv:A},x=new Promise((w,y)=>{P.resolveRecv=w,P.rejectRecv=y,n.enqueue(P)});try{if(!(m!=null&&m.signal))g=await x;else{const w=m.signal;w.throwIfAborted(),g=await Promise.race([x,new Promise((y,o)=>{w.addEventListener("abort",()=>{Promise.resolve().then(()=>o(w.reason)).catch(A)})})])}}catch(w){const y=n.indexOf(P);throw y!==-1&&n.remove(y),w}}return g.resolveSend(),g.value}async function*p(){for(;t.filledSlots$.content()>0;)yield await v()}function O(){if(i.content())return;i.set(!0);const m=new q;for(const g of n)g.rejectRecv(m);for(const g of t)g.rejectSend(m);s.clear()}return{buffer:s,tx:{send:a,sendWait:h,canWrite$:f,closed$:i,close:O,availableOutboxSlots$:u,capacity:r},rx:{pendingRecvPromises$:n.filledSlots$,recv:v,iter:p,[Symbol.asyncIterator]:p,canRead$:$,closed$:i,close:O,capacity:r,filledInboxSlots$:d}}}exports.ChannelClosedError=q;exports.ChannelFullError=I;exports.ChannelTooManyPendingRecvError=z;exports.NotEnoughAvailableSlotsQueueError=Q;exports.NotEnoughFilledSlotsQueueError=k;exports.makeChannel=ne;