reactive-channel
Version:
A simple yet powerful abstraction that enables communication between asynchronous tasks.
738 lines (737 loc) • 26.3 kB
JavaScript
var __defProp$1 = Object.defineProperty;
var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$1 = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
if (__getOwnPropSymbols$1)
for (var prop of __getOwnPropSymbols$1(b)) {
if (__propIsEnum$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
}
return a;
};
function makeSignal$1() {
const subscribers = [];
function emit(v) {
if (subscribers.length === 0) {
return;
}
for (const subscriber of subscribers.slice()) {
subscriber(v);
}
}
function unsubscribe(subscriber) {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
}
function subscribe(subscriber) {
const index = subscribers.indexOf(subscriber);
if (index === -1) {
subscribers.push(subscriber);
}
return () => unsubscribe(subscriber);
}
function subscribeOnce(subscriber) {
const unsubscribeWrapper = subscribe((v) => {
unsubscribeWrapper();
subscriber(v);
});
return unsubscribeWrapper;
}
return {
emit,
subscribe,
subscribeOnce,
nOfSubscriptions() {
return subscribers.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 makeDerivedStore$1(readonlyStoreOrStores, map, config) {
const isArray = Array.isArray(readonlyStoreOrStores);
const argumentIsAStore = !isArray && "subscribe" in readonlyStoreOrStores && "nOfSubscriptions" in readonlyStoreOrStores && "content" in readonlyStoreOrStores;
const nOfSources = argumentIsAStore ? 1 : isArray ? readonlyStoreOrStores.length : Object.keys(readonlyStoreOrStores).length;
const derived$ = makeReadonlyStore$1(void 0, {
comparator: config == null ? void 0 : config.comparator,
start: nOfSources === 0 ? (set) => {
set(map(isArray ? [] : {}));
} : argumentIsAStore ? (set) => {
const unsubscribe = readonlyStoreOrStores.subscribe((newValue) => set(map(newValue)));
return unsubscribe;
} : isArray ? (set) => {
let cache = new Array(readonlyStoreOrStores.length);
let subscriptionCounter = 0;
const subscriptions = readonlyStoreOrStores.map((store$, i) => store$.subscribe((newValue) => {
if (subscriptionCounter < nOfSources) {
cache[i] = newValue;
subscriptionCounter++;
}
if (subscriptionCounter === nOfSources) {
const updatedCached = [...cache];
updatedCached[i] = newValue;
set(map(updatedCached));
cache = updatedCached;
}
}));
return () => {
for (const unsubscribe of subscriptions) {
unsubscribe();
}
subscriptionCounter = 0;
};
} : (set) => {
let cache = {};
let subscriptionCounter = 0;
const subscriptions = Object.entries(readonlyStoreOrStores).map(([name, store$]) => store$.subscribe((newValue) => {
if (subscriptionCounter < nOfSources) {
cache[name] = newValue;
subscriptionCounter++;
}
if (subscriptionCounter === nOfSources) {
const updatedCached = __spreadValues$1({}, cache);
updatedCached[name] = newValue;
set(map(updatedCached));
cache = updatedCached;
}
}));
return () => {
for (const unsubscribe of subscriptions) {
unsubscribe();
}
subscriptionCounter = 0;
};
}
});
return derived$;
}
/**
* @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 makeStore$1(initialValue, startOrConfig) {
var _a;
let mutableValue = initialValue;
const signal = makeSignal$1();
let stopHandler;
const startHandler = typeof startOrConfig === "function" ? startOrConfig : startOrConfig == null ? void 0 : startOrConfig.start;
const comparator = (_a = typeof startOrConfig === "function" ? void 0 : startOrConfig == null ? void 0 : startOrConfig.comparator) != null ? _a : (a, b) => a === b;
const get = () => {
if (signal.nOfSubscriptions() > 0) {
return mutableValue;
}
let v;
const unsubscribe = subscribe((current) => v = current);
unsubscribe();
return v;
};
const set = (newValue) => {
if (mutableValue !== void 0 && comparator(mutableValue, newValue)) {
return;
}
mutableValue = newValue;
signal.emit(mutableValue);
};
const subscribe = (s) => {
if (signal.nOfSubscriptions() === 0) {
stopHandler = startHandler == null ? void 0 : startHandler(set);
}
const unsubscribe = signal.subscribe(s);
s(mutableValue);
return () => {
unsubscribe();
if (signal.nOfSubscriptions() === 0) {
stopHandler == null ? void 0 : stopHandler();
stopHandler = void 0;
}
};
};
const update = (updater) => {
set(updater(get()));
};
return {
content: get,
set,
subscribe,
update,
nOfSubscriptions: signal.nOfSubscriptions
};
}
function makeReadonlyStore$1(initialValue, startOrConfig) {
const { content, nOfSubscriptions, subscribe } = makeStore$1(initialValue, startOrConfig);
return {
content,
nOfSubscriptions,
subscribe
};
}
class NotEnoughFilledSlotsQueueError extends Error {
constructor(requestedItems, filledSlots) {
super(`queue doesn't contain enough elements, requested ${requestedItems}, filled slots ${filledSlots}`);
this.requestedItems = requestedItems;
this.filledSlots = filledSlots;
}
}
class NotEnoughAvailableSlotsQueueError extends Error {
constructor(requestedItems, availableSlots) {
super(`queue doesn't have enough space, requested ${requestedItems}, available slots ${availableSlots}`);
this.requestedItems = requestedItems;
this.availableSlots = availableSlots;
}
}
function makeCircularQueue(capacityOrArray, optionalCapacity) {
const isArray = Array.isArray(capacityOrArray);
const capacity = isArray ? optionalCapacity != null ? optionalCapacity : capacityOrArray.length : capacityOrArray;
let queue = new Array(capacity);
let head = 0;
let tail = 0;
const filledSlots$ = makeStore$1(0);
const full$ = makeDerivedStore$1(filledSlots$, (filled) => filled === capacity);
const empty$ = makeDerivedStore$1(filledSlots$, (filled) => filled === 0);
const availableSlots$ = makeDerivedStore$1(filledSlots$, (filled) => capacity - filled);
if (isArray) {
const copyableItems = Math.min(capacityOrArray.length, capacity);
for (let i = 0; i < copyableItems; i++) {
queue[tail] = capacityOrArray[i];
tail = (tail + 1) % capacity;
}
filledSlots$.update((n) => n + copyableItems);
}
const enqueue = (v) => {
if (full$.content()) {
throw new NotEnoughAvailableSlotsQueueError(1, 0);
}
queue[tail] = v;
tail = (tail + 1) % capacity;
filledSlots$.update((n) => n + 1);
};
const enqueueMulti = (v) => {
const available = availableSlots$.content();
if (available < v.length) {
throw new NotEnoughAvailableSlotsQueueError(v.length, available);
}
for (let i = 0; i < v.length; i++) {
queue[tail] = v[i];
tail = (tail + 1) % capacity;
}
filledSlots$.update((n) => n + v.length);
};
const clear = () => {
head = 0;
tail = 0;
queue = new Array(capacity);
filledSlots$.set(0);
};
function dequeue(items) {
const filled = filledSlots$.content();
if (typeof items === "undefined") {
if (filled === 0) {
throw new NotEnoughFilledSlotsQueueError(1, 0);
}
const value = queue[head];
queue[head] = void 0;
head = (head + 1) % capacity;
filledSlots$.update((n) => n - 1);
return value;
} else {
if (items > filled) {
throw new NotEnoughFilledSlotsQueueError(items, filled);
}
const values = new Array(items);
for (let i = 0; i < values.length; i++) {
values[i] = queue[(head + i) % capacity];
queue[(head + i) % capacity] = void 0;
}
head = (head + items) % capacity;
filledSlots$.set(filled - items);
return values;
}
}
const dequeueAll = () => dequeue(filledSlots$.content());
function* iter() {
while (filledSlots$.content() > 0) {
yield dequeue();
}
}
const toArray = () => {
const array = new Array(filledSlots$.content());
for (let i = 0; i < array.length; i++) {
array[i] = queue[(head + i) % capacity];
}
return array;
};
const at = (i) => {
const filled = filledSlots$.content();
if (i >= filled || i < -filled) {
return void 0;
}
if (i >= 0) {
return queue[(head + i) % capacity];
} else {
return queue[(head + filled + i) % capacity];
}
};
const replace = (rawIndex, item) => {
const filled = filledSlots$.content();
if (rawIndex >= filled || rawIndex < -filled) {
throw new RangeError(`${rawIndex} is not a valid positive nor negative index. The number of filled slots is ${filled}`);
}
const distanceFromHead = rawIndex >= 0 ? rawIndex : filled + rawIndex;
const normalizedIndex = (head + distanceFromHead) % capacity;
const previousElement = queue[normalizedIndex];
queue[normalizedIndex] = item;
return previousElement;
};
const remove = (rawIndex) => {
const filled = filledSlots$.content();
if (rawIndex >= filled || rawIndex < -filled) {
throw new RangeError(`${rawIndex} is not a valid positive nor negative index. The number of filled slots is ${filled}`);
}
const distanceFromHead = rawIndex >= 0 ? rawIndex : filled + rawIndex;
const normalizedIndex = (head + distanceFromHead) % capacity;
const previousElement = queue[normalizedIndex];
if (filled - distanceFromHead < distanceFromHead) {
for (let i = head; i < head + filled - distanceFromHead - 1; i++) {
queue[i % capacity] = queue[(i + 1) % capacity];
}
tail = (tail + capacity - 1) % capacity;
} else {
for (let i = head + distanceFromHead - 1; i >= head; i--) {
queue[(i + 1) % capacity] = queue[i % capacity];
}
head = (head + 1) % capacity;
}
filledSlots$.set(filled - 1);
return previousElement;
};
const indexOf = (searchElement) => {
const filled = filledSlots$.content();
for (let i = 0; i < filled; i++) {
if (queue[(head + i) % capacity] === searchElement) {
return i;
}
}
return -1;
};
return {
enqueue,
enqueueMulti,
dequeue,
dequeueAll,
toArray,
at,
indexOf,
replace,
remove,
availableSlots$,
filledSlots$,
capacity,
iter,
[Symbol.iterator]: iter,
full$,
empty$,
clear
};
}
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
function makeSignal() {
const subscribers = [];
function emit(v) {
if (subscribers.length === 0) {
return;
}
for (const subscriber of subscribers.slice()) {
subscriber(v);
}
}
function unsubscribe(subscriber) {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
}
function subscribe(subscriber) {
const index = subscribers.indexOf(subscriber);
if (index === -1) {
subscribers.push(subscriber);
}
return () => unsubscribe(subscriber);
}
function subscribeOnce(subscriber) {
const unsubscribeWrapper = subscribe((v) => {
unsubscribeWrapper();
subscriber(v);
});
return unsubscribeWrapper;
}
return {
emit,
subscribe,
subscribeOnce,
nOfSubscriptions() {
return subscribers.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 makeDerivedStore(readonlyStoreOrStores, map, config) {
const isArray = Array.isArray(readonlyStoreOrStores);
const argumentIsAStore = !isArray && "subscribe" in readonlyStoreOrStores && "nOfSubscriptions" in readonlyStoreOrStores && "content" in readonlyStoreOrStores;
const nOfSources = argumentIsAStore ? 1 : isArray ? readonlyStoreOrStores.length : Object.keys(readonlyStoreOrStores).length;
const derived$ = makeReadonlyStore(void 0, {
comparator: config == null ? void 0 : config.comparator,
start: nOfSources === 0 ? (set) => {
set(map(isArray ? [] : {}));
} : argumentIsAStore ? (set) => {
const unsubscribe = readonlyStoreOrStores.subscribe((newValue) => set(map(newValue)));
return unsubscribe;
} : isArray ? (set) => {
let cache = new Array(readonlyStoreOrStores.length);
let subscriptionCounter = 0;
const subscriptions = readonlyStoreOrStores.map((store$, i) => store$.subscribe((newValue) => {
if (subscriptionCounter < nOfSources) {
cache[i] = newValue;
subscriptionCounter++;
}
if (subscriptionCounter === nOfSources) {
const updatedCached = [...cache];
updatedCached[i] = newValue;
set(map(updatedCached));
cache = updatedCached;
}
}));
return () => {
for (const unsubscribe of subscriptions) {
unsubscribe();
}
subscriptionCounter = 0;
};
} : (set) => {
let cache = {};
let subscriptionCounter = 0;
const subscriptions = Object.entries(readonlyStoreOrStores).map(([name, store$]) => store$.subscribe((newValue) => {
if (subscriptionCounter < nOfSources) {
cache[name] = newValue;
subscriptionCounter++;
}
if (subscriptionCounter === nOfSources) {
const updatedCached = __spreadValues({}, cache);
updatedCached[name] = newValue;
set(map(updatedCached));
cache = updatedCached;
}
}));
return () => {
for (const unsubscribe of subscriptions) {
unsubscribe();
}
subscriptionCounter = 0;
};
}
});
return derived$;
}
/**
* @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 makeStore(initialValue, startOrConfig) {
var _a;
let mutableValue = initialValue;
const signal = makeSignal();
let stopHandler;
const startHandler = typeof startOrConfig === "function" ? startOrConfig : startOrConfig == null ? void 0 : startOrConfig.start;
const comparator = (_a = typeof startOrConfig === "function" ? void 0 : startOrConfig == null ? void 0 : startOrConfig.comparator) != null ? _a : (a, b) => a === b;
const get = () => {
if (signal.nOfSubscriptions() > 0) {
return mutableValue;
}
let v;
const unsubscribe = subscribe((current) => v = current);
unsubscribe();
return v;
};
const set = (newValue) => {
if (mutableValue !== void 0 && comparator(mutableValue, newValue)) {
return;
}
mutableValue = newValue;
signal.emit(mutableValue);
};
const subscribe = (s) => {
if (signal.nOfSubscriptions() === 0) {
stopHandler = startHandler == null ? void 0 : startHandler(set);
}
const unsubscribe = signal.subscribe(s);
s(mutableValue);
return () => {
unsubscribe();
if (signal.nOfSubscriptions() === 0) {
stopHandler == null ? void 0 : stopHandler();
stopHandler = void 0;
}
};
};
const update = (updater) => {
set(updater(get()));
};
return {
content: get,
set,
subscribe,
update,
nOfSubscriptions: signal.nOfSubscriptions
};
}
function makeReadonlyStore(initialValue, startOrConfig) {
const { content, nOfSubscriptions, subscribe } = makeStore(initialValue, startOrConfig);
return {
content,
nOfSubscriptions,
subscribe
};
}
const noop = () => void 0;
class ChannelFullError extends Error {
constructor() {
super("channel full, cannot enqueue data");
}
}
class ChannelClosedError extends Error {
constructor() {
super("channel closed");
}
}
class ChannelTooManyPendingRecvError extends Error {
constructor() {
super("channel has already too many pending recv");
}
}
function makeChannel(params) {
const { capacity = 1024, maxConcurrentPendingRecv = 1024 } = params || {};
const metadataQueue = makeCircularQueue(capacity);
const itemsQueue = makeCircularQueue(capacity);
const recvQueue = makeCircularQueue(maxConcurrentPendingRecv);
const closed$ = makeStore(false);
const availableOutboxSlots$ = makeDerivedStore(
[closed$, metadataQueue.availableSlots$],
([closed, availableSlots]) => closed ? 0 : availableSlots
);
const filledInboxSlots$ = makeDerivedStore(
[closed$, metadataQueue.filledSlots$],
([closed, filledSlots]) => closed ? 0 : filledSlots
);
const canWrite$ = makeDerivedStore(
availableOutboxSlots$,
(availableOutboxSlots) => availableOutboxSlots > 0
);
const canRead$ = makeDerivedStore(
[filledInboxSlots$, recvQueue.full$],
([filledInboxSlots, recvFull]) => filledInboxSlots > 0 && !recvFull
);
async function sendWait(v, options) {
if (closed$.content()) {
throw new ChannelClosedError();
}
if (metadataQueue.full$.content()) {
throw new ChannelFullError();
}
let resolveSend = noop;
let rejectSend = noop;
const promise = new Promise((res, rej) => {
resolveSend = res;
rejectSend = rej;
});
let metadataItem;
if (!recvQueue.empty$.content()) {
recvQueue.dequeue().resolveRecv({
promise,
resolveSend,
rejectSend,
value: v
});
} else {
metadataItem = {
promise,
resolveSend,
rejectSend
};
metadataQueue.enqueue(metadataItem);
itemsQueue.enqueue(v);
}
try {
if (!(options == null ? void 0 : options.signal)) {
await promise;
} else {
const signal = options.signal;
signal.throwIfAborted();
await Promise.race([
promise,
new Promise((_, rej) => {
signal.addEventListener("abort", () => {
Promise.resolve().then(() => rej(signal.reason)).catch(noop);
});
})
]);
}
} catch (err) {
if (metadataItem) {
const metadataItemIndex = metadataQueue.indexOf(metadataItem);
if (metadataItemIndex !== -1) {
metadataQueue.remove(metadataItemIndex);
itemsQueue.remove(metadataItemIndex);
}
}
throw err;
}
}
function send(v) {
if (closed$.content()) {
throw new ChannelClosedError();
}
if (metadataQueue.full$.content()) {
throw new ChannelFullError();
}
sendWait(v).catch(noop);
}
async function recv(options) {
if (closed$.content()) {
throw new ChannelClosedError();
}
let item;
if (!metadataQueue.empty$.content()) {
item = { ...metadataQueue.dequeue(), value: itemsQueue.dequeue() };
} else {
if (recvQueue.full$.content()) {
throw new ChannelTooManyPendingRecvError();
}
const recvContext = {
resolveRecv: noop,
rejectRecv: noop
};
const recvPromise = new Promise((res, rej) => {
recvContext.resolveRecv = res;
recvContext.rejectRecv = rej;
recvQueue.enqueue(recvContext);
});
try {
if (!(options == null ? void 0 : options.signal)) {
item = await recvPromise;
} else {
const signal = options.signal;
signal.throwIfAborted();
item = await Promise.race([
recvPromise,
new Promise((_, rej) => {
signal.addEventListener("abort", () => {
Promise.resolve().then(() => rej(signal.reason)).catch(noop);
});
})
]);
}
} catch (err) {
const recvContextIndex = recvQueue.indexOf(recvContext);
if (recvContextIndex !== -1) {
recvQueue.remove(recvContextIndex);
}
throw err;
}
}
item.resolveSend();
return item.value;
}
async function* iter() {
while (metadataQueue.filledSlots$.content() > 0) {
yield await recv();
}
}
function close() {
if (closed$.content()) {
return;
}
closed$.set(true);
const channelClosedError = new ChannelClosedError();
for (const pendingRecv of recvQueue) {
pendingRecv.rejectRecv(channelClosedError);
}
for (const item of metadataQueue) {
item.rejectSend(channelClosedError);
}
itemsQueue.clear();
}
return {
buffer: itemsQueue,
tx: {
send,
sendWait,
canWrite$,
closed$,
close,
availableOutboxSlots$,
capacity
},
rx: {
pendingRecvPromises$: recvQueue.filledSlots$,
recv,
iter,
[Symbol.asyncIterator]: iter,
canRead$,
closed$,
close,
capacity,
filledInboxSlots$
}
};
}
export { ChannelClosedError, ChannelFullError, ChannelTooManyPendingRecvError, NotEnoughAvailableSlotsQueueError, NotEnoughFilledSlotsQueueError, makeChannel };