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 @@
1
+ {"version":3,"file":"Reactive.mjs","sources":["../../src/Reactive/flow.ts","../../src/Reactive/flow-combination.ts","../../src/Reactive/pace.ts","../../src/Reactive/event_emitter.ts"],"sourcesContent":["// ========================================\n// ./src/Reactive/flow.ts\n// ========================================\n\nimport type {MaybePromise} from 'src/Utils/type-tool';\nimport {FlowCompletionError, UseAfterFreeError} from 'src/Errors';\nimport {noop} from 'src/Utils/Functions/base';\nimport {ensureDOMException} from 'src/unknown-error';\n\n/**\n * Symbol indicating the flow should continue processing.\n * When a controller returns this symbol, the flow keeps waiting for the next value.\n */\nexport const FlowContinue = Symbol('Flow Continue');\n\n/**\n * Stops the flow with the given return value.\n * When a controller returns this, the flow completes and resolves with the value.\n * @template T - The type of the return value.\n * @param value - The value to return.\n * @returns The same value passed in.\n */\nexport const FlowStop = <T>(value: T): T => value;\n\ntype FlowController<T, R> = (\n value: T,\n iteration: number,\n signal: AbortSignal | undefined,\n) => MaybePromise<R | typeof FlowContinue>;\n\ntype SwitchFlowController<T, R> = (\n value: T,\n iteration: number,\n signal: AbortSignal,\n) => MaybePromise<R | typeof FlowContinue>;\n\n/**\n * Options for consuming a Flow.\n * @template R - The return type of the consume operation.\n */\ninterface ConsumeOptions<R> {\n /** Callback invoked when the flow completes normally. */\n on_complete?: () => MaybePromise<R>;\n /** Callback invoked when the flow errors. */\n on_error?: (err: unknown) => MaybePromise<R>;\n /** Optional AbortSignal to cancel the consume operation. */\n signal?: AbortSignal;\n}\n\n// -- 内部类型定义 --\n\ninterface PendingItem<R = unknown> {\n resolve: (value: R) => void;\n reject: (err: unknown) => void;\n on_complete?: () => MaybePromise<R>;\n on_error?: (err: unknown) => MaybePromise<R>;\n queue_index: number;\n}\n\nexport interface Observer<T> {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n}\n\nexport type Unsubscribable = Readonly<{\n unsubscribe: () => void;\n [Symbol.dispose](): void;\n}>;\n\n// -- 常量定义 --\n\nconst EMPTY_SUBSCRIPTION: Unsubscribable = {\n unsubscribe: noop,\n [Symbol.dispose]: noop,\n};\n\nconst MIN_QUEUE_SIZE_FOR_COMPACTION = 64;\nconst WASTE_RATIO_THRESHOLD = 0.65;\n\n// ============================================\n// Helper Functions\n// ============================================\n\n// 判断是否需要压缩数组(当浪费空间超过阈值时触发)\nfunction shouldCompactArray(readIndex: number, length: number): boolean {\n if (readIndex < MIN_QUEUE_SIZE_FOR_COMPACTION) return false;\n const waste_ratio = readIndex / Math.max(1, length);\n return waste_ratio > WASTE_RATIO_THRESHOLD;\n}\n\n// 压缩普通数组,移除已读取的元素\nfunction compactArray<T>(queue: T[], readIndex: number): number {\n let write = 0;\n for (let i = readIndex; i < queue.length; i++) {\n queue[write] = queue[i];\n write++;\n }\n queue.length = write;\n return 0;\n}\n\n// 压缩可空数组,同时更新元素的 queue_index\nfunction compactNullableArray<T extends {queue_index: number}>(\n queue: (T | null)[],\n readIndex: number,\n): number {\n let write = 0;\n for (let i = readIndex; i < queue.length; i++) {\n const item = queue[i]!;\n queue[write] = item;\n item.queue_index = write;\n write++;\n }\n queue.length = write;\n return 0;\n}\n\n// ============================================\n// Flow Class\n// ============================================\n\n/**\n * A reactive stream that emits values to subscribers.\n * Supports both push-based (observer pattern) and pull-based (async iterator) consumption.\n * @template T - The type of values emitted by this flow.\n */\nexport class Flow<T> {\n protected observers = new Set<Observer<T>>();\n protected teardowns = new Array<() => void>();\n\n protected has_error = false;\n protected is_completed = false;\n protected thrown_error: unknown;\n\n // pending_items 用于追踪所有正在等待的 consume 调用\n protected pending_items = new Array<PendingItem | null>();\n protected queue_head = 0;\n\n // -- 广播方法 --\n\n protected broadcast(value: T): void {\n if (this.closed) return;\n this.observers.forEach((obs) => obs.next?.(value));\n }\n\n protected broadcastError(err: unknown): void {\n this.thrown_error = err;\n this.has_error = true;\n this.observers.forEach((obs) => obs.error?.(err));\n this.disposeInternal();\n }\n\n protected broadcastComplete(): void {\n this.is_completed = true;\n this.observers.forEach((obs) => obs.complete?.());\n this.disposeInternal();\n }\n\n // -- 生命周期管理 --\n\n protected disposeInternal(): void {\n for (const fn of this.teardowns) fn();\n this.teardowns.length = 0;\n this.observers.clear();\n }\n\n // -- 队列管理 --\n\n protected shouldCompact(): boolean {\n return shouldCompactArray(this.queue_head, this.pending_items.length);\n }\n\n protected compactQueue(): void {\n this.queue_head = compactNullableArray(this.pending_items, this.queue_head);\n }\n\n // 从队列中移除一个 pending item,标记为 null 以便后续压缩\n protected removePendingItem(item: PendingItem): void {\n this.pending_items[item.queue_index] = null;\n if (item.queue_index === this.queue_head) {\n this.queue_head++;\n }\n }\n\n // -- 公开 API --\n\n /** Returns true if the flow has errored or completed. */\n get closed(): boolean {\n return this.has_error || this.is_completed;\n }\n\n /**\n * Registers a teardown function to be called when the flow completes or errors.\n * If the flow is already closed, the teardown is called immediately.\n */\n addTeardown(teardown: () => void): void {\n if (this.closed) {\n teardown();\n } else {\n this.teardowns.push(teardown);\n }\n }\n\n /**\n * Subscribes to the flow with an observer or callback.\n * @param observerOrNext - An Observer object or a callback function for next values.\n * @returns An Unsubscribable that can be used to unsubscribe.\n */\n subscribe(observerOrNext: Observer<T> | ((v: T) => void)): Unsubscribable {\n const observer =\n typeof observerOrNext === 'function'\n ? {next: observerOrNext}\n : observerOrNext;\n\n // 已关闭时立即通知并返回空订阅\n if (this.has_error) {\n observer.error?.(this.thrown_error);\n return EMPTY_SUBSCRIPTION;\n }\n if (this.is_completed) {\n observer.complete?.();\n return EMPTY_SUBSCRIPTION;\n }\n\n this.observers.add(observer);\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const unsubscribe = () => {\n self.observers.delete(observer);\n };\n return {unsubscribe, [Symbol.dispose]: unsubscribe};\n }\n\n /** Emits a value to all subscribers. */\n next(value: T): void {\n this.broadcast(value);\n }\n\n /** Signals an error to all subscribers and completes the flow. */\n error(err: unknown): void {\n if (this.closed) return;\n\n // 处理所有等待中的 consume 调用\n for (let i = this.queue_head; i < this.pending_items.length; i++) {\n const item = this.pending_items[i]!;\n if (item.on_error) {\n void Promise.resolve(item.on_error(err)).then(\n item.resolve,\n item.reject,\n );\n } else {\n item.reject(err);\n }\n }\n this.pending_items.length = 0;\n this.queue_head = 0;\n\n this.broadcastError(err);\n }\n\n /** Signals completion to all subscribers. */\n complete(): void {\n if (this.closed) return;\n\n // 处理所有等待中的 consume 调用\n for (let i = this.queue_head; i < this.pending_items.length; i++) {\n const item = this.pending_items[i]!;\n if (item.on_complete) {\n void Promise.resolve(item.on_complete()).then(\n item.resolve,\n item.reject,\n );\n } else {\n item.reject(new FlowCompletionError());\n }\n }\n this.pending_items.length = 0;\n this.queue_head = 0;\n\n this.broadcastComplete();\n }\n\n // -- Consume 相关 --\n\n protected createPendingItem<R>(): PendingItem<R> {\n const item: PendingItem<R> = {\n resolve: noop,\n reject: noop,\n queue_index: this.pending_items.length,\n };\n this.pending_items.push(item as PendingItem);\n return item;\n }\n\n /**\n * Consumes values from the flow until the controller returns a value.\n * Each emitted value is passed to the controller, which can return:\n * - FlowContinue: keep waiting for more values\n * - Any other value: resolve the promise with that value\n * @template R - The return type of the consume operation.\n * @param controller - Function called for each emitted value.\n * @param options - Optional callbacks for completion/error and abort signal.\n * @returns Promise that resolves when the controller returns a value.\n */\n async consume<R>(\n controller: FlowController<T, R>,\n options?: ConsumeOptions<R>,\n ): Promise<R> {\n const {on_complete, on_error, signal} = options ?? {};\n if (this.closed) throw new UseAfterFreeError('Subject is closed');\n if (signal?.aborted) throw ensureDOMException(signal.reason);\n\n return new Promise<R>((resolve, reject) => {\n let iteration = 0;\n let settled = false;\n\n const pending_item = this.createPendingItem<R>();\n pending_item.resolve = resolve;\n pending_item.reject = reject;\n if (on_complete) pending_item.on_complete = on_complete;\n if (on_error) pending_item.on_error = on_error;\n\n const cleanup = () => {\n signal?.removeEventListener('abort', abort_handler);\n this.observers.delete(internalObserver);\n this.removePendingItem(pending_item as PendingItem);\n if (this.shouldCompact()) this.compactQueue();\n };\n\n const abort_handler = () => {\n cleanup();\n reject(ensureDOMException(signal!.reason));\n };\n\n signal?.addEventListener('abort', abort_handler);\n const internalObserver: Observer<T> = {\n next: (value: T) => {\n void (async () => {\n try {\n const result = await controller(value, iteration++, signal);\n if (settled || signal?.aborted) return;\n if (result !== FlowContinue) {\n settled = true;\n cleanup();\n resolve(result);\n }\n } catch (e) {\n cleanup();\n reject(e as Error);\n }\n })();\n },\n };\n this.observers.add(internalObserver);\n });\n }\n\n /**\n * Similar to consume, but cancels the previous controller call when a new value arrives.\n * Useful for scenarios like search-as-you-type where only the latest input matters.\n * @template R - The return type of the consume operation.\n * @param controller - Function called for each emitted value with an AbortSignal.\n * @param options - Optional callbacks for completion/error and abort signal.\n * @returns Promise that resolves when the controller returns a value.\n */\n async switchConsume<R>(\n controller: SwitchFlowController<T, R>,\n options?: ConsumeOptions<R>,\n ): Promise<R> {\n const {on_complete, on_error, signal: external_signal} = options ?? {};\n if (this.closed) throw new UseAfterFreeError('Subject is closed');\n if (external_signal?.aborted)\n throw ensureDOMException(external_signal.reason);\n\n return new Promise<R>((resolve, reject) => {\n let iteration = 0;\n let current_abort: AbortController | null = null;\n let settled = false;\n\n const pending_item = this.createPendingItem<R>();\n pending_item.resolve = resolve;\n pending_item.reject = reject;\n if (on_complete) pending_item.on_complete = on_complete;\n if (on_error) pending_item.on_error = on_error;\n\n const abort_handler = () => {\n current_abort?.abort();\n cleanup();\n reject(ensureDOMException(external_signal!.reason));\n };\n\n const cleanup = () => {\n external_signal?.removeEventListener('abort', abort_handler);\n this.observers.delete(internalObserver);\n this.removePendingItem(pending_item as PendingItem);\n if (this.shouldCompact()) this.compactQueue();\n };\n\n external_signal?.addEventListener('abort', abort_handler);\n\n const internalObserver: Observer<T> = {\n next: (value: T) => {\n void (async () => {\n // 取消上一次的执行,实现 switch 语义\n current_abort?.abort();\n const abort = new AbortController();\n current_abort = abort;\n\n // 合并外部 signal 和内部 abort\n const combined_signal = abort.signal;\n if (external_signal) {\n const external_abort_handler = () => abort.abort();\n external_signal.addEventListener(\n 'abort',\n external_abort_handler,\n {once: true},\n );\n }\n\n try {\n const result = await controller(\n value,\n iteration++,\n combined_signal,\n );\n // 检查是否已被新调用取代或已取消\n if (settled || abort.signal.aborted) return;\n if (result !== FlowContinue) {\n settled = true;\n cleanup();\n resolve(result);\n }\n } catch (e) {\n // 忽略内部主动 abort 引发的错误\n if (e instanceof DOMException && e.name === 'AbortError') return;\n settled = true;\n\n cleanup();\n reject(e as Error);\n }\n })();\n },\n };\n\n this.observers.add(internalObserver);\n });\n }\n\n /** Returns an async iterator for the flow, enabling for-await-of syntax. */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const buffer = new Array<T>();\n let resolveNext: ((value: IteratorResult<T>) => void) | null = null;\n let error: unknown = null;\n let done = false;\n\n const subscription = this.subscribe({\n next: (value) => {\n if (resolveNext) {\n resolveNext({value, done: false});\n resolveNext = null;\n } else {\n buffer.push(value);\n }\n },\n error: (err) => {\n error = err;\n if (resolveNext) {\n resolveNext({value: undefined, done: true});\n resolveNext = null;\n }\n },\n complete: () => {\n done = true;\n if (resolveNext) {\n resolveNext({value: undefined, done: true});\n resolveNext = null;\n }\n },\n });\n\n return {\n next: async (): Promise<IteratorResult<T>> => {\n if (error) throw error as Error;\n if (buffer.length > 0) return {value: buffer.shift()!, done: false};\n if (done) return {value: undefined, done: true};\n return new Promise((resolve) => {\n resolveNext = resolve;\n });\n },\n return: (): Promise<IteratorResult<T>> => {\n subscription.unsubscribe();\n return Promise.resolve({value: undefined, done: true});\n },\n };\n }\n}\n\n// ============================================\n// SerialFlow Class\n// ============================================\n\n/**\n * A Flow variant that processes values sequentially.\n * Unlike the base Flow, SerialFlow ensures each value is fully processed\n * before the next one is handled, preventing concurrent controller executions.\n * @template T - The type of values emitted by this flow.\n */\nexport class SerialFlow<T> extends Flow<T> {\n protected pending_queue = new Array<T>();\n protected queue_read_index = 0;\n protected is_consuming = false;\n\n override switchConsume(): never {\n throw new TypeError(\n 'SerialFlow does not support switchConsume. Use consume() instead.',\n );\n }\n\n /**\n * Consumes values sequentially, ensuring each value is fully processed before the next.\n * Values emitted during processing are queued and processed in order.\n */\n async consume<R>(\n controller: FlowController<T, R>,\n options?: ConsumeOptions<R>,\n ): Promise<R> {\n const {on_complete, on_error, signal} = options ?? {};\n if (this.closed) throw new UseAfterFreeError('SerialFlow is closed');\n if (signal?.aborted) throw ensureDOMException(signal.reason);\n\n return new Promise<R>((resolve, reject) => {\n let iteration = 0;\n\n const pending_item = this.createPendingItem<R>();\n pending_item.resolve = resolve;\n pending_item.reject = reject;\n if (on_complete) pending_item.on_complete = on_complete;\n if (on_error) pending_item.on_error = on_error;\n\n const cleanup = () => {\n signal?.removeEventListener('abort', abort_handler);\n this.observers.delete(internalObserver);\n this.removePendingItem(pending_item as PendingItem);\n };\n\n const abort_handler = () => {\n cleanup();\n reject(ensureDOMException(signal!.reason));\n };\n\n signal?.addEventListener('abort', abort_handler);\n\n // 串行处理循环:逐个处理队列中的值\n const runLoop = async () => {\n if (this.is_consuming) return;\n this.is_consuming = true;\n\n while (\n this.queue_read_index < this.pending_queue.length &&\n !this.is_completed &&\n !signal?.aborted\n ) {\n const value = this.pending_queue[this.queue_read_index];\n this.queue_read_index++;\n\n try {\n const result = await controller(value, iteration++, signal);\n if (signal?.aborted) break;\n if (result !== FlowContinue) {\n cleanup();\n if (\n shouldCompactArray(\n this.queue_read_index,\n this.pending_queue.length,\n )\n )\n this.queue_read_index = compactArray(\n this.pending_queue,\n this.queue_read_index,\n );\n resolve(result);\n return;\n }\n } catch (e) {\n if (signal?.aborted) return; // 外部中止,静默退出\n cleanup();\n if (\n shouldCompactArray(\n this.queue_read_index,\n this.pending_queue.length,\n )\n )\n this.queue_read_index = compactArray(\n this.pending_queue,\n this.queue_read_index,\n );\n\n reject(e as Error);\n return;\n }\n }\n\n this.is_consuming = false;\n };\n\n const internalObserver: Observer<T> = {\n next: (value: T) => {\n this.pending_queue.push(value);\n void runLoop();\n },\n };\n\n this.observers.add(internalObserver);\n });\n }\n}\n\n// ============================================\n// BehaviorFlow Class\n// ============================================\n\n/**\n * A Flow that always has a current value and emits it to new subscribers immediately.\n * Similar to RxJS's BehaviorSubject.\n * @template T - The type of the current value.\n */\nexport class BehaviorFlow<T> extends Flow<T> {\n private _value: T;\n\n constructor(initialValue: T) {\n super();\n this._value = initialValue;\n }\n\n /** Returns the current value. */\n get value(): T {\n return this._value;\n }\n\n /**\n * Subscribes to the flow and immediately receives the current value.\n * @param observerOrNext - An Observer object or a callback function.\n * @returns An Unsubscribable that can be used to unsubscribe.\n */\n override subscribe(\n observerOrNext: Observer<T> | ((v: T) => void),\n ): Unsubscribable {\n const observer =\n typeof observerOrNext === 'function'\n ? {next: observerOrNext}\n : observerOrNext;\n\n if (this.has_error) {\n observer.error?.(this.thrown_error);\n return EMPTY_SUBSCRIPTION;\n }\n if (this.is_completed) {\n observer.complete?.();\n return EMPTY_SUBSCRIPTION;\n }\n\n // 立即发射当前值给新订阅者\n observer.next?.(this._value);\n\n this.observers.add(observer);\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const unsubscribe = () => {\n self.observers.delete(observer);\n };\n return {unsubscribe, [Symbol.dispose]: unsubscribe};\n }\n\n /** Updates the current value and emits it to all subscribers. */\n override next(value: T): void {\n this._value = value;\n super.next(value);\n }\n}\n\n// ============================================\n// ColdFlow Implementation\n// ============================================\n\n/** Function type that produces values into a Flow. */\nexport type FlowProducer<T> = (flow: Flow<T>) => (() => void) | void;\n\n/**\n * A Flow that starts producing values only when subscribed (cold stream).\n * Each subscription triggers the producer function.\n * @template T - The type of values emitted by this flow.\n */\nexport class ColdFlow<T> extends Flow<T> {\n private producer: FlowProducer<T>;\n\n constructor(producer: FlowProducer<T>) {\n super();\n this.producer = producer;\n }\n\n /**\n * Subscribes to the flow and starts the producer.\n * The producer is called once per subscription.\n */\n override subscribe(\n observerOrNext: Observer<T> | ((v: T) => void),\n ): Unsubscribable {\n if (this.closed) return super.subscribe(observerOrNext);\n\n const sub = super.subscribe(observerOrNext);\n\n try {\n const teardown = this.producer(this);\n if (teardown) {\n this.addTeardown(teardown);\n }\n } catch (err) {\n this.error(err);\n }\n\n return sub;\n }\n}\n\n// ============================================\n// Factory Functions\n// ============================================\n\n/** Creates a Flow from a producer function. */\nexport function fromProducer<T>(producer: FlowProducer<T>): Flow<T> {\n return new ColdFlow(producer);\n}\n\n/** Creates a SerialFlow from a producer function. */\nexport function fromSerialProducer<T>(\n producer: FlowProducer<T>,\n): SerialFlow<T> {\n return new SerialColdFlow(producer);\n}\n\n/** Creates a Flow that emits the given values and completes. */\nexport function of<T>(...values: T[]): Flow<T> {\n return fromProducer((dest) => {\n for (const value of values) {\n if (dest.closed) return;\n dest.next(value);\n }\n dest.complete();\n });\n}\n\n// -- from 函数重载 --\n\nexport function from<T>(source: Iterable<T>): Flow<T>;\nexport function from<T>(source: AsyncIterable<T>): Flow<T>;\nexport function from<T>(source: Promise<T>): Flow<T>;\nexport function from<T>(source: ArrayLike<T>): Flow<T>;\n\n/**\n * Creates a Flow from various source types.\n * @param source - An Iterable, AsyncIterable, Promise, or ArrayLike.\n * @returns A Flow that emits the source's values.\n */\nexport function from<T>(\n source: Iterable<T> | AsyncIterable<T> | Promise<T> | ArrayLike<T>,\n): Flow<T> {\n // Promise: 发射单个值后完成\n if (source instanceof Promise) {\n return fromProducer((dest) => {\n source.then(\n (value) => {\n if (!dest.closed) {\n dest.next(value);\n dest.complete();\n }\n },\n (err) => {\n if (!dest.closed) dest.error(err);\n },\n );\n });\n }\n\n // AsyncIterable: 异步迭代发射值\n if (\n typeof (source as AsyncIterable<T>)[Symbol.asyncIterator] === 'function'\n ) {\n return fromProducer((dest) => {\n let cancelled = false;\n void (async () => {\n try {\n for await (const value of source as AsyncIterable<T>) {\n if (cancelled || dest.closed) return;\n dest.next(value);\n }\n dest.complete();\n } catch (err) {\n dest.error(err);\n }\n })();\n return () => {\n cancelled = true;\n };\n });\n }\n\n // Iterable: 同步迭代发射值\n if (typeof (source as Iterable<T>)[Symbol.iterator] === 'function') {\n return fromProducer((dest) => {\n for (const value of source as Iterable<T>) {\n if (dest.closed) return;\n dest.next(value);\n }\n dest.complete();\n });\n }\n\n // ArrayLike: 按索引访问发射值\n if ('length' in source) {\n return fromProducer((dest) => {\n const arr = source;\n for (let i = 0; i < arr.length; i++) {\n if (dest.closed) return;\n dest.next(arr[i]);\n }\n dest.complete();\n });\n }\n\n throw new TypeError('Cannot convert the provided source to a Flow');\n}\n\n// ============================================\n// SerialColdFlow Class\n// ============================================\n\n/**\n * A SerialFlow that starts producing values only when subscribed.\n * Combines cold stream behavior with sequential processing.\n * @template T - The type of values emitted by this flow.\n */\nexport class SerialColdFlow<T> extends SerialFlow<T> {\n private producer: FlowProducer<T>;\n\n constructor(producer: FlowProducer<T>) {\n super();\n this.producer = producer;\n }\n\n override subscribe(\n observerOrNext: Observer<T> | ((v: T) => void),\n ): Unsubscribable {\n if (this.closed) return super.subscribe(observerOrNext);\n\n const sub = super.subscribe(observerOrNext);\n\n try {\n const teardown = this.producer(this);\n if (teardown) {\n this.addTeardown(teardown);\n }\n } catch (err) {\n this.error(err);\n }\n\n return sub;\n }\n}\n","// ============================================\n// ./src/Reactive/flow-combination.ts\n// ============================================\n\nimport {noop} from 'src/Utils/Functions/base';\nimport {Flow, fromProducer, type Observer, type Unsubscribable} from './flow';\n\ntype FlowInputValue<T> = T extends FlowInput<infer R> ? R : never;\ntype FlowInputTuple<T extends readonly FlowInput<unknown>[]> = {\n [K in keyof T]: FlowInputValue<T[K]>;\n};\ntype PrependTuple<T, R extends readonly unknown[]> = [T, ...R];\n\ninterface FlowInput<T> {\n subscribe(observer: Observer<T>): Unsubscribable;\n}\n\n/**\n * Merges multiple Flow sources into a single Flow that emits values\n * from all sources concurrently. Completes when all sources complete.\n * @template T The value type emitted by the sources\n * @param sources Flow sources to merge\n * @returns A Flow emitting values from all sources as they arrive\n */\nexport function mergeFlow<T>(\n ...sources: [FlowInput<T>, ...FlowInput<T>[]]\n): Flow<T> {\n return fromProducer((dest) => {\n // -- 追踪完成状态 --\n let completedCount = 0;\n const subscriptions: Unsubscribable[] = [];\n\n sources.forEach((source) => {\n const sub = source.subscribe({\n next: (v) => dest.next(v),\n error: (err) => dest.error(err),\n complete: () => {\n completedCount++;\n // 所有源都完成后,才完成目标流\n if (completedCount === sources.length) {\n dest.complete();\n }\n },\n });\n subscriptions.push(sub);\n });\n\n // 取消订阅时,清理所有子订阅\n return () => subscriptions.forEach((sub) => sub.unsubscribe());\n });\n}\n\n/**\n * Concatenates multiple Flow sources sequentially, subscribing to each\n * source only after the previous one completes.\n * @template T The value type emitted by the sources\n * @param sources Flow sources to concatenate\n * @returns A Flow emitting values from each source in order\n */\nexport function concatFlow<T>(\n ...sources: [FlowInput<T>, ...FlowInput<T>[]]\n): Flow<T> {\n return fromProducer((dest) => {\n let index = 0;\n let currentSub: Unsubscribable | null = null;\n\n // 顺序订阅下一个源\n const subscribeNext = () => {\n // 所有源都已处理完毕\n if (index >= sources.length) {\n dest.complete();\n return;\n }\n\n const source = sources[index++];\n currentSub = source.subscribe({\n next: (v) => dest.next(v),\n error: (err) => dest.error(err),\n // 当前源完成后,继续订阅下一个\n complete: () => {\n subscribeNext();\n },\n });\n };\n\n subscribeNext();\n\n return () => currentSub?.unsubscribe();\n });\n}\n\n/**\n * Races multiple Flow sources, emitting the first value, error, or completion\n * from any source and immediately unsubscribing from all others.\n * @template T The value type emitted by the sources\n * @param sources Flow sources to race\n * @returns A Flow mirroring the first source to emit\n */\nexport function raceFlow<T>(\n ...sources: [FlowInput<T>, ...FlowInput<T>[]]\n): Flow<T> {\n return fromProducer((dest) => {\n const subscriptions: Unsubscribable[] = [];\n let finished = false;\n\n // 取消所有订阅并标记完成\n const unsubscribeAll = () => {\n finished = true;\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n\n sources.forEach((source) => {\n const sub = source.subscribe({\n // 第一个发射的值胜出\n next: (v) => {\n if (finished) return;\n unsubscribeAll();\n dest.next(v);\n dest.complete();\n },\n // 第一个错误胜出\n error: (err) => {\n if (finished) return;\n unsubscribeAll();\n dest.error(err);\n },\n // 第一个完成胜出\n complete: () => {\n if (finished) return;\n unsubscribeAll();\n dest.complete();\n },\n });\n subscriptions.push(sub);\n });\n\n return unsubscribeAll;\n });\n}\n\n/**\n * Combines multiple Flow sources to emit tuples of the latest values\n * from all sources whenever any source emits. Waits for all sources\n * to emit at least once before emitting.\n * @template T A tuple type of Flow sources\n * @param sources Flow sources to combine\n * @returns A Flow emitting tuples of the latest values from all sources\n */\nexport function combineLatestFlow<\n T extends readonly [FlowInput<unknown>, ...FlowInput<unknown>[]],\n>(...sources: T): Flow<FlowInputTuple<T>> {\n return fromProducer((dest) => {\n const subscriptions: Unsubscribable[] = [];\n // 存储每个源的最新值\n const values = new Array<FlowInputValue<T[number]>>(sources.length);\n // 标记每个源是否已发射过值\n const hasValue = new Array<boolean>(sources.length).fill(false);\n let hasValueCount = 0;\n let completedCount = 0;\n\n sources.forEach((source, i) => {\n values[i] = undefined as FlowInputValue<T[number]>;\n\n const sub = source.subscribe({\n next: (v) => {\n values[i] = v as FlowInputValue<T[number]>;\n // 首次收到该源的值\n if (!hasValue[i]) {\n hasValue[i] = true;\n hasValueCount++;\n }\n\n // 所有源都至少发射过一次值后,才发射组合值\n if (hasValueCount === sources.length) {\n dest.next([...values] as FlowInputTuple<T>);\n }\n },\n error: (err) => dest.error(err),\n complete: () => {\n completedCount++;\n if (completedCount === sources.length) {\n dest.complete();\n }\n },\n });\n subscriptions.push(sub);\n });\n\n return () => subscriptions.forEach((s) => s.unsubscribe());\n });\n}\n\n/**\n * Combines a source Flow with other Flows, emitting a tuple of the source value\n * and the latest values from other sources whenever the source emits.\n * Waits for all other sources to emit at least once.\n * @template T The value type emitted by the main source\n * @template R A tuple type of other Flow sources\n * @param source The main Flow that triggers emissions\n * @param others Other Flow sources to combine with\n * @returns A Flow emitting tuples with the source value prepended to other values\n */\nexport function withLatestFromFlow<\n T,\n R extends readonly [FlowInput<unknown>, ...FlowInput<unknown>[]],\n>(\n source: FlowInput<T>,\n ...others: R\n): Flow<PrependTuple<T, FlowInputTuple<R>>> {\n return fromProducer((dest) => {\n // 存储其他源的最新值\n const otherValues = new Array<FlowInputValue<R[number]>>(others.length);\n const hasOthersValue = new Array<boolean>(others.length).fill(false);\n let hasOthersValueCount = 0;\n const subs: Unsubscribable[] = [];\n\n // 先订阅其他源,持续收集它们的最新值\n others.forEach((other, i) => {\n otherValues[i] = undefined as FlowInputValue<R[number]>;\n const sub = other.subscribe({\n next: (v) => {\n otherValues[i] = v as FlowInputValue<R[number]>;\n if (!hasOthersValue[i]) {\n hasOthersValue[i] = true;\n hasOthersValueCount++;\n }\n },\n error: (err) => dest.error(err),\n // 其他源完成不影响主源的行为\n complete: noop,\n });\n subs.push(sub);\n });\n\n // 订阅主源,每次发射时组合其他源的最新值\n const mainSub = source.subscribe({\n next: (v) => {\n // 确保所有其他源都已发射过值\n if (hasOthersValueCount === others.length) {\n dest.next([v, ...otherValues] as unknown as PrependTuple<\n T,\n FlowInputTuple<R>\n >);\n }\n },\n error: (err) => dest.error(err),\n complete: () => dest.complete(),\n });\n subs.push(mainSub);\n\n return () => subs.forEach((s) => s.unsubscribe());\n });\n}\n\n/**\n * Waits for all Flow sources to complete, then emits a tuple of their last values.\n * Emits once when all sources complete. Completes without emitting if any\n * source completes without emitting.\n * @template T A tuple type of Flow sources\n * @param sources Flow sources to join\n * @returns A Flow emitting a single tuple of last values when all sources complete\n */\nexport function forkJoinFlow<\n T extends readonly [FlowInput<unknown>, ...FlowInput<unknown>[]],\n>(...sources: T): Flow<FlowInputTuple<T>> {\n return fromProducer((dest) => {\n // 存储每个源的最后值\n const lastValues = new Array<FlowInputValue<T[number]>>(sources.length);\n const hasEmitted = new Array<boolean>(sources.length).fill(false);\n let completedCount = 0;\n const subs: Unsubscribable[] = [];\n\n sources.forEach((source, i) => {\n const sub = source.subscribe({\n // 只记录最后收到的值,不立即发射\n next: (v) => {\n lastValues[i] = v as FlowInputValue<T[number]>;\n hasEmitted[i] = true;\n },\n error: (err) => dest.error(err),\n complete: () => {\n completedCount++;\n // 如果有源完成但从未发射值,则不发射任何值直接完成\n if (!hasEmitted[i]) {\n dest.complete();\n return;\n }\n\n // 所有源都完成后,发射所有最后值的元组\n if (completedCount === sources.length) {\n dest.next([...lastValues] as FlowInputTuple<T>);\n dest.complete();\n }\n },\n });\n subs.push(sub);\n });\n\n return () => subs.forEach((s) => s.unsubscribe());\n });\n}\n\n/**\n * Zips multiple Flow sources by index, emitting tuples containing the nth\n * value from each source. Completes when any source completes and its\n * buffer is empty.\n * @template T A tuple type of Flow sources\n * @param sources Flow sources to zip\n * @returns A Flow emitting tuples of values at the same index from each source\n */\nexport function zipFlow<\n T extends readonly [FlowInput<unknown>, ...FlowInput<unknown>[]],\n>(\n ...sources: T\n): Flow<{[K in keyof T]: T[K] extends FlowInput<infer R> ? R : never}> {\n return fromProducer((dest) => {\n // 每个源的值缓冲区\n const buffers: unknown[][] = sources.map(() => []);\n // 标记每个源是否已完成\n const doneFlags: boolean[] = sources.map(() => false);\n // 已准备好(缓冲区非空)的源数量\n let readyCount = 0;\n // 已耗尽(完成且缓冲区空)的源数量\n let deadSourceCount = 0;\n const subs: Unsubscribable[] = [];\n\n // 尝试消费缓冲区中的值\n const tryConsume = () => {\n // 当所有源都有值时,按索引配对发射\n while (readyCount === sources.length) {\n const tuple = buffers.map((buf) => buf.shift()!);\n dest.next(\n tuple as {\n [K in keyof T]: T[K] extends FlowInput<infer R> ? R : never;\n },\n );\n\n // 重新计算就绪数量\n let newReadyCount = 0;\n for (let i = 0; i < buffers.length; i++) {\n if (buffers[i].length > 0) newReadyCount++;\n else if (doneFlags[i]) {\n // 缓冲区空且源已完成,该源已耗尽\n deadSourceCount++;\n }\n }\n readyCount = newReadyCount;\n\n // 有源耗尽时,整个 zip 完成\n if (deadSourceCount > 0) {\n dest.complete();\n return;\n }\n }\n };\n\n sources.forEach((source, i) => {\n if (dest.closed) return;\n\n const sub = source.subscribe({\n next: (v) => {\n const wasEmpty = buffers[i].length === 0;\n buffers[i].push(v);\n // 缓冲区从空变非空,增加就绪计数\n if (wasEmpty) readyCount++;\n tryConsume();\n },\n error: (err) => dest.error(err),\n complete: () => {\n doneFlags[i] = true;\n // 源完成且缓冲区空,标记为耗尽\n if (buffers[i].length === 0) {\n deadSourceCount++;\n dest.complete();\n }\n },\n });\n subs.push(sub);\n });\n\n return () => subs.forEach((s) => s.unsubscribe());\n });\n}\n","// ========================================\r\n// ./src/Utils/Functions/pace.ts\r\n// ========================================\r\nimport {delay} from 'src/Concurrent/delay';\r\nimport {Err, Ok} from 'src/Result/base';\r\nimport type {Result} from 'src/Result/types';\r\nimport type {MaybePromise} from '../Utils/type-tool';\r\n\r\n// 定义下一次动作的类型:停止并返回值,或者继续等待\r\ntype NextAction<R> = {readonly value: R} | {readonly delay: number};\r\n\r\n/**\r\n * @template R1 - The input result type from the executed function\r\n * @template R2 - The output result type after pacing logic\r\n */\r\ntype PaceFunction<R1, R2> = (\r\n output: Result<R1, unknown>,\r\n iteration: number,\r\n interval: number,\r\n) => MaybePromise<NextAction<R2>>;\r\n\r\n/**\r\n * Signals the pacer to stop and return a value.\r\n * @template T - The type of value to return\r\n */\r\nexport const Stop = <T>(value: T) => ({value});\r\n\r\n/**\r\n * Signals the pacer to continue waiting with the specified delay.\r\n */\r\nexport const Continue = (delay: number) => ({delay});\r\n\r\n/**\r\n * Calculates exponential backoff delay.\r\n * @param attempt - Current attempt number (0-indexed)\r\n * @param base - Base delay in milliseconds (default: 1000)\r\n * @param max - Maximum delay cap in milliseconds (default: 30000)\r\n */\r\nexport const expBackoff = (attempt: number, base = 1000, max = 30000): number =>\r\n Math.min(base * 2 ** attempt, max);\r\n\r\n/**\r\n * Exponential backoff with jitter strategies to prevent thundering herd.\r\n * @param attempt - Current attempt number (0-indexed)\r\n * @param base - Base delay in milliseconds (default: 1000)\r\n * @param max - Maximum delay cap in milliseconds (default: 30000)\r\n * @param jitter - Jitter strategy: 'full' | 'equal' | 'decorrelated' (default: 'full')\r\n */\r\nexport const expJitter = (\r\n attempt: number,\r\n base = 1000,\r\n max = 30000,\r\n jitter: 'full' | 'equal' | 'decorrelated' = 'full',\r\n): number => {\r\n const delay = expBackoff(attempt, base, max);\r\n const rand = Math.random();\r\n switch (jitter) {\r\n case 'full':\r\n return rand * delay;\r\n case 'equal':\r\n return delay / 2 + rand * (delay / 2);\r\n case 'decorrelated':\r\n return Math.min(base + rand * delay, max);\r\n }\r\n};\r\n\r\n/**\r\n * Executes a function repeatedly with custom pacing logic.\r\n *\r\n * The pace function controls when to stop and what to return based on\r\n * each iteration's result. Useful for implementing retry logic, polling,\r\n * or any iterative async operation with custom backoff strategies.\r\n *\r\n * @template R1 - The return type of the executed function\r\n * @template R2 - The final output type after pacing logic completes\r\n * @param fn - The function to execute on each iteration\r\n * @param pace - Controls iteration flow; return `Stop(value)` to complete or `Continue(ms)` to retry\r\n * @param signal - Optional AbortSignal for cancellation\r\n * @returns The value passed to `Stop()` when pacing completes\r\n */\r\nexport async function pacer<R1, R2>(\r\n fn: () => MaybePromise<R1>,\r\n pace: PaceFunction<R1, R2>,\r\n signal?: AbortSignal,\r\n): Promise<R2> {\r\n signal?.throwIfAborted();\r\n let interval = 0;\r\n\r\n for (let iteration = 0; ; iteration++) {\r\n let output: Result<R1, unknown>;\r\n try {\r\n output = Ok(await fn());\r\n signal?.throwIfAborted();\r\n } catch (error) {\r\n output = Err(error);\r\n }\r\n\r\n const action = await pace(output, iteration, interval);\r\n signal?.throwIfAborted();\r\n\r\n // 决定停止,返回最终值\r\n if ('value' in action) return action.value;\r\n else {\r\n const ms = action.delay;\r\n // 只有延迟时间大于 0 才真正等待\r\n if (ms > 0) await delay(ms, signal);\r\n interval = ms;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Options for retry operations with exponential backoff.\r\n */\r\ninterface PaceRetryOptions {\r\n /** Maximum number of retry attempts (default: 5) */\r\n readonly maxRetries?: number;\r\n /** Base delay in milliseconds for exponential backoff (default: 1000) */\r\n readonly baseDelayMs?: number;\r\n /** Maximum delay cap in milliseconds (default: 30000) */\r\n readonly maxBackoffMs?: number;\r\n\r\n /** Optional AbortSignal for cancellation */\r\n signal?: AbortSignal;\r\n}\r\n\r\n/**\r\n * Retries an async task with exponential backoff and jitter.\r\n *\r\n * @template T - The return type of the task\r\n * @param task - The async function to retry\r\n * @param options - Retry configuration options\r\n * @param signal - Optional AbortSignal for cancellation\r\n * @returns The result of the successful task execution\r\n * @throws Last error if all retry attempts fail\r\n */\r\nexport async function retry<T>(\r\n task: () => MaybePromise<T>,\r\n options?: PaceRetryOptions,\r\n): Promise<T> {\r\n const {\r\n maxRetries = 5,\r\n baseDelayMs = 1000,\r\n maxBackoffMs = 30000,\r\n signal,\r\n } = options ?? {};\r\n signal?.throwIfAborted();\r\n\r\n let last_error: unknown;\r\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\r\n try {\r\n const result = await task();\r\n signal?.throwIfAborted();\r\n return result;\r\n } catch (error) {\r\n last_error = error;\r\n if (attempt < maxRetries) {\r\n const wait_ms = expJitter(attempt, baseDelayMs, maxBackoffMs, 'equal');\r\n await delay(wait_ms, signal);\r\n }\r\n }\r\n }\r\n\r\n throw last_error;\r\n}\r\n","// ============================================\r\n// ./src/Reactive/event_emitter.ts\r\n// ============================================\r\n\r\nimport {isPromiseLike} from 'src/helper';\r\nimport {ensureDOMException} from 'src/unknown-error';\r\n\r\ntype Callback<T extends Record<string, unknown[]>, K extends keyof T> = (\r\n ...args: T[K]\r\n) => void;\r\n\r\nconst ORIGINAL_CALLBACK = Symbol('Original callback');\r\n\r\ntype WrappedFn = ((...args: unknown[]) => PromiseLike<void> | void) & {\r\n [ORIGINAL_CALLBACK]?: (...args: unknown[]) => PromiseLike<void> | void;\r\n};\r\n\r\ntype ListenerList = {\r\n prepend: WrappedFn[];\r\n normal: WrappedFn[];\r\n};\r\n\r\ntype Storage = null | WrappedFn | ListenerList;\r\n\r\ntype PendingAddition = {\r\n event: PropertyKey;\r\n callback: WrappedFn;\r\n prepend: boolean;\r\n};\r\n\r\ntype PendingRemoval = {\r\n event: PropertyKey;\r\n callback: WrappedFn;\r\n};\r\n\r\n/**\r\n * A type-safe event emitter that supports synchronous and asynchronous event handling.\r\n *\r\n * Features:\r\n * - Full TypeScript type safety with event map support\r\n * - Special events: `newListener`, `removeListener`, `error`\r\n * - Supports prepend/once/async patterns\r\n * - Deferred listener modification during emit (prevents iteration issues)\r\n * - Optimized storage: single function -> list transition\r\n *\r\n * @template T - Event map where keys are event names and values are argument tuples\r\n *\r\n * @example\r\n * ```ts\r\n * interface MyEvents {\r\n * message: [text: string, from: string];\r\n * data: [payload: unknown];\r\n * error: [err: Error];\r\n * }\r\n *\r\n * const emitter = new EventEmitter<MyEvents>();\r\n * emitter.on('message', (text, from) => console.log(`${from}: ${text}`));\r\n * emitter.emit('message', 'Hello', 'Alice');\r\n * ```\r\n */\r\nexport class EventEmitter<T extends Record<PropertyKey, unknown[]>> {\r\n private events: Map<keyof T, Storage>;\r\n\r\n // 当前嵌套 emit 调用深度,用于延迟处理 on/off 操作\r\n private emitting_depth = 0;\r\n // emit 期间被移除的监听器,待 emit 结束后统一处理\r\n private pending_removals_set: Set<WrappedFn> | null = null;\r\n private pending_removals_list: PendingRemoval[] | null = null;\r\n // emit 期间被添加的监听器,待 emit 结束后统一处理\r\n private pending_additions: PendingAddition[] | null = null;\r\n\r\n /**\r\n * Creates a new EventEmitter instance.\r\n */\r\n constructor() {\r\n this.events = new Map();\r\n }\r\n\r\n private emitRemoveListener<K extends keyof T>(\r\n event: K,\r\n callback: Callback<T, K>,\r\n ): void {\r\n (this.emit as (event: PropertyKey, ...args: unknown[]) => boolean)(\r\n 'removeListener',\r\n event,\r\n callback,\r\n );\r\n }\r\n\r\n // ============================================\r\n // 事件监听管理\r\n // ============================================\r\n\r\n /**\r\n * Registers an event listener that will be invoked each time the event is emitted.\r\n *\r\n * Triggers `newListener` event before adding the listener.\r\n * During an active emit, additions are deferred until the emit completes.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to listen for\r\n * @param callback - The listener function to register\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n on<K extends keyof T>(event: K, callback: Callback<T, K>): this {\r\n const wrapped = callback as WrappedFn;\r\n\r\n (this.emit as (event: PropertyKey, ...args: unknown[]) => boolean)(\r\n 'newListener',\r\n event,\r\n callback,\r\n );\r\n\r\n // emit 期间延迟添加,避免遍历过程中修改数组\r\n if (this.emitting_depth > 0) {\r\n this.pending_additions ??= [];\r\n this.pending_additions.push({event, callback: wrapped, prepend: false});\r\n return this;\r\n }\r\n\r\n const current = this.events.get(event);\r\n\r\n // 优化分支:\r\n // 1. 热路径:已有列表,直接 push\r\n // 2. 冷路径:空,首次添加\r\n // 3. 冷路径:单函数,转换为列表\r\n if (current)\r\n if (typeof current === 'object') current.normal.push(wrapped);\r\n else this.events.set(event, {prepend: [], normal: [current, wrapped]});\r\n else this.events.set(event, wrapped);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Removes a previously registered event listener.\r\n *\r\n * Triggers `removeListener` event after removing the listener.\r\n * During an active emit, removals are deferred until the emit completes.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to remove the listener from\r\n * @param callback - The listener function to remove\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n off<K extends keyof T>(event: K, callback: Callback<T, K>): this {\r\n const current = this.events.get(event);\r\n if (!current) return this;\r\n\r\n const target = callback as WrappedFn;\r\n\r\n // 快速路径:单函数直接匹配\r\n if (typeof current === 'function') {\r\n if (current === target || current[ORIGINAL_CALLBACK] === callback) {\r\n if (this.emitting_depth > 0) {\r\n this.pending_removals_set ??= new Set<WrappedFn>();\r\n this.pending_removals_list ??= [];\r\n if (!this.pending_removals_set.has(current)) {\r\n this.pending_removals_set.add(current);\r\n this.pending_removals_list.push({event, callback: current});\r\n }\r\n } else {\r\n this.events.delete(event);\r\n this.emitRemoveListener(event, callback);\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n // emit 期间延迟移除\r\n if (this.emitting_depth > 0) {\r\n const actual_target = this.findWrappedFn(current, callback);\r\n if (actual_target && !this.isPendingRemoval(actual_target, event)) {\r\n this.pending_removals_set ??= new Set<WrappedFn>();\r\n this.pending_removals_list ??= [];\r\n this.pending_removals_set.add(actual_target);\r\n this.pending_removals_list.push({event, callback: actual_target});\r\n }\r\n return this;\r\n }\r\n\r\n const removed = this.removeFromList(current, callback);\r\n if (!removed) return this;\r\n\r\n // 列表只剩一个时降级为单函数存储\r\n const total = current.prepend.length + current.normal.length;\r\n if (total === 1) {\r\n const single = current.prepend[0] ?? current.normal[0];\r\n this.events.set(event, single);\r\n }\r\n\r\n this.emitRemoveListener(event, callback);\r\n return this;\r\n }\r\n\r\n // 在监听器列表中查找匹配的包装函数\r\n // 优先搜索 normal 列表(绝大多数监听器在此)\r\n private findWrappedFn<K extends keyof T>(\r\n list: ListenerList,\r\n callback: Callback<T, K>,\r\n ): WrappedFn | null {\r\n const target = callback as WrappedFn;\r\n const normal = list.normal;\r\n const prepend = list.prepend;\r\n\r\n for (let i = 0, len = normal.length; i < len; i++) {\r\n const cb = normal[i];\r\n if (cb === target || cb[ORIGINAL_CALLBACK] === callback) return cb;\r\n }\r\n for (let i = 0, len = prepend.length; i < len; i++) {\r\n const cb = prepend[i];\r\n if (cb === target || cb[ORIGINAL_CALLBACK] === callback) return cb;\r\n }\r\n return null;\r\n }\r\n\r\n // 从监听器列表中移除指定回调\r\n // 优先搜索 normal 列表,从后向前遍历符合 LIFO 预期\r\n private removeFromList<K extends keyof T>(\r\n list: ListenerList,\r\n callback: Callback<T, K>,\r\n ): boolean {\r\n const target = callback as WrappedFn;\r\n const normal = list.normal;\r\n const prepend = list.prepend;\r\n\r\n for (let i = normal.length - 1; i >= 0; i--) {\r\n const cb = normal[i];\r\n if (cb === target || cb[ORIGINAL_CALLBACK] === callback) {\r\n normal.splice(i, 1);\r\n return true;\r\n }\r\n }\r\n for (let i = prepend.length - 1; i >= 0; i--) {\r\n const cb = prepend[i];\r\n if (cb === target || cb[ORIGINAL_CALLBACK] === callback) {\r\n prepend.splice(i, 1);\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Emits an event, invoking all registered listeners with the provided arguments.\r\n *\r\n * Listeners are invoked in order: prepend listeners (reverse order) then normal listeners.\r\n * If no listeners exist and the event is `error`, the error is thrown.\r\n * Listener errors are caught and forwarded to `error` event handlers.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to emit\r\n * @param args - Arguments to pass to the listeners\r\n * @returns `true` if all listeners completed without errors, `false` otherwise\r\n * @throws The error argument if emitting `error` with no listeners\r\n */\r\n emit<K extends keyof T>(event: K, ...args: T[K]): boolean {\r\n const events = this.events;\r\n const current = events.get(event);\r\n\r\n // 空检查\r\n if (!current) {\r\n if (event === 'error') throw args[0];\r\n return false;\r\n }\r\n\r\n // 分支预测优化:高频事件通常是列表(对象),优先判断 object\r\n if (typeof current === 'object') {\r\n const prepend = current.prepend;\r\n const normal = current.normal;\r\n\r\n this.emitting_depth++;\r\n let has_error = false;\r\n\r\n try {\r\n // 反向遍历 prepend(后添加的先执行)\r\n for (let i = prepend.length - 1; i >= 0; i--) {\r\n const cb = prepend[i];\r\n try {\r\n cb(...args);\r\n } catch (error) {\r\n has_error = true;\r\n this.handleEmitError(event, error);\r\n }\r\n }\r\n\r\n // 正向遍历 normal\r\n for (let i = 0, listLen = normal.length; i < listLen; i++) {\r\n const cb = normal[i];\r\n try {\r\n cb(...args);\r\n } catch (error) {\r\n has_error = true;\r\n this.handleEmitError(event, error);\r\n }\r\n }\r\n } finally {\r\n this.emitting_depth--;\r\n\r\n if (\r\n this.emitting_depth === 0 &&\r\n (this.pending_removals_list || this.pending_additions)\r\n )\r\n this.flushPendingOperations();\r\n }\r\n\r\n return !has_error;\r\n }\r\n\r\n // 单函数情况(低频/初始状态)\r\n try {\r\n current(...args);\r\n } catch (error) {\r\n this.handleEmitError(event, error);\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n private handleEmitError<K extends keyof T>(event: K, error: unknown): void {\r\n if (event === 'error') throw error;\r\n\r\n const storage = this.events.get('error');\r\n if (!storage) throw error;\r\n\r\n if (typeof storage === 'function') {\r\n if (!this.isPendingRemoval(storage, 'error')) storage(error);\r\n else throw error;\r\n return;\r\n }\r\n\r\n // 保持执行顺序:prepend -> normal\r\n const prepend = storage.prepend;\r\n const normal = storage.normal;\r\n let has_called = false;\r\n\r\n for (let i = 0, len = prepend.length; i < len; i++) {\r\n const cb = prepend[i];\r\n if (this.isPendingRemoval(cb, 'error')) continue;\r\n cb(error);\r\n has_called = true;\r\n }\r\n\r\n for (let i = 0, len = normal.length; i < len; i++) {\r\n const cb = normal[i];\r\n if (this.isPendingRemoval(cb, 'error')) continue;\r\n cb(error);\r\n has_called = true;\r\n }\r\n\r\n if (!has_called) throw error;\r\n }\r\n\r\n // 检查回调是否已在待移除列表中(O(1) 复杂度)\r\n private isPendingRemoval(callback: WrappedFn, _event: keyof T): boolean {\r\n return this.pending_removals_set?.has(callback) ?? false;\r\n }\r\n\r\n // 处理 emit 期间延迟的添加/移除操作\r\n private flushPendingOperations(): void {\r\n const pending_removals = this.pending_removals_list;\r\n this.pending_removals_list = null;\r\n this.pending_removals_set = null;\r\n\r\n const pending_additions = this.pending_additions;\r\n this.pending_additions = null;\r\n\r\n if (pending_removals) {\r\n for (let i = 0, len = pending_removals.length; i < len; i++) {\r\n const {event, callback} = pending_removals[i];\r\n const storage = this.events.get(event);\r\n\r\n if (!storage) continue;\r\n\r\n if (typeof storage === 'function') {\r\n if (storage === callback) this.events.delete(event);\r\n } else {\r\n let idx = storage.normal.indexOf(callback);\r\n if (idx !== -1) {\r\n storage.normal.splice(idx, 1);\r\n } else {\r\n idx = storage.prepend.indexOf(callback);\r\n if (idx !== -1) storage.prepend.splice(idx, 1);\r\n }\r\n\r\n const total = storage.prepend.length + storage.normal.length;\r\n if (total === 1) {\r\n const single = storage.prepend[0] ?? storage.normal[0];\r\n this.events.set(event, single);\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\r\n this.emitRemoveListener(event, callback);\r\n }\r\n }\r\n\r\n if (pending_additions) {\r\n for (let i = 0, len = pending_additions.length; i < len; i++) {\r\n const {event, callback, prepend} = pending_additions[i];\r\n const current = this.events.get(event);\r\n\r\n if (!current) {\r\n this.events.set(event, callback);\r\n } else if (typeof current === 'object') {\r\n if (prepend) current.prepend.push(callback);\r\n else current.normal.push(callback);\r\n } else {\r\n this.events.set(\r\n event,\r\n prepend\r\n ? {prepend: [callback], normal: [current]}\r\n : {prepend: [], normal: [current, callback]},\r\n );\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Registers a one-time listener that removes itself after first invocation.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to listen for\r\n * @param callback - The listener function to register\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n once<K extends keyof T>(event: K, callback: Callback<T, K>): this {\r\n const wrapper = (...args: T[K]) => {\r\n this.off(event, wrapper);\r\n callback(...args);\r\n };\r\n wrapper[ORIGINAL_CALLBACK] = callback as WrappedFn;\r\n return this.on(event, wrapper);\r\n }\r\n\r\n /**\r\n * Registers a listener that will be invoked before other listeners.\r\n *\r\n * Prepend listeners are invoked in reverse order of registration (LIFO).\r\n * Triggers `newListener` event before adding the listener.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to listen for\r\n * @param callback - The listener function to register\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n prependListener<K extends keyof T>(event: K, callback: Callback<T, K>): this {\r\n const wrapped = callback as WrappedFn;\r\n\r\n (this.emit as (event: PropertyKey, ...args: unknown[]) => boolean)(\r\n 'newListener',\r\n event,\r\n callback,\r\n );\r\n\r\n if (this.emitting_depth > 0) {\r\n this.pending_additions ??= [];\r\n this.pending_additions.push({event, callback: wrapped, prepend: true});\r\n return this;\r\n }\r\n\r\n const current = this.events.get(event);\r\n\r\n if (current) {\r\n if (typeof current === 'object') {\r\n current.prepend.push(wrapped);\r\n } else {\r\n this.events.set(event, {prepend: [wrapped], normal: [current]});\r\n }\r\n } else {\r\n this.events.set(event, wrapped);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Registers a one-time prepend listener.\r\n *\r\n * Combines `prependListener` and `once` behavior.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to listen for\r\n * @param callback - The listener function to register\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n prependOnceListener<K extends keyof T>(\r\n event: K,\r\n callback: Callback<T, K>,\r\n ): this {\r\n const wrapper = (...args: T[K]) => {\r\n this.off(event, wrapper);\r\n callback(...args);\r\n };\r\n wrapper[ORIGINAL_CALLBACK] = callback;\r\n return this.prependListener(event, wrapper);\r\n }\r\n\r\n // ============================================\r\n // 监听器查询\r\n // ============================================\r\n\r\n /**\r\n * Returns the number of listeners registered for the specified event.\r\n *\r\n * @param event - The event name to query\r\n * @returns The count of registered listeners\r\n */\r\n listenerCount(event: keyof T): number {\r\n const current = this.events.get(event);\r\n if (!current) return 0;\r\n if (typeof current === 'function') return 1;\r\n return current.prepend.length + current.normal.length;\r\n }\r\n\r\n /**\r\n * Returns a copy of the listeners array for the specified event.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to query\r\n * @returns Array of registered listener functions\r\n */\r\n listeners<K extends keyof T>(event: K): Callback<T, K>[] {\r\n const current = this.events.get(event);\r\n if (!current) return [];\r\n if (typeof current === 'function') return [current];\r\n return [...current.prepend, ...current.normal];\r\n }\r\n\r\n /**\r\n * Returns an array of event names that have registered listeners.\r\n *\r\n * @returns Array of event names with at least one listener\r\n */\r\n eventNames(): (keyof T)[] {\r\n return Array.from(this.events.keys());\r\n }\r\n\r\n /**\r\n * Removes all listeners for a specific event, or all listeners if no event is specified.\r\n *\r\n * Triggers `removeListener` event for each removed listener.\r\n * During an active emit, removals are deferred until the emit completes.\r\n *\r\n * @param event - Optional event name to remove listeners from\r\n * @returns This EventEmitter instance for chaining\r\n */\r\n removeAllListeners(event?: keyof T): this {\r\n // --------------------------------------------\r\n // 场景 A: 正在 emit 过程中 (需要延迟处理)\r\n // --------------------------------------------\r\n if (this.emitting_depth > 0) {\r\n if (event) {\r\n const storage = this.events.get(event);\r\n if (storage) {\r\n this.pending_removals_set ??= new Set<WrappedFn>();\r\n this.pending_removals_list ??= [];\r\n\r\n if (typeof storage === 'function') {\r\n this.pending_removals_set.add(storage);\r\n this.pending_removals_list.push({event, callback: storage});\r\n } else {\r\n // 不去重,同一回调可能在 prepend 和 normal 中各有一份\r\n for (let i = 0, len = storage.prepend.length; i < len; i++) {\r\n const cb = storage.prepend[i];\r\n this.pending_removals_set.add(cb);\r\n this.pending_removals_list.push({event, callback: cb});\r\n }\r\n for (let i = 0, len = storage.normal.length; i < len; i++) {\r\n const cb = storage.normal[i];\r\n this.pending_removals_set.add(cb);\r\n this.pending_removals_list.push({event, callback: cb});\r\n }\r\n }\r\n }\r\n } else {\r\n this.pending_removals_set ??= new Set<WrappedFn>();\r\n this.pending_removals_list ??= [];\r\n\r\n for (const [evt, storage] of this.events) {\r\n if (typeof storage === 'function') {\r\n this.pending_removals_set.add(storage);\r\n this.pending_removals_list.push({event: evt, callback: storage});\r\n } else {\r\n for (let i = 0, len = storage!.prepend.length; i < len; i++) {\r\n const cb = storage!.prepend[i];\r\n this.pending_removals_set.add(cb);\r\n this.pending_removals_list.push({event: evt, callback: cb});\r\n }\r\n for (let i = 0, len = storage!.normal.length; i < len; i++) {\r\n const cb = storage!.normal[i];\r\n this.pending_removals_set.add(cb);\r\n this.pending_removals_list.push({event: evt, callback: cb});\r\n }\r\n }\r\n }\r\n }\r\n return this;\r\n }\r\n\r\n // --------------------------------------------\r\n // 场景 B: 非 emit 期间 (立即处理)\r\n // --------------------------------------------\r\n\r\n if (event) {\r\n // 移除特定事件\r\n const storage = this.events.get(event);\r\n this.events.delete(event);\r\n if (storage) {\r\n // 准备触发 removeListener 事件\r\n const rlStorage = this.events.get('removeListener' as keyof T);\r\n const rlListeners: WrappedFn[] = [];\r\n\r\n if (rlStorage) {\r\n if (typeof rlStorage === 'function') {\r\n rlListeners.push(rlStorage);\r\n } else {\r\n rlListeners.push(...rlStorage.prepend, ...rlStorage.normal);\r\n }\r\n }\r\n\r\n const triggerRemove = (\r\n removedEvent: keyof T,\r\n removedCallback: WrappedFn,\r\n ) => {\r\n for (let i = 0, len = rlListeners.length; i < len; i++) {\r\n try {\r\n rlListeners[i](removedEvent, removedCallback);\r\n } catch (e) {\r\n console.error('Error in removeListener handler:', e);\r\n }\r\n }\r\n };\r\n\r\n if (typeof storage === 'function') {\r\n triggerRemove(event, storage);\r\n } else {\r\n for (const cb of storage.prepend) triggerRemove(event, cb);\r\n for (const cb of storage.normal) triggerRemove(event, cb);\r\n }\r\n }\r\n } else {\r\n // 移除所有事件\r\n // 先快照所有监听器\r\n const snapshot: Array<{event: keyof T; callback: WrappedFn}> = [];\r\n for (const [evt, storage] of this.events) {\r\n if (typeof storage === 'function') {\r\n snapshot.push({event: evt, callback: storage});\r\n } else {\r\n for (let i = 0, len = storage!.prepend.length; i < len; i++)\r\n snapshot.push({event: evt, callback: storage!.prepend[i]});\r\n for (let i = 0, len = storage!.normal.length; i < len; i++)\r\n snapshot.push({event: evt, callback: storage!.normal[i]});\r\n }\r\n }\r\n\r\n // 分离 removeListener 监听器和普通监听器\r\n const normal_listeners: typeof snapshot = [];\r\n const remove_listeners: typeof snapshot = [];\r\n\r\n for (let i = 0, len = snapshot.length; i < len; i++) {\r\n const item = snapshot[i];\r\n if (item.event === 'removeListener') {\r\n remove_listeners.push(item);\r\n } else {\r\n normal_listeners.push(item);\r\n }\r\n }\r\n\r\n // 触发 removeListener 事件\r\n const triggerRemoveFromSnapshot = (\r\n removedEvent: keyof T,\r\n removedCallback: WrappedFn,\r\n ) => {\r\n for (let i = 0, len = remove_listeners.length; i < len; i++) {\r\n try {\r\n remove_listeners[i].callback(removedEvent, removedCallback);\r\n } catch (e) {\r\n console.error('Error in removeListener handler:', e);\r\n }\r\n }\r\n };\r\n\r\n // 执行单个监听器移除\r\n const process_removal = (item: {event: keyof T; callback: WrappedFn}) => {\r\n const {event, callback} = item;\r\n const current = this.events.get(event);\r\n if (current) {\r\n if (typeof current === 'function') {\r\n if (current === callback) this.events.delete(event);\r\n } else {\r\n let idx = current.normal.indexOf(callback);\r\n if (idx !== -1) {\r\n current.normal.splice(idx, 1);\r\n } else {\r\n idx = current.prepend.indexOf(callback);\r\n if (idx !== -1) current.prepend.splice(idx, 1);\r\n }\r\n const total = current.prepend.length + current.normal.length;\r\n if (total === 0) this.events.delete(event);\r\n }\r\n }\r\n triggerRemoveFromSnapshot(event, callback);\r\n };\r\n\r\n // 先移除普通监听器,最后移除 removeListener 监听器\r\n for (let i = 0, len = normal_listeners.length; i < len; i++)\r\n process_removal(normal_listeners[i]);\r\n for (let i = 0, len = remove_listeners.length; i < len; i++)\r\n process_removal(remove_listeners[i]);\r\n\r\n this.events.clear();\r\n }\r\n\r\n return this;\r\n }\r\n\r\n // ============================================\r\n // 异步方法\r\n // ============================================\r\n\r\n /**\r\n * Asynchronously emits an event, awaiting all listener results.\r\n *\r\n * All listeners are executed in parallel using `Promise.all`.\r\n * Listener errors are collected and thrown as `AggregateError` if multiple,\r\n * or re-thrown directly if only one error occurred.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to emit\r\n * @param args - Arguments to pass to the listeners\r\n * @returns Promise resolving to `true` if all listeners succeeded\r\n * @throws The error argument if emitting `error` with no listeners\r\n * @throws AggregateError if multiple listeners threw errors\r\n */\r\n async emitAsync<K extends keyof T>(\r\n event: K,\r\n ...args: T[K]\r\n ): Promise<boolean> {\r\n const events = this.events;\r\n const current = events.get(event);\r\n\r\n if (!current) {\r\n if (event === 'error') throw args[0];\r\n return false;\r\n }\r\n\r\n const listeners =\r\n typeof current === 'object'\r\n ? [...current.prepend, ...current.normal]\r\n : [current];\r\n\r\n const errors = new Array<unknown>();\r\n let has_error = false;\r\n\r\n // 并行执行所有监听器\r\n await Promise.all(\r\n listeners.map(async (cb) => {\r\n try {\r\n await cb(...args);\r\n } catch (error) {\r\n has_error = true;\r\n if (event !== 'error') {\r\n const handler_result = await this.handleAsyncError(event, error);\r\n if (handler_result !== null) errors.push(handler_result);\r\n } else {\r\n errors.push(error);\r\n }\r\n }\r\n }),\r\n );\r\n\r\n if (errors.length === 1) throw errors[0];\r\n if (errors.length > 1) throw new AggregateError(errors);\r\n\r\n return !has_error;\r\n }\r\n\r\n // 异步错误处理,返回需要抛出的错误,null 表示已成功处理\r\n private async handleAsyncError<K extends keyof T>(\r\n _event: K,\r\n error: unknown,\r\n ): Promise<unknown> {\r\n const storage = this.events.get('error');\r\n if (!storage) return error;\r\n\r\n const listeners =\r\n typeof storage === 'object'\r\n ? [...storage.prepend, ...storage.normal]\r\n : [storage];\r\n\r\n try {\r\n await Promise.all(\r\n listeners.map((cb) => {\r\n const result = cb(error);\r\n return isPromiseLike(result) ? result : Promise.resolve();\r\n }),\r\n );\r\n return null;\r\n } catch (handler_error) {\r\n return handler_error;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a promise that resolves when the specified event is emitted.\r\n *\r\n * Supports timeout, filter function, and AbortSignal for cancellation.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to wait for\r\n * @param options - Optional configuration\r\n * @param options.timeout - Maximum time to wait in milliseconds\r\n * @param options.filter - Function to filter which emissions to accept\r\n * @param options.signal - AbortSignal for cancellation\r\n * @returns Promise resolving to the event arguments tuple\r\n * @throws Error on timeout\r\n * @throws DOMException when aborted via signal\r\n */\r\n waitFor<K extends keyof T>(\r\n event: K,\r\n options?: {\r\n timeout?: number;\r\n filter?: (...args: T[K]) => boolean;\r\n signal?: AbortSignal;\r\n },\r\n ): Promise<T[K]> {\r\n return new Promise<T[K]>((resolve, reject) => {\r\n // AbortSignal 检查\r\n if (options?.signal?.aborted) {\r\n reject(ensureDOMException(options.signal.reason));\r\n return;\r\n }\r\n\r\n let timeout_id: ReturnType<typeof setTimeout> | undefined;\r\n\r\n const cleanup = () => {\r\n if (timeout_id !== undefined) clearTimeout(timeout_id);\r\n this.off(event, handler);\r\n options?.signal?.removeEventListener('abort', abort_handler);\r\n };\r\n\r\n const handler = (...args: T[K]) => {\r\n if (options?.filter && !options.filter(...args)) return;\r\n cleanup();\r\n resolve(args);\r\n };\r\n\r\n const abort_handler = () => {\r\n cleanup();\r\n reject(ensureDOMException(options!.signal!.reason));\r\n };\r\n\r\n if (options?.timeout !== undefined) {\r\n timeout_id = setTimeout(() => {\r\n cleanup();\r\n reject(new Error(`Timeout waiting for event \"${String(event)}\"`));\r\n }, options.timeout);\r\n }\r\n\r\n options?.signal?.addEventListener('abort', abort_handler, {once: true});\r\n this.on(event, handler);\r\n });\r\n }\r\n\r\n /**\r\n * Alias for `waitFor` without filter support.\r\n *\r\n * @template K - Event name key\r\n * @param event - The event name to wait for\r\n * @param options - Optional configuration\r\n * @param options.timeout - Maximum time to wait in milliseconds\r\n * @param options.signal - AbortSignal for cancellation\r\n * @returns Promise resolving to the event arguments tuple\r\n */\r\n onceAsync<K extends keyof T>(\r\n event: K,\r\n options?: {timeout?: number; signal?: AbortSignal},\r\n ): Promise<T[K]> {\r\n return this.waitFor(event, options);\r\n }\r\n}\r\n"],"names":["FlowContinue","FlowStop","value","EMPTY_SUBSCRIPTION","noop","MIN_QUEUE_SIZE_FOR_COMPACTION","WASTE_RATIO_THRESHOLD","shouldCompactArray","readIndex","length","compactArray","queue","write","i","compactNullableArray","item","Flow","obs","err","fn","teardown","observerOrNext","observer","self","unsubscribe","FlowCompletionError","controller","options","on_complete","on_error","signal","UseAfterFreeError","ensureDOMException","resolve","reject","iteration","settled","pending_item","cleanup","abort_handler","internalObserver","result","e","external_signal","current_abort","abort","combined_signal","external_abort_handler","buffer","resolveNext","error","done","subscription","SerialFlow","runLoop","BehaviorFlow","initialValue","ColdFlow","producer","sub","fromProducer","fromSerialProducer","SerialColdFlow","of","values","dest","from","source","cancelled","arr","mergeFlow","sources","completedCount","subscriptions","v","concatFlow","index","currentSub","subscribeNext","raceFlow","finished","unsubscribeAll","combineLatestFlow","hasValue","hasValueCount","s","withLatestFromFlow","others","otherValues","hasOthersValue","hasOthersValueCount","subs","other","mainSub","forkJoinFlow","lastValues","hasEmitted","zipFlow","buffers","doneFlags","readyCount","deadSourceCount","tryConsume","tuple","buf","newReadyCount","wasEmpty","Stop","Continue","delay","expBackoff","attempt","base","max","expJitter","jitter","rand","pacer","pace","interval","output","Ok","Err","action","ms","retry","task","maxRetries","baseDelayMs","maxBackoffMs","last_error","wait_ms","ORIGINAL_CALLBACK","EventEmitter","event","callback","wrapped","current","target","actual_target","single","list","normal","prepend","len","cb","args","has_error","listLen","storage","has_called","_event","pending_removals","pending_additions","idx","wrapper","evt","rlStorage","rlListeners","triggerRemove","removedEvent","removedCallback","snapshot","normal_listeners","remove_listeners","triggerRemoveFromSnapshot","process_removal","listeners","errors","handler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A;AAAA;AAAA;AAAA,EAYA,UACEvC,GACA3G,GACe;AACf,WAAO,KAAK,QAAQ2G,GAAO3G,CAAO;AAAA,EACpC;AACF;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("../chunks/local-Da4yU-nE.cjs"),d=e=>r=>e,a=(e,r)=>t=>{const n=e(t),s=r(t);return n(s)},y=()=>e=>e,f=(e,r)=>t=>{const n=e(t);return r(n)},m=(e,r)=>t=>{const n=e(t);return r(n)(t)},h=(e,r)=>t=>{const n=e(t);return r(n)(t),n},i=e=>(r,t)=>a(f(r,n=>s=>e(n,s)),t),b=e=>(r,t,n)=>{const c=i((o,u)=>S=>e(o,u,S))(r,t);return a(c,n)},x=e=>async r=>e,T=()=>async e=>e,l=(e,r)=>t=>e(t).then(r),g=(e,r)=>t=>e(t).then(s=>r(s)(t)),_=(e,r)=>t=>{const n=e(t),s=r(t);return Promise.all([n,s]).then(([c,o])=>c(o))},k=(e,r)=>t=>e(t).then(s=>r(s)(t).then(()=>s)),p=e=>(r,t)=>{const n=l(r,s=>c=>e(s,c));return _(n,t)},R=e=>(r,t,n)=>{const s=p((c,o)=>u=>e(c,o,u))(r,t);return _(s,n)},j=Object.freeze(Object.defineProperty({__proto__:null,anThen:m,anThenAsync:g,ap:a,apAsync:_,ask:y,askAsync:T,liftA2:i,liftA2Async:p,liftA3:b,liftA3Async:R,local:A.local,map:f,mapAsync:l,of:d,ofAsync:x,tap:h,tapAsync:k},Symbol.toStringTag,{value:"Module"}));exports.local=A.local;exports.__exportReader__=j;exports.anThen=m;exports.anThenAsync=g;exports.ap=a;exports.apAsync=_;exports.ask=y;exports.askAsync=T;exports.liftA2=i;exports.liftA2Async=p;exports.liftA3=b;exports.liftA3Async=R;exports.map=f;exports.mapAsync=l;exports.of=d;exports.ofAsync=x;exports.tap=h;exports.tapAsync=k;
2
+ //# sourceMappingURL=Reader.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Reader.cjs","sources":["../../src/Reader/reader.ts","../../src/Reader/reader-async.ts"],"sourcesContent":["// ========================================\r\n// ./src/Reader/reader.ts\r\n// ========================================\r\nimport type {Reader} from './types';\r\n\r\n/**\r\n * Creates a Reader that ignores the environment (R) and returns the given value (A).\r\n * This is the 'return' or 'pure' operation (Applicative/Monad).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in Reader.\r\n * @returns Reader<R, A> that returns 'a'.\r\n */\r\nexport const of = <R, A>(a: A): Reader<R, A> => {\r\n return (_env: R) => a; // 忽略环境参数 R,直接返回传入的值 a。\r\n};\r\n\r\n/**\r\n * Applies a function contained within a Reader (R, (A) => B) to a value\r\n * contained within another Reader (R, A), preserving the environment.\r\n * This is the 'ap' operation (Applicative Functor).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - Reader containing the function (A) => B.\r\n * @param reader_a - Reader containing the input value A.\r\n * @returns Reader<R, B> containing the result of applying the function.\r\n */\r\nexport const ap = <R, A, B>(\r\n reader_fab: Reader<R, (a: A) => B>,\r\n reader_a: Reader<R, A>\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const f_ab = reader_fab(env);\r\n const result_a = reader_a(env);\r\n return f_ab(result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Creates a Reader that retrieves the environment (R) and returns it.\r\n * This is the 'ask' operation in Reader Monad.\r\n *\r\n * @typeParam R - The Environment type.\r\n * @returns Reader<R, R> that returns the environment 'R'.\r\n */\r\nexport const ask = <R>(): Reader<R, R> => {\r\n return (env: R) => env;\r\n};\r\n\r\n/**\r\n * Applies a function (A) => B to the value inside the Reader, maintaining the\r\n * environment context. This is the 'map' operation (Functor).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source Reader<R, A>.\r\n * @param f - The mapping function (A) => B.\r\n * @returns Reader<R, B> containing the mapped value.\r\n */\r\nexport const map = <R, A, B>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => B\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n return f(result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two Reader computations. The result of the first reader (A) is used to\r\n * produce the second reader (Reader<R, B>).\r\n * This is the 'flatMap' or 'bind' operation (Monad).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial Reader<R, A>.\r\n * @param f - A function that takes the result of 'reader' and returns the next Reader<R, B>.\r\n * @returns Reader<R, B> containing the final result.\r\n */\r\nexport const anThen = <R, A, B>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => Reader<R, B>\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n const next_reader = f(result_a);\r\n return next_reader(env);\r\n };\r\n};\r\n\r\n/**\r\n * Performs a side effect using the result of the first Reader, and then returns\r\n * the original result, ignoring the side effect's return value.\r\n * Note: The side effect function must return a Reader.\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source Reader<R, A>.\r\n * @param f - A function that takes A and returns a Reader<R, unknown> (the side effect).\r\n * @returns Reader<R, A> containing the original value.\r\n */\r\nexport const tap = <R, A>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => Reader<R, unknown>\r\n): Reader<R, A> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n const side_effect_reader = f(result_a);\r\n side_effect_reader(env);\r\n return result_a;\r\n };\r\n};\r\n\r\n/**\r\n * Lifts a binary function (A, B) => C into the Reader context.\r\n * It takes a standard two-argument function and two Readers, and returns a new Reader\r\n * that applies the function to the values within the Readers. This is achieved via Currying and 'ap'.\r\n *\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the output value\r\n * @param f_abc - The binary function (A, B) => C\r\n * @returns A function that takes two Readers and returns a Reader<R, C>\r\n */\r\nexport const liftA2 =\r\n <R, A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n (reader_a: Reader<R, A>, reader_b: Reader<R, B>): Reader<R, C> => {\r\n return ap(\r\n map(reader_a, (a: A) => (b: B) => f_abc(a, b)),\r\n reader_b\r\n );\r\n };\r\n\r\n/**\r\n * Lifts a ternary function (A, B, C) => D into the Reader context.\r\n * It takes a standard three-argument function and three Readers, and returns a new Reader\r\n * that applies the function to the values within the Readers. This is built upon liftA2 and 'ap'.\r\n *\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the third input value\r\n * @typeParam D - The type of the output value\r\n * @param f_abcd - The ternary function (A, B, C) => D\r\n * @returns A function that takes three Readers and returns a Reader<R, D>\r\n */\r\nexport const liftA3 =\r\n <R, A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n (\r\n reader_a: Reader<R, A>,\r\n reader_b: Reader<R, B>,\r\n reader_c: Reader<R, C>\r\n ): Reader<R, D> => {\r\n const liftA2_R = liftA2<R, A, B, (c: C) => D>(\r\n (a: A, b: B) => (c: C) => f_abcd(a, b, c)\r\n );\r\n const reader_f_cd = liftA2_R(reader_a, reader_b);\r\n return ap(reader_f_cd, reader_c);\r\n };\r\n","// ========================================\r\n// ./src/Reader/reader-async.ts\r\n// ========================================\r\n/* eslint-disable @typescript-eslint/require-await */\r\nimport type {AsyncReader} from './types';\r\n\r\n/**\r\n * Creates an AsyncReader that ignores the environment (R) and resolves immediately\r\n * with the given value (A). This is the 'return' or 'pure' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in AsyncReader.\r\n * @returns AsyncReader<R, A> that resolves to 'a'.\r\n */\r\nexport const ofAsync = <R, A>(a: A): AsyncReader<R, A> => {\r\n return async (_env: R) => a;\r\n};\r\n\r\n/**\r\n * Creates an AsyncReader that retrieves the environment (R) and resolves with it.\r\n * This is the 'ask' operation in Reader Monad.\r\n * @typeParam R - The Environment type.\r\n * @returns AsyncReader<R, R> that resolves to the environment 'R'.\r\n */\r\nexport const askAsync = <R>(): AsyncReader<R, R> => {\r\n return async (env: R) => env;\r\n};\r\n\r\n/**\r\n * Applies a function (A) => B to the value inside the AsyncReader, maintaining the\r\n * environment context. This is the 'map' operation (Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source AsyncReader<R, A>.\r\n * @param f - The mapping function (A) => B.\r\n * @returns AsyncReader<R, B> containing the mapped value.\r\n */\r\nexport const mapAsync = <R, A, B>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => B\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then(f);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two AsyncReader computations. The result of the first reader (A) is used to\r\n * produce the second reader (AsyncReader<R, B>). This is the 'flatMap' or 'bind' operation (Monad).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial AsyncReader<R, A>.\r\n * @param f - A function that takes the result of 'reader' and returns the next AsyncReader<R, B>.\r\n * @returns AsyncReader<R, B> containing the final result.\r\n */\r\nexport const anThenAsync = <R, A, B>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => AsyncReader<R, B>\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then((result_a) => {\r\n // 拿到第一个reader的结果A后,执行函数f,得到下一个AsyncReader<R, B>\r\n const next_reader = f(result_a);\r\n // 在相同的环境env下执行next_reader,返回最终的Promise<B>\r\n return next_reader(env);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Applies a function contained within an AsyncReader (R, (A) => B) to a value\r\n * contained within another AsyncReader (R, A), preserving the environment. This is the 'ap' operation (Applicative Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - AsyncReader containing the function (A) => B.\r\n * @param reader_a - AsyncReader containing the input value A.\r\n * @returns AsyncReader<R, B> containing the result of applying the function.\r\n */\r\nexport const apAsync = <R, A, B>(\r\n reader_fab: AsyncReader<R, (a: A) => B>,\r\n reader_a: AsyncReader<R, A>\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_fab = reader_fab(env);\r\n const promise_a = reader_a(env);\r\n // 同时执行两个Reader,得到函数f和值a,然后应用f(a)\r\n return Promise.all([promise_fab, promise_a]).then(([f_ab, result_a]) =>\r\n f_ab(result_a)\r\n );\r\n };\r\n};\r\n\r\n/**\r\n * Performs a side effect using the result of the first AsyncReader, and then returns\r\n * the original result, ignoring the side effect's return value.\r\n * Note: The side effect function must return an AsyncReader.\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source AsyncReader<R, A>.\r\n * @param f - A function that takes A and returns an AsyncReader<R, unknown> (the side effect).\r\n * @returns AsyncReader<R, A> containing the original value.\r\n */\r\nexport const tapAsync = <R, A>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => AsyncReader<R, unknown>\r\n): AsyncReader<R, A> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then((result_a) => {\r\n // 得到result_a后,创建副作用reader\r\n const side_effect_reader = f(result_a);\r\n // 在相同的环境env下执行副作用reader\r\n const promise_side_effect = side_effect_reader(env);\r\n // 等待副作用完成后,返回原始结果result_a(忽略副作用reader的返回值)\r\n return promise_side_effect.then(() => result_a);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Asynchronously lifts a binary function (A, B) => C into the AsyncReader context.\r\n * It combines two AsyncReaders using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the output value\r\n * @param f_abc - The binary function (A, B) => C\r\n * @returns A function that takes two AsyncReaders and returns an AsyncReader<R, C>\r\n */\r\nexport const liftA2Async =\r\n <R, A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n (\r\n reader_a: AsyncReader<R, A>,\r\n reader_b: AsyncReader<R, B>\r\n ): AsyncReader<R, C> => {\r\n const reader_f_bc = mapAsync(reader_a, (a: A) => (b: B) => f_abc(a, b));\r\n return apAsync(reader_f_bc, reader_b);\r\n };\r\n\r\n/**\r\n * Asynchronously lifts a ternary function (A, B, C) => D into the AsyncReader context.\r\n * It combines three AsyncReaders using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the third input value\r\n * @typeParam D - The type of the output value\r\n * @param f_abcd - The ternary function (A, B, C) => D\r\n * @returns A function that takes three AsyncReaders and returns an AsyncReader<R, D>\r\n */\r\nexport const liftA3Async =\r\n <R, A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n (\r\n reader_a: AsyncReader<R, A>,\r\n reader_b: AsyncReader<R, B>,\r\n reader_c: AsyncReader<R, C>\r\n ): AsyncReader<R, D> => {\r\n const reader_f_cd = liftA2Async<R, A, B, (c: C) => D>(\r\n (a: A, b: B) => (c: C) => f_abcd(a, b, c)\r\n )(reader_a, reader_b);\r\n return apAsync(reader_f_cd, reader_c);\r\n };\r\n"],"names":["of","a","_env","ap","reader_fab","reader_a","env","f_ab","result_a","ask","map","reader","f","anThen","tap","liftA2","f_abc","reader_b","b","liftA3","f_abcd","reader_c","reader_f_cd","c","ofAsync","askAsync","mapAsync","anThenAsync","apAsync","promise_fab","promise_a","tapAsync","liftA2Async","reader_f_bc","liftA3Async"],"mappings":"gIAcaA,EAAYC,GACfC,GAAYD,E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CAAS,CAAC,EAAE,KAAK,CAAC,CAACvB,EAAMC,CAAQ,IAChED,EAAKC,CAAQ,CAAA,CAEjB,EAaWuB,EAAW,CACtBpB,EACAC,IAEQN,GACYK,EAAOL,CAAG,EACX,KAAME,GAEMI,EAAEJ,CAAQ,EAEUF,CAAG,EAEvB,KAAK,IAAME,CAAQ,CAC/C,EAcQwB,EACEhB,GACb,CACEX,EACAY,IACsB,CACtB,MAAMgB,EAAcP,EAASrB,EAAWJ,GAAUiB,GAASF,EAAMf,EAAGiB,CAAC,CAAC,EACtE,OAAOU,EAAQK,EAAahB,CAAQ,CACtC,EAaWiB,EACKd,GAChB,CACEf,EACAY,EACAI,IACsB,CACtB,MAAMC,EAAcU,EAClB,CAAC/B,EAAMiB,IAAUK,GAASH,EAAOnB,EAAGiB,EAAGK,CAAC,CAAA,EACxClB,EAAUY,CAAQ,EACpB,OAAOW,EAAQN,EAAaD,CAAQ,CACtC"}
@@ -0,0 +1,75 @@
1
+ import { l as m } from "../chunks/local-8JVtLN0O.mjs";
2
+ const A = (e) => (t) => e, a = (e, t) => (r) => {
3
+ const n = e(r), s = t(r);
4
+ return n(s);
5
+ }, y = () => (e) => e, f = (e, t) => (r) => {
6
+ const n = e(r);
7
+ return t(n);
8
+ }, h = (e, t) => (r) => {
9
+ const n = e(r);
10
+ return t(n)(r);
11
+ }, b = (e, t) => (r) => {
12
+ const n = e(r);
13
+ return t(n)(r), n;
14
+ }, i = (e) => (t, r) => a(
15
+ f(t, (n) => (s) => e(n, s)),
16
+ r
17
+ ), x = (e) => (t, r, n) => {
18
+ const o = i(
19
+ (c, _) => (l) => e(c, _, l)
20
+ )(t, r);
21
+ return a(o, n);
22
+ }, R = (e) => async (t) => e, T = () => async (e) => e, d = (e, t) => (r) => e(r).then(t), g = (e, t) => (r) => e(r).then((s) => t(s)(r)), u = (e, t) => (r) => {
23
+ const n = e(r), s = t(r);
24
+ return Promise.all([n, s]).then(
25
+ ([o, c]) => o(c)
26
+ );
27
+ }, j = (e, t) => (r) => e(r).then((s) => t(s)(r).then(() => s)), p = (e) => (t, r) => {
28
+ const n = d(t, (s) => (o) => e(s, o));
29
+ return u(n, r);
30
+ }, k = (e) => (t, r, n) => {
31
+ const s = p(
32
+ (o, c) => (_) => e(o, c, _)
33
+ )(t, r);
34
+ return u(s, n);
35
+ }, P = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
36
+ __proto__: null,
37
+ anThen: h,
38
+ anThenAsync: g,
39
+ ap: a,
40
+ apAsync: u,
41
+ ask: y,
42
+ askAsync: T,
43
+ liftA2: i,
44
+ liftA2Async: p,
45
+ liftA3: x,
46
+ liftA3Async: k,
47
+ local: m,
48
+ map: f,
49
+ mapAsync: d,
50
+ of: A,
51
+ ofAsync: R,
52
+ tap: b,
53
+ tapAsync: j
54
+ }, Symbol.toStringTag, { value: "Module" }));
55
+ export {
56
+ P as _,
57
+ h as anThen,
58
+ g as anThenAsync,
59
+ a as ap,
60
+ u as apAsync,
61
+ y as ask,
62
+ T as askAsync,
63
+ i as liftA2,
64
+ p as liftA2Async,
65
+ x as liftA3,
66
+ k as liftA3Async,
67
+ m as local,
68
+ f as map,
69
+ d as mapAsync,
70
+ A as of,
71
+ R as ofAsync,
72
+ b as tap,
73
+ j as tapAsync
74
+ };
75
+ //# sourceMappingURL=Reader.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Reader.mjs","sources":["../../src/Reader/reader.ts","../../src/Reader/reader-async.ts"],"sourcesContent":["// ========================================\r\n// ./src/Reader/reader.ts\r\n// ========================================\r\nimport type {Reader} from './types';\r\n\r\n/**\r\n * Creates a Reader that ignores the environment (R) and returns the given value (A).\r\n * This is the 'return' or 'pure' operation (Applicative/Monad).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in Reader.\r\n * @returns Reader<R, A> that returns 'a'.\r\n */\r\nexport const of = <R, A>(a: A): Reader<R, A> => {\r\n return (_env: R) => a; // 忽略环境参数 R,直接返回传入的值 a。\r\n};\r\n\r\n/**\r\n * Applies a function contained within a Reader (R, (A) => B) to a value\r\n * contained within another Reader (R, A), preserving the environment.\r\n * This is the 'ap' operation (Applicative Functor).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - Reader containing the function (A) => B.\r\n * @param reader_a - Reader containing the input value A.\r\n * @returns Reader<R, B> containing the result of applying the function.\r\n */\r\nexport const ap = <R, A, B>(\r\n reader_fab: Reader<R, (a: A) => B>,\r\n reader_a: Reader<R, A>\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const f_ab = reader_fab(env);\r\n const result_a = reader_a(env);\r\n return f_ab(result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Creates a Reader that retrieves the environment (R) and returns it.\r\n * This is the 'ask' operation in Reader Monad.\r\n *\r\n * @typeParam R - The Environment type.\r\n * @returns Reader<R, R> that returns the environment 'R'.\r\n */\r\nexport const ask = <R>(): Reader<R, R> => {\r\n return (env: R) => env;\r\n};\r\n\r\n/**\r\n * Applies a function (A) => B to the value inside the Reader, maintaining the\r\n * environment context. This is the 'map' operation (Functor).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source Reader<R, A>.\r\n * @param f - The mapping function (A) => B.\r\n * @returns Reader<R, B> containing the mapped value.\r\n */\r\nexport const map = <R, A, B>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => B\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n return f(result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two Reader computations. The result of the first reader (A) is used to\r\n * produce the second reader (Reader<R, B>).\r\n * This is the 'flatMap' or 'bind' operation (Monad).\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial Reader<R, A>.\r\n * @param f - A function that takes the result of 'reader' and returns the next Reader<R, B>.\r\n * @returns Reader<R, B> containing the final result.\r\n */\r\nexport const anThen = <R, A, B>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => Reader<R, B>\r\n): Reader<R, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n const next_reader = f(result_a);\r\n return next_reader(env);\r\n };\r\n};\r\n\r\n/**\r\n * Performs a side effect using the result of the first Reader, and then returns\r\n * the original result, ignoring the side effect's return value.\r\n * Note: The side effect function must return a Reader.\r\n *\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source Reader<R, A>.\r\n * @param f - A function that takes A and returns a Reader<R, unknown> (the side effect).\r\n * @returns Reader<R, A> containing the original value.\r\n */\r\nexport const tap = <R, A>(\r\n reader: Reader<R, A>,\r\n f: (a: A) => Reader<R, unknown>\r\n): Reader<R, A> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n const side_effect_reader = f(result_a);\r\n side_effect_reader(env);\r\n return result_a;\r\n };\r\n};\r\n\r\n/**\r\n * Lifts a binary function (A, B) => C into the Reader context.\r\n * It takes a standard two-argument function and two Readers, and returns a new Reader\r\n * that applies the function to the values within the Readers. This is achieved via Currying and 'ap'.\r\n *\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the output value\r\n * @param f_abc - The binary function (A, B) => C\r\n * @returns A function that takes two Readers and returns a Reader<R, C>\r\n */\r\nexport const liftA2 =\r\n <R, A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n (reader_a: Reader<R, A>, reader_b: Reader<R, B>): Reader<R, C> => {\r\n return ap(\r\n map(reader_a, (a: A) => (b: B) => f_abc(a, b)),\r\n reader_b\r\n );\r\n };\r\n\r\n/**\r\n * Lifts a ternary function (A, B, C) => D into the Reader context.\r\n * It takes a standard three-argument function and three Readers, and returns a new Reader\r\n * that applies the function to the values within the Readers. This is built upon liftA2 and 'ap'.\r\n *\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the third input value\r\n * @typeParam D - The type of the output value\r\n * @param f_abcd - The ternary function (A, B, C) => D\r\n * @returns A function that takes three Readers and returns a Reader<R, D>\r\n */\r\nexport const liftA3 =\r\n <R, A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n (\r\n reader_a: Reader<R, A>,\r\n reader_b: Reader<R, B>,\r\n reader_c: Reader<R, C>\r\n ): Reader<R, D> => {\r\n const liftA2_R = liftA2<R, A, B, (c: C) => D>(\r\n (a: A, b: B) => (c: C) => f_abcd(a, b, c)\r\n );\r\n const reader_f_cd = liftA2_R(reader_a, reader_b);\r\n return ap(reader_f_cd, reader_c);\r\n };\r\n","// ========================================\r\n// ./src/Reader/reader-async.ts\r\n// ========================================\r\n/* eslint-disable @typescript-eslint/require-await */\r\nimport type {AsyncReader} from './types';\r\n\r\n/**\r\n * Creates an AsyncReader that ignores the environment (R) and resolves immediately\r\n * with the given value (A). This is the 'return' or 'pure' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in AsyncReader.\r\n * @returns AsyncReader<R, A> that resolves to 'a'.\r\n */\r\nexport const ofAsync = <R, A>(a: A): AsyncReader<R, A> => {\r\n return async (_env: R) => a;\r\n};\r\n\r\n/**\r\n * Creates an AsyncReader that retrieves the environment (R) and resolves with it.\r\n * This is the 'ask' operation in Reader Monad.\r\n * @typeParam R - The Environment type.\r\n * @returns AsyncReader<R, R> that resolves to the environment 'R'.\r\n */\r\nexport const askAsync = <R>(): AsyncReader<R, R> => {\r\n return async (env: R) => env;\r\n};\r\n\r\n/**\r\n * Applies a function (A) => B to the value inside the AsyncReader, maintaining the\r\n * environment context. This is the 'map' operation (Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source AsyncReader<R, A>.\r\n * @param f - The mapping function (A) => B.\r\n * @returns AsyncReader<R, B> containing the mapped value.\r\n */\r\nexport const mapAsync = <R, A, B>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => B\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then(f);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two AsyncReader computations. The result of the first reader (A) is used to\r\n * produce the second reader (AsyncReader<R, B>). This is the 'flatMap' or 'bind' operation (Monad).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial AsyncReader<R, A>.\r\n * @param f - A function that takes the result of 'reader' and returns the next AsyncReader<R, B>.\r\n * @returns AsyncReader<R, B> containing the final result.\r\n */\r\nexport const anThenAsync = <R, A, B>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => AsyncReader<R, B>\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then((result_a) => {\r\n // 拿到第一个reader的结果A后,执行函数f,得到下一个AsyncReader<R, B>\r\n const next_reader = f(result_a);\r\n // 在相同的环境env下执行next_reader,返回最终的Promise<B>\r\n return next_reader(env);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Applies a function contained within an AsyncReader (R, (A) => B) to a value\r\n * contained within another AsyncReader (R, A), preserving the environment. This is the 'ap' operation (Applicative Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - AsyncReader containing the function (A) => B.\r\n * @param reader_a - AsyncReader containing the input value A.\r\n * @returns AsyncReader<R, B> containing the result of applying the function.\r\n */\r\nexport const apAsync = <R, A, B>(\r\n reader_fab: AsyncReader<R, (a: A) => B>,\r\n reader_a: AsyncReader<R, A>\r\n): AsyncReader<R, B> => {\r\n return (env: R) => {\r\n const promise_fab = reader_fab(env);\r\n const promise_a = reader_a(env);\r\n // 同时执行两个Reader,得到函数f和值a,然后应用f(a)\r\n return Promise.all([promise_fab, promise_a]).then(([f_ab, result_a]) =>\r\n f_ab(result_a)\r\n );\r\n };\r\n};\r\n\r\n/**\r\n * Performs a side effect using the result of the first AsyncReader, and then returns\r\n * the original result, ignoring the side effect's return value.\r\n * Note: The side effect function must return an AsyncReader.\r\n * @typeParam R - The Environment type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source AsyncReader<R, A>.\r\n * @param f - A function that takes A and returns an AsyncReader<R, unknown> (the side effect).\r\n * @returns AsyncReader<R, A> containing the original value.\r\n */\r\nexport const tapAsync = <R, A>(\r\n reader: AsyncReader<R, A>,\r\n f: (a: A) => AsyncReader<R, unknown>\r\n): AsyncReader<R, A> => {\r\n return (env: R) => {\r\n const promise_a = reader(env);\r\n return promise_a.then((result_a) => {\r\n // 得到result_a后,创建副作用reader\r\n const side_effect_reader = f(result_a);\r\n // 在相同的环境env下执行副作用reader\r\n const promise_side_effect = side_effect_reader(env);\r\n // 等待副作用完成后,返回原始结果result_a(忽略副作用reader的返回值)\r\n return promise_side_effect.then(() => result_a);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Asynchronously lifts a binary function (A, B) => C into the AsyncReader context.\r\n * It combines two AsyncReaders using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the output value\r\n * @param f_abc - The binary function (A, B) => C\r\n * @returns A function that takes two AsyncReaders and returns an AsyncReader<R, C>\r\n */\r\nexport const liftA2Async =\r\n <R, A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n (\r\n reader_a: AsyncReader<R, A>,\r\n reader_b: AsyncReader<R, B>\r\n ): AsyncReader<R, C> => {\r\n const reader_f_bc = mapAsync(reader_a, (a: A) => (b: B) => f_abc(a, b));\r\n return apAsync(reader_f_bc, reader_b);\r\n };\r\n\r\n/**\r\n * Asynchronously lifts a ternary function (A, B, C) => D into the AsyncReader context.\r\n * It combines three AsyncReaders using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type\r\n * @typeParam A - The type of the first input value\r\n * @typeParam B - The type of the second input value\r\n * @typeParam C - The type of the third input value\r\n * @typeParam D - The type of the output value\r\n * @param f_abcd - The ternary function (A, B, C) => D\r\n * @returns A function that takes three AsyncReaders and returns an AsyncReader<R, D>\r\n */\r\nexport const liftA3Async =\r\n <R, A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n (\r\n reader_a: AsyncReader<R, A>,\r\n reader_b: AsyncReader<R, B>,\r\n reader_c: AsyncReader<R, C>\r\n ): AsyncReader<R, D> => {\r\n const reader_f_cd = liftA2Async<R, A, B, (c: C) => D>(\r\n (a: A, b: B) => (c: C) => f_abcd(a, b, c)\r\n )(reader_a, reader_b);\r\n return apAsync(reader_f_cd, reader_c);\r\n };\r\n"],"names":["of","a","_env","ap","reader_fab","reader_a","env","f_ab","result_a","ask","map","reader","f","anThen","tap","liftA2","f_abc","reader_b","b","liftA3","f_abcd","reader_c","reader_f_cd","c","ofAsync","askAsync","mapAsync","anThenAsync","apAsync","promise_fab","promise_a","tapAsync","liftA2Async","reader_f_bc","liftA3Async"],"mappings":";AAcO,MAAMA,IAAK,CAAOC,MAChB,CAACC,MAAYD,GAeTE,IAAK,CAChBC,GACAC,MAEO,CAACC,MAAW;AACjB,QAAMC,IAAOH,EAAWE,CAAG,GACrBE,IAAWH,EAASC,CAAG;AAC7B,SAAOC,EAAKC,CAAQ;AACtB,GAUWC,IAAM,MACV,CAACH,MAAWA,GAcRI,IAAM,CACjBC,GACAC,MAEO,CAACN,MAAW;AACjB,QAAME,IAAWG,EAAOL,CAAG;AAC3B,SAAOM,EAAEJ,CAAQ;AACnB,GAeWK,IAAS,CACpBF,GACAC,MAEO,CAACN,MAAW;AACjB,QAAME,IAAWG,EAAOL,CAAG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CAAahB,MACb,CACEX,GACAY,MACsB;AACtB,QAAMgB,IAAcP,EAASrB,GAAU,CAACJ,MAAS,CAACiB,MAASF,EAAMf,GAAGiB,CAAC,CAAC;AACtE,SAAOU,EAAQK,GAAahB,CAAQ;AACtC,GAaWiB,IACX,CAAgBd,MAChB,CACEf,GACAY,GACAI,MACsB;AACtB,QAAMC,IAAcU;AAAA,IAClB,CAAC/B,GAAMiB,MAAS,CAACK,MAASH,EAAOnB,GAAGiB,GAAGK,CAAC;AAAA,EAAA,EACxClB,GAAUY,CAAQ;AACpB,SAAOW,EAAQN,GAAaD,CAAQ;AACtC;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/base-BTXL1y_I.cjs"),u=require("../chunks/combine-async-DcG-3p8i.cjs"),E=require("../chunks/base-BvHqpP_s.cjs"),T=require("../chunks/local-Da4yU-nE.cjs"),O=r=>e=>o.Ok(r),v=()=>r=>o.Ok(r),w=r=>e=>o.Err(r),h=r=>e=>r,f=(r,e)=>n=>E.isSome(r)?o.Ok(r):o.Err(e),q=f,i=(r,e)=>n=>{const t=r(n);return u.map(t,e)},x=(r,e)=>n=>{const t=r(n);return u.andThen(t,s=>e(s)(n))},l=(r,e)=>n=>{const t=r(n),s=e(n);return u.ap(t,s)},A=r=>(e,n)=>{const t=i(e,s=>c=>r(s,c));return l(t,n)},M=r=>(e,n,t)=>{const s=A((c,a)=>y=>r(c,a,y))(e,n);return l(s,t)},R=(r,e)=>n=>{const t=r(n);return u.andThen(t,s=>{const a=e(s)(n);return a.ok?o.Ok(s):a})},S=(r,e)=>n=>{const t=r(n);return u.mapErr(t,e)},g=(r,e)=>n=>{const t=r(n);if(t.ok)return t;const s=t.error;return e(s)(n)},d=r=>e=>n=>{const t=e.map(s=>r(s)(n));return u.all(t)},N=r=>d(e=>e)(r),P=r=>async e=>o.Ok(r),j=()=>async r=>o.Ok(r),z=r=>async e=>o.Err(r),$=r=>async e=>r,m=(r,e)=>async n=>E.isSome(r)?o.Ok(r):o.Err(e),B=m,p=(r,e)=>async n=>{const t=await r(n);return u.mapAsync(t,e)},C=(r,e)=>async n=>{const t=await r(n);return u.andThenAsync(t,async s=>await e(s)(n))},_=(r,e)=>async n=>{const t=r(n),s=e(n),[c,a]=await Promise.all([t,s]);return u.apAsync(c,a)},b=r=>(e,n)=>{const t=p(e,s=>c=>r(s,c));return _(t,n)},D=r=>(e,n,t)=>{const s=b((c,a)=>y=>r(c,a,y))(e,n);return _(s,t)},F=(r,e)=>async n=>{const t=await r(n);return u.andThenAsync(t,async s=>{const a=await e(s)(n);return a.ok?o.Ok(s):a})},G=(r,e)=>async n=>{const t=await r(n);return u.mapErrAsync(t,e)},H=(r,e)=>async n=>{const t=await r(n);if(t.ok)return t;const s=t.error;return await e(s)(n)},k=r=>e=>async n=>{const t=e.map(c=>r(c)(n)),s=await Promise.all(t);return u.allAsync(s)},I=r=>k(e=>e)(r),J=Object.freeze(Object.defineProperty({__proto__:null,andThen:x,andThenAsync:C,ap:l,apAsync:_,ask:v,askAsync:j,fail:w,failAsync:z,fromMaybe:f,fromMaybeAsync:m,fromNullable:q,fromNullableAsync:B,fromResult:h,fromResultAsync:$,liftA2:A,liftA2Async:b,liftA3:M,liftA3Async:D,local:T.local,map:i,mapAsync:p,mapErr:S,mapErrAsync:G,of:O,ofAsync:P,orElse:g,orElseAsync:H,sequence:N,sequenceAsync:I,tap:R,tapAsync:F,traverse:d,traverseAsync:k},Symbol.toStringTag,{value:"Module"}));exports.local=T.local;exports.__exportReaderT__=J;exports.andThen=x;exports.andThenAsync=C;exports.ap=l;exports.apAsync=_;exports.ask=v;exports.askAsync=j;exports.fail=w;exports.failAsync=z;exports.fromMaybe=f;exports.fromMaybeAsync=m;exports.fromNullable=q;exports.fromNullableAsync=B;exports.fromResult=h;exports.fromResultAsync=$;exports.liftA2=A;exports.liftA2Async=b;exports.liftA3=M;exports.liftA3Async=D;exports.map=i;exports.mapAsync=p;exports.mapErr=S;exports.mapErrAsync=G;exports.of=O;exports.ofAsync=P;exports.orElse=g;exports.orElseAsync=H;exports.sequence=N;exports.sequenceAsync=I;exports.tap=R;exports.tapAsync=F;exports.traverse=d;exports.traverseAsync=k;
2
+ //# sourceMappingURL=ReaderT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReaderT.cjs","sources":["../../src/Reader/readerT.ts","../../src/Reader/readerT-async.ts"],"sourcesContent":["// ========================================\r\n// ./src/Reader/readerT.ts\r\n// ========================================\r\nimport type {ReaderT} from './types';\r\nimport {Ok, Err} from '../Result/base';\r\nimport type {Result} from '../Result/types';\r\nimport {\r\n map as mapResult,\r\n andThen as andThenResult,\r\n mapErr as mapErrResult,\r\n} from '../Result/Operators/transform';\r\nimport {ap as apResult, all as allResult} from '../Result/Operators/combine';\r\nimport {type Maybe, isSome} from '../Maybe/__export__';\r\n\r\n/**\r\n * Lifts a pure value (A) into the ReaderT context as a successful result.\r\n * This is the 'return' or 'pure' operation for ReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in ReaderT.\r\n * @returns ReaderT<R, E, A> that always returns Ok(a).\r\n */\r\nexport const of = <R, E, A>(a: A): ReaderT<R, E, A> => {\r\n return (_env: R) => Ok(a);\r\n};\r\n\r\n/**\r\n * Retrieves the environment (R) as a successful result.\r\n * This is the 'ask' operation in ReaderT context.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @returns ReaderT<R, E, R> that returns Ok(env).\r\n */\r\nexport const ask = <R, E>(): ReaderT<R, E, R> => {\r\n return (env: R) => Ok(env);\r\n};\r\n\r\n/**\r\n * Creates a ReaderT that immediately fails with the given error (E).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type parameter (not used, but required for type consistency).\r\n * @param e - The error value.\r\n * @returns ReaderT<R, E, A> that always returns Err(e).\r\n */\r\nexport const fail = <R, E, A>(e: E): ReaderT<R, E, A> => {\r\n return (_env: R) => Err(e);\r\n};\r\n\r\n/**\r\n * Lifts an existing Result into the ReaderT context.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The success value type.\r\n * @param result - The Result<A, E> to wrap.\r\n * @returns ReaderT<R, E, A> that always returns the wrapped Result.\r\n */\r\nexport const fromResult = <R, E, A>(result: Result<A, E>): ReaderT<R, E, A> => {\r\n return (_env: R) => result;\r\n};\r\n\r\n/**\r\n * Converts a Maybe value into a ReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The success value type.\r\n * @param maybe - The Maybe<A> value.\r\n * @param on_none_error - The error to use if Maybe is None.\r\n * @returns ReaderT<R, E, A> that returns Ok(A) if Some, otherwise Err(on_none_error).\r\n */\r\nexport const fromMaybe = <R, E, A>(\r\n maybe: Maybe<A>,\r\n on_none_error: E,\r\n): ReaderT<R, E, A> => {\r\n return (_env: R) => {\r\n if (isSome(maybe)) {\r\n return Ok(maybe);\r\n }\r\n return Err(on_none_error);\r\n };\r\n};\r\n\r\n/**\r\n * Converts a nullable value into a ReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The success value type.\r\n * @param maybe - The nullable value (A | null | undefined).\r\n * @param on_none_error - The error to use if the value is null or undefined.\r\n * @returns ReaderT<R, E, A> that returns Ok(A) if value exists, otherwise Err(on_none_error).\r\n */\r\nexport const fromNullable = fromMaybe;\r\n\r\n/**\r\n * Applies a pure function (A) => B to the success value inside the ReaderT.\r\n * This is the 'map' operation (Functor) for ReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source ReaderT<R, E, A>.\r\n * @param f_ab - The mapping function (A) => B.\r\n * @returns ReaderT<R, E, B> with the transformed success value.\r\n */\r\nexport const map = <R, E, A, B>(\r\n reader: ReaderT<R, E, A>,\r\n f_ab: (a: A) => B,\r\n): ReaderT<R, E, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n return mapResult(result_a, f_ab);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two ReaderT computations. The result of the first reader (A) is used to\r\n * produce the second reader (ReaderT<R, E, B>). This is the 'flatMap' or 'bind' operation (Monad).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial ReaderT<R, E, A>.\r\n * @param f_next - A function that takes the result of 'reader' and returns the next ReaderT<R, E, B>.\r\n * @returns ReaderT<R, E, B> containing the result of the chained computation.\r\n */\r\nexport const andThen = <R, E, A, B>(\r\n reader: ReaderT<R, E, A>,\r\n f_next: (a: A) => ReaderT<R, E, B>,\r\n): ReaderT<R, E, B> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n return andThenResult(result_a, (a: A) => {\r\n const next_reader = f_next(a);\r\n return next_reader(env);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Applies a function contained within a ReaderT (R, E, (A) => B) to a value\r\n * contained within another ReaderT (R, E, A). This is the 'ap' operation (Applicative Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - ReaderT containing the function (A) => B.\r\n * @param reader_a - ReaderT containing the input value A.\r\n * @returns ReaderT<R, E, B> containing the applied result.\r\n */\r\nexport const ap = <R, E, A, B>(\r\n reader_fab: ReaderT<R, E, (a: A) => B>,\r\n reader_a: ReaderT<R, E, A>,\r\n): ReaderT<R, E, B> => {\r\n return (env: R) => {\r\n const result_fab = reader_fab(env);\r\n const result_a = reader_a(env);\r\n return apResult(result_fab, result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Lifts a binary function (A, B) => C into the ReaderT context.\r\n * It combines two ReaderTs using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the first input value.\r\n * @typeParam B - The type of the second input value.\r\n * @typeParam C - The type of the output value.\r\n * @param f_abc - The binary function (A, B) => C.\r\n * @returns A function that takes two ReaderTs and returns a ReaderT<R, E, C>.\r\n */\r\nexport const liftA2 =\r\n <R, E, A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n (\r\n reader_a: ReaderT<R, E, A>,\r\n reader_b: ReaderT<R, E, B>,\r\n ): ReaderT<R, E, C> => {\r\n const reader_f_bc = map(reader_a, (a: A) => (b: B) => f_abc(a, b));\r\n return ap(reader_f_bc, reader_b);\r\n };\r\n\r\n/**\r\n * Lifts a ternary function (A, B, C) => D into the ReaderT context.\r\n * It combines three ReaderTs using the Applicative 'ap' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the first input value.\r\n * @typeParam B - The type of the second input value.\r\n * @typeParam C - The type of the third input value.\r\n * @typeParam D - The type of the output value.\r\n * @param f_abcd - The ternary function (A, B, C) => D.\r\n * @returns A function that takes three ReaderTs and returns a ReaderT<R, E, D>.\r\n */\r\nexport const liftA3 =\r\n <R, E, A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n (\r\n reader_a: ReaderT<R, E, A>,\r\n reader_b: ReaderT<R, E, B>,\r\n reader_c: ReaderT<R, E, C>,\r\n ): ReaderT<R, E, D> => {\r\n const reader_f_cd = liftA2<R, E, A, B, (c: C) => D>(\r\n (a: A, b: B) => (c: C) => f_abcd(a, b, c),\r\n )(reader_a, reader_b);\r\n\r\n return ap(reader_f_cd, reader_c);\r\n };\r\n\r\n/**\r\n * Performs a side effect using the result of the first ReaderT, and then returns\r\n * the original result. The side effect can fail (return Err), in which case the\r\n * entire computation fails with that error.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source ReaderT<R, E, A>.\r\n * @param f - A function that takes A and returns a ReaderT<R, E, unknown> (the side effect).\r\n * @returns ReaderT<R, E, A> that returns the original success value or the side effect's error.\r\n */\r\nexport const tap = <R, E, A>(\r\n reader: ReaderT<R, E, A>,\r\n f: (a: A) => ReaderT<R, E, unknown>,\r\n): ReaderT<R, E, A> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n\r\n return andThenResult(result_a, (a: A) => {\r\n const side_effect_reader = f(a);\r\n const side_effect_result = side_effect_reader(env);\r\n\r\n if (!side_effect_result.ok) {\r\n return side_effect_result;\r\n }\r\n return Ok(a);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Transforms the error type (E) of a ReaderT using a mapping function.\r\n * This is the 'mapError' operation for ReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The original Error type.\r\n * @typeParam A - The success value type.\r\n * @typeParam F - The new Error type.\r\n * @param reader - The source ReaderT<R, E, A>.\r\n * @param fn_fe - The function (E) => F to map the error.\r\n * @returns ReaderT<R, F, A> with the transformed error type.\r\n */\r\nexport const mapErr = <R, E, A, F>(\r\n reader: ReaderT<R, E, A>,\r\n fn_fe: (e: E) => F,\r\n): ReaderT<R, F, A> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n return mapErrResult(result_a, fn_fe);\r\n };\r\n};\r\n\r\n/**\r\n * Provides an alternative ReaderT to execute if the primary ReaderT fails.\r\n * This allows for error recovery or fallback behavior.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The primary error type.\r\n * @typeParam A - The success value type.\r\n * @typeParam F - The alternative error type.\r\n * @param reader - The primary ReaderT<R, E, A>.\r\n * @param alternative_reader - A function that takes the error E and returns a recovery ReaderT<R, F, A>.\r\n * @returns ReaderT<R, F, A> that is either the success of the primary reader, or the result of the alternative reader.\r\n */\r\nexport const orElse = <R, E, A, F>(\r\n reader: ReaderT<R, E, A>,\r\n alternative_reader: (e: E) => ReaderT<R, F, A>,\r\n): ReaderT<R, F, A> => {\r\n return (env: R) => {\r\n const result_a = reader(env);\r\n if (result_a.ok) {\r\n return result_a as Result<A, F>;\r\n }\r\n const error = result_a.error;\r\n const recovered_reader = alternative_reader(error);\r\n return recovered_reader(env);\r\n };\r\n};\r\n\r\n/**\r\n * Maps a list of items (T[]) to ReaderT computations and collects the results (A[])\r\n * into a single ReaderT. This is the 'traverse' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam T - The type of input items.\r\n * @typeParam A - The type of output values.\r\n * @param f_ta - The function (T) => ReaderT<R, E, A> to apply to each item.\r\n * @param items - The list of items T to process.\r\n * @returns ReaderT<R, E, A[]> that contains an array of results A or the first error E.\r\n */\r\nexport const traverse =\r\n <R, E, T, A>(f_ta: (t: T) => ReaderT<R, E, A>) =>\r\n (items: readonly T[]): ReaderT<R, E, A[]> => {\r\n return (env: R) => {\r\n const results: Result<A, E>[] = items.map((item) => {\r\n const reader = f_ta(item);\r\n return reader(env);\r\n });\r\n return allResult(results);\r\n };\r\n };\r\n\r\n/**\r\n * Sequences a list of ReaderT computations into a single ReaderT.\r\n * This is a specialization of 'traverse' where the function is the identity.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The success value type.\r\n * @param readers - The list of ReaderT<R, E, A> computations.\r\n * @returns ReaderT<R, E, A[]> that contains an array of results A or the first error E.\r\n */\r\nexport const sequence = <R, E, A>(\r\n readers: readonly ReaderT<R, E, A>[],\r\n): ReaderT<R, E, A[]> => {\r\n return traverse((reader: ReaderT<R, E, A>) => reader)(readers);\r\n};\r\n","// ========================================\r\n// ./src/Reader/readerT-async.ts\r\n// ========================================\r\n/* eslint-disable @typescript-eslint/require-await */\r\n\r\nimport type {AsyncReaderT} from './types';\r\nimport {Ok, Err} from '../Result/base';\r\nimport type {Result} from '../Result/types';\r\nimport {\r\n mapAsync as mapResultAsync,\r\n andThenAsync as andThenResultAsync,\r\n mapErrAsync as mapErrResultAsync,\r\n} from '../Result/Operators/Async/transform-async';\r\nimport {\r\n apAsync as apResultAsync,\r\n allAsync as allResultAsync,\r\n} from '../Result/Operators/Async/combine-async';\r\nimport {type Maybe, isSome} from '../Maybe/__export__';\r\nimport {UnknownError} from '../unknown-error';\r\n\r\n/**\r\n * Creates an AsyncReaderT that ignores the environment (R) and resolves immediately\r\n * with a successful Result containing the given value (A). This is the 'return' or 'pure' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the value to wrap.\r\n * @param a - The value to be wrapped in AsyncReaderT.\r\n * @returns AsyncReaderT<R, E, A> that resolves to Ok(a).\r\n */\r\nexport const ofAsync = <R, E, A>(a: A): AsyncReaderT<R, E, A> => {\r\n return async (_env: R) => Ok(a);\r\n};\r\n\r\n/**\r\n * Creates an AsyncReaderT that retrieves the environment (R) and resolves with it\r\n * in a successful Result. This is the 'ask' operation in ReaderT Monad.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @returns AsyncReaderT<R, E, R> that resolves to Ok(env).\r\n */\r\nexport const askAsync = <R, E>(): AsyncReaderT<R, E, R> => {\r\n return async (env: R) => Ok(env);\r\n};\r\n\r\n/**\r\n * Creates an AsyncReaderT that always fails with the given error (E), ignoring the environment.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type parameter for the value (unused, for consistency).\r\n * @param e - The error value to wrap in a failed Result.\r\n * @returns AsyncReaderT<R, E, A> that resolves to Err(e).\r\n */\r\nexport const failAsync = <R, E, A>(e: E): AsyncReaderT<R, E, A> => {\r\n return async (_env: R) => Err(e);\r\n};\r\n\r\n/**\r\n * Lifts a Result<A, E> into the AsyncReaderT context, ignoring the environment.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the value.\r\n * @param result - The Result to lift.\r\n * @returns AsyncReaderT<R, E | UnknownError, A> that resolves to the given result.\r\n */\r\nexport const fromResultAsync = <R, E, A>(\r\n result: Result<A, E>,\r\n): AsyncReaderT<R, E, A> => {\r\n return async (_env: R) => result;\r\n};\r\n\r\n/**\r\n * Lifts a Maybe<A> into the AsyncReaderT context, converting it to a Result.\r\n * If the Maybe is Some, returns Ok with the value; if None, returns Err with the given error.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the value.\r\n * @param maybe - The Maybe value to convert.\r\n * @param on_none_error - The error to use if the Maybe is None.\r\n * @returns AsyncReaderT<R, E | UnknownError, A> that resolves to Ok(a) or Err(on_none_error).\r\n */\r\nexport const fromMaybeAsync = <R, E, A>(\r\n maybe: Maybe<A>,\r\n on_none_error: E,\r\n): AsyncReaderT<R, E | UnknownError, A> => {\r\n return async (_env: R) => {\r\n if (isSome(maybe)) {\r\n return Ok(maybe);\r\n }\r\n return Err(on_none_error);\r\n };\r\n};\r\n\r\n/**\r\n * Lifts a nullable value (A | null | undefined) into the AsyncReaderT context.\r\n * If the value is not null or undefined, returns Ok with the value; otherwise returns Err.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the value.\r\n * @param maybe - The nullable value to convert.\r\n * @param on_none_error - The error to use if the value is null or undefined.\r\n * @returns AsyncReaderT<R, E | UnknownError, A> that resolves accordingly.\r\n */\r\nexport const fromNullableAsync = fromMaybeAsync;\r\n\r\n/**\r\n * Applies a function (A) => B to the successful value inside the AsyncReaderT,\r\n * maintaining the environment context and propagating errors. This is the 'map' operation.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader - The source AsyncReaderT<R, E, A>.\r\n * @param fn - The mapping function (A) => B.\r\n * @returns AsyncReaderT<R, E | UnknownError, B> containing the mapped value or the original error.\r\n */\r\nexport const mapAsync = <R, E, A, B>(\r\n reader: AsyncReaderT<R, E, A>,\r\n fn: (a: A) => B,\r\n): AsyncReaderT<R, E | UnknownError | DOMException, B> => {\r\n return async (env: R) => {\r\n const result_a = await reader(env);\r\n return mapResultAsync(result_a, fn);\r\n };\r\n};\r\n\r\n/**\r\n * Chains two AsyncReaderT computations. The successful result of the first reader (A) is used to\r\n * produce the second reader (AsyncReaderT<R, E, B>). Errors are propagated.\r\n * This is the 'flatMap' or 'bind' operation (Monad).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value of the first reader.\r\n * @typeParam B - The type of the final output value.\r\n * @param reader - The initial AsyncReaderT<R, E, A>.\r\n * @param f_next - A function that takes the successful result of 'reader' and returns the next AsyncReaderT<R, E, B>.\r\n * @returns AsyncReaderT<R, E | UnknownError, B> containing the final result or an error.\r\n */\r\nexport const andThenAsync = <R, E, A, B>(\r\n reader: AsyncReaderT<R, E, A>,\r\n f_next: (a: A, signal?: AbortSignal) => AsyncReaderT<R, E, B>,\r\n): AsyncReaderT<R, E | UnknownError | DOMException, B> => {\r\n return async (env: R) => {\r\n const result_a = await reader(env);\r\n return andThenResultAsync(result_a, async (a: A) => {\r\n const next_reader = f_next(a);\r\n return await next_reader(env);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Applies a function contained within an AsyncReaderT (R, (A) => B) to a value\r\n * contained within another AsyncReaderT (R, A), preserving the environment and propagating errors.\r\n * This is the 'ap' operation (Applicative Functor).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the input value.\r\n * @typeParam B - The type of the output value.\r\n * @param reader_fab - AsyncReaderT containing the function (A) => B.\r\n * @param reader_a - AsyncReaderT containing the input value A.\r\n * @returns AsyncReaderT<R, E | UnknownError, B> containing the result of applying the function or an error.\r\n */\r\nexport const apAsync = <R, E, A, B>(\r\n reader_fab: AsyncReaderT<R, E, (a: A) => B>,\r\n reader_a: AsyncReaderT<R, E, A>,\r\n): AsyncReaderT<R, E | UnknownError | DOMException, B> => {\r\n return async (env: R) => {\r\n const promise_fab = reader_fab(env);\r\n const promise_a = reader_a(env);\r\n\r\n const [result_fab, result_a] = await Promise.all([promise_fab, promise_a]);\r\n\r\n return apResultAsync(result_fab, result_a);\r\n };\r\n};\r\n\r\n/**\r\n * Asynchronously lifts a binary function (A, B) => C into the AsyncReaderT context.\r\n * It combines two AsyncReaderTs using the Applicative 'ap' operation, propagating errors.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the first input value.\r\n * @typeParam B - The type of the second input value.\r\n * @typeParam C - The type of the output value.\r\n * @param f_abc - The binary function (A, B) => C.\r\n * @returns A function that takes two AsyncReaderTs and returns an AsyncReaderT<R, E | UnknownError, C>.\r\n */\r\nexport const liftA2Async =\r\n <A, B, C>(f_abc: (a: A, b: B) => C) =>\r\n <R, E>(\r\n reader_a: AsyncReaderT<R, E, A>,\r\n reader_b: AsyncReaderT<R, E, B>,\r\n ): AsyncReaderT<R, E | UnknownError | DOMException, C> => {\r\n const reader_f_bc = mapAsync(reader_a, (a: A) => (b: B) => f_abc(a, b));\r\n return apAsync(reader_f_bc, reader_b);\r\n };\r\n\r\n/**\r\n * Asynchronously lifts a ternary function (A, B, C) => D into the AsyncReaderT context.\r\n * It combines three AsyncReaderTs using the Applicative 'ap' operation, propagating errors.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the first input value.\r\n * @typeParam B - The type of the second input value.\r\n * @typeParam C - The type of the third input value.\r\n * @typeParam D - The type of the output value.\r\n * @param f_abcd - The ternary function (A, B, C) => D.\r\n * @returns A function that takes three AsyncReaderTs and returns an AsyncReaderT<R, E | UnknownError, D>.\r\n */\r\nexport const liftA3Async =\r\n <A, B, C, D>(f_abcd: (a: A, b: B, c: C) => D) =>\r\n <R, E>(\r\n reader_a: AsyncReaderT<R, E, A>,\r\n reader_b: AsyncReaderT<R, E, B>,\r\n reader_c: AsyncReaderT<R, E, C>,\r\n ): AsyncReaderT<R, E | UnknownError | DOMException, D> => {\r\n const reader_f_cd = liftA2Async((a: A, b: B) => (c: C) => f_abcd(a, b, c))(\r\n reader_a,\r\n reader_b,\r\n );\r\n return apAsync(reader_f_cd, reader_c);\r\n };\r\n\r\n/**\r\n * Performs a side effect using the successful result of the AsyncReaderT, and then returns\r\n * the original result, ignoring the side effect's return value. If the side effect fails,\r\n * the error is propagated.\r\n * Note: The side effect function must return an AsyncReaderT.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The type of the original value to be passed through.\r\n * @param reader - The source AsyncReaderT<R, E, A>.\r\n * @param f - A function that takes A and returns an AsyncReaderT<R, E, unknown> (the side effect).\r\n * @returns AsyncReaderT<R, E | UnknownError, A> containing the original value or an error.\r\n */\r\nexport const tapAsync = <R, E, A>(\r\n reader: AsyncReaderT<R, E, A>,\r\n f: (a: A) => AsyncReaderT<R, E, unknown>,\r\n): AsyncReaderT<R, E | UnknownError | DOMException, A> => {\r\n return async (env: R) => {\r\n const result_a = await reader(env);\r\n\r\n return andThenResultAsync(result_a, async (a: A) => {\r\n const side_effect_reader = f(a);\r\n const side_effect_result = await side_effect_reader(env);\r\n\r\n if (!side_effect_result.ok) {\r\n return side_effect_result;\r\n }\r\n return Ok(a);\r\n });\r\n };\r\n};\r\n\r\n/**\r\n * Transforms the error value inside a failed AsyncReaderT using the given function.\r\n * Successful results are passed through unchanged.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The original Error type.\r\n * @typeParam A - The value type.\r\n * @typeParam F - The new Error type.\r\n * @param reader - The source AsyncReaderT<R, E, A>.\r\n * @param fn_fe - The error transformation function (E) => Promise<F> | F.\r\n * @returns AsyncReaderT<R, F | UnknownError, A> with transformed error or original success.\r\n */\r\nexport const mapErrAsync = <R, E, A, F>(\r\n reader: AsyncReaderT<R, E, A>,\r\n fn_fe: (e: E) => Promise<F> | F,\r\n): AsyncReaderT<R, F | UnknownError | DOMException, A> => {\r\n return async (env: R) => {\r\n const result_a = await reader(env);\r\n return mapErrResultAsync(result_a, fn_fe);\r\n };\r\n};\r\n\r\n/**\r\n * Recovers from an error in the AsyncReaderT by executing an alternative reader.\r\n * If the original reader succeeds, its result is returned; otherwise, the error is\r\n * passed to the alternative function which returns a new reader to try.\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The original Error type.\r\n * @typeParam A - The value type.\r\n * @typeParam F - The alternative Error type.\r\n * @param reader - The original AsyncReaderT<R, E, A>.\r\n * @param alternative_reader - A function that takes the error and returns an alternative AsyncReaderT<R, F, A>.\r\n * @returns AsyncReaderT<R, F | UnknownError, A> with either the original success or the alternative result.\r\n */\r\nexport const orElseAsync = <R, E, A, F>(\r\n reader: AsyncReaderT<R, E, A>,\r\n alternative_reader: (e: E) => AsyncReaderT<R, F, A>,\r\n): AsyncReaderT<R, F | UnknownError, A> => {\r\n return async (env: R) => {\r\n const result_a = await reader(env);\r\n\r\n if (result_a.ok) {\r\n return result_a;\r\n }\r\n\r\n const error = result_a.error;\r\n const recovered_reader = alternative_reader(error);\r\n return await recovered_reader(env);\r\n };\r\n};\r\n\r\n/**\r\n * Transforms a list of items (T) into an AsyncReaderT that processes each item\r\n * with the given function and collects all results into an array.\r\n * All items are processed in parallel (using Promise.all).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam T - The type of input items.\r\n * @typeParam A - The type of output values.\r\n * @param f_ta - A function that transforms each item T into an AsyncReaderT<R, E, A>.\r\n * @returns A function that takes an array of T and returns an AsyncReaderT<R, E | UnknownError, A[]>\r\n * containing all successful results, or the first error encountered.\r\n */\r\nexport const traverseAsync =\r\n <R, E, T, A>(f_ta: (t: T) => AsyncReaderT<R, E, A>) =>\r\n (\r\n items: readonly T[],\r\n ): AsyncReaderT<R, E | UnknownError | DOMException, A[]> => {\r\n return async (env: R) => {\r\n const promises: Promise<Result<A, E>>[] = items.map((item) => {\r\n const reader = f_ta(item);\r\n return reader(env);\r\n });\r\n\r\n const results: Result<A, E>[] = await Promise.all(promises);\r\n\r\n return allResultAsync(results);\r\n };\r\n };\r\n\r\n/**\r\n * Converts a list of AsyncReaderTs into a single AsyncReaderT that contains an array of results.\r\n * All readers are executed in parallel (using Promise.all).\r\n * @typeParam R - The Environment type.\r\n * @typeParam E - The Error type.\r\n * @typeParam A - The value type.\r\n * @param readers - An array of AsyncReaderT<R, E, A> to sequence.\r\n * @returns AsyncReaderT<R, E | UnknownError, A[]> containing all successful results, or the first error.\r\n */\r\nexport const sequenceAsync = <R, E, A>(\r\n readers: readonly AsyncReaderT<R, E, A>[],\r\n): AsyncReaderT<R, E | UnknownError | DOMException, A[]> => {\r\n return traverseAsync((reader: AsyncReaderT<R, E, A>) => reader)(readers);\r\n};\r\n"],"names":["of","a","_env","Ok","ask","env","fail","e","Err","fromResult","result","fromMaybe","maybe","on_none_error","isSome","fromNullable","map","reader","f_ab","result_a","mapResult","andThen","f_next","andThenResult","ap","reader_fab","reader_a","result_fab","apResult","liftA2","f_abc","reader_b","reader_f_bc","b","liftA3","f_abcd","reader_c","reader_f_cd","c","tap","f","side_effect_result","mapErr","fn_fe","mapErrResult","orElse","alternative_reader","error","traverse","f_ta","items","results","item","allResult","sequence","readers","ofAsync","askAsync","failAsync","fromResultAsync","fromMaybeAsync","fromNullableAsync","mapAsync","fn","mapResultAsync","andThenAsync","andThenResultAsync","apAsync","promise_fab","promise_a","apResultAsync","liftA2Async","liftA3Async","tapAsync","mapErrAsync","mapErrResultAsync","orElseAsync","traverseAsync","promises","allResultAsync","sequenceAsync"],"mappings":"oQAuBaA,EAAeC,GAClBC,GAAYC,EAAAA,GAAGF,CAAC,EAUbG,EAAM,IACTC,GAAWF,EAAAA,GAAGE,CAAG,EAWdC,EAAiBC,GACpBL,GAAYM,EAAAA,IAAID,CAAC,EAWdE,EAAuBC,GAC1BR,GAAYQ,EAYTC,EAAY,CACvBC,EACAC,IAEQX,GACFY,EAAAA,OAAOF,CAAK,EACPT,EAAAA,GAAGS,CAAK,EAEVJ,EAAAA,IAAIK,CAAa,EAafE,EAAeJ,EAaf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