@mark1russell7/collections 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -1
  3. package/build/dag/index.d.ts +144 -0
  4. package/build/dag/index.d.ts.map +1 -0
  5. package/build/dag/index.js +294 -0
  6. package/build/dag/index.js.map +1 -0
  7. package/build/graph/index.d.ts +20 -0
  8. package/build/graph/index.d.ts.map +1 -0
  9. package/build/graph/index.js +48 -0
  10. package/build/graph/index.js.map +1 -0
  11. package/build/index.d.ts +4952 -0
  12. package/build/index.d.ts.map +1 -0
  13. package/build/index.js +7811 -0
  14. package/build/index.js.map +1 -0
  15. package/build/testing/index.d.ts +25 -0
  16. package/build/testing/index.d.ts.map +1 -0
  17. package/build/testing/index.js +72 -0
  18. package/build/testing/index.js.map +1 -0
  19. package/package.json +71 -4
  20. package/src/async/async-queue.ts +481 -0
  21. package/src/async/channels.ts +450 -0
  22. package/src/async/settled.ts +41 -0
  23. package/src/behaviors/bounded.ts +485 -0
  24. package/src/behaviors/composite.ts +99 -0
  25. package/src/behaviors/evented.ts +464 -0
  26. package/src/behaviors/lru.ts +449 -0
  27. package/src/behaviors/readonly.ts +236 -0
  28. package/src/behaviors/safe.ts +358 -0
  29. package/src/behaviors/synchronized.ts +316 -0
  30. package/src/behaviors/ttl.ts +464 -0
  31. package/src/core/effects.ts +327 -0
  32. package/src/core/events.ts +363 -0
  33. package/src/core/middleware.ts +413 -0
  34. package/src/core/policies.ts +316 -0
  35. package/src/core/traits.ts +164 -0
  36. package/src/dag/builder.ts +124 -0
  37. package/src/dag/executor.ts +190 -0
  38. package/src/dag/index.ts +14 -0
  39. package/src/dag/traversal.ts +129 -0
  40. package/src/dag/types.ts +87 -0
  41. package/src/fx/collectors.ts +500 -0
  42. package/src/fx/iter.ts +536 -0
  43. package/src/graph/hub-order.ts +53 -0
  44. package/src/graph/index.ts +5 -0
  45. package/src/impl/array-deque.ts +463 -0
  46. package/src/impl/array-list.ts +490 -0
  47. package/src/impl/hash-map.ts +623 -0
  48. package/src/impl/hash-set.ts +342 -0
  49. package/src/impl/linked-hash-map.ts +572 -0
  50. package/src/impl/linked-list.ts +610 -0
  51. package/src/impl/priority-queue.ts +448 -0
  52. package/src/impl/summary-tree.ts +594 -0
  53. package/src/impl/tree-map.ts +913 -0
  54. package/src/impl/tree-set.ts +469 -0
  55. package/src/index.ts +237 -0
  56. package/src/interfaces/collection.ts +141 -0
  57. package/src/interfaces/list.ts +281 -0
  58. package/src/interfaces/map.ts +405 -0
  59. package/src/interfaces/queue.ts +353 -0
  60. package/src/interfaces/set.ts +158 -0
  61. package/src/order/index.ts +6 -0
  62. package/src/order/rank.ts +271 -0
  63. package/src/storage/listeners.ts +72 -0
  64. package/src/testing/check.ts +81 -0
  65. package/src/testing/index.ts +7 -0
  66. package/src/utils/defaults.ts +345 -0
  67. package/src/utils/factories.ts +357 -0
  68. package/src/utils/helpers.ts +248 -0
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The checks of the contract suite. The suite does not import a test framework, so a runtime
3
+ * entry of this package does not load one. A failed check throws `ContractViolation`.
4
+ */
5
+ /** The error of a failed check of the contract suite. */
6
+ export declare class ContractViolation extends Error {
7
+ override readonly name = "ContractViolation";
8
+ }
9
+ /** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */
10
+ export declare function show(value: unknown): string;
11
+ /**
12
+ * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
13
+ * are equal when they have the same keys with equal values, in any order.
14
+ */
15
+ export declare function deepEqual(actual: unknown, expected: unknown): boolean;
16
+ /** This function throws `ContractViolation` when the two values are not deeply equal. */
17
+ export declare function same(actual: unknown, expected: unknown, what: string): void;
18
+ /** This function throws `ContractViolation` when the condition is false. */
19
+ export declare function holds(condition: boolean, what: string): void;
20
+ /**
21
+ * This function starts an operation that must fail with a rejected promise, and gives the error.
22
+ * A synchronous throw breaks the contract too: each method of a storage gives a promise.
23
+ */
24
+ export declare function rejects(start: () => Promise<unknown>, what: string): Promise<unknown>;
25
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/testing/check.ts"],"mappings":";;;;;qBAMa,0BAA0B;oBACnB;;;wBAIJ,KAAK;;;;;wBAmBL,UAAU,iBAAiB;;wBAqB3B,KAAK,iBAAiB,mBAAmB;;wBAOzC,MAAM,oBAAoB;;;;;wBAQpB,QAAQ,aAAa,kBAAkB,eAAe"}
@@ -0,0 +1,72 @@
1
+ // src/testing/check.ts
2
+ /**
3
+ * The checks of the contract suite. The suite does not import a test framework, so a runtime
4
+ * entry of this package does not load one. A failed check throws `ContractViolation`.
5
+ */
6
+ /** The error of a failed check of the contract suite. */
7
+ var ContractViolation = class extends Error {
8
+ name = "ContractViolation";
9
+ };
10
+ /** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */
11
+ function show(value) {
12
+ if (value === void 0) return "undefined";
13
+ try {
14
+ return JSON.stringify(value, (_key, item) => item instanceof Map ? { Map: [...item.entries()] } : item === void 0 ? "<undefined>" : item);
15
+ } catch {
16
+ return String(value);
17
+ }
18
+ }
19
+ function isPlainObject(value) {
20
+ if (typeof value !== "object" || value === null) return false;
21
+ const prototype = Object.getPrototypeOf(value);
22
+ return prototype === Object.prototype || prototype === null;
23
+ }
24
+ /**
25
+ * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
26
+ * are equal when they have the same keys with equal values, in any order.
27
+ */
28
+ function deepEqual(actual, expected) {
29
+ if (Object.is(actual, expected)) return true;
30
+ if (actual instanceof Map && expected instanceof Map) {
31
+ if (actual.size !== expected.size) return false;
32
+ for (const [key, value] of actual) if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;
33
+ return true;
34
+ }
35
+ if (Array.isArray(actual) && Array.isArray(expected)) return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));
36
+ if (isPlainObject(actual) && isPlainObject(expected)) {
37
+ const keys = Object.keys(actual);
38
+ if (keys.length !== Object.keys(expected).length) return false;
39
+ return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));
40
+ }
41
+ return false;
42
+ }
43
+ /** This function throws `ContractViolation` when the two values are not deeply equal. */
44
+ function same(actual, expected, what) {
45
+ if (!deepEqual(actual, expected)) throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);
46
+ }
47
+ /** This function throws `ContractViolation` when the condition is false. */
48
+ function holds(condition, what) {
49
+ if (!condition) throw new ContractViolation(what);
50
+ }
51
+ /**
52
+ * This function starts an operation that must fail with a rejected promise, and gives the error.
53
+ * A synchronous throw breaks the contract too: each method of a storage gives a promise.
54
+ */
55
+ async function rejects(start, what) {
56
+ let promise;
57
+ try {
58
+ promise = start();
59
+ } catch (error) {
60
+ throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);
61
+ }
62
+ holds(typeof promise?.then === "function", `${what}: the method did not give a promise`);
63
+ try {
64
+ await promise;
65
+ } catch (error) {
66
+ return error;
67
+ }
68
+ throw new ContractViolation(`${what}: the promise did not reject`);
69
+ }
70
+ export { ContractViolation, deepEqual, holds, rejects, same, show };
71
+
72
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/testing/check.ts"],"sourcesContent":["/**\n * The checks of the contract suite. The suite does not import a test framework, so a runtime\n * entry of this package does not load one. A failed check throws `ContractViolation`.\n */\n\n/** The error of a failed check of the contract suite. */\nexport class ContractViolation extends Error {\n override readonly name = \"ContractViolation\";\n}\n\n/** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */\nexport function show(value: unknown): string {\n if (value === undefined) return \"undefined\";\n try {\n return JSON.stringify(value, (_key, item: unknown) => (item instanceof Map ? { Map: [...item.entries()] } : item === undefined ? \"<undefined>\" : item));\n } catch {\n return String(value);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps\n * are equal when they have the same keys with equal values, in any order.\n */\nexport function deepEqual(actual: unknown, expected: unknown): boolean {\n if (Object.is(actual, expected)) return true;\n if (actual instanceof Map && expected instanceof Map) {\n if (actual.size !== expected.size) return false;\n for (const [key, value] of actual) {\n if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;\n }\n return true;\n }\n if (Array.isArray(actual) && Array.isArray(expected)) {\n return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));\n }\n if (isPlainObject(actual) && isPlainObject(expected)) {\n const keys = Object.keys(actual);\n if (keys.length !== Object.keys(expected).length) return false;\n return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));\n }\n return false;\n}\n\n/** This function throws `ContractViolation` when the two values are not deeply equal. */\nexport function same(actual: unknown, expected: unknown, what: string): void {\n if (!deepEqual(actual, expected)) {\n throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);\n }\n}\n\n/** This function throws `ContractViolation` when the condition is false. */\nexport function holds(condition: boolean, what: string): void {\n if (!condition) throw new ContractViolation(what);\n}\n\n/**\n * This function starts an operation that must fail with a rejected promise, and gives the error.\n * A synchronous throw breaks the contract too: each method of a storage gives a promise.\n */\nexport async function rejects(start: () => Promise<unknown>, what: string): Promise<unknown> {\n let promise: Promise<unknown>;\n try {\n promise = start();\n } catch (error) {\n throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);\n }\n holds(typeof promise?.then === \"function\", `${what}: the method did not give a promise`);\n try {\n await promise;\n } catch (error) {\n return error;\n }\n throw new ContractViolation(`${what}: the promise did not reject`);\n}\n"],"mappings":";;;;;;AAMA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAyB;AAC3B;;AAGA,SAAgB,KAAK,OAAwB;CAC3C,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI;EACF,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAmB,gBAAgB,MAAM,EAAE,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,EAAE,IAAI,SAAS,KAAA,IAAY,gBAAgB,IAAK;CACxJ,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;;;;AAMA,SAAgB,UAAU,QAAiB,UAA4B;CACrE,IAAI,OAAO,GAAG,QAAQ,QAAQ,GAAG,OAAO;CACxC,IAAI,kBAAkB,OAAO,oBAAoB,KAAK;EACpD,IAAI,OAAO,SAAS,SAAS,MAAM,OAAO;EAC1C,KAAK,MAAM,CAAC,KAAK,UAAU,QACzB,IAAI,CAAC,SAAS,IAAI,GAAG,KAAK,CAAC,UAAU,OAAO,SAAS,IAAI,GAAG,CAAC,GAAG,OAAO;EAEzE,OAAO;CACT;CACA,IAAI,MAAM,QAAQ,MAAM,KAAK,MAAM,QAAQ,QAAQ,GACjD,OAAO,OAAO,WAAW,SAAS,UAAU,OAAO,OAAO,MAAM,UAAU,UAAU,MAAM,SAAS,MAAM,CAAC;CAE5G,IAAI,cAAc,MAAM,KAAK,cAAc,QAAQ,GAAG;EACpD,MAAM,OAAO,OAAO,KAAK,MAAM;EAC/B,IAAI,KAAK,WAAW,OAAO,KAAK,QAAQ,CAAC,CAAC,QAAQ,OAAO;EACzD,OAAO,KAAK,OAAO,QAAQ,OAAO,UAAU,eAAe,KAAK,UAAU,GAAG,KAAK,UAAU,OAAO,MAAM,SAAS,IAAI,CAAC;CACzH;CACA,OAAO;AACT;;AAGA,SAAgB,KAAK,QAAiB,UAAmB,MAAoB;CAC3E,IAAI,CAAC,UAAU,QAAQ,QAAQ,GAC7B,MAAM,IAAI,kBAAkB,GAAG,KAAK,aAAa,KAAK,QAAQ,EAAE,QAAQ,KAAK,MAAM,GAAG;AAE1F;;AAGA,SAAgB,MAAM,WAAoB,MAAoB;CAC5D,IAAI,CAAC,WAAW,MAAM,IAAI,kBAAkB,IAAI;AAClD;;;;;AAMA,eAAsB,QAAQ,OAA+B,MAAgC;CAC3F,IAAI;CACJ,IAAI;EACF,UAAU,MAAM;CAClB,SAAS,OAAO;EACd,MAAM,IAAI,kBAAkB,GAAG,KAAK,8BAA8B,KAAK,iBAAiB,QAAQ,MAAM,UAAU,KAAK,EAAE,uCAAuC;CAChK;CACA,MAAM,OAAO,SAAS,SAAS,YAAY,GAAG,KAAK,oCAAoC;CACvF,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,OAAO;CACT;CACA,MAAM,IAAI,kBAAkB,GAAG,KAAK,6BAA6B;AACnE"}
package/package.json CHANGED
@@ -1,13 +1,80 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/collections",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "A placeholder that lets npm trust the release workflow of mark1russell7/collections. Use a later version.",
4
+ "version": "0.1.0",
5
+ "description": "Collections with no dependencies: lists, maps, queues, a summary tree, channels, lazy operations and dependency graphs.",
6
+ "keywords": [
7
+ "collections",
8
+ "data-structures",
9
+ "tree-map",
10
+ "priority-queue",
11
+ "lru",
12
+ "summary-tree",
13
+ "channels",
14
+ "dag",
15
+ "topological-sort",
16
+ "typescript"
17
+ ],
18
+ "homepage": "https://mark1russell7.github.io/collections/",
19
+ "bugs": {
20
+ "url": "https://github.com/mark1russell7/collections/issues"
21
+ },
5
22
  "repository": {
6
23
  "type": "git",
7
- "url": "git+https://github.com/mark1russell7/collections.git"
24
+ "url": "git+https://github.com/mark1russell7/collections.git",
25
+ "directory": "packages/collections"
8
26
  },
