modern-ts 0.8.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 (261) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +223 -0
  3. package/README.zh-CN.md +223 -0
  4. package/dist/chunks/Errors-BWEYu-AB.cjs +2 -0
  5. package/dist/chunks/Errors-BWEYu-AB.cjs.map +1 -0
  6. package/dist/chunks/Errors-DwUAvFIF.mjs +63 -0
  7. package/dist/chunks/Errors-DwUAvFIF.mjs.map +1 -0
  8. package/dist/chunks/Math-CGEH1ClN.mjs +68 -0
  9. package/dist/chunks/Math-CGEH1ClN.mjs.map +1 -0
  10. package/dist/chunks/Math-CWZVxSF-.cjs +2 -0
  11. package/dist/chunks/Math-CWZVxSF-.cjs.map +1 -0
  12. package/dist/chunks/base-B9k8Lqvf.mjs +56 -0
  13. package/dist/chunks/base-B9k8Lqvf.mjs.map +1 -0
  14. package/dist/chunks/base-BTXL1y_I.cjs +2 -0
  15. package/dist/chunks/base-BTXL1y_I.cjs.map +1 -0
  16. package/dist/chunks/base-BpECeKwU.mjs +19 -0
  17. package/dist/chunks/base-BpECeKwU.mjs.map +1 -0
  18. package/dist/chunks/base-BvHqpP_s.cjs +2 -0
  19. package/dist/chunks/base-BvHqpP_s.cjs.map +1 -0
  20. package/dist/chunks/base-K-RHLZ-S.mjs +46 -0
  21. package/dist/chunks/base-K-RHLZ-S.mjs.map +1 -0
  22. package/dist/chunks/base-r6kn0B0D.cjs +2 -0
  23. package/dist/chunks/base-r6kn0B0D.cjs.map +1 -0
  24. package/dist/chunks/combine-async-DcG-3p8i.cjs +2 -0
  25. package/dist/chunks/combine-async-DcG-3p8i.cjs.map +1 -0
  26. package/dist/chunks/combine-async-Dcg4ya1R.mjs +236 -0
  27. package/dist/chunks/combine-async-Dcg4ya1R.mjs.map +1 -0
  28. package/dist/chunks/delay-CG3cD7bk.cjs +2 -0
  29. package/dist/chunks/delay-CG3cD7bk.cjs.map +1 -0
  30. package/dist/chunks/delay-CKIXpP71.mjs +32 -0
  31. package/dist/chunks/delay-CKIXpP71.mjs.map +1 -0
  32. package/dist/chunks/helper-BVabbpmX.mjs +165 -0
  33. package/dist/chunks/helper-BVabbpmX.mjs.map +1 -0
  34. package/dist/chunks/helper-tsqZMRHW.cjs +3 -0
  35. package/dist/chunks/helper-tsqZMRHW.cjs.map +1 -0
  36. package/dist/chunks/local-8JVtLN0O.mjs +10 -0
  37. package/dist/chunks/local-8JVtLN0O.mjs.map +1 -0
  38. package/dist/chunks/local-Da4yU-nE.cjs +2 -0
  39. package/dist/chunks/local-Da4yU-nE.cjs.map +1 -0
  40. package/dist/chunks/types-B7X_LBjM.cjs +2 -0
  41. package/dist/chunks/types-B7X_LBjM.cjs.map +1 -0
  42. package/dist/chunks/types-DE2SnSbz.mjs +5 -0
  43. package/dist/chunks/types-DE2SnSbz.mjs.map +1 -0
  44. package/dist/index.cjs +2 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.mjs +759 -0
  47. package/dist/index.mjs.map +1 -0
  48. package/dist/subpath/Arr.cjs +2 -0
  49. package/dist/subpath/Arr.cjs.map +1 -0
  50. package/dist/subpath/Arr.mjs +539 -0
  51. package/dist/subpath/Arr.mjs.map +1 -0
  52. package/dist/subpath/Concurrent.cjs +15 -0
  53. package/dist/subpath/Concurrent.cjs.map +1 -0
  54. package/dist/subpath/Concurrent.mjs +4044 -0
  55. package/dist/subpath/Concurrent.mjs.map +1 -0
  56. package/dist/subpath/FetchQ.cjs +2 -0
  57. package/dist/subpath/FetchQ.cjs.map +1 -0
  58. package/dist/subpath/FetchQ.mjs +519 -0
  59. package/dist/subpath/FetchQ.mjs.map +1 -0
  60. package/dist/subpath/Fit.cjs +2 -0
  61. package/dist/subpath/Fit.cjs.map +1 -0
  62. package/dist/subpath/Fit.mjs +914 -0
  63. package/dist/subpath/Fit.mjs.map +1 -0
  64. package/dist/subpath/Lazy.cjs +2 -0
  65. package/dist/subpath/Lazy.cjs.map +1 -0
  66. package/dist/subpath/Lazy.mjs +72 -0
  67. package/dist/subpath/Lazy.mjs.map +1 -0
  68. package/dist/subpath/Maps.cjs +2 -0
  69. package/dist/subpath/Maps.cjs.map +1 -0
  70. package/dist/subpath/Maps.mjs +123 -0
  71. package/dist/subpath/Maps.mjs.map +1 -0
  72. package/dist/subpath/Maybe.cjs +2 -0
  73. package/dist/subpath/Maybe.cjs.map +1 -0
  74. package/dist/subpath/Maybe.mjs +329 -0
  75. package/dist/subpath/Maybe.mjs.map +1 -0
  76. package/dist/subpath/Reactive.cjs +2 -0
  77. package/dist/subpath/Reactive.cjs.map +1 -0
  78. package/dist/subpath/Reactive.mjs +1204 -0
  79. package/dist/subpath/Reactive.mjs.map +1 -0
  80. package/dist/subpath/Reader.cjs +2 -0
  81. package/dist/subpath/Reader.cjs.map +1 -0
  82. package/dist/subpath/Reader.mjs +75 -0
  83. package/dist/subpath/Reader.mjs.map +1 -0
  84. package/dist/subpath/ReaderT.cjs +2 -0
  85. package/dist/subpath/ReaderT.cjs.map +1 -0
  86. package/dist/subpath/ReaderT.mjs +148 -0
  87. package/dist/subpath/ReaderT.mjs.map +1 -0
  88. package/dist/subpath/Resource.cjs +2 -0
  89. package/dist/subpath/Resource.cjs.map +1 -0
  90. package/dist/subpath/Resource.mjs +150 -0
  91. package/dist/subpath/Resource.mjs.map +1 -0
  92. package/dist/subpath/Result.cjs +2 -0
  93. package/dist/subpath/Result.cjs.map +1 -0
  94. package/dist/subpath/Result.mjs +337 -0
  95. package/dist/subpath/Result.mjs.map +1 -0
  96. package/dist/subpath/Sets.cjs +2 -0
  97. package/dist/subpath/Sets.cjs.map +1 -0
  98. package/dist/subpath/Sets.mjs +92 -0
  99. package/dist/subpath/Sets.mjs.map +1 -0
  100. package/dist/subpath/Str.cjs +2 -0
  101. package/dist/subpath/Str.cjs.map +1 -0
  102. package/dist/subpath/Str.mjs +114 -0
  103. package/dist/subpath/Str.mjs.map +1 -0
  104. package/dist/subpath/TxScope.cjs +2 -0
  105. package/dist/subpath/TxScope.cjs.map +1 -0
  106. package/dist/subpath/TxScope.mjs +138 -0
  107. package/dist/subpath/TxScope.mjs.map +1 -0
  108. package/dist/subpath/TypeTool.cjs +2 -0
  109. package/dist/subpath/TypeTool.cjs.map +1 -0
  110. package/dist/subpath/TypeTool.mjs +9 -0
  111. package/dist/subpath/TypeTool.mjs.map +1 -0
  112. package/dist/subpath/Utils.cjs +2 -0
  113. package/dist/subpath/Utils.cjs.map +1 -0
  114. package/dist/subpath/Utils.mjs +835 -0
  115. package/dist/subpath/Utils.mjs.map +1 -0
  116. package/dist/subpath/VirtualTime.cjs +2 -0
  117. package/dist/subpath/VirtualTime.cjs.map +1 -0
  118. package/dist/subpath/VirtualTime.mjs +1186 -0
  119. package/dist/subpath/VirtualTime.mjs.map +1 -0
  120. package/dist/types/Arr.d.ts +2 -0
  121. package/dist/types/Concurrent/Lock/condition_variable.d.ts +138 -0
  122. package/dist/types/Concurrent/Lock/mutex.d.ts +185 -0
  123. package/dist/types/Concurrent/Lock/rwlock.d.ts +253 -0
  124. package/dist/types/Concurrent/Lock/semaphore.d.ts +208 -0
  125. package/dist/types/Concurrent/Valve/__export__.d.ts +5 -0
  126. package/dist/types/Concurrent/Valve/circuit-breaker.d.ts +146 -0
  127. package/dist/types/Concurrent/Valve/leaky-bucket.d.ts +115 -0
  128. package/dist/types/Concurrent/Valve/sliding-window.d.ts +91 -0
  129. package/dist/types/Concurrent/Valve/token-bucket.d.ts +68 -0
  130. package/dist/types/Concurrent/__export__.d.ts +15 -0
  131. package/dist/types/Concurrent/barrier.d.ts +255 -0
  132. package/dist/types/Concurrent/channel.d.ts +239 -0
  133. package/dist/types/Concurrent/delay.d.ts +42 -0
  134. package/dist/types/Concurrent/ext/map.d.ts +82 -0
  135. package/dist/types/Concurrent/ext/other.d.ts +113 -0
  136. package/dist/types/Concurrent/ext/race.d.ts +31 -0
  137. package/dist/types/Concurrent/ext/some.d.ts +64 -0
  138. package/dist/types/Concurrent/limiter.d.ts +131 -0
  139. package/dist/types/Concurrent/scheduler.d.ts +171 -0
  140. package/dist/types/Concurrent/task-scope.d.ts +282 -0
  141. package/dist/types/Concurrent.d.ts +2 -0
  142. package/dist/types/Errors.d.ts +66 -0
  143. package/dist/types/FetchQ.d.ts +2 -0
  144. package/dist/types/Fit/__export__.d.ts +5 -0
  145. package/dist/types/Fit/base.d.ts +325 -0
  146. package/dist/types/Fit/parser.d.ts +110 -0
  147. package/dist/types/Fit/standard-schema.d.ts +127 -0
  148. package/dist/types/Fit/sugar.d.ts +274 -0
  149. package/dist/types/Fit/tool.d.ts +585 -0
  150. package/dist/types/Fit.d.ts +2 -0
  151. package/dist/types/Lazy.d.ts +2 -0
  152. package/dist/types/Maps.d.ts +2 -0
  153. package/dist/types/Maybe/__export__.d.ts +6 -0
  154. package/dist/types/Maybe/base.d.ts +62 -0
  155. package/dist/types/Maybe/consumers-async.d.ts +58 -0
  156. package/dist/types/Maybe/consumers.d.ts +63 -0
  157. package/dist/types/Maybe/operators-async.d.ts +145 -0
  158. package/dist/types/Maybe/operators.d.ts +177 -0
  159. package/dist/types/Maybe/types.d.ts +12 -0
  160. package/dist/types/Maybe.d.ts +2 -0
  161. package/dist/types/MockClock/Timeline.d.ts +392 -0
  162. package/dist/types/MockClock/TimerHandle.d.ts +159 -0
  163. package/dist/types/MockClock/TimerHeap.d.ts +21 -0
  164. package/dist/types/MockClock/VirtualTimeManager.d.ts +23 -0
  165. package/dist/types/MockClock/__export__.d.ts +104 -0
  166. package/dist/types/MockClock/hooks/__export__.d.ts +9 -0
  167. package/dist/types/MockClock/hooks/hookAbortSignal.d.ts +3 -0
  168. package/dist/types/MockClock/hooks/hookDate.d.ts +3 -0
  169. package/dist/types/MockClock/hooks/hookIntl.d.ts +3 -0
  170. package/dist/types/MockClock/hooks/hookMessageChannel.d.ts +3 -0
  171. package/dist/types/MockClock/hooks/hookMicrotasks.d.ts +3 -0
  172. package/dist/types/MockClock/hooks/hookOs.d.ts +3 -0
  173. package/dist/types/MockClock/hooks/hookPerformance.d.ts +3 -0
  174. package/dist/types/MockClock/hooks/hookProcess.d.ts +3 -0
  175. package/dist/types/MockClock/hooks/hookTimers.d.ts +3 -0
  176. package/dist/types/MockClock/types.d.ts +103 -0
  177. package/dist/types/Other/FetchQ.d.ts +320 -0
  178. package/dist/types/Other/deque.d.ts +59 -0
  179. package/dist/types/Other/disjointSet.d.ts +53 -0
  180. package/dist/types/Other/heap.d.ts +41 -0
  181. package/dist/types/Other/lazy.d.ts +127 -0
  182. package/dist/types/Other/queue.d.ts +42 -0
  183. package/dist/types/Other/secret.d.ts +111 -0
  184. package/dist/types/Other/stack.d.ts +40 -0
  185. package/dist/types/Reactive/__export__.d.ts +4 -0
  186. package/dist/types/Reactive/event_emitter.d.ts +195 -0
  187. package/dist/types/Reactive/flow-combination.d.ts +74 -0
  188. package/dist/types/Reactive/flow.d.ts +180 -0
  189. package/dist/types/Reactive/pace.d.ts +80 -0
  190. package/dist/types/Reactive.d.ts +2 -0
  191. package/dist/types/Reader/__export-readerT__.d.ts +4 -0
  192. package/dist/types/Reader/__export-reader__.d.ts +4 -0
  193. package/dist/types/Reader/local.d.ts +39 -0
  194. package/dist/types/Reader/reader-async.d.ts +84 -0
  195. package/dist/types/Reader/reader.d.ts +96 -0
  196. package/dist/types/Reader/readerT-async.d.ts +186 -0
  197. package/dist/types/Reader/readerT.d.ts +178 -0
  198. package/dist/types/Reader/types.d.ts +37 -0
  199. package/dist/types/Reader.d.ts +2 -0
  200. package/dist/types/ReaderT.d.ts +2 -0
  201. package/dist/types/Resource/TxScope-async.d.ts +86 -0
  202. package/dist/types/Resource/TxScope.d.ts +85 -0
  203. package/dist/types/Resource/__export-TxScope__.d.ts +2 -0
  204. package/dist/types/Resource/__export-resource__.d.ts +2 -0
  205. package/dist/types/Resource/resource-async.d.ts +79 -0
  206. package/dist/types/Resource/resource.d.ts +78 -0
  207. package/dist/types/Resource/types.d.ts +79 -0
  208. package/dist/types/Resource.d.ts +2 -0
  209. package/dist/types/Result/Consumers/branch-async.d.ts +77 -0
  210. package/dist/types/Result/Consumers/branch.d.ts +70 -0
  211. package/dist/types/Result/Consumers/inspect.d.ts +66 -0
  212. package/dist/types/Result/Operators/Async/combine-async.d.ts +69 -0
  213. package/dist/types/Result/Operators/Async/partition-async.d.ts +29 -0
  214. package/dist/types/Result/Operators/Async/reduce-async.d.ts +15 -0
  215. package/dist/types/Result/Operators/Async/transform-async.d.ts +90 -0
  216. package/dist/types/Result/Operators/combine.d.ts +60 -0
  217. package/dist/types/Result/Operators/flatten.d.ts +26 -0
  218. package/dist/types/Result/Operators/partition.d.ts +25 -0
  219. package/dist/types/Result/Operators/reduce.d.ts +12 -0
  220. package/dist/types/Result/Operators/transform.d.ts +70 -0
  221. package/dist/types/Result/__export__.d.ts +14 -0
  222. package/dist/types/Result/base.d.ts +115 -0
  223. package/dist/types/Result/types.d.ts +34 -0
  224. package/dist/types/Result.d.ts +2 -0
  225. package/dist/types/Sets.d.ts +2 -0
  226. package/dist/types/Str.d.ts +2 -0
  227. package/dist/types/TxScope.d.ts +2 -0
  228. package/dist/types/TypeTool.d.ts +2 -0
  229. package/dist/types/Utils/Array/__export__.d.ts +10 -0
  230. package/dist/types/Utils/Array/filtering.d.ts +89 -0
  231. package/dist/types/Utils/Array/flatten.d.ts +45 -0
  232. package/dist/types/Utils/Array/grouping.d.ts +44 -0
  233. package/dist/types/Utils/Array/iteration.d.ts +86 -0
  234. package/dist/types/Utils/Array/operators.d.ts +62 -0
  235. package/dist/types/Utils/Array/randomization.d.ts +76 -0
  236. package/dist/types/Utils/Array/set.d.ts +108 -0
  237. package/dist/types/Utils/Array/slice.d.ts +189 -0
  238. package/dist/types/Utils/Array/sorting.d.ts +55 -0
  239. package/dist/types/Utils/Array/zip.d.ts +93 -0
  240. package/dist/types/Utils/Functions/__export__.d.ts +5 -0
  241. package/dist/types/Utils/Functions/base.d.ts +157 -0
  242. package/dist/types/Utils/Functions/curry.d.ts +73 -0
  243. package/dist/types/Utils/Functions/debounce.d.ts +240 -0
  244. package/dist/types/Utils/Functions/defer.d.ts +43 -0
  245. package/dist/types/Utils/Functions/pipe.d.ts +205 -0
  246. package/dist/types/Utils/Map.d.ts +284 -0
  247. package/dist/types/Utils/Math.d.ts +225 -0
  248. package/dist/types/Utils/Object/__export__.d.ts +2 -0
  249. package/dist/types/Utils/Object/base.d.ts +131 -0
  250. package/dist/types/Utils/Object/clone.d.ts +81 -0
  251. package/dist/types/Utils/Predicates.d.ts +361 -0
  252. package/dist/types/Utils/Set.d.ts +105 -0
  253. package/dist/types/Utils/String.d.ts +217 -0
  254. package/dist/types/Utils/__export__.d.ts +9 -0
  255. package/dist/types/Utils/type-tool.d.ts +168 -0
  256. package/dist/types/Utils.d.ts +2 -0
  257. package/dist/types/VirtualTime.d.ts +2 -0
  258. package/dist/types/helper.d.ts +71 -0
  259. package/dist/types/index.d.ts +21 -0
  260. package/dist/types/unknown-error.d.ts +98 -0
  261. package/package.json +179 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Special symbol indicating the channel is closed