9
27
  "license": "MIT",
28
+ "author": "Mark Russell (https://github.com/mark1russell7)",
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "main": "./build/index.js",
32
+ "types": "./build/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./build/index.d.ts",
36
+ "default": "./build/index.js"
37
+ },
38
+ "./dag": {
39
+ "types": "./build/dag/index.d.ts",
40
+ "default": "./build/dag/index.js"
41
+ },
42
+ "./graph": {
43
+ "types": "./build/graph/index.d.ts",
44
+ "default": "./build/graph/index.js"
45
+ },
46
+ "./testing": {
47
+ "types": "./build/testing/index.d.ts",
48
+ "default": "./build/testing/index.js"
49
+ },
50
+ "./package.json": "./package.json"
51
+ },
52
+ "files": [
53
+ "build",
54
+ "src",
55
+ "!src/**/*.test.ts",
56
+ "!src/**/*.test.tsx",
57
+ "!src/contracts"
58
+ ],
10
59
  "publishConfig": {
11
60
  "access": "public"
61
+ },
62
+ "engines": {
63
+ "node": ">=22.12"
64
+ },
65
+ "devDependencies": {
66
+ "@mark1russell7/cue": "^2.0.0",
67
+ "@types/node": "^26.6.5",
68
+ "esbuild": "^0.28.2",
69
+ "fast-check": "^4.10.2",
70
+ "tsdown": "^0.23.1",
71
+ "typescript": "^7.0.2",
72
+ "vitest": "^5.0.3"
73
+ },
74
+ "scripts": {
75
+ "build": "tsdown",
76
+ "test": "vitest run",
77
+ "test:watch": "vitest",
78
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
12
79
  }