3
+ * @remarks Returned by receive methods when channel is closed and no data remains
4
+ */
5
+ export declare const CHANNEL_CLOSED: unique symbol;
6
+ interface ResizeOptions {
7
+ /** Strategy when reducing capacity below current data size */
8
+ strategy?: 'error' | 'discard-oldest' | 'discard-newest';
9
+ /** Whether to process pending senders after resize */
10
+ flush_pending?: boolean;
11
+ }
12
+ declare const Tag_Channel: unique symbol;
13
+ /**
14
+ * A channel implementing producer-consumer pattern with bounded capacity
15
+ * @template T Type of data transmitted through the channel
16
+ * @remarks
17
+ * - Uses a circular buffer for data storage
18
+ * - Maintains separate queues for waiting senders and receivers
19
+ * - Supports abort signals for async operations
20
+ * - Auto-compacts internal queues when many slots become empty
21
+ * @throws {UseAfterFreeError} When attempting operations after disposal
22
+ * @throws {ParameterError} When resize would lose data without explicit strategy
23
+ */
24
+ export declare class Channel<T = unknown> {
25
+ readonly [Tag_Channel]: void;
26
+ private static readonly COMPACTION_THRESHOLD;
27
+ private static readonly MIN_QUEUE_SIZE_FOR_COMPACTION;
28
+ private buffer;
29
+ private buffer_head;
30
+ private buffer_tail;
31
+ private buffer_size;
32
+ private _capacity;
33
+ private state;
34
+ private senders;
35
+ private sender_head;
36
+ private receivers;
37
+ private receiver_head;
38
+ /**
39
+ * Creates a new channel with specified capacity
40
+ * @param capacity Maximum number of items buffer can hold (default: 0)
41
+ * @remarks Zero capacity creates a rendezvous channel (no buffering)
42
+ * @throws {RangeError} If capacity is negative (implicitly, through Math.max)
43
+ */
44
+ constructor(capacity?: number);
45
+ private throwIfDisposed;
46
+ private throwIfClosedOrDisposed;
47
+ private cleanupSender;
48
+ private cleanupReceiver;
49
+ private handleSenderAbort;
50
+ private handleReceiverAbort;
51
+ private processReceiver;
52
+ private processSender;
53
+ /**
54
+ * Changes the channel's capacity
55
+ * @param new_capacity New maximum buffer size
56
+ * @param options Resize behavior options
57
+ * @returns True if resize succeeded
58
+ * @throws {UseAfterFreeError} When channel is disposed or closed
59
+ * @throws {ParameterError} When new capacity < current data size and strategy='error'
60
+ * @remarks
61
+ * - Strategy 'discard-oldest' removes from buffer head
62
+ * - Strategy 'discard-newest' removes from buffer tail
63
+ * - By default, processes pending senders after successful resize
64
+ * - Buffer data is preserved and compacted during resize
65
+ */
66
+ resize(new_capacity: number, options?: ResizeOptions): boolean;
67
+ /**
68
+ * Attempts to resize channel, returns false on failure
69
+ * @param new_capacity New maximum buffer size
70
+ * @param options Resize behavior options
71
+ * @returns True if resize succeeded, false otherwise
72
+ * @remarks Does not throw on resize failure, returns false instead
73
+ */
74
+ tryResize(new_capacity: number, options?: ResizeOptions): boolean;
75
+ /**
76
+ * Asynchronously sends a value through the channel
77
+ * @param value Value to send
78
+ * @param signal Optional abort signal to cancel the send
79
+ * @returns Promise that resolves when value is accepted
80
+ * @throws {UseAfterFreeError} When channel is disposed or closed
81
+ * @throws {DOMException} When abort signal is already triggered
82
+ * @remarks
83
+ * 1. First tries to match with waiting receiver (rendezvous)
84
+ * 2. If buffer space available, stores immediately
85
+ * 3. Otherwise waits in sender queue until space available or abort
86
+ */
87
+ send(value: T, signal?: AbortSignal): Promise<void>;
88
+ /**
89
+ * Synchronously attempts to send a value
90
+ * @param value Value to send
91
+ * @returns True if value was accepted, false otherwise
92
+ * @throws {UseAfterFreeError} When channel is disposed or closed
93
+ * @remarks Does not wait - returns false immediately if no buffer space and no waiting receiver
94
+ */
95
+ sendSync(value: T): boolean;
96
+ /**
97
+ * Attempts to send a value if channel is open
98
+ * @param value Value to send
99
+ * @returns True if value was accepted, false if channel is closed
100
+ * @remarks Silent version of sendSync that returns false instead of throwing when closed
101
+ */
102
+ trySend(value: T): boolean;
103
+ /**
104
+ * Asynchronously receives a value from the channel
105
+ * @param signal Optional abort signal to cancel the receive
106
+ * @returns Promise resolving to received value or CHANNEL_CLOSED symbol
107
+ * @throws {UseAfterFreeError} When channel is disposed
108
+ * @throws {DOMException} When abort signal is already triggered
109
+ * @remarks
110
+ * 1. First tries to dequeue from buffer
111
+ * 2. If closed and buffer empty, returns CHANNEL_CLOSED
112
+ * 3. Otherwise waits in receiver queue until data available, channel closes, or abort
113
+ */
114
+ receive(signal?: AbortSignal): Promise<T | typeof CHANNEL_CLOSED>;
115
+ /**
116
+ * Synchronously attempts to receive a value
117
+ * @returns Received value, CHANNEL_CLOSED, or undefined if no data
118
+ * @throws {UseAfterFreeError} When channel is disposed
119
+ * @remarks
120
+ * - Returns T if data available in buffer or from waiting sender
121
+ * - Returns CHANNEL_CLOSED if channel closed and buffer empty
122
+ * - Returns undefined if no data available and channel still open
123
+ */
124
+ tryReceive(): T | typeof CHANNEL_CLOSED | undefined;
125
+ /**
126
+ * Clears all buffered data
127
+ * @returns Number of items drained from buffer
128
+ * @throws {UseAfterFreeError} When channel is disposed or closed
129
+ * @remarks Processes pending senders after draining if capacity > 0
130
+ */
131
+ drain(): number;
132
+ /**
133
+ * Closes the channel to new sends
134
+ * @remarks
135
+ * - Rejects all pending senders with UseAfterFreeError
136
+ * - Resolves all pending receivers with done: true
137
+ * - Does nothing if already closed or disposed
138
+ */
139
+ close(): void;
140
+ /**
141
+ * Disposes the channel, releasing all resources
142
+ * @remarks Calls close() then marks as disposed and clears buffer
143
+ */
144
+ dispose(): void;
145
+ /** 从环形缓冲区出队一个值,并处理可能等待的发送者 */
146
+ private dequeueBuffer;
147
+ /** 处理等待的发送者,利用缓冲区空间 */
148
+ private processPendingSenders;
149
+ /** 压缩接收队列以回收内存 */
150
+ private compactReceiverQueueIfNeeded;
151
+ /** 压缩队列,移除空槽并更新节点索引 */
152
+ private compactQueue;
153
+ /** Gets current channel statistics */
154
+ get stats(): {
155
+ capacity: number;
156
+ buffered: number;
157
+ waiting_senders: number;
158
+ waiting_receivers: number;
159
+ closed: boolean;
160
+ disposed: boolean;
161
+ };
162
+ /** Current channel capacity */
163
+ get capacity(): number;
164
+ /** Whether channel is closed to new sends */
165
+ get isClosed(): boolean;
166
+ /** Whether channel is fully disposed */
167
+ get isDisposed(): boolean;
168
+ /** Number of items currently buffered */
169
+ get buffered(): number;
170
+ /**
171
+ * Async iterator yielding values until channel closes
172
+ * @yields {T} Next value from channel
173
+ * @returns When channel closes
174
+ */
175
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, unknown>;
176
+ /**
177
+ * Receives values in batches
178
+ * @param max_size Maximum batch size (default: Infinity)
179
+ * @param signal Optional abort signal
180
+ * @yields {T[]} Batch of values
181
+ * @throws {DOMException} When abort signal triggered
182
+ * @remarks Yields final partial batch even if channel closes early
183
+ */
184
+ receiveBatch(max_size?: number, signal?: AbortSignal): AsyncGenerator<T[], void, unknown>;
185
+ /** Synchronous disposal (for using with `using` statement) */
186
+ [Symbol.dispose](): void;
187
+ }
188
+ type SelectableChannel<T> = {
189
+ trySend(value: T): boolean;
190
+ tryReceive(): T | typeof CHANNEL_CLOSED | undefined;
191
+ send(value: T, signal?: AbortSignal): Promise<void>;
192
+ receive(signal?: AbortSignal): Promise<T | typeof CHANNEL_CLOSED>;
193
+ readonly [Tag_Channel]: void;
194
+ };
195
+ interface SelectSendCase<T = unknown> {
196
+ op: 'send';
197
+ channel: SelectableChannel<T>;
198
+ value: T;
199
+ }
200
+ interface SelectReceiveCase<T = unknown> {
201
+ op: 'receive';
202
+ channel: SelectableChannel<T>;
203
+ }
204
+ type SelectCase<T = unknown> = SelectSendCase<T> | SelectReceiveCase<T>;
205
+ export type SelectResult<C extends SelectCase<unknown>> = (C extends SelectSendCase<infer T> ? SelectSendCase<T> & {
206
+ value: T;
207
+ } : C extends SelectReceiveCase<infer T> ? SelectReceiveCase<T> & {
208
+ value: T | typeof CHANNEL_CLOSED;
209
+ } : never) | SelectDefaultResult;
210
+ export interface SelectDefaultResult {
211
+ op: 'default';
212
+ }
213
+ export interface SelectOptions {
214
+ /**
215
+ * If provided, this function is called if no other case is ready immediately.
216
+ * This makes the select operation non-blocking.
217
+ */
218
+ default?: () => void;
219
+ }
220
+ /**
221
+ * Waits for multiple channel operations and returns when one completes.
222
+ * This implements CSP-style select semantics: it checks if any operation can
223
+ * proceed immediately without blocking; otherwise, it waits until one does.
224
+ *
225
+ * @template Cases The array type of select cases
226
+ * @param cases Array of send or receive cases
227
+ * @param signal Optional AbortSignal to cancel the entire select operation
228
+ * @param options Optional configuration object, supports 'default' callback for non-blocking behavior
229
+ * @returns Promise resolving to the case that fired, augmented with the value (for receive), or default
230
+ * @throws {UseAfterFreeError} If a channel operation fails permanently
231
+ * @throws {DOMException} If the provided signal is aborted
232
+ * @remarks
233
+ * - Prioritizes cases that can complete synchronously (using `trySend`/`tryReceive`).
234
+ * - If multiple are ready, the first one in the array is selected.
235
+ * - If none are ready and `options.default` is provided, it executes the callback and returns immediately.
236
+ * - If none are ready and no default is provided, it races async operations.
237
+ */
238
+ export declare function select<Cases extends [SelectCase, ...SelectCase[]]>(cases: Cases, signal?: AbortSignal, options?: SelectOptions): Promise<SelectResult<Cases[number]>>;
239
+ export {};
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Delays the execution for a specified number of milliseconds.
3
+ * @param ms - The duration to wait in milliseconds.
4
+ * @param signal - An optional `AbortSignal` to cancel the delay.
5
+ * If the signal is aborted, the promise rejects with a `DOMException`.
6
+ * @returns A promise that resolves after the timeout or rejects if aborted.
7
+ * @example
8
+ * ```ts
9
+ * try {
10
+ * await delay(1000, controller.signal);
11
+ * } catch (err) {
12
+ * console.error("Delayed action was cancelled!");
13
+ * }
14
+ * ```
15
+ */
16
+ export declare function delay(ms: number, signal?: AbortSignal): Promise<void>;
17
+ /**
18
+ * A safe version of the delay function that never rejects.
19
+ * Instead of rejecting on abort, it resolves with a DOMException.
20
+ * @param ms - The duration to wait in milliseconds.
21
+ * @param signal - An optional `AbortSignal` to cancel the delay.
22
+ * If the signal is aborted, the promise resolves with a `DOMException` instead of rejecting.
23
+ * @returns A promise that resolves after the timeout or resolves with a DOMException if aborted.
24
+ * This is useful when you want to handle abort conditions without try-catch blocks.
25
+ * @example
26
+ * ```ts
27
+ * const result = await delaySafe(1000, controller.signal);
28
+ * if (result instanceof DOMException) {
29
+ * console.log("Delay was aborted:", result.message);
30
+ * } else {
31
+ * console.log("Delay completed successfully");
32
+ * }
33
+ * ```
34
+ */
35
+ export declare function delaySafe(ms: number, signal?: AbortSignal): Promise<undefined | DOMException>;
36
+ /**
37
+ * A simplified, non-cancelable version of {@link delay}.
38
+ * Useful for basic pauses where abort logic is not required.
39
+ * @param ms - The duration to sleep in milliseconds.
40
+ * @returns A promise that resolves after the timeout.
41
+ */
42
+ export declare const sleep: (ms: number) => Promise<void>;
@@ -0,0 +1,82 @@
1
+ import { MaybePromise } from '../../Utils/type-tool';
2
+ /** Symbol used to skip an item in the map result. */
3
+ export declare const MAP_SKIP: unique symbol;
4
+ export type MapSkipType = typeof MAP_SKIP;
5
+ /** Options for {@link asyncMap}. */
6
+ interface MapOptions {
7
+ /** Maximum number of concurrent map operations. Defaults to `Infinity`. */
8
+ readonly concurrency?: number;
9
+ /** If `true`, stop processing on first error and reject with that error. If `false`, collect errors and reject with `AggregateError` at the end. Defaults to `true`. */
10
+ readonly stopOnError?: boolean;
11
+ /** AbortSignal to cancel the operation. */
12
+ readonly signal?: AbortSignal;
13
+ }
14
+ /**
15
+ * Mapping function type used by {@link asyncMap} and {@link asyncMapIterable}.
16
+ *
17
+ * @template T - Type of the input item.
18
+ * @template R - Type of the mapped result.
19
+ * @param item - The current item from the iterable.
20
+ * @param index - The index of the current item.
21
+ * @returns The mapped value, a promise of it, or {@link MAP_SKIP} to exclude this item.
22
+ */
23
+ type Mapper<T, R> = (item: T, index: number) => R | MapSkipType | PromiseLike<R | MapSkipType>;
24
+ /**
25
+ * Asynchronously maps items from an iterable (sync/async) using a concurrency‑controlled mapper.
26
+ *
27
+ * The function processes items in parallel up to `concurrency`, and returns an array of results
28
+ * in the same order as the original iterable. Items for which the mapper returns `MAP_SKIP` are
29
+ * omitted from the final array.
30
+ *
31
+ * @template T - Type of items in the input iterable (may be wrapped in a promise).
32
+ * @template R - Type of the mapped results.
33
+ * @param iterable - Source of items. Can be synchronous, asynchronous, or contain promises.
34
+ * @param mapper - Async mapping function applied to each item.
35
+ * @param options - Configuration options.
36
+ * @returns Promise resolving to an array of mapped results (excluding skipped items).
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const result = await asyncMap([1, 2, 3], async x => x * 2, { concurrency: 2 });
41
+ * // result = [2, 4, 6]
42
+ * ```
43
+ */
44
+ export declare function asyncMap<T, R>(iterable: Iterable<MaybePromise<T>> | AsyncIterable<MaybePromise<T>>, mapper: Mapper<T, R>, { concurrency, stopOnError, signal }?: MapOptions): Promise<Array<R>>;
45
+ /** Options for {@link asyncMapIterable}. */
46
+ interface MapIterableOptions {
47
+ /** Maximum number of concurrent map operations. Defaults to `Infinity`. */
48
+ readonly concurrency?: number;
49
+ /**
50
+ * Maximum number of pending results buffered ahead of consumption.
51
+ * Must be at least `concurrency`. Helps to prevent the producer from outrunning the consumer.
52
+ * Defaults to `concurrency`.
53
+ */
54
+ readonly backpressure?: number;
55
+ /** AbortSignal to cancel the operation. */
56
+ readonly signal?: AbortSignal;
57
+ }
58
+ /**
59
+ * Asynchronously maps items from an iterable (sync/async) into an async generator,
60
+ * with concurrency control and backpressure.
61
+ *
62
+ * Items are processed in parallel up to `concurrency`, and results are yielded as soon as they
63
+ * become available (preserving the original order). Use `backpressure` to limit how many results
64
+ * are buffered ahead of consumption, preventing uncontrolled memory growth.
65
+ *
66
+ * @template T - Type of items in the input iterable (may be wrapped in a promise).
67
+ * @template R - Type of the mapped results.
68
+ * @param iterable - Source of items. Can be synchronous, asynchronous, or contain promises.
69
+ * @param mapper - Async mapping function applied to each item.
70
+ * @param options - Configuration options.
71
+ * @returns AsyncGenerator yielding mapped results (excluding skipped items).
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const gen = asyncMapIterable([1, 2, 3], async x => x * 2, { concurrency: 2 });
76
+ * for await (const val of gen) {
77
+ * console.log(val); // 2, 4, 6 (in order)
78
+ * }
79
+ * ```
80
+ */
81
+ export declare function asyncMapIterable<T, R>(iterable: Iterable<MaybePromise<T>> | AsyncIterable<MaybePromise<T>>, mapper: Mapper<T, R>, { concurrency, backpressure, signal, }?: MapIterableOptions): AsyncGenerator<R, void, void>;
82
+ export {};
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Options for timeout operations.
3
+ * @template T - The type of the original promise result
4
+ * @template R - The type of the fallback result (defaults to T)
5
+ */
6
+ export interface TimeoutOptions<T, R = T> {
7
+ /** Timeout duration in milliseconds */
8
+ readonly ms: number;
9
+ /** Optional fallback function to call on timeout */
10
+ readonly fallback?: () => R;
11
+ /** Optional abort signal for cancellation */
12
+ readonly signal?: AbortSignal;
13
+ }
14
+ /**
15
+ * Wraps a promise with a timeout, returning either the promise result or a fallback value.
16
+ *
17
+ * @template T - The type of the original promise result
18
+ * @template R - The type of the fallback result (defaults to never if no fallback)
19
+ * @param promise - The promise to wrap with timeout
20
+ * @param options - Timeout options including duration, fallback, and abort signal
21
+ * @returns A promise that resolves with the original result or fallback value, with a `clear` method to cancel
22
+ * @throws {ParameterError} If `ms` is not a positive integer
23
+ * @throws {DOMException} With 'TimeoutError' if timeout occurs without fallback, or 'AbortError' if cleared/cancelled
24
+ */
25
+ export declare function asyncTimeout<T, R = never>(promise: PromiseLike<T>, options: TimeoutOptions<R>): Promise<T | R> & {
26
+ clear: () => void;
27
+ };
28
+ /**
29
+ * Executes an async mapper function over an array with controlled concurrency,
30
+ * returning settled results (fulfilled or rejected) for each element.
31
+ *
32
+ * @template T - The type of array elements
33
+ * @template R - The type of mapper result
34
+ * @param array - The array to process
35
+ * @param options - Options including concurrency limit, mapper function, and abort signal
36
+ * @returns An array of settled results preserving the original order
37
+ * @throws {ParameterError} If `concurrency` is not a positive integer or Infinity
38
+ * @throws {DOMException} If the abort signal is triggered
39
+ */
40
+ export declare function asyncSettle<T, R>(array: T[], options: {
41
+ concurrency?: number;
42
+ mapper: (element: T, index: number) => Promise<R> | R;
43
+ signal?: AbortSignal;
44
+ }): Promise<({
45
+ status: 'fulfilled';
46
+ value: R;
47
+ } | {
48
+ status: 'rejected';
49
+ reason: unknown;
50
+ })[]>;
51
+ declare const doneValue: unique symbol;
52
+ /**
53
+ * Internal interface for resolving asyncWaitFor with a specific value.
54
+ * @template T - The type of the resolved value
55
+ */
56
+ interface ResolveWithValue<T> {
57
+ [doneValue]: T;
58
+ }
59
+ /**
60
+ * Options for waitFor timeout behavior.
61
+ * @template T - The type of the fallback return value
62
+ */
63
+ export interface WaitForTimeoutOptions<T> {
64
+ /** Timeout duration in milliseconds */
65
+ readonly ms: number;
66
+ /** Optional fallback function to call on timeout */
67
+ readonly fallback?: () => T | Promise<T>;
68
+ /** Optional custom error message or Error object for timeout */
69
+ readonly message?: string;
70
+ }
71
+ /**
72
+ * Timeout option type - either a simple number or detailed options.
73
+ * @template T - The type of the fallback return value
74
+ */
75
+ export type TimeoutOption<T> = number | WaitForTimeoutOptions<T>;
76
+ /**
77
+ * Options for asyncWaitFor function.
78
+ * @template T - The type of the value to resolve with
79
+ */
80
+ export interface WaitForOptions<T> {
81
+ /** Interval between condition checks in milliseconds (default: 20) */
82
+ readonly interval?: number;
83
+ /** Timeout configuration - either milliseconds or detailed options */
84
+ readonly timeout?: TimeoutOption<T>;
85
+ /** Whether to check condition before first delay (default: true) */
86
+ readonly before?: boolean;
87
+ /** Optional abort signal for cancellation */
88
+ readonly signal?: AbortSignal;
89
+ }
90
+ /**
91
+ * Waits for a condition to become true, polling at specified intervals.
92
+ *
93
+ * @param condition - A function that returns true when the wait should end, or an object with doneValue
94
+ * @param options - Wait options including interval, timeout, and abort signal
95
+ * @throws {ParameterError} If interval or timeout values are invalid
96
+ * @throws {DOMException} With 'TimeoutError' if timeout occurs, or 'AbortError' if cancelled
97
+ */
98
+ export declare function asyncWaitFor(condition: () => boolean | Promise<boolean>, options?: WaitForOptions<void>): Promise<void>;
99
+ /**
100
+ * Waits for a condition to resolve with a specific value.
101
+ *
102
+ * @template T - The type of the value to resolve with
103
+ * @param condition - A function that returns true, false, or an object with doneValue
104
+ * @param options - Wait options including interval, timeout, and abort signal
105
+ * @returns The value from doneValue if condition returns one, otherwise undefined
106
+ * @throws {ParameterError} If interval or timeout values are invalid, or condition returns invalid type
107
+ * @throws {DOMException} With 'TimeoutError' if timeout occurs, or 'AbortError' if cancelled
108
+ */
109
+ export declare function asyncWaitFor<T>(condition: () => (boolean | ResolveWithValue<T>) | Promise<boolean | ResolveWithValue<T>>, options?: WaitForOptions<T>): Promise<T>;
110
+ export declare namespace asyncWaitFor {
111
+ var done: <T>(value: T) => ResolveWithValue<T>;
112
+ }
113
+ export {};
@@ -0,0 +1,31 @@
1
+ import { MaybePromise } from '../../Utils/type-tool';
2
+ type RaceExecutor<T> = (signal?: AbortSignal) => MaybePromise<T>[];
3
+ /**
4
+ * Race multiple tasks and return the result of the first settled task (resolve or reject).
5
+ *
6
+ * Accepts either an array of tasks or an executor function that returns an array of tasks.
7
+ * When the first task settles, all other pending tasks are aborted via the provided AbortSignal.
8
+ *
9
+ * @template T - The type of the resolved value.
10
+ * @param executor_or_tasks - An array of tasks (each can be a value or a Promise-like), or a function that receives an AbortSignal and returns such an array.
11
+ * @returns A Promise that resolves or rejects with the result of the first settled task.
12
+ * @throws {ParameterError} If the provided tasks array is empty or not an array.
13
+ */
14
+ export declare function asyncRace<T>(executor_or_tasks: MaybePromise<T>[] | RaceExecutor<T>): Promise<T>;
15
+ type FirstSource<T> = Iterable<MaybePromise<T>> | AsyncIterable<MaybePromise<T>>;
16
+ /**
17
+ * Resolves with the first successfully fulfilled value from an (async) iterable source.
18
+ *
19
+ * Iterates over the source sequentially, starting each task (each element may be a value or a Promise-like).
20
+ * If any task resolves successfully, that value becomes the result and all remaining tasks are aborted.
21
+ * If all tasks reject, the function rejects with the last error encountered.
22
+ *
23
+ * @template T - The type of the resolved value.
24
+ * @param source - An iterable or async iterable where each item can be a value or a Promise-like.
25
+ * @param signal - Optional AbortSignal to cancel the operation externally.
26
+ * @returns A Promise that resolves with the first successful value, or rejects if all fail or no tasks are provided.
27
+ * @throws {ParameterError} If the source yields no tasks (empty iterable).
28
+ * @throws {DOMException} If the provided signal is already aborted (synchronously).
29
+ */
30
+ export declare function asyncFirst<T>(source: FirstSource<T>, signal?: AbortSignal): Promise<T>;
31
+ export {};
@@ -0,0 +1,64 @@
1
+ import { MaybePromise } from '../../Utils/type-tool';
2
+ interface EveryOptions {
3
+ readonly concurrency?: number;
4
+ readonly signal?: AbortSignal;
5
+ }
6
+ /**
7
+ * Tests whether all elements in the iterable pass the test implemented by the provided predicate.
8
+ * Executes predicates concurrently with a configurable concurrency limit.
9
+ *
10
+ * Short-circuits immediately when any predicate returns `false` or throws.
11
+ *
12
+ * @template T - The type of elements in the iterable
13
+ * @param iterable - An iterable of promises resolving to values
14
+ * @param predicate - A function to test each element
15
+ * @param options - Configuration options
16
+ * @returns `true` if all elements pass the predicate, `false` otherwise
17
+ * @throws {ParameterError} If concurrency is invalid
18
+ * @throws {DOMException} If the abort signal is triggered
19
+ */
20
+ export declare function asyncEvery<T>(iterable: Iterable<Promise<T>>, predicate: (value: T, index: number) => MaybePromise<boolean>, options?: EveryOptions): Promise<boolean>;
21
+ interface SomeOptions<T> {
22
+ readonly count?: number;
23
+ readonly concurrency?: number;
24
+ readonly filter?: (value: T) => MaybePromise<boolean>;
25
+ readonly signal?: AbortSignal;
26
+ }
27
+ /**
28
+ * Collects elements that satisfy the filter predicate until the specified count is reached.
29
+ * Executes filters concurrently with a configurable concurrency limit.
30
+ *
31
+ * Short-circuits immediately when enough elements are found.
32
+ *
33
+ * @template T - The type of elements in the iterable
34
+ * @param iterable - An iterable of promises resolving to values
35
+ * @param options - Configuration options including count, concurrency, filter, and abort signal
36
+ * @returns An array of elements that passed the filter, with length equal to `count`
37
+ * @throws {ParameterError} If count or concurrency is invalid
38
+ * @throws {RangeError} If the iterable contains fewer elements than `count`
39
+ * @throws {AggregateError} If insufficient elements pass the filter
40
+ * @throws {DOMException} If the abort signal is triggered
41
+ */
42
+ export declare function asyncSome<T>(iterable: Iterable<Promise<T>>, options: SomeOptions<T>): Promise<T[]>;
43
+ interface AnyOptions<T> {
44
+ readonly concurrency?: number;
45
+ readonly filter?: (value: T) => MaybePromise<boolean>;
46
+ readonly signal?: AbortSignal;
47
+ }
48
+ /**
49
+ * Returns the first element that satisfies the filter predicate.
50
+ * Executes filters concurrently with a configurable concurrency limit.
51
+ *
52
+ * Short-circuits immediately when a matching element is found.
53
+ * Similar to Promise.any but with support for filtering and concurrency control.
54
+ *
55
+ * @template T - The type of elements in the iterable
56
+ * @param iterable - An iterable of promises resolving to values
57
+ * @param options - Configuration options including concurrency, filter, and abort signal
58
+ * @returns The first element that passed the filter
59
+ * @throws {ParameterError} If concurrency is invalid
60
+ * @throws {AggregateError} If no elements pass the filter or all promises reject
61
+ * @throws {DOMException} If the abort signal is triggered
62
+ */
63
+ export declare function asyncAny<T>(iterable: Iterable<Promise<T>>, options?: AnyOptions<T>): Promise<T>;
64
+ export {};