13
- }
80
+ }
@@ -0,0 +1,481 @@
1
+ /**
2
+ * AsyncQueue - An async iterable queue with backpressure support.
3
+ *
4
+ * The queue is for producer-consumer patterns where producers can wait when
5
+ * the queue is full and consumers can wait when the queue is empty.
6
+ * This module implements AsyncIterable for use with for-await-of loops.
7
+ *
8
+ * @example
9
+ * const queue = asyncQueue<number>({ capacity: 10 })
10
+ *
11
+ * // Producer
12
+ * await queue.put(42) // Waits if queue is full
13
+ *
14
+ * // Consumer
15
+ * const value = await queue.take() // Waits if queue is empty
16
+ *
17
+ * // Async iteration
18
+ * for await (const value of queue) {
19
+ * console.log(value)
20
+ * }
21
+ */
22
+
23
+ import type { AsyncQueue as IAsyncQueue } from "../interfaces/queue.js";
24
+
25
+ /**
26
+ * Options for making an AsyncQueue.
27
+ */
28
+ export interface AsyncQueueOptions {
29
+ /**
30
+ * Maximum capacity. Infinity for unbounded queue.
31
+ * @default Infinity
32
+ */
33
+ capacity?: number;
34
+
35
+ /**
36
+ * Timeout for put/take operations in milliseconds.
37
+ * @default undefined (no timeout)
38
+ */
39
+ timeout?: number;
40
+ }
41
+
42
+ /**
43
+ * Resolver for waiting operations.
44
+ */
45
+ interface Resolver<T> {
46
+ resolve: (value: T) => void;
47
+ reject: (reason: any) => void;
48
+ timeoutId?: ReturnType<typeof setTimeout>;
49
+ }
50
+
51
+ /** A waiting put: it keeps its element until the queue takes it. */
52
+ interface Putter<T> extends Resolver<void> {
53
+ element: T;
54
+ }
55
+
56
+ /**
57
+ * AsyncQueue<T> - Thread-safe async queue with backpressure.
58
+ *
59
+ * Features:
60
+ * - Blocking put() when full (backpressure)
61
+ * - Blocking take() when empty
62
+ * - AsyncIterable support
63
+ * - Graceful closing
64
+ * - Timeouts
65
+ *
66
+ * Perfect for:
67
+ * - Producer-consumer patterns
68
+ * - Rate limiting
69
+ * - Task queues
70
+ * - Stream processing
71
+ */
72
+ export class AsyncQueue<T> implements IAsyncQueue<T> {
73
+ private buffer: T[] = [];
74
+ private putters: Putter<T>[] = [];
75
+ private takers: Resolver<T>[] = [];
76
+ /** The calls of `peek` that wait: they see the next element, but they do not take it. */
77
+ private peekers: Resolver<T>[] = [];
78
+ private _isClosed = false;
79
+ private readonly capacity: number;
80
+ private readonly defaultTimeout?: number;
81
+
82
+ constructor(options: AsyncQueueOptions = {}) {
83
+ this.capacity = options.capacity ?? Infinity;
84
+ if (options.timeout !== undefined) {
85
+ this.defaultTimeout = options.timeout;
86
+ }
87
+ }
88
+
89
+ // ========================================================================
90
+ // Size and state
91
+ // ========================================================================
92
+
93
+ get size(): number {
94
+ return this.buffer.length;
95
+ }
96
+
97
+ get isEmpty(): boolean {
98
+ return this.buffer.length === 0;
99
+ }
100
+
101
+ get isFull(): boolean {
102
+ return this.buffer.length >= this.capacity;
103
+ }
104
+
105
+ get isClosed(): boolean {
106
+ return this._isClosed;
107
+ }
108
+
109
+ get remainingCapacity(): number {
110
+ return this.capacity === Infinity ? Infinity : this.capacity - this.buffer.length;
111
+ }
112
+
113
+ // ========================================================================
114
+ // Blocking operations
115
+ // ========================================================================
116
+
117
+ /**
118
+ * This method adds an element to the queue.
119
+ * If the queue is full, waits until space is available. With a capacity of 0, it waits until
120
+ * a taker takes the element (a rendezvous).
121
+ *
122
+ * @throws Error if queue is closed
123
+ * @throws Error if timeout expires
124
+ */
125
+ async put(element: T, timeout?: number): Promise<void> {
126
+ if (this._isClosed) {
127
+ throw new Error("Queue is closed");
128
+ }
129
+ if (this.tryPutNow(element)) {
130
+ return;
131
+ }
132
+
133
+ // A waiting peek sees the element of a waiting put (a capacity of 0)
134
+ this.wakePeekers(element);
135
+
136
+ // Queue is full: wait with the element. (Before, a waiting putter kept only its resolve
137
+ // function, so its element was dropped when space came: BUGS-2026-07 C11.)
138
+ return new Promise<void>((resolve, reject) => {
139
+ const putter: Putter<T> = { element, resolve, reject };
140
+ const timeoutMs = timeout ?? this.defaultTimeout;
141
+ if (timeoutMs !== undefined) {
142
+ putter.timeoutId = setTimeout(() => {
143
+ const index = this.putters.indexOf(putter);
144
+ if (index !== -1) {
145
+ this.putters.splice(index, 1);
146
+ }
147
+ reject(new Error(`Put timeout after ${timeoutMs}ms`));
148
+ }, timeoutMs);
149
+ }
150
+ this.putters.push(putter);
151
+ });
152
+ }
153
+
154
+ /**
155
+ * Removes and gives an element from the queue.
156
+ * If the queue is empty, waits until an element is available.
157
+ *
158
+ * @throws Error if queue is closed and empty
159
+ * @throws Error if timeout expires
160
+ */
161
+ async take(timeout?: number): Promise<T> {
162
+ const next = this.takeNow();
163
+ if (next.found) {
164
+ return next.element;
165
+ }
166
+
167
+ // If closed and empty, throw
168
+ if (this._isClosed) {
169
+ throw new Error("Queue is closed and empty");
170
+ }
171
+
172
+ // Wait for an element
173
+ return new Promise<T>((resolve, reject) => {
174
+ const taker: Resolver<T> = { resolve, reject };
175
+ const timeoutMs = timeout ?? this.defaultTimeout;
176
+ if (timeoutMs !== undefined) {
177
+ taker.timeoutId = setTimeout(() => {
178
+ const index = this.takers.indexOf(taker);
179
+ if (index !== -1) {
180
+ this.takers.splice(index, 1);
181
+ }
182
+ reject(new Error(`Take timeout after ${timeoutMs}ms`));
183
+ }, timeoutMs);
184
+ }
185
+ this.takers.push(taker);
186
+ });
187
+ }
188
+
189
+ /**
190
+ * This method waits for the next element, as `take` does, but it gives the element to
191
+ * `onElement` and the closure of the queue to `onClosed`. These calls are synchronous: they
192
+ * occur in the call that adds the element or closes the queue. The method has no timeout.
193
+ *
194
+ * The function that it gives withdraws the wait. A withdrawn wait gets no element, so no
195
+ * element goes to a taker that left. `select` races its cases with this method.
196
+ *
197
+ * @returns A function that withdraws the wait. It gives true when the wait had no element yet.
198
+ */
199
+ waitTake(onElement: (element: T) => void, onClosed: (error: Error) => void): () => boolean {
200
+ const next = this.takeNow();
201
+ if (next.found) {
202
+ onElement(next.element);
203
+ return () => false;
204
+ }
205
+ if (this._isClosed) {
206
+ onClosed(new Error("Queue is closed and empty"));
207
+ return () => false;
208
+ }
209
+ const taker: Resolver<T> = { resolve: onElement, reject: onClosed };
210
+ this.takers.push(taker);
211
+ return () => {
212
+ const index = this.takers.indexOf(taker);
213
+ if (index === -1) return false;
214
+ this.takers.splice(index, 1);
215
+ return true;
216
+ };
217
+ }
218
+
219
+ // ========================================================================
220
+ // Non-blocking operations
221
+ // ========================================================================
222
+
223
+ /**
224
+ * This method tries to add an element without waiting.
225
+ * This method gives false if queue is full (with a capacity of 0: if no taker waits).
226
+ */
227
+ tryPut(element: T): boolean {
228
+ if (this._isClosed) {
229
+ return false;
230
+ }
231
+ return this.tryPutNow(element);
232
+ }
233
+
234
+ /**
235
+ * This method tries to remove an element without waiting.
236
+ * This method gives undefined if queue is empty.
237
+ */
238
+ tryTake(): T | undefined {
239
+ const next = this.takeNow();
240
+ return next.found ? next.element : undefined;
241
+ }
242
+
243
+ /** This method gives the element to a waiting taker, or puts it in the buffer when there is space. */
244
+ private tryPutNow(element: T): boolean {
245
+ // A waiting taker gets the element directly (the buffer is empty when a taker waits)
246
+ const taker = this.takers.shift();
247
+ if (taker) {
248
+ this.wakePeekers(element);
249
+ this.clearTimeout(taker);
250
+ taker.resolve(element);
251
+ return true;
252
+ }
253
+ if (this.buffer.length < this.capacity) {
254
+ this.buffer.push(element);
255
+ this.wakePeekers(element);
256
+ return true;
257
+ }
258
+ return false;
259
+ }
260
+
261
+ /** Each waiting peek gets the element, which stays where it is. */
262
+ private wakePeekers(element: T): void {
263
+ const peekers = this.peekers;
264
+ this.peekers = [];
265
+ for (const peeker of peekers) {
266
+ this.clearTimeout(peeker);
267
+ peeker.resolve(element);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * This method takes the next element: from the buffer (then a waiting putter moves its element into the
273
+ * buffer), or directly from a waiting putter (a capacity of 0). (Before, the direct path
274
+ * released the putter but did not give its element to the taker, so the taker waited forever:
275
+ * BUGS-2026-07 C11.)
276
+ */
277
+ private takeNow(): { found: true; element: T } | { found: false } {
278
+ if (this.buffer.length > 0) {
279
+ const element = this.buffer.shift()!;
280
+ this.admitPutter();
281
+ return { found: true, element };
282
+ }
283
+ const putter = this.putters.shift();
284
+ if (putter) {
285
+ this.clearTimeout(putter);
286
+ putter.resolve();
287
+ return { found: true, element: putter.element };
288
+ }
289
+ return { found: false };
290
+ }
291
+
292
+ // ========================================================================
293
+ // Peeking
294
+ // ========================================================================
295
+
296
+ /**
297
+ * This method gives the next element without removing it.
298
+ * Waits if queue is empty.
299
+ */
300
+ async peek(): Promise<T> {
301
+ if (this.buffer.length > 0) {
302
+ return this.buffer[0]!;
303
+ }
304
+ if (this.putters.length > 0) {
305
+ return this.putters[0]!.element;
306
+ }
307
+
308
+ if (this._isClosed) {
309
+ throw new Error("Queue is closed and empty");
310
+ }
311
+
312
+ // Wait for the next element without a take. (Before, peek took the element and put it back
313
+ // at the front: a take that waited after it kept waiting, and the order changed: audit pass 2.)
314
+ return new Promise<T>((resolve, reject) => {
315
+ const peeker: Resolver<T> = { resolve, reject };
316
+ const timeoutMs = this.defaultTimeout;
317
+ if (timeoutMs !== undefined) {
318
+ peeker.timeoutId = setTimeout(() => {
319
+ const index = this.peekers.indexOf(peeker);
320
+ if (index !== -1) {
321
+ this.peekers.splice(index, 1);
322
+ }
323
+ reject(new Error(`Peek timeout after ${timeoutMs}ms`));
324
+ }, timeoutMs);
325
+ }
326
+ this.peekers.push(peeker);
327
+ });
328
+ }
329
+
330
+ /**
331
+ * This method gives the next element without waiting.
332
+ * This method gives undefined if queue is empty.
333
+ */
334
+ tryPeek(): T | undefined {
335
+ return this.buffer.length > 0 ? this.buffer[0] : this.putters[0]?.element;
336
+ }
337
+
338
+ // ========================================================================
339
+ // Closing and draining
340
+ // ========================================================================
341
+
342
+ /**
343
+ * This method closes the queue. No more elements can be added.
344
+ * Existing elements can still be consumed.
345
+ */
346
+ close(): void {
347
+ this._isClosed = true;
348
+
349
+ // Reject all waiting putters
350
+ for (const putter of this.putters) {
351
+ this.clearTimeout(putter);
352
+ putter.reject(new Error("Queue closed"));
353
+ }
354
+ this.putters = [];
355
+
356
+ // Wake up takers if queue is empty
357
+ if (this.buffer.length === 0) {
358
+ for (const taker of this.takers) {
359
+ this.clearTimeout(taker);
360
+ taker.reject(new Error("Queue closed and empty"));
361
+ }
362
+ this.takers = [];
363
+ for (const peeker of this.peekers) {
364
+ this.clearTimeout(peeker);
365
+ peeker.reject(new Error("Queue closed and empty"));
366
+ }
367
+ this.peekers = [];
368
+ }
369
+ }
370
+
371
+ /**
372
+ * This method drains all elements into an array.
373
+ * This method gives immediately with current elements.
374
+ */
375
+ drain(): T[] {
376
+ // The buffer, then the elements of the waiting putters, in order. (Before, the waiting
377
+ // putters were released but their elements were dropped.)
378
+ const elements = this.buffer.slice();
379
+ this.buffer = [];
380
+ for (const putter of this.putters.splice(0)) {
381
+ this.clearTimeout(putter);
382
+ putter.resolve();
383
+ elements.push(putter.element);
384
+ }
385
+ return elements;
386
+ }
387
+
388
+ // ========================================================================
389
+ // Async iteration
390
+ // ========================================================================
391
+
392
+ /**
393
+ * Async iterator that yields elements as they become available.
394
+ * Stops when queue is closed and empty.
395
+ */
396
+ async *[Symbol.asyncIterator](): AsyncIterator<T> {
397
+ while (true) {
398
+ const next = this.takeNow();
399
+ if (next.found) {
400
+ yield next.element;
401
+ } else if (this._isClosed) {
402
+ break;
403
+ } else {
404
+ let element: T;
405
+ try {
406
+ element = await this.take();
407
+ } catch (error) {
408
+ // The queue was closed while the iterator waited
409
+ if (this._isClosed) break;
410
+ throw error;
411
+ }
412
+ yield element;
413
+ }
414
+ }
415
+ }
416
+
417
+ // ========================================================================
418
+ // Private helpers
419
+ // ========================================================================
420
+
421
+ /** When the buffer has space, the first waiting putter moves its element into it. */
422
+ private admitPutter(): void {
423
+ if (this.putters.length > 0 && this.buffer.length < this.capacity) {
424
+ const putter = this.putters.shift()!;
425
+ this.clearTimeout(putter);
426
+ this.buffer.push(putter.element);
427
+ putter.resolve();
428
+ }
429
+ }
430
+
431
+ private clearTimeout(resolver: Resolver<any>): void {
432
+ if (resolver.timeoutId) {
433
+ clearTimeout(resolver.timeoutId);
434
+ }
435
+ }
436
+
437
+ // ========================================================================
438
+ // Utility methods
439
+ // ========================================================================
440
+
441
+ /**
442
+ * This method gives statistics about the queue.
443
+ */
444
+ getStats() : {
445
+ size: number;
446
+ capacity: number;
447
+ isEmpty: boolean;
448
+ isFull: boolean;
449
+ isClosed: boolean;
450
+ waitingPutters: number;
451
+ waitingTakers: number;
452
+ remainingCapacity: number;
453
+ } {
454
+ return {
455
+ size: this.size,
456
+ capacity: this.capacity,
457
+ isEmpty: this.isEmpty,
458
+ isFull: this.isFull,
459
+ isClosed: this._isClosed,
460
+ waitingPutters: this.putters.length,
461
+ waitingTakers: this.takers.length,
462
+ remainingCapacity: this.remainingCapacity,
463
+ };
464
+ }
465
+
466
+ toString(): string {
467
+ return `AsyncQueue[size=${this.size}, capacity=${this.capacity}, closed=${this._isClosed}]`;
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Factory function to make an AsyncQueue.
473
+ *
474
+ * @example
475
+ * const queue = asyncQueue<number>({ capacity: 100 })
476
+ * await queue.put(42)
477
+ * const value = await queue.take()
478
+ */
479
+ export function asyncQueue<T>(options?: AsyncQueueOptions): AsyncQueue<T> {
480
+ return new AsyncQueue<T>(options);
481
+ }