@nicolastoulemont/std 0.8.2 → 0.10.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 (206) hide show
  1. package/README.md +391 -40
  2. package/dist/brand/index.d.mts +1 -1
  3. package/dist/brand/index.mjs +1 -1
  4. package/dist/{brand-DZgGDrAe.mjs → brand-DP-C92GS.mjs} +2 -2
  5. package/dist/{brand-DZgGDrAe.mjs.map → brand-DP-C92GS.mjs.map} +1 -1
  6. package/dist/{brand.types-B3NDX1vo.d.mts → brand.types-C_7QgCA4.d.mts} +1 -1
  7. package/dist/{brand.types-B3NDX1vo.d.mts.map → brand.types-C_7QgCA4.d.mts.map} +1 -1
  8. package/dist/context/index.d.mts +1 -1
  9. package/dist/context/index.mjs +1 -1
  10. package/dist/{context-0xDbwtpx.mjs → context-7oKePrBY.mjs} +2 -2
  11. package/dist/{context-0xDbwtpx.mjs.map → context-7oKePrBY.mjs.map} +1 -1
  12. package/dist/{context-B2dWloPl.d.mts → context-B9oWzbwF.d.mts} +2 -2
  13. package/dist/{context-B2dWloPl.d.mts.map → context-B9oWzbwF.d.mts.map} +1 -1
  14. package/dist/data/index.d.mts +1 -1
  15. package/dist/data/index.mjs +1 -1
  16. package/dist/data-W10ldR5l.mjs +2 -0
  17. package/dist/data-W10ldR5l.mjs.map +1 -0
  18. package/dist/{dual-fN6OUwN_.mjs → dual-CZhzZslG.mjs} +1 -1
  19. package/dist/{dual-fN6OUwN_.mjs.map → dual-CZhzZslG.mjs.map} +1 -1
  20. package/dist/duration/index.d.mts +1 -1
  21. package/dist/duration/index.mjs +1 -1
  22. package/dist/{duration-CYoDHcOR.mjs → duration-Dwtjy95Z.mjs} +2 -2
  23. package/dist/{duration-CYoDHcOR.mjs.map → duration-Dwtjy95Z.mjs.map} +1 -1
  24. package/dist/either/index.d.mts +1 -1
  25. package/dist/either/index.mjs +1 -1
  26. package/dist/{either-G7uOu4Ar.mjs → either-B2TvVY_j.mjs} +2 -2
  27. package/dist/{either-G7uOu4Ar.mjs.map → either-B2TvVY_j.mjs.map} +1 -1
  28. package/dist/exit-DOdhmr81.d.mts +67 -0
  29. package/dist/exit-DOdhmr81.d.mts.map +1 -0
  30. package/dist/fiber/index.d.mts +2 -0
  31. package/dist/fiber/index.mjs +1 -0
  32. package/dist/fiber-CZsyrDdd.mjs +2 -0
  33. package/dist/fiber-CZsyrDdd.mjs.map +1 -0
  34. package/dist/{flow-CNyLsPGb.mjs → flow-D8_tllWl.mjs} +1 -1
  35. package/dist/{flow-CNyLsPGb.mjs.map → flow-D8_tllWl.mjs.map} +1 -1
  36. package/dist/functions/index.mjs +1 -1
  37. package/dist/functions-DmOZ7O4j.mjs +2 -0
  38. package/dist/{functions-ByAk682_.mjs.map → functions-DmOZ7O4j.mjs.map} +1 -1
  39. package/dist/fx/index.d.mts +1 -1
  40. package/dist/fx/index.mjs +1 -1
  41. package/dist/fx-DXBw4iYX.mjs +2 -0
  42. package/dist/fx-DXBw4iYX.mjs.map +1 -0
  43. package/dist/fx.runtime-B2_rL7h_.mjs +2 -0
  44. package/dist/fx.runtime-B2_rL7h_.mjs.map +1 -0
  45. package/dist/fx.runtime-BuIElLpZ.d.mts +16 -0
  46. package/dist/fx.runtime-BuIElLpZ.d.mts.map +1 -0
  47. package/dist/{fx.types-DyQVgTS8.mjs → fx.types-Bg-Mmdm5.mjs} +1 -1
  48. package/dist/{fx.types-DyQVgTS8.mjs.map → fx.types-Bg-Mmdm5.mjs.map} +1 -1
  49. package/dist/{fx.types-BdN1EWxr.d.mts → fx.types-CpFKa-Jj.d.mts} +1 -1
  50. package/dist/{fx.types-BdN1EWxr.d.mts.map → fx.types-CpFKa-Jj.d.mts.map} +1 -1
  51. package/dist/{index-DCUGtEcj.d.mts → index-5QkUtJ-4.d.mts} +4 -4
  52. package/dist/{index-DCUGtEcj.d.mts.map → index-5QkUtJ-4.d.mts.map} +1 -1
  53. package/dist/{index-C4DOLLaU.d.mts → index-B3xia3Jl.d.mts} +82 -58
  54. package/dist/index-B3xia3Jl.d.mts.map +1 -0
  55. package/dist/{index-CIvNgjsx.d.mts → index-B4rHoUK4.d.mts} +2 -2
  56. package/dist/{index-CIvNgjsx.d.mts.map → index-B4rHoUK4.d.mts.map} +1 -1
  57. package/dist/{index-BA0EsFxS.d.mts → index-BDUhDs4D.d.mts} +3 -3
  58. package/dist/{index-BA0EsFxS.d.mts.map → index-BDUhDs4D.d.mts.map} +1 -1
  59. package/dist/{index-CNTYbcY9.d.mts → index-BZ1-IrU_.d.mts} +1 -1
  60. package/dist/{index-CNTYbcY9.d.mts.map → index-BZ1-IrU_.d.mts.map} +1 -1
  61. package/dist/{index-uE3S3Krx.d.mts → index-BZP6t2h9.d.mts} +5 -5
  62. package/dist/{index-uE3S3Krx.d.mts.map → index-BZP6t2h9.d.mts.map} +1 -1
  63. package/dist/{index-D8rDE60Y.d.mts → index-Bu-z5Xoq.d.mts} +1 -1
  64. package/dist/index-Bu-z5Xoq.d.mts.map +1 -0
  65. package/dist/index-C8KMi_I9.d.mts +226 -0
  66. package/dist/index-C8KMi_I9.d.mts.map +1 -0
  67. package/dist/{index-dCRymj_g.d.mts → index-CfXGmPMY.d.mts} +5 -5
  68. package/dist/{index-dCRymj_g.d.mts.map → index-CfXGmPMY.d.mts.map} +1 -1
  69. package/dist/index-Cv48HmyO.d.mts +59 -0
  70. package/dist/index-Cv48HmyO.d.mts.map +1 -0
  71. package/dist/{index-B2Z7-XGR.d.mts → index-D-KxgnwF.d.mts} +59 -34
  72. package/dist/index-D-KxgnwF.d.mts.map +1 -0
  73. package/dist/{index-DR7hzXU4.d.mts → index-DLkMqvw4.d.mts} +137 -29
  74. package/dist/index-DLkMqvw4.d.mts.map +1 -0
  75. package/dist/index-DlWm_PwP.d.mts +436 -0
  76. package/dist/index-DlWm_PwP.d.mts.map +1 -0
  77. package/dist/{index-B0flvtFB.d.mts → index-DogEz6WQ.d.mts} +2 -2
  78. package/dist/{index-B0flvtFB.d.mts.map → index-DogEz6WQ.d.mts.map} +1 -1
  79. package/dist/{index-crtzMG48.d.mts → index-XxPUUAGQ.d.mts} +41 -6
  80. package/dist/index-XxPUUAGQ.d.mts.map +1 -0
  81. package/dist/{index-BqJ1GWAF.d.mts → index-pC80zLHb.d.mts} +2 -2
  82. package/dist/{index-BqJ1GWAF.d.mts.map → index-pC80zLHb.d.mts.map} +1 -1
  83. package/dist/index.d.mts +23 -20
  84. package/dist/index.mjs +1 -1
  85. package/dist/layer/index.d.mts +1 -1
  86. package/dist/layer/index.mjs +1 -1
  87. package/dist/layer-BmrPWBkT.mjs +2 -0
  88. package/dist/layer-BmrPWBkT.mjs.map +1 -0
  89. package/dist/{layer.types-BB0MrvLg.d.mts → layer.types-DsCTjICW.d.mts} +4 -4
  90. package/dist/{layer.types-BB0MrvLg.d.mts.map → layer.types-DsCTjICW.d.mts.map} +1 -1
  91. package/dist/log/index.d.mts +2 -0
  92. package/dist/log/index.mjs +1 -0
  93. package/dist/log-Bh8G5umo.mjs +2 -0
  94. package/dist/log-Bh8G5umo.mjs.map +1 -0
  95. package/dist/multithread/index.d.mts +1 -1
  96. package/dist/multithread/index.mjs +1 -1
  97. package/dist/multithread-CovZ2ioL.mjs +21 -0
  98. package/dist/multithread-CovZ2ioL.mjs.map +1 -0
  99. package/dist/option/index.d.mts +1 -1
  100. package/dist/option/index.mjs +1 -1
  101. package/dist/{option-C2iCxAuJ.mjs → option-BlyP5LA2.mjs} +2 -2
  102. package/dist/{option-C2iCxAuJ.mjs.map → option-BlyP5LA2.mjs.map} +1 -1
  103. package/dist/{option.types-D9hrKcfa.d.mts → option.types-DLp3QpFE.d.mts} +3 -3
  104. package/dist/{option.types-D9hrKcfa.d.mts.map → option.types-DLp3QpFE.d.mts.map} +1 -1
  105. package/dist/{option.types-CbY_swma.mjs → option.types-bFFSErJ-.mjs} +1 -1
  106. package/dist/{option.types-CbY_swma.mjs.map → option.types-bFFSErJ-.mjs.map} +1 -1
  107. package/dist/order/index.d.mts +1 -1
  108. package/dist/order/index.mjs +1 -1
  109. package/dist/{order-BXOBEKvB.mjs → order-VTXpppmI.mjs} +2 -2
  110. package/dist/{order-BXOBEKvB.mjs.map → order-VTXpppmI.mjs.map} +1 -1
  111. package/dist/{pipeable-BIrevC0D.d.mts → pipeable-BY9yPsNK.d.mts} +1 -1
  112. package/dist/{pipeable-BIrevC0D.d.mts.map → pipeable-BY9yPsNK.d.mts.map} +1 -1
  113. package/dist/pipeable-COGyGMUV.mjs +2 -0
  114. package/dist/{pipeable-Dp1_23zH.mjs.map → pipeable-COGyGMUV.mjs.map} +1 -1
  115. package/dist/predicate/index.d.mts +1 -1
  116. package/dist/predicate/index.mjs +1 -1
  117. package/dist/{predicate-D_1SsIi4.mjs → predicate-8hY-0Ocv.mjs} +2 -2
  118. package/dist/{predicate-D_1SsIi4.mjs.map → predicate-8hY-0Ocv.mjs.map} +1 -1
  119. package/dist/provide/index.d.mts +1 -1
  120. package/dist/provide/index.mjs +1 -1
  121. package/dist/provide-K-6oXtLm.mjs +2 -0
  122. package/dist/provide-K-6oXtLm.mjs.map +1 -0
  123. package/dist/queue/index.d.mts +1 -1
  124. package/dist/queue/index.mjs +1 -1
  125. package/dist/{queue-apiEOlRD.mjs → queue-CeEIUHcY.mjs} +2 -2
  126. package/dist/{queue-apiEOlRD.mjs.map → queue-CeEIUHcY.mjs.map} +1 -1
  127. package/dist/result/index.d.mts +1 -1
  128. package/dist/result/index.mjs +1 -1
  129. package/dist/{result-D3VY0qBG.mjs → result-C74pRN2x.mjs} +2 -2
  130. package/dist/{result-D3VY0qBG.mjs.map → result-C74pRN2x.mjs.map} +1 -1
  131. package/dist/{result.types-BKzChyWY.d.mts → result.types-CnhiVFEV.d.mts} +3 -3
  132. package/dist/{result.types-BKzChyWY.d.mts.map → result.types-CnhiVFEV.d.mts.map} +1 -1
  133. package/dist/schedule/index.d.mts +1 -1
  134. package/dist/schedule/index.mjs +1 -1
  135. package/dist/{schedule-C6iN3oMt.mjs → schedule-ChcIgvd5.mjs} +2 -2
  136. package/dist/{schedule-C6iN3oMt.mjs.map → schedule-ChcIgvd5.mjs.map} +1 -1
  137. package/dist/{schedule-D2651VJY.d.mts → schedule-DiidMLcl.d.mts} +3 -3
  138. package/dist/{schedule-D2651VJY.d.mts.map → schedule-DiidMLcl.d.mts.map} +1 -1
  139. package/dist/schema/index.d.mts +1 -1
  140. package/dist/schema/index.mjs +1 -1
  141. package/dist/schema-CT_wO7tN.mjs +2 -0
  142. package/dist/schema-CT_wO7tN.mjs.map +1 -0
  143. package/dist/scope/index.d.mts +1 -1
  144. package/dist/scope/index.mjs +1 -1
  145. package/dist/{scope-CuM3CzwG.d.mts → scope-7bLTmdRX.d.mts} +4 -4
  146. package/dist/scope-7bLTmdRX.d.mts.map +1 -0
  147. package/dist/scope-D2AqJy7j.mjs +2 -0
  148. package/dist/scope-D2AqJy7j.mjs.map +1 -0
  149. package/dist/service/index.d.mts +1 -1
  150. package/dist/service/index.mjs +1 -1
  151. package/dist/{service-D8mr0wwg.d.mts → service-C4xUfS_M.d.mts} +2 -2
  152. package/dist/{service-D8mr0wwg.d.mts.map → service-C4xUfS_M.d.mts.map} +1 -1
  153. package/dist/{service-CWAIEH46.mjs → service-DHkeorS3.mjs} +2 -2
  154. package/dist/{service-CWAIEH46.mjs.map → service-DHkeorS3.mjs.map} +1 -1
  155. package/dist/trace/index.d.mts +2 -0
  156. package/dist/trace/index.mjs +1 -0
  157. package/dist/trace-ByjppUes.mjs +2 -0
  158. package/dist/trace-ByjppUes.mjs.map +1 -0
  159. package/dist/trace-D_7sjH22.d.mts +375 -0
  160. package/dist/trace-D_7sjH22.d.mts.map +1 -0
  161. package/package.json +13 -5
  162. package/dist/adt/index.d.mts +0 -2
  163. package/dist/adt/index.mjs +0 -1
  164. package/dist/adt-CPG_sa8q.mjs +0 -2
  165. package/dist/adt-CPG_sa8q.mjs.map +0 -1
  166. package/dist/data-BHYPdqWZ.mjs +0 -2
  167. package/dist/data-BHYPdqWZ.mjs.map +0 -1
  168. package/dist/discriminator.types-C-ygT2S1.d.mts +0 -7
  169. package/dist/discriminator.types-C-ygT2S1.d.mts.map +0 -1
  170. package/dist/equality-BX6BUidG.mjs +0 -2
  171. package/dist/equality-BX6BUidG.mjs.map +0 -1
  172. package/dist/functions-ByAk682_.mjs +0 -2
  173. package/dist/fx-DUXDxwsU.mjs +0 -2
  174. package/dist/fx-DUXDxwsU.mjs.map +0 -1
  175. package/dist/fx.runtime-jQxh77s3.mjs +0 -2
  176. package/dist/fx.runtime-jQxh77s3.mjs.map +0 -1
  177. package/dist/index-B2Z7-XGR.d.mts.map +0 -1
  178. package/dist/index-B41_sFR6.d.mts +0 -64
  179. package/dist/index-B41_sFR6.d.mts.map +0 -1
  180. package/dist/index-C4DOLLaU.d.mts.map +0 -1
  181. package/dist/index-C6W3_n_Q.d.mts +0 -458
  182. package/dist/index-C6W3_n_Q.d.mts.map +0 -1
  183. package/dist/index-D8rDE60Y.d.mts.map +0 -1
  184. package/dist/index-DR7hzXU4.d.mts.map +0 -1
  185. package/dist/index-crtzMG48.d.mts.map +0 -1
  186. package/dist/layer-CKtH7TRL.mjs +0 -2
  187. package/dist/layer-CKtH7TRL.mjs.map +0 -1
  188. package/dist/multithread-Cyc8Bz45.mjs +0 -19
  189. package/dist/multithread-Cyc8Bz45.mjs.map +0 -1
  190. package/dist/pipeable-Dp1_23zH.mjs +0 -2
  191. package/dist/provide--yZE8x-n.mjs +0 -2
  192. package/dist/provide--yZE8x-n.mjs.map +0 -1
  193. package/dist/schema-DstB1_VK.mjs +0 -2
  194. package/dist/schema-DstB1_VK.mjs.map +0 -1
  195. package/dist/schema.shared-Bjyroa6b.mjs +0 -2
  196. package/dist/schema.shared-Bjyroa6b.mjs.map +0 -1
  197. package/dist/schema.types-E1pjcc0Y.d.mts +0 -62
  198. package/dist/schema.types-E1pjcc0Y.d.mts.map +0 -1
  199. package/dist/scope-CuM3CzwG.d.mts.map +0 -1
  200. package/dist/scope-gVt4PESc.mjs +0 -2
  201. package/dist/scope-gVt4PESc.mjs.map +0 -1
  202. package/dist/service-resolution-BefYr4nR.mjs +0 -2
  203. package/dist/service-resolution-BefYr4nR.mjs.map +0 -1
  204. /package/dist/{chunk-oQKkju2G.mjs → chunk-6rpU2rUb.mjs} +0 -0
  205. /package/dist/{option-CXXiA1w-.mjs → option-BqAUkJ8e.mjs} +0 -0
  206. /package/dist/{result-xFLfwriM.mjs → result-B5WbPg8C.mjs} +0 -0
@@ -1,2 +1,2 @@
1
- import { t as layer_d_exports } from "../index-uE3S3Krx.mjs";
1
+ import { t as layer_d_exports } from "../index-BZP6t2h9.mjs";
2
2
  export { layer_d_exports as Layer };
@@ -1 +1 @@
1
- import{t as e}from"../layer-CKtH7TRL.mjs";export{e as Layer};
1
+ import{t as e}from"../layer-BmrPWBkT.mjs";export{e as Layer};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{i as n,n as r,r as i}from"./context-7oKePrBY.mjs";import{_ as a,b as o,l as s}from"./fx.runtime-B2_rL7h_.mjs";var c=e({err:()=>g,fx:()=>_,merge:()=>b,ok:()=>h,provide:()=>y,scoped:()=>v});const l=(e,n)=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){return i(e,n)}})}),u=e=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>e,_R:()=>void 0},*[Symbol.iterator](){throw yield e,Error(`Unreachable`)}})});function d(e){return n=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:()=>n._tag===`AsyncFx`?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let t=n[Symbol.asyncIterator](),r=await t.next();for(;r.done!==!0;){let e=yield r.value;r=await t.next(e)}return i(e,r.value)}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=n[Symbol.iterator](),r=t.next();for(;r.done!==!0;){let e=yield r.value;r=t.next(e)}return i(e,r.value)}}})}function f(e){return n=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:(r,a)=>n._tag===`AsyncFx`?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let t=n[Symbol.asyncIterator](),r=await t.next();for(;r.done!==!0;){let e=r.value;if(o(e)?.key===`@std/Scope`)r=await t.next(a);else{let n=yield e;r=await t.next(n)}}return i(e,r.value)}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=n[Symbol.iterator](),r=t.next();for(;r.done!==!0;){let e=r.value;if(o(e)?.key===`@std/Scope`)r=t.next(a);else{let n=yield e;r=t.next(n)}}return i(e,r.value)}}})}function p(e){return r=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:(i,o)=>{let c=e.build(i,o);return c._tag===`AsyncFx`?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let e=c[Symbol.asyncIterator](),t=await e.next();for(;t.done!==!0;){let n=yield t.value;t=await e.next(n)}let l=t.value;return n(l,yield*a(r.build(i,o),s(l)))}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let e=c[Symbol.iterator](),t=e.next();for(;t.done!==!0;){let n=yield t.value;t=e.next(n)}let l=t.value,u=r.build(i,o);if(u._tag===`SyncFx`)return n(l,yield*a(u,s(l)));throw Error(`Cannot use async layer in sync context`)}}}})}function m(...e){return{_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:(i,o)=>e.some(e=>e.build(i,o)._tag===`AsyncFx`)?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let t=r();for(let r of e){let e=yield*a(r.build(i,o),s(t));t=n(t,e)}return t}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=r();for(let r of e){let e=r.build(i,o);if(e._tag!==`SyncFx`)throw Error(`Expected sync layer in sync context`);let c=yield*a(e,s(t));t=n(t,c)}return t}}}}const h=l,g=u,_=d,v=f,y=p,b=m;export{b as n,c as t};
2
+ //# sourceMappingURL=layer-BmrPWBkT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layer-BmrPWBkT.mjs","names":["Context.make","fx","Context.merge","Context.empty"],"sources":["../src/layer/layer.ts"],"sourcesContent":["/**\n * Layer construction and composition for service dependency graphs.\n *\n * **Mental model**\n * - A `Layer` builds one or more services, potentially requiring other services.\n * - Compose layers and provide dependencies before running `Fx`.\n *\n * **Common tasks**\n * - Build from values with `Layer.ok`.\n * - Build from effects with `Layer.fx` or `Layer.scoped`.\n * - Compose with `Layer.provide` and `Layer.merge`.\n *\n * **Gotchas**\n * - Async layers force async execution paths.\n * - Scoped layers require scope finalization.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const program = Fx.gen(function* () {\n * return yield* Port\n * })\n * const exit = Fx.run(Provide.layer(Layer.ok(Port, 3000))(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n *\n * @module\n */\nimport * as Context from \"../context/context\"\nimport type { Context as ContextType } from \"../context/context\"\nimport { mergeRuntimeServices, withRuntimeStateCommit } from \"../fx/fx.runtime\"\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { RunnableFx, SyncFx, AsyncFx, FxYield } from \"../fx/fx.types\"\nimport type { ScopeService, ExcludeScope } from \"../scope/scope\"\nimport type { ServiceClass } from \"../service/service\"\nimport { asServiceRequest } from \"../service/service-resolution\"\nimport type { Layer as LayerType, MergeROut, MergeError, UnprovidedDeps, AllSync } from \"./layer.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Layer composition carries erased generic channels and phantom type slots that require assertion-based reconstruction. */\n\n/**\n * Create a layer from a synchronous value (no dependencies).\n */\nconst layerOk = <S>(service: ServiceClass<S>, impl: S): LayerType<S, never, never, true> => ({\n _tag: \"Layer\",\n _ROut: undefined as unknown as S,\n _E: undefined as never,\n _RIn: undefined as never,\n _Sync: undefined as unknown as true,\n build: (): SyncFx<ContextType<S>> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<S>,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, ContextType<S>, unknown> {\n return Context.make(service, impl)\n },\n }),\n})\n\n/**\n * Create a layer that always fails with an error.\n */\nconst layerErr = <E>(error: E): LayerType<never, E, never, true> => ({\n _tag: \"Layer\",\n _ROut: undefined as never,\n _E: undefined as unknown as E,\n _RIn: undefined as never,\n _Sync: undefined as unknown as true,\n build: (): SyncFx<ContextType, E> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as never,\n _E: () => error,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<E, never, unknown> {\n yield error\n throw new Error(\"Unreachable\")\n },\n }),\n})\n\n/**\n * Create a layer from an Fx computation (can have dependencies).\n * The Sync type parameter is inferred from the input fx:\n * - SyncFx input → Layer with Sync=true\n * - AsyncFx input → Layer with Sync=false\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const portLayer = Layer.fx(Port)(Fx.gen(function* () {\n * return 3000\n * }))\n * const program = Fx.gen(function* () {\n * return yield* Port\n * })\n * const exit = Fx.run(Provide.layer(portLayer)(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nfunction layerFx<S>(service: ServiceClass<S>): {\n <E, R>(fx: SyncFx<S, E, R>): LayerType<S, E, R, true>\n <E, R>(fx: AsyncFx<S, E, R>): LayerType<S, E, R, false>\n <E, R>(fx: RunnableFx<S, E, R>): LayerType<S, E, R>\n}\nfunction layerFx<S>(service: ServiceClass<S>) {\n return <E, R>(fx: RunnableFx<S, E, R>): LayerType<S, E, R> => ({\n _tag: \"Layer\",\n _ROut: undefined as unknown as S,\n _E: undefined as unknown as E,\n _RIn: undefined as unknown as R,\n _Sync: undefined as unknown as boolean,\n build: (): RunnableFx<ContextType<S>, E, R> => {\n if (fx._tag === \"AsyncFx\") {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<S>,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as R,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<E, R>, ContextType<S>, unknown> {\n const gen = fx[Symbol.asyncIterator]()\n let result = await gen.next()\n while (result.done !== true) {\n const value = yield result.value\n // oxlint-disable-next-line no-await-in-loop\n result = await gen.next(value)\n }\n return Context.make(service, result.value)\n },\n } as AsyncFx<ContextType<S>, E, R>\n }\n\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<S>,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as R,\n },\n *[Symbol.iterator](): Generator<FxYield<E, R>, ContextType<S>, unknown> {\n const gen = fx[Symbol.iterator]()\n let result = gen.next()\n while (result.done !== true) {\n const value = yield result.value\n result = gen.next(value)\n }\n return Context.make(service, result.value)\n },\n } as SyncFx<ContextType<S>, E, R>\n },\n })\n}\n\n/**\n * Create a scoped layer (with resource cleanup).\n * The Sync type parameter is inferred from the input fx.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Scope, Service } from \"@nicolastoulemont/std\"\n *\n * const Resource = Service.tag<{ readonly id: number }>(\"Resource\")\n * const ScopeTag = Service.tag<Scope.ScopeService>(\"@std/Scope\")\n * let finalized = 0\n *\n * const resourceLayer = Layer.scoped(Resource)(Fx.gen(function* () {\n * const scope = yield* ScopeTag\n * yield* scope.addFinalizer(() =>\n * Fx.gen(function* () {\n * finalized += 1\n * }),\n * )\n * return { id: 1 }\n * }))\n * const program = Fx.gen(function* () {\n * return (yield* Resource).id\n * })\n * const exit = Fx.run(Provide.layer(resourceLayer)(program))\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n */\nfunction layerScoped<S>(service: ServiceClass<S>): {\n <E, R>(fx: SyncFx<S, E, R | ScopeService>): LayerType<S, E, ExcludeScope<R>, true>\n <E, R>(fx: AsyncFx<S, E, R | ScopeService>): LayerType<S, E, ExcludeScope<R>, false>\n <E, R>(fx: RunnableFx<S, E, R | ScopeService>): LayerType<S, E, ExcludeScope<R>>\n}\nfunction layerScoped<S>(service: ServiceClass<S>) {\n return <E, R>(fx: RunnableFx<S, E, R | ScopeService>): LayerType<S, E, ExcludeScope<R>> => ({\n _tag: \"Layer\",\n _ROut: undefined as unknown as S,\n _E: undefined as unknown as E,\n _RIn: undefined as unknown as ExcludeScope<R>,\n _Sync: undefined as unknown as boolean,\n build: (_memoMap, scope): RunnableFx<ContextType<S>, E, ExcludeScope<R>> => {\n if (fx._tag === \"AsyncFx\") {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<S>,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as ExcludeScope<R>,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<E, ExcludeScope<R>>, ContextType<S>, unknown> {\n const gen = fx[Symbol.asyncIterator]()\n let result = await gen.next()\n while (result.done !== true) {\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest?.key === \"@std/Scope\") {\n // oxlint-disable-next-line no-await-in-loop\n result = await gen.next(scope)\n } else {\n const value = yield yielded as FxYield<E, ExcludeScope<R>>\n // oxlint-disable-next-line no-await-in-loop\n result = await gen.next(value)\n }\n }\n return Context.make(service, result.value)\n },\n } as AsyncFx<ContextType<S>, E, ExcludeScope<R>>\n }\n\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<S>,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as ExcludeScope<R>,\n },\n *[Symbol.iterator](): Generator<FxYield<E, ExcludeScope<R>>, ContextType<S>, unknown> {\n const gen = fx[Symbol.iterator]()\n let result = gen.next()\n while (result.done !== true) {\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest?.key === \"@std/Scope\") {\n result = gen.next(scope)\n } else {\n const value = yield yielded as FxYield<E, ExcludeScope<R>>\n result = gen.next(value)\n }\n }\n return Context.make(service, result.value)\n },\n } as SyncFx<ContextType<S>, E, ExcludeScope<R>>\n },\n })\n}\n\n// ============================================================================\n// Layer Composition\n// ============================================================================\n\n/**\n * Provide dependencies to a layer and merge outputs.\n * Sync is preserved only if both the deps layer and the consuming layer are sync.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const Server = Service.tag<{ readonly port: number }>(\"Server\")\n * const portLayer = Layer.ok(Port, 3000)\n * const serverLayer = Layer.fx(Server)(Fx.gen(function* () {\n * const port = yield* Port\n * return { port }\n * }))\n * const provided = Layer.provide(portLayer)(serverLayer)\n * const program = Fx.gen(function* () {\n * return (yield* Server).port\n * })\n * const exit = Fx.run(Provide.layer(provided)(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nfunction layerProvide<DepsROut, DepsE, DepsRIn, DepsSync extends boolean>(\n deps: LayerType<DepsROut, DepsE, DepsRIn, DepsSync>,\n): {\n <ROut, E, RIn extends DepsROut, LayerSync extends boolean>(\n layer: LayerType<ROut, E, RIn, LayerSync>,\n ): LayerType<ROut | DepsROut, E | DepsE, DepsRIn, LayerSync extends true ? DepsSync : false>\n}\nfunction layerProvide<DepsROut, DepsE, DepsRIn>(deps: LayerType<DepsROut, DepsE, DepsRIn>) {\n return <ROut, E, RIn extends DepsROut>(\n layer: LayerType<ROut, E, RIn>,\n ): LayerType<ROut | DepsROut, E | DepsE, DepsRIn> => ({\n _tag: \"Layer\",\n _ROut: undefined as unknown as ROut | DepsROut,\n _E: undefined as unknown as E | DepsE,\n _RIn: undefined as unknown as DepsRIn,\n _Sync: undefined as unknown as boolean,\n build: (memoMap, scope): RunnableFx<ContextType<ROut | DepsROut>, E | DepsE, DepsRIn> => {\n const depsBuildFx = deps.build(memoMap, scope)\n\n if (depsBuildFx._tag === \"AsyncFx\") {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<ROut | DepsROut>,\n _E: () => undefined as unknown as E | DepsE,\n _R: () => undefined as unknown as DepsRIn,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<\n FxYield<E | DepsE, DepsRIn>,\n ContextType<ROut | DepsROut>,\n unknown\n > {\n const depsGen = depsBuildFx[Symbol.asyncIterator]()\n let depsResult = await depsGen.next()\n while (depsResult.done !== true) {\n const value = yield depsResult.value\n // oxlint-disable-next-line no-await-in-loop\n depsResult = await depsGen.next(value)\n }\n const depsCtx = depsResult.value\n\n const layerBuildFx = layer.build(memoMap, scope)\n const layerCtx = yield* withRuntimeStateCommit(layerBuildFx, mergeRuntimeServices(depsCtx)) as RunnableFx<\n ContextType<ROut>,\n E,\n DepsRIn\n >\n return Context.merge(depsCtx, layerCtx)\n },\n } as AsyncFx<ContextType<ROut | DepsROut>, E | DepsE, DepsRIn>\n }\n\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<ROut | DepsROut>,\n _E: () => undefined as unknown as E | DepsE,\n _R: () => undefined as unknown as DepsRIn,\n },\n *[Symbol.iterator](): Generator<FxYield<E | DepsE, DepsRIn>, ContextType<ROut | DepsROut>, unknown> {\n const depsGen = depsBuildFx[Symbol.iterator]()\n let depsResult = depsGen.next()\n while (depsResult.done !== true) {\n const value = yield depsResult.value\n depsResult = depsGen.next(value)\n }\n const depsCtx = depsResult.value\n\n const layerBuildFx = layer.build(memoMap, scope)\n if (layerBuildFx._tag === \"SyncFx\") {\n const layerCtx = yield* withRuntimeStateCommit(layerBuildFx, mergeRuntimeServices(depsCtx)) as SyncFx<\n ContextType<ROut>,\n E,\n DepsRIn\n >\n return Context.merge(depsCtx, layerCtx)\n }\n throw new Error(\"Cannot use async layer in sync context\")\n },\n } as SyncFx<ContextType<ROut | DepsROut>, E | DepsE, DepsRIn>\n },\n })\n}\n\n/**\n * Merge multiple layers with automatic dependency resolution.\n * The merged layer is sync only if ALL input layers are sync.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.tag<{ readonly prefix: string }>(\"Logger\")\n * const Clock = Service.tag<{ readonly now: () => number }>(\"Clock\")\n * const merged = Layer.merge(\n * Layer.ok(Logger, { prefix: \"dev\" }),\n * Layer.ok(Clock, { now: () => 123 }),\n * )\n * const program = Fx.gen(function* () {\n * const logger = yield* Logger\n * const clock = yield* Clock\n * return `${logger.prefix}:${clock.now()}`\n * })\n * const exit = Fx.run(Provide.layer(merged)(program))\n * // => { _tag: \"Ok\", value: \"dev:123\" }\n * ```\n */\nfunction layerMerge<L extends LayerType<unknown, unknown, unknown>[]>(\n ...layers: L\n): LayerType<MergeROut<L>, MergeError<L>, UnprovidedDeps<L>, AllSync<L>>\nfunction layerMerge<L extends LayerType<unknown, unknown, unknown>[]>(\n ...layers: L\n): LayerType<MergeROut<L>, MergeError<L>, UnprovidedDeps<L>> {\n return {\n _tag: \"Layer\",\n _ROut: undefined as unknown as MergeROut<L>,\n _E: undefined as unknown as MergeError<L>,\n _RIn: undefined as unknown as UnprovidedDeps<L>,\n _Sync: undefined as unknown as boolean,\n build: (memoMap, scope): RunnableFx<ContextType<MergeROut<L>>, MergeError<L>, UnprovidedDeps<L>> => {\n const hasAsync = layers.some((l) => l.build(memoMap, scope)._tag === \"AsyncFx\")\n\n if (hasAsync) {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<MergeROut<L>>,\n _E: () => undefined as unknown as MergeError<L>,\n _R: () => undefined as unknown as UnprovidedDeps<L>,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<\n FxYield<MergeError<L>, UnprovidedDeps<L>>,\n ContextType<MergeROut<L>>,\n unknown\n > {\n let ctx = Context.empty() as ContextType<unknown>\n for (const layer of layers) {\n const buildFx = layer.build(memoMap, scope)\n const layerCtx = yield* withRuntimeStateCommit(buildFx, mergeRuntimeServices(ctx)) as RunnableFx<\n ContextType<unknown>,\n MergeError<L>,\n UnprovidedDeps<L>\n >\n ctx = Context.merge(ctx, layerCtx)\n }\n return ctx as ContextType<MergeROut<L>>\n },\n } as AsyncFx<ContextType<MergeROut<L>>, MergeError<L>, UnprovidedDeps<L>>\n }\n\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextType<MergeROut<L>>,\n _E: () => undefined as unknown as MergeError<L>,\n _R: () => undefined as unknown as UnprovidedDeps<L>,\n },\n *[Symbol.iterator](): Generator<FxYield<MergeError<L>, UnprovidedDeps<L>>, ContextType<MergeROut<L>>, unknown> {\n let ctx = Context.empty() as ContextType<unknown>\n for (const layer of layers) {\n const buildFx = layer.build(memoMap, scope)\n if (buildFx._tag !== \"SyncFx\") {\n throw new Error(\"Expected sync layer in sync context\")\n }\n const layerCtx = yield* withRuntimeStateCommit(buildFx, mergeRuntimeServices(ctx)) as SyncFx<\n ContextType<unknown>,\n MergeError<L>,\n UnprovidedDeps<L>\n >\n ctx = Context.merge(ctx, layerCtx)\n }\n return ctx as ContextType<MergeROut<L>>\n },\n } as SyncFx<ContextType<MergeROut<L>>, MergeError<L>, UnprovidedDeps<L>>\n },\n }\n}\n\n/**\n * Create a successful no-dependency layer from a plain service value.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const program = Fx.gen(function* () {\n * return yield* Port\n * })\n * const exit = Fx.run(Provide.layer(Layer.ok(Port, 3000))(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nexport const ok = layerOk\n\n/**\n * Create a layer that always fails with an error.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(function* () {\n * return 1\n * })\n * const exit = Fx.run(Provide.layer(Layer.err(\"missing-config\"))(program))\n * // => { _tag: \"Err\", error: \"missing-config\" }\n * ```\n */\nexport const err = layerErr\n\n/**\n * Create a layer from an effectful service builder.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const portLayer = Layer.fx(Port)(Fx.gen(function* () {\n * return 3000\n * }))\n * const program = Fx.gen(function* () {\n * return yield* Port\n * })\n * const exit = Fx.run(Provide.layer(portLayer)(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nexport const fx = layerFx\n\n/**\n * Create a scoped layer that registers resource finalizers.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Scope, Service } from \"@nicolastoulemont/std\"\n *\n * const Resource = Service.tag<{ readonly id: number }>(\"Resource\")\n * const ScopeTag = Service.tag<Scope.ScopeService>(\"@std/Scope\")\n * let finalized = 0\n *\n * const resourceLayer = Layer.scoped(Resource)(Fx.gen(function* () {\n * const scope = yield* ScopeTag\n * yield* scope.addFinalizer(() =>\n * Fx.gen(function* () {\n * finalized += 1\n * }),\n * )\n * return { id: 1 }\n * }))\n * const program = Fx.gen(function* () {\n * return (yield* Resource).id\n * })\n * const exit = Fx.run(Provide.layer(resourceLayer)(program))\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n */\nexport const scoped = layerScoped\n\n/**\n * Provide one layer to another, satisfying dependencies.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const Server = Service.tag<{ readonly port: number }>(\"Server\")\n * const portLayer = Layer.ok(Port, 3000)\n * const serverLayer = Layer.fx(Server)(Fx.gen(function* () {\n * const port = yield* Port\n * return { port }\n * }))\n * const provided = Layer.provide(portLayer)(serverLayer)\n * const program = Fx.gen(function* () {\n * return (yield* Server).port\n * })\n * const exit = Fx.run(Provide.layer(provided)(program))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nexport const provide = layerProvide\n\n/**\n * Merge multiple layers into a single composite layer.\n *\n * @example\n * ```ts\n * import { Fx, Layer, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.tag<{ readonly prefix: string }>(\"Logger\")\n * const Clock = Service.tag<{ readonly now: () => number }>(\"Clock\")\n * const merged = Layer.merge(\n * Layer.ok(Logger, { prefix: \"dev\" }),\n * Layer.ok(Clock, { now: () => 123 }),\n * )\n * const program = Fx.gen(function* () {\n * const logger = yield* Logger\n * const clock = yield* Clock\n * return `${logger.prefix}:${clock.now()}`\n * })\n * const exit = Fx.run(Provide.layer(merged)(program))\n * // => { _tag: \"Ok\", value: \"dev:123\" }\n * ```\n */\nexport const merge = layerMerge\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"mRA+CA,MAAM,GAAc,EAA0B,KAA+C,CAC3F,KAAM,QACN,MAAO,IAAA,GACP,GAAI,IAAA,GACJ,KAAM,IAAA,GACN,MAAO,IAAA,GACP,WAAsC,CACpC,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,EAAE,OAAO,WAAuD,CAC9D,OAAOA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AW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,EAAE,OAAO,WAAsG,CAC7G,IAAI,EAAMC,GAAe,CACzB,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAU,EAAM,MAAM,EAAS,EAAM,CAC3C,GAAI,EAAQ,OAAS,SACnB,MAAU,MAAM,sCAAsC,CAExD,IAAM,EAAW,MAAO,EAAuB,EAAS,EAAqB,EAAI,CAAC,CAKlF,EAAMD,EAAc,EAAK,EAAS,CAEpC,OAAO,GAEV,CAEJ,CAkBH,MAAa,EAAK,EAgBL,EAAM,EAoBN,EAAK,EA6BL,EAAS,EAwBT,EAAU,EAwBV,EAAQ"}
@@ -1,6 +1,6 @@
1
- import { f as RunnableFx, m as SyncFx } from "./fx.types-BdN1EWxr.mjs";
2
- import { t as Context } from "./context-B2dWloPl.mjs";
3
- import { n as ScopeService } from "./scope-CuM3CzwG.mjs";
1
+ import { f as RunnableFx, m as SyncFx } from "./fx.types-CpFKa-Jj.mjs";
2
+ import { t as Context } from "./context-B9oWzbwF.mjs";
3
+ import { n as ScopeService } from "./scope-7bLTmdRX.mjs";
4
4
 
5
5
  //#region src/provide/memo-map.d.ts
6
6
 
@@ -97,4 +97,4 @@ type MergeRIn<L extends readonly Layer<unknown, unknown, unknown>[]> = L[number]
97
97
  type AllSync<L extends readonly Layer<unknown, unknown, unknown>[]> = L extends readonly [] ? true : L extends readonly [Layer<unknown, unknown, unknown, infer S>, ...infer Rest] ? S extends true ? Rest extends readonly Layer<unknown, unknown, unknown>[] ? AllSync<Rest> : false : false : false;
98
98
  //#endregion
99
99
  export { UnprovidedDeps as a, MergeROut as i, Layer as n, MergeError as r, AllSync as t };
100
- //# sourceMappingURL=layer.types-BB0MrvLg.d.mts.map
100
+ //# sourceMappingURL=layer.types-DsCTjICW.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"layer.types-BB0MrvLg.d.mts","names":[],"sources":["../src/provide/memo-map.ts","../src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
+ export { log_d_exports as Log };
@@ -0,0 +1 @@
1
+ import{t as e}from"../log-Bh8G5umo.mjs";export{e as Log};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{n}from"./context-7oKePrBY.mjs";import{h as r,i,m as a}from"./fx.runtime-B2_rL7h_.mjs";var o=e({console:()=>g,context:()=>p,emit:()=>d,json:()=>_,layer:()=>v,withFields:()=>m,withSpan:()=>h});const s=e=>typeof e==`object`&&!!e&&`log`in e&&typeof e.log==`function`,c=e=>typeof e==`object`&&!!e&&`context`in e&&`event`in e,l=e=>e.filter(s),u=e=>{if(c(e))return{traceId:e.context.traceId,spanId:e.context.spanId,spanName:e.name}},d=(e,n,r)=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=yield*i(),a=Date.now(),o={timestamp:new Date(a),level:e,message:n,fields:{...t.logFields,...r},logSpans:t.logSpans.map(e=>({label:e.label,elapsedMs:a-e.startedAt})),trace:u(t.currentSpan),fiberId:t.fiberId};c(t.currentSpan)&&t.currentSpan.event(`log.${e}`,{message:n,...o.fields});for(let e of l(t.loggers))try{e.log(o)}catch{}}}),f=e=>({debug:(t,n)=>d(`debug`,t,{...e,...n}),info:(t,n)=>d(`info`,t,{...e,...n}),warn:(t,n)=>d(`warn`,t,{...e,...n}),error:(t,n)=>d(`error`,t,{...e,...n})}),p=(e,n)=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){return yield*a(t=>({...t,logFields:{...t.logFields,...e},logSpans:n?.logSpan===void 0?t.logSpans:[...t.logSpans,{label:n.logSpan,startedAt:Date.now()}]})),f(e)}}),m=e=>t=>r(t,t=>({...t,logFields:{...t.logFields,...e}})),h=e=>t=>r(t,t=>({...t,logSpans:[...t.logSpans,{label:e,startedAt:Date.now()}]})),g=()=>({log:e=>{globalThis.console[e.level](e.message,e.fields)}}),_=()=>({log:e=>{globalThis.console.log(JSON.stringify(e))}}),v=e=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=Array.isArray(e)?e:[e];return yield*a(e=>({...e,loggers:[...e.loggers,...t]})),n()}})});export{o as t};
2
+ //# sourceMappingURL=log-Bh8G5umo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-Bh8G5umo.mjs","names":["Context.empty"],"sources":["../src/log/log.ts"],"sourcesContent":["/**\n * Runtime-local logging helpers for `Fx` programs.\n *\n * Log context is execution state, not a service requirement. Install logger\n * backends with `Log.layer`, add contextual fields with `Log.context` or\n * `Log.withFields`, and emit events with `Log.emit` or the contextual logger.\n *\n * @example\n * ```ts\n * import { Fx, Log, Provide } from \"@nicolastoulemont/std\"\n *\n * const events: Log.Event[] = []\n * const program = Provide.layer(Log.layer({ log: (event) => events.push(event) }))(\n * Fx.gen(function* () {\n * const log = yield* Log.context({ requestId: \"req_1\" })\n * yield* log.info(\"request received\")\n * return \"ok\"\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"ok\" }\n * ```\n *\n * @module\n */\nimport * as Context from \"../context/context\"\nimport { getRuntimeState, updateRuntimeState, withRuntimeState } from \"../fx/fx.runtime\"\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { FxYield, RunnableFx, SyncFx } from \"../fx/fx.types\"\nimport type { Layer } from \"../layer/layer.types\"\nimport type { Span } from \"../trace/trace\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Log reads typed values out of internal runtime state slots. */\n\n/**\n * Supported log event levels.\n *\n * @example\n * ```ts\n * import type { Log } from \"@nicolastoulemont/std\"\n *\n * const level: Log.Level = \"info\"\n * ```\n */\nexport type Level = \"debug\" | \"info\" | \"warn\" | \"error\"\n\n/**\n * Structured fields attached to log events.\n *\n * @example\n * ```ts\n * import type { Log } from \"@nicolastoulemont/std\"\n *\n * const fields: Log.Fields = { requestId: \"req_1\" }\n * ```\n */\nexport type Fields = Record<string, unknown>\n\n/**\n * Concrete event delivered to installed logger backends.\n *\n * Events include merged contextual fields, active log spans, trace correlation\n * when a current span exists, and the current fiber id.\n *\n * @example\n * ```ts\n * import type { Log } from \"@nicolastoulemont/std\"\n *\n * const logger: Log.Logger = {\n * log: (event) => {\n * globalThis.console.log(event.level, event.message, event.fields)\n * },\n * }\n * ```\n */\nexport type Event = {\n readonly timestamp: Date\n readonly level: Level\n readonly message: string\n readonly fields: Fields\n readonly logSpans: ReadonlyArray<{\n readonly label: string\n readonly elapsedMs: number\n }>\n readonly trace:\n | {\n readonly traceId: string\n readonly spanId: string\n readonly spanName: string\n }\n | undefined\n readonly fiberId: number | undefined\n}\n\n/**\n * Logger backend installed through `Log.layer`.\n *\n * @example\n * ```ts\n * import type { Log } from \"@nicolastoulemont/std\"\n *\n * const events: Log.Event[] = []\n * const logger: Log.Logger = { log: (event) => events.push(event) }\n * ```\n */\nexport type Logger = {\n readonly log: (event: Event) => void\n}\n\n/**\n * Logger returned by `Log.context`.\n *\n * @example\n * ```ts\n * import { Fx, Log } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(function* () {\n * const log = yield* Log.context({ requestId: \"req_1\" })\n * yield* log.info(\"request received\")\n * })\n * ```\n */\nexport type ContextualLogger = {\n readonly debug: (message: string, fields?: Fields) => SyncFx<void>\n readonly info: (message: string, fields?: Fields) => SyncFx<void>\n readonly warn: (message: string, fields?: Fields) => SyncFx<void>\n readonly error: (message: string, fields?: Fields) => SyncFx<void>\n}\n\ntype LogContextOptions = {\n readonly logSpan?: string\n}\n\nconst isLogger = (value: unknown): value is Logger =>\n typeof value === \"object\" && value !== null && \"log\" in value && typeof value.log === \"function\"\n\nconst isSpan = (value: unknown): value is Span =>\n typeof value === \"object\" && value !== null && \"context\" in value && \"event\" in value\n\nconst runtimeLoggers = (loggers: ReadonlyArray<unknown>): ReadonlyArray<Logger> => loggers.filter(isLogger)\n\nconst runtimeTrace = (span: unknown): Event[\"trace\"] => {\n if (!isSpan(span)) {\n return undefined\n }\n\n return {\n traceId: span.context.traceId,\n spanId: span.context.spanId,\n spanName: span.name,\n }\n}\n\n/**\n * Emit one log event at the given level.\n *\n * The event is delivered to every logger installed in the current runtime state.\n * Logger failures are swallowed so logging cannot fail the user program.\n *\n * @example\n * ```ts\n * import { Fx, Log, Provide } from \"@nicolastoulemont/std\"\n *\n * const program = Provide.layer(Log.layer(Log.console()))(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"request received\", { route: \"/orders\" })\n * return \"ok\"\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"ok\" }\n * ```\n */\nexport const emit = (level: Level, message: string, fields?: Fields): SyncFx<void> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<never, never>, void, unknown> {\n const state = yield* getRuntimeState()\n const now = Date.now()\n const event: Event = {\n timestamp: new Date(now),\n level,\n message,\n fields: {\n ...state.logFields,\n ...fields,\n },\n logSpans: state.logSpans.map((span) => ({\n label: span.label,\n elapsedMs: now - span.startedAt,\n })),\n trace: runtimeTrace(state.currentSpan),\n fiberId: state.fiberId,\n }\n\n if (isSpan(state.currentSpan)) {\n state.currentSpan.event(`log.${level}`, {\n message,\n ...event.fields,\n })\n }\n\n for (const logger of runtimeLoggers(state.loggers)) {\n try {\n logger.log(event)\n } catch {\n // Logging is best-effort and must not affect the user program.\n }\n }\n },\n})\n\nconst makeContextualLogger = (fields: Fields): ContextualLogger => ({\n debug: (message, callFields) => emit(\"debug\", message, { ...fields, ...callFields }),\n info: (message, callFields) => emit(\"info\", message, { ...fields, ...callFields }),\n warn: (message, callFields) => emit(\"warn\", message, { ...fields, ...callFields }),\n error: (message, callFields) => emit(\"error\", message, { ...fields, ...callFields }),\n})\n\n/**\n * Add log fields to the current runtime state and return a contextual logger.\n *\n * Fields are inherited by nested effects and merged into later log events.\n * Passing `logSpan` also adds elapsed-time decoration to later log events.\n *\n * @example\n * ```ts\n * import { Fx, Log } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(function* () {\n * const log = yield* Log.context({ requestId: \"req_1\" }, { logSpan: \"request\" })\n * yield* log.info(\"loaded user\", { userId: \"user_1\" })\n * return \"ok\"\n * })\n * ```\n */\nexport const context = (fields: Fields, options?: LogContextOptions): SyncFx<ContextualLogger> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as ContextualLogger,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<never, never>, ContextualLogger, unknown> {\n yield* updateRuntimeState((state) => ({\n ...state,\n logFields: {\n ...state.logFields,\n ...fields,\n },\n logSpans:\n options?.logSpan === undefined\n ? state.logSpans\n : [\n ...state.logSpans,\n {\n label: options.logSpan,\n startedAt: Date.now(),\n },\n ],\n }))\n\n return makeContextualLogger(fields)\n },\n})\n\n/**\n * Run an effect with additional log fields.\n *\n * @example\n * ```ts\n * import { Fx, Log } from \"@nicolastoulemont/std\"\n *\n * const program = Log.withFields({ service: \"checkout\" })(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"started\")\n * return \"ok\"\n * }),\n * )\n * ```\n */\nexport const withFields =\n (fields: Fields) =>\n <A, E, R>(fx: RunnableFx<A, E, R>): RunnableFx<A, E, R> =>\n withRuntimeState(fx, (state) => ({\n ...state,\n logFields: {\n ...state.logFields,\n ...fields,\n },\n })) as RunnableFx<A, E, R>\n\n/**\n * Run an effect with an active log span.\n *\n * Log spans decorate log events with elapsed time. Use `Trace.span` when you\n * need a real tracing span.\n *\n * @example\n * ```ts\n * import { Fx, Log } from \"@nicolastoulemont/std\"\n *\n * const program = Log.withSpan(\"load-user\")(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"loaded user\")\n * return \"user_1\"\n * }),\n * )\n * ```\n */\nexport const withSpan =\n (label: string) =>\n <A, E, R>(fx: RunnableFx<A, E, R>): RunnableFx<A, E, R> =>\n withRuntimeState(fx, (state) => ({\n ...state,\n logSpans: [\n ...state.logSpans,\n {\n label,\n startedAt: Date.now(),\n },\n ],\n })) as RunnableFx<A, E, R>\n\n/**\n * Create a logger backend that writes events to `globalThis.console`.\n *\n * @example\n * ```ts\n * import { Fx, Log, Provide } from \"@nicolastoulemont/std\"\n *\n * const program = Provide.layer(Log.layer(Log.console()))(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"hello\")\n * }),\n * )\n * ```\n */\nexport const console = (): Logger => ({\n log: (event) => {\n globalThis.console[event.level](event.message, event.fields)\n },\n})\n\n/**\n * Create a logger backend that writes JSON events to `globalThis.console.log`.\n *\n * @example\n * ```ts\n * import { Fx, Log, Provide } from \"@nicolastoulemont/std\"\n *\n * const program = Provide.layer(Log.layer(Log.json()))(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"hello\")\n * }),\n * )\n * ```\n */\nexport const json = (): Logger => ({\n log: (event) => {\n globalThis.console.log(JSON.stringify(event))\n },\n})\n\n/**\n * Install one or more logger backends in the current Fx runtime.\n *\n * @example\n * ```ts\n * import { Fx, Log, Provide } from \"@nicolastoulemont/std\"\n *\n * const events: Log.Event[] = []\n * const program = Provide.layer(Log.layer({ log: (event) => events.push(event) }))(\n * Fx.gen(function* () {\n * yield* Log.emit(\"info\", \"stored\")\n * return events.length\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n */\nexport const layer = (loggers: Logger | ReadonlyArray<Logger>): Layer<never, never, never, true> => ({\n _tag: \"Layer\",\n _ROut: undefined as never,\n _E: undefined as never,\n _RIn: undefined as never,\n _Sync: undefined as unknown as true,\n build: (): SyncFx<Context.Context> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as Context.Context,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<never, never>, Context.Context, unknown> {\n const installed: ReadonlyArray<Logger> = Array.isArray(loggers) ? loggers : [loggers]\n yield* updateRuntimeState((state) => ({\n ...state,\n loggers: [...state.loggers, ...installed],\n }))\n return Context.empty()\n },\n }),\n})\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"sRAsIA,MAAM,EAAY,GAChB,OAAO,GAAU,YAAY,GAAkB,QAAS,GAAS,OAAO,EAAM,KAAQ,WAElF,EAAU,GACd,OAAO,GAAU,YAAY,GAAkB,YAAa,GAAS,UAAW,EAE5E,EAAkB,GAA2D,EAAQ,OAAO,EAAS,CAErG,EAAgB,GAAkC,CACjD,KAAO,EAAK,CAIjB,MAAO,CACL,QAAS,EAAK,QAAQ,QACtB,OAAQ,EAAK,QAAQ,OACrB,SAAU,EAAK,KAChB,EAwBU,GAAQ,EAAc,EAAiB,KAAmC,CACrF,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,EAAE,OAAO,WAA6D,CACpE,IAAM,EAAQ,MAAO,GAAiB,CAChC,EAAM,KAAK,KAAK,CAChB,EAAe,CACnB,UAAW,IAAI,KAAK,EAAI,CACxB,QACA,UACA,OAAQ,CACN,GAAG,EAAM,UACT,GAAG,EACJ,CACD,SAAU,EAAM,SAAS,IAAK,IAAU,CACtC,MAAO,EAAK,MACZ,UAAW,EAAM,EAAK,UACvB,EAAE,CACH,MAAO,EAAa,EAAM,YAAY,CACtC,QAAS,EAAM,QAChB,CAEG,EAAO,EAAM,YAAY,EAC3B,EAAM,YAAY,MAAM,OAAO,IAAS,CACtC,UACA,GAAG,EAAM,OACV,CAAC,CAGJ,IAAK,IAAM,KAAU,EAAe,EAAM,QAAQ,CAChD,GAAI,CACF,EAAO,IAAI,EAAM,MACX,IAKb,EAEK,EAAwB,IAAsC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A,GACP,WAAuC,CACrC,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,EAAE,OAAO,WAAwE,CAC/E,IAAM,EAAmC,MAAM,QAAQ,EAAQ,CAAG,EAAU,CAAC,EAAQ,CAKrF,OAJA,MAAO,EAAoB,IAAW,CACpC,GAAG,EACH,QAAS,CAAC,GAAG,EAAM,QAAS,GAAG,EAAU,CAC1C,EAAE,CACIA,GAAe,EAEzB,EACF"}
@@ -1,2 +1,2 @@
1
- import { t as multithread_d_exports } from "../index-DR7hzXU4.mjs";
1
+ import { t as multithread_d_exports } from "../index-DLkMqvw4.mjs";
2
2
  export { multithread_d_exports as Multithread };
@@ -1 +1 @@
1
- import{t as e}from"../multithread-Cyc8Bz45.mjs";export{e as Multithread};
1
+ import{t as e}from"../multithread-CovZ2ioL.mjs";export{e as Multithread};
@@ -0,0 +1,21 @@
1
+ import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{i as n,t as r}from"./result-C74pRN2x.mjs";import{n as i}from"./context-7oKePrBY.mjs";import{o as a}from"./fx.runtime-B2_rL7h_.mjs";var o=e({configure:()=>Q,filter:()=>se,firstSuccess:()=>me,flatMap:()=>le,forEach:()=>ae,fx:()=>H,layer:()=>ge,map:()=>K,race:()=>fe,run:()=>R,shutdown:()=>$,task:()=>B});const s=`@nicolastoulemont/std/multithread/cancelled`;let c,l=!1,u;const d=new WeakMap,f=()=>({fiberId:void 0,logFields:{},trace:void 0}),p=e=>typeof e==`object`&&!!e&&`traceId`in e&&typeof e.traceId==`string`&&`spanId`in e&&typeof e.spanId==`string`,m=e=>{if(!(typeof e!=`object`||!e)){if(`context`in e&&p(e.context))return{traceId:e.context.traceId,spanId:e.context.spanId,...e.context.traceFlags===void 0?{}:{traceFlags:e.context.traceFlags}};if(p(e))return{traceId:e.traceId,spanId:e.spanId,...e.traceFlags===void 0?{}:{traceFlags:e.traceFlags}}}},h=e=>({fiberId:e.fiberId,logFields:{...e.logFields},trace:m(e.currentSpan)}),ee=(e,t=`Optional peer dependency "multithreading" is unavailable. Install it to use Multithread APIs.`)=>({_tag:`MultithreadRuntimeUnavailableError`,message:t,cause:e}),te=(e=`Multithread runtime is already initialized and can no longer be configured.`)=>({_tag:`MultithreadRuntimeAlreadyInitializedError`,message:e}),g=(e,t)=>({_tag:`MultithreadWorkerExecutionError`,message:e,cause:t}),_=(e=`Multithread operation was cancelled before completion.`)=>({_tag:`MultithreadCancelledError`,message:e}),v=(e,t)=>({_tag:`MultithreadAllFailedError`,message:e,errors:t}),y=e=>e instanceof Error?e.message:typeof e==`string`?e:void 0,b=e=>{let t=y(e);return t===s||t===`Task aborted`},x=e=>{let t=y(e);return typeof t==`string`&&t.startsWith(`Could not parse coordinates from:`)},S=e=>{if(typeof e!=`object`||!e||!(`_tag`in e))return!1;let t=Reflect.get(e,`_tag`);return t===`Ok`?`value`in e:t===`Err`?`error`in e:!1},C=e=>n(e),w=e=>r(e),T=e=>S(e)?e:C(e),E=(e,t)=>S(e)?e._tag===`Err`?Promise.resolve(w(e.error)):t(e.value).result():t(e),D=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e))return t;let n=Math.floor(e);return n>0?n:t},O=e=>typeof e==`function`,ne=e=>typeof e==`object`&&!!e,k=e=>ne(e)?e:void 0,A=()=>c===void 0?typeof navigator<`u`&&typeof navigator.hardwareConcurrency==`number`?D(navigator.hardwareConcurrency,4):4:c.maxWorkers,j=()=>typeof SharedArrayBuffer==`function`?new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)):null,M=()=>{let e=j(),t=new Set,n=!1;return{signal:e,isCancelled:()=>n||e!==null&&Atomics.load(e,0)===1,cancel:()=>{if(n)return;n=!0,e!==null&&(Atomics.store(e,0,1),Atomics.notify(e,0));let r=Array.from(t);t.clear();for(let e of r)try{e()}catch{}},onCancel:e=>{if(n){e();return}t.add(e)}}},N=async()=>{try{return u??=import(`multithreading`),C(await u)}catch(e){return w(ee(e))}},P=async()=>{let e=await N();if(e._tag===`Err`)return e;let t=e.value;if(!l)try{c!==void 0&&t.initRuntime(c),l=!0}catch(e){return w(g(`Failed to initialize multithreading runtime.`,e))}return C(t)},re=e=>{let t=d.get(e);if(t!==void 0)return t;let n=e.toString(),r=Function(`
2
+ return async function (...__args) {
3
+ const __runtime = __args.pop()
4
+ const __signal = __args.pop()
5
+ const __isCancelled = () => __signal !== null && Atomics.load(__signal, 0) === 1
6
+ const __throwIfCancelled = () => {
7
+ if (__isCancelled()) {
8
+ throw new Error(${JSON.stringify(s)})
9
+ }
10
+ }
11
+ const __ctx = {
12
+ signal: __signal,
13
+ runtime: __runtime,
14
+ isCancelled: __isCancelled,
15
+ throwIfCancelled: __throwIfCancelled,
16
+ }
17
+ const __worker = (${n})
18
+ return await __worker(...__args, __ctx)
19
+ }
20
+ `)();return d.set(e,r),r},F=e=>{let n=M(),r,i=(t=f())=>r===void 0?n.isCancelled()?(r=Promise.resolve(w(_())),r):(r=e(n,t).catch(e=>w(g(`Multithread operation failed.`,e))).then(e=>n.isCancelled()?w(_()):e),r):r,o=(e,t)=>i().then(e,t);return{_tag:`MultithreadOp`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},result:i,abort:()=>{n.cancel()},then:o,async*[Symbol.asyncIterator](){return yield*a(e=>i(h(e)),()=>{n.cancel()})}}},ie=async(e,t,n,r)=>{if(n.isCancelled())return w(_());let i={signal:n.signal,runtime:r,isCancelled:()=>n.isCancelled(),throwIfCancelled:()=>{if(n.isCancelled())throw Error(s)}};try{let r=await e(...t,i);if(n.isCancelled())return w(_());let a=T(r);return a._tag===`Err`?w(a.error):C(a.value)}catch(e){return n.isCancelled()||b(e)?w(_()):w(g(`Multithread worker failed during execution.`,e))}},I=(e,t)=>F(async(n,r)=>{if(n.isCancelled())return w(_());let i=await P();if(i._tag===`Err`)return w(i.error);let a=i.value,o=re(e),s;try{let e=a.move(...t,n.signal,r);s=a.spawn(e,o),n.onCancel(()=>{s?.abort()})}catch(i){return x(i)?ie(e,t,n,r):n.isCancelled()||b(i)?w(_()):w(g(`Failed to start multithread worker.`,i))}try{let e=await s.join();if(n.isCancelled())return w(_());if(!e.ok){let t=e.error??Error(`Multithread worker returned an unknown error.`);return b(t)?w(_()):w(g(`Multithread worker failed during execution.`,t))}let t=T(e.value);return t._tag===`Err`?w(t.error):C(t.value)}catch(e){return n.isCancelled()||b(e)?w(_()):w(g(`Failed to join multithread worker.`,e))}});function L(e,...t){if(!O(e))throw TypeError(`Multithread.run expects a worker function as first argument.`);return I(e,t)}const R=L;function z(e){if(!O(e))throw TypeError(`Multithread.task expects a worker function.`);return(...t)=>I(e,t)}const B=z;function V(e,...n){if(!O(e))throw TypeError(`Multithread.fx expects a worker function as first argument.`);return{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){return yield*I(e,n)}}}const H=V,U=(e,t,n,r)=>e.length===0?Promise.resolve(C([])):new Promise(i=>{let a=new Map,o=[],s=0,c=0,l=0,u=!1,d=()=>{for(let e of a.values())e.abort();a.clear()},f=e=>{u||(u=!0,d(),i(e))};r.onCancel(()=>{f(w(_()))});let p=(t,n)=>{(async()=>{try{let r=await n.result();if(--s,a.delete(t),u)return;if(r._tag===`Err`){f(w(r.error));return}if(o[t]=r.value,l+=1,l===e.length){u=!0,i(C(o));return}m()}catch(e){if(--s,a.delete(t),u)return;if(r.isCancelled()||b(e)){f(w(_()));return}f(w(g(`Failed while executing multithread batch.`,e)))}})()},m=()=>{for(;!u&&s<n&&c<e.length;){let n=c;c+=1;let r=t(e[n],n);a.set(n,r),s+=1,p(n,r)}};m()}),W=(e,t,n)=>F(r=>U(e,(e,n)=>I(t,[e,n]),D(n?.parallelism,A()),r));function G(e,t,n){if(typeof e==`function`){let n=k(t);return(t=>E(t,t=>W(t,e,n)))}if(typeof t!=`function`)throw TypeError(`Multithread.map(values, worker, options) requires a worker function.`);return E(e,e=>W(e,t,n))}const K=G,q=(e,t,n)=>F(async r=>{let i=await U(e,(e,n)=>I(t,[e,n]),D(n?.parallelism,A()),r);return i._tag===`Err`?w(i.error):C(void 0)});function J(e,t,n){if(typeof e==`function`){let n=k(t);return(t=>E(t,t=>q(t,e,n)))}if(typeof t!=`function`)throw TypeError(`Multithread.forEach(values, worker, options) requires a worker function.`);return E(e,e=>q(e,t,n))}const ae=J,Y=(e,t,n)=>F(async r=>{let i=await U(e,(e,n)=>I(t,[e,n]),D(n?.parallelism,A()),r);if(i._tag===`Err`)return w(i.error);let a=[];for(let t=0;t<e.length;t+=1)i.value[t]===!0&&a.push(e[t]);return C(a)});function oe(e,t,n){if(typeof e==`function`){let n=k(t);return(t=>E(t,t=>Y(t,e,n)))}if(typeof t!=`function`)throw TypeError(`Multithread.filter(values, worker, options) requires a worker function.`);return E(e,e=>Y(e,t,n))}const se=oe,X=(e,t,n)=>F(async r=>{let i=await U(e,(e,n)=>I(t,[e,n]),D(n?.parallelism,A()),r);if(i._tag===`Err`)return w(i.error);let a=[];for(let e of i.value)a.push(...e);return C(a)});function ce(e,t,n){if(typeof e==`function`){let n=k(t);return(t=>E(t,t=>X(t,e,n)))}if(typeof t!=`function`)throw TypeError(`Multithread.flatMap(values, worker, options) requires a worker function.`);return E(e,e=>X(e,t,n))}const le=ce,ue=e=>F(t=>e.length===0?Promise.resolve(w(v(`Cannot race an empty list of operations.`,[]))):new Promise(n=>{let r=!1,i=()=>{for(let t of e)t.abort()},a=e=>{r||(r=!0,i(),n(e))};t.onCancel(()=>{a(w(_()))});let o=e=>{(async()=>{try{a(await e.result())}catch(e){if(t.isCancelled()||b(e)){a(w(_()));return}a(w(g(`Multithread race failed.`,e)))}})()};for(let t of e)o(t)}));function de(e){return E(e,e=>ue(e))}const fe=de,Z=e=>F(t=>e.length===0?Promise.resolve(w(v(`Cannot select a first success from an empty list of operations.`,[]))):new Promise(n=>{let r=Array.from({length:e.length}),i=e.length,a=!1,o=()=>{for(let t of e)t.abort()},s=e=>{a||(a=!0,o(),n(e))};t.onCancel(()=>{s(w(_()))});let c=(e,n)=>{(async()=>{try{let t=await e.result();if(a)return;if(t._tag===`Ok`){s(C(t.value));return}r[n]=t.error,--i,i===0&&s(w(v(`All multithread operations failed before any success was produced.`,r.filter(e=>e!==void 0))))}catch(e){if(a)return;if(t.isCancelled()||b(e)){s(w(_()));return}r[n]=g(`Multithread operation rejected unexpectedly.`,e),--i,i===0&&s(w(v(`All multithread operations failed before any success was produced.`,r.filter(e=>e!==void 0))))}})()};e.forEach((e,t)=>{c(e,t)})}));function pe(e){return E(e,e=>Z(e))}const me=pe,Q=e=>l?w(te()):(c={maxWorkers:D(e.maxWorkers,1)},C(void 0)),he=e=>{let t=Error(`Failed to shutdown multithread runtime while closing scope.`);return t.cause=e,t},ge=e=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:(n,r)=>({_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let n=Q(e);if(n._tag===`Err`)throw yield n.error,Error(`Unreachable: Fx runtime should short-circuit on yielded Multithread layer errors.`);let a=await P();if(a._tag===`Err`)throw yield a.error,Error(`Unreachable: Fx runtime should short-circuit on yielded Multithread layer errors.`);return yield*r.addFinalizer(()=>({_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let e=await $();if(e._tag===`Err`)throw he(e.error)}})),i()}})}),$=async()=>{if(!l)return C(void 0);let e=await N();if(e._tag===`Err`)return l=!1,w(e.error);try{return e.value.shutdown(),C(void 0)}catch(e){return w(g(`Failed to shutdown multithreading runtime.`,e))}finally{l=!1}};export{o as t};
21
+ //# sourceMappingURL=multithread-CovZ2ioL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multithread-CovZ2ioL.mjs","names":["Context.empty"],"sources":["../src/multithread/multithread.ts"],"sourcesContent":["/**\n * Parallel worker orchestration helpers built on the optional `multithreading` runtime.\n *\n * **Mental model**\n * - `MultithreadOp` represents cancelable worker execution.\n * - Use `fx` inside `Fx.gen` when each execution should start a fresh worker operation.\n * - Use `run`, `task`, and collection combinators for lower-level operation control.\n *\n * **Common tasks**\n * - Execute one worker operation with `Multithread.run`.\n * - Run worker-backed effects inside `Fx.gen` with `Multithread.fx`.\n * - Create reusable tasks with `Multithread.task`.\n * - Process collections in parallel with `Multithread.map` / `forEach`.\n * - Configure worker-pool lifecycle with `Multithread.configure` or `Multithread.layer`.\n *\n * **Gotchas**\n * - Requires optional `multithreading` peer dependency.\n * - Runtime should be configured before first operation.\n * - Worker callbacks are serialized, so they should be self-contained.\n * - Cancellation is cooperative: call `ctx.throwIfCancelled()` inside long-running work.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const op = Multithread.run((input: string, ctx) => {\n * ctx.throwIfCancelled()\n * return input.toUpperCase()\n * }, \"hello\")\n *\n * const result = await op.result()\n * // => { _tag: \"Ok\", value: \"HELLO\" }\n * ```\n *\n * @module\n */\nimport * as Context from \"../context/context\"\nimport { interruptibleAsync } from \"../fx/fx.runtime\"\nimport type { RuntimeState } from \"../fx/fx.runtime\"\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { AsyncFx, FxYield } from \"../fx/fx.types\"\nimport { err, ok } from \"../result/result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport type {\n MultithreadAllFailedError,\n MultithreadCancelledError,\n MultithreadCtx,\n MultithreadError,\n MultithreadFilter,\n MultithreadFilterWorker,\n MultithreadFirstSuccess,\n MultithreadFlatMap,\n MultithreadFlatMapWorker,\n MultithreadForEach,\n MultithreadFx,\n MultithreadLayer,\n MultithreadMap,\n MultithreadMapWorker,\n MultithreadOp,\n MultithreadParallelOptions,\n MultithreadRace,\n MultithreadRun,\n MultithreadRuntimeAlreadyInitializedError,\n MultithreadRuntimeSnapshot,\n MultithreadRuntimeUnavailableError,\n MultithreadSignal,\n MultithreadTask,\n MultithreadWorkerExecutionError,\n WorkerReturn,\n} from \"./multithread.types\"\nexport {\n /**\n * Re-exported worker context passed to multithread workers.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * type Example = Multithread.MultithreadCtx\n * ```\n *\n */\n type MultithreadCtx,\n type MultithreadRuntimeSnapshot,\n} from \"./multithread.types\"\nexport {\n /**\n * Re-exported union of multithread runtime and worker errors.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * type Example = Multithread.MultithreadError\n * ```\n *\n */\n type MultithreadError,\n} from \"./multithread.types\"\nexport {\n /**\n * Re-exported cancelable multithread operation type.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * type Example = Multithread.MultithreadOp<unknown, unknown>\n * ```\n *\n */\n type MultithreadOp,\n} from \"./multithread.types\"\n\n/**\n * Internal runtime shape loaded from the optional \"multithreading\" peer dependency.\n */\ntype MultithreadingRuntime = {\n initRuntime(config: { maxWorkers: number }): void\n shutdown(): void\n move<Args extends unknown[]>(...args: Args): unknown\n spawn<R>(\n payload: unknown,\n fn: (...args: unknown[]) => R | Promise<R>,\n ): {\n join(): Promise<{ ok: boolean; value?: R; error?: Error }>\n abort(): void\n }\n}\n\ntype WorkerLike = (...args: unknown[]) => unknown\ntype WorkerEntrypoint = (...args: unknown[]) => Promise<unknown>\n\ntype InternalCancelController = {\n readonly signal: MultithreadSignal\n isCancelled(): boolean\n cancel(): void\n onCancel(listener: () => void): void\n}\n\nconst CANCELLED_ERROR_MESSAGE = \"@nicolastoulemont/std/multithread/cancelled\"\n\nlet runtimeConfig: { maxWorkers: number } | undefined\nlet runtimeInitialized = false\nlet runtimeImportPromise: Promise<MultithreadingRuntime> | undefined\n\nconst workerEntrypointCache = new WeakMap<object, WorkerEntrypoint>()\n\nconst emptyRuntimeSnapshot = (): MultithreadRuntimeSnapshot => ({\n fiberId: undefined,\n logFields: {},\n trace: undefined,\n})\n\nconst isSpanContext = (\n value: unknown,\n): value is { readonly traceId: string; readonly spanId: string; readonly traceFlags?: number } =>\n typeof value === \"object\" &&\n value !== null &&\n \"traceId\" in value &&\n typeof value.traceId === \"string\" &&\n \"spanId\" in value &&\n typeof value.spanId === \"string\"\n\nconst runtimeTraceSnapshot = (span: unknown): MultithreadRuntimeSnapshot[\"trace\"] => {\n if (typeof span !== \"object\" || span === null) {\n return undefined\n }\n\n if (\"context\" in span && isSpanContext(span.context)) {\n return {\n traceId: span.context.traceId,\n spanId: span.context.spanId,\n ...(span.context.traceFlags === undefined ? {} : { traceFlags: span.context.traceFlags }),\n }\n }\n\n if (isSpanContext(span)) {\n return {\n traceId: span.traceId,\n spanId: span.spanId,\n ...(span.traceFlags === undefined ? {} : { traceFlags: span.traceFlags }),\n }\n }\n\n return undefined\n}\n\nconst runtimeSnapshotFromState = (state: RuntimeState): MultithreadRuntimeSnapshot => ({\n fiberId: state.fiberId,\n logFields: { ...state.logFields },\n trace: runtimeTraceSnapshot(state.currentSpan),\n})\n\nconst makeRuntimeUnavailableError = (\n cause?: unknown,\n message = 'Optional peer dependency \"multithreading\" is unavailable. Install it to use Multithread APIs.',\n): MultithreadRuntimeUnavailableError => ({\n _tag: \"MultithreadRuntimeUnavailableError\",\n message,\n cause,\n})\n\nconst makeRuntimeAlreadyInitializedError = (\n message = \"Multithread runtime is already initialized and can no longer be configured.\",\n): MultithreadRuntimeAlreadyInitializedError => ({\n _tag: \"MultithreadRuntimeAlreadyInitializedError\",\n message,\n})\n\nconst makeWorkerExecutionError = (message: string, cause: unknown): MultithreadWorkerExecutionError => ({\n _tag: \"MultithreadWorkerExecutionError\",\n message,\n cause,\n})\n\nconst makeCancelledError = (\n message = \"Multithread operation was cancelled before completion.\",\n): MultithreadCancelledError => ({\n _tag: \"MultithreadCancelledError\",\n message,\n})\n\nconst makeAllFailedError = (message: string, errors: readonly unknown[]): MultithreadAllFailedError => ({\n _tag: \"MultithreadAllFailedError\",\n message,\n errors,\n})\n\nconst getErrorMessage = (cause: unknown): string | undefined =>\n cause instanceof Error ? cause.message : typeof cause === \"string\" ? cause : undefined\n\nconst isCancelledCause = (cause: unknown): boolean => {\n const message = getErrorMessage(cause)\n return message === CANCELLED_ERROR_MESSAGE || message === \"Task aborted\"\n}\n\nconst isCallerLocationFailure = (cause: unknown): boolean => {\n const message = getErrorMessage(cause)\n return typeof message === \"string\" && message.startsWith(\"Could not parse coordinates from:\")\n}\n\nconst isResultLike = (value: unknown): value is ResultType<unknown, unknown> => {\n if (typeof value !== \"object\" || value === null || !(\"_tag\" in value)) return false\n const tag = Reflect.get(value, \"_tag\")\n if (tag === \"Ok\") return \"value\" in value\n if (tag === \"Err\") return \"error\" in value\n return false\n}\n\nconst resultOk = <A>(value: A): ResultType<A, never> => ok(value)\nconst resultErr = <E>(error: E): ResultType<never, E> => err(error)\n\nconst normalizeWorkerReturn = <A, E>(value: unknown): ResultType<A, E> => {\n if (isResultLike(value)) {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- isResultLike confirms runtime shape; generic channels are erased.\n return value as ResultType<A, E>\n }\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Worker return value is user-defined and mapped to generic success type.\n return resultOk(value as A)\n}\n\nconst runFromInputResult = (\n input: unknown,\n execute: (value: unknown) => MultithreadOp<unknown, unknown>,\n): MultithreadOp<unknown, unknown> | Promise<ResultType<unknown, unknown>> => {\n if (!isResultLike(input)) {\n return execute(input)\n }\n\n if (input._tag === \"Err\") {\n return Promise.resolve(resultErr(input.error))\n }\n\n return execute(input.value).result()\n}\n\nconst normalizeParallelism = (parallelism: number | undefined, fallback: number): number => {\n if (typeof parallelism !== \"number\" || !Number.isFinite(parallelism)) return fallback\n const rounded = Math.floor(parallelism)\n return rounded > 0 ? rounded : fallback\n}\n\nconst isWorkerLike = (value: unknown): value is WorkerLike => typeof value === \"function\"\n\nconst isParallelOptions = (value: unknown): value is MultithreadParallelOptions =>\n typeof value === \"object\" && value !== null\n\nconst resolveParallelOptions = (value: unknown): MultithreadParallelOptions | undefined =>\n isParallelOptions(value) ? value : undefined\n\nconst getDefaultParallelism = (): number => {\n if (runtimeConfig !== undefined) {\n return runtimeConfig.maxWorkers\n }\n if (typeof navigator !== \"undefined\" && typeof navigator.hardwareConcurrency === \"number\") {\n return normalizeParallelism(navigator.hardwareConcurrency, 4)\n }\n return 4\n}\n\nconst createSharedSignal = (): MultithreadSignal => {\n if (typeof SharedArrayBuffer !== \"function\") return null\n return new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))\n}\n\nconst createCancelController = (): InternalCancelController => {\n const signal = createSharedSignal()\n const listeners = new Set<() => void>()\n let cancelled = false\n\n const isCancelled = (): boolean => cancelled || (signal !== null && Atomics.load(signal, 0) === 1)\n\n const cancel = (): void => {\n if (cancelled) return\n cancelled = true\n\n if (signal !== null) {\n Atomics.store(signal, 0, 1)\n Atomics.notify(signal, 0)\n }\n\n const activeListeners = Array.from(listeners)\n listeners.clear()\n\n for (const listener of activeListeners) {\n try {\n listener()\n } catch {\n // Intentionally ignore listener disposal errors during cancellation fanout.\n }\n }\n }\n\n const onCancel = (listener: () => void): void => {\n if (cancelled) {\n listener()\n return\n }\n listeners.add(listener)\n }\n\n return {\n signal,\n isCancelled,\n cancel,\n onCancel,\n }\n}\n\nconst loadRuntimeModule = async (): Promise<ResultType<MultithreadingRuntime, MultithreadError>> => {\n try {\n runtimeImportPromise ??= import(\"multithreading\") as Promise<MultithreadingRuntime>\n return resultOk(await runtimeImportPromise)\n } catch (cause) {\n return resultErr(makeRuntimeUnavailableError(cause))\n }\n}\n\nconst getRuntime = async (): Promise<ResultType<MultithreadingRuntime, MultithreadError>> => {\n const runtimeResult = await loadRuntimeModule()\n if (runtimeResult._tag === \"Err\") return runtimeResult\n\n const runtime = runtimeResult.value\n\n if (!runtimeInitialized) {\n try {\n if (runtimeConfig !== undefined) {\n runtime.initRuntime(runtimeConfig)\n }\n runtimeInitialized = true\n } catch (cause) {\n return resultErr(makeWorkerExecutionError(\"Failed to initialize multithreading runtime.\", cause))\n }\n }\n\n return resultOk(runtime)\n}\n\nconst createWorkerEntrypoint = <Args extends readonly unknown[], A, E>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n): WorkerEntrypoint => {\n const cached = workerEntrypointCache.get(worker)\n if (cached !== undefined) {\n return cached\n }\n\n const source = worker.toString()\n // oxlint-disable-next-line typescript-eslint/no-implied-eval, typescript-eslint/no-unsafe-type-assertion -- Worker code must be reconstructed from serialized callback source and typed at runtime.\n const factory = new Function(\n `\nreturn async function (...__args) {\n const __runtime = __args.pop()\n const __signal = __args.pop()\n const __isCancelled = () => __signal !== null && Atomics.load(__signal, 0) === 1\n const __throwIfCancelled = () => {\n if (__isCancelled()) {\n throw new Error(${JSON.stringify(CANCELLED_ERROR_MESSAGE)})\n }\n }\n const __ctx = {\n signal: __signal,\n runtime: __runtime,\n isCancelled: __isCancelled,\n throwIfCancelled: __throwIfCancelled,\n }\n const __worker = (${source})\n return await __worker(...__args, __ctx)\n}\n`,\n ) as () => WorkerEntrypoint\n\n const entrypoint = factory()\n workerEntrypointCache.set(worker, entrypoint)\n return entrypoint\n}\n\nconst createMultithreadOperation = <A, E>(\n execute: (\n controller: InternalCancelController,\n runtimeSnapshot: MultithreadRuntimeSnapshot,\n ) => Promise<ResultType<A, E | MultithreadError>>,\n): MultithreadOp<A, E | MultithreadError> => {\n const controller = createCancelController()\n let runPromise: Promise<ResultType<A, E | MultithreadError>> | undefined\n\n const start = (\n runtimeSnapshot: MultithreadRuntimeSnapshot = emptyRuntimeSnapshot(),\n ): Promise<ResultType<A, E | MultithreadError>> => {\n if (runPromise !== undefined) return runPromise\n\n if (controller.isCancelled()) {\n runPromise = Promise.resolve(resultErr(makeCancelledError()))\n return runPromise\n }\n\n runPromise = execute(controller, runtimeSnapshot)\n .catch((cause: unknown) => resultErr(makeWorkerExecutionError(\"Multithread operation failed.\", cause)))\n .then((result) => {\n if (controller.isCancelled()) {\n return resultErr(makeCancelledError())\n }\n return result\n })\n\n return runPromise\n }\n\n const then: PromiseLike<ResultType<A, E | MultithreadError>>[\"then\"] = (onfulfilled, onrejected) =>\n start().then(onfulfilled, onrejected)\n\n return {\n _tag: \"MultithreadOp\",\n [FxTypeId]: {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Fx marker channels are phantom-only type metadata.\n _A: () => undefined as unknown as A,\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Fx marker channels are phantom-only type metadata.\n _E: () => undefined as unknown as E | MultithreadError,\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Fx marker channels are phantom-only type metadata.\n _R: () => undefined as never,\n },\n result: start,\n abort: () => {\n controller.cancel()\n },\n // oxlint-disable-next-line eslint-plugin-unicorn/no-thenable -- MultithreadOp is intentionally PromiseLike for `await op` ergonomics.\n then,\n async *[Symbol.asyncIterator](): AsyncGenerator<E | MultithreadError, A, unknown> {\n const fx = interruptibleAsync(\n (state) => start(runtimeSnapshotFromState(state)),\n () => {\n controller.cancel()\n },\n ) as unknown as {\n [Symbol.asyncIterator](): AsyncGenerator<E | MultithreadError, A, unknown>\n }\n return yield* fx\n },\n }\n}\n\nconst runWorkerLocally = async <Args extends readonly unknown[], A, E>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n args: Args,\n controller: InternalCancelController,\n runtimeSnapshot: MultithreadRuntimeSnapshot,\n): Promise<ResultType<A, E | MultithreadError>> => {\n if (controller.isCancelled()) {\n return resultErr(makeCancelledError())\n }\n\n const ctx: MultithreadCtx = {\n signal: controller.signal,\n runtime: runtimeSnapshot,\n isCancelled: () => controller.isCancelled(),\n throwIfCancelled: () => {\n if (controller.isCancelled()) throw new Error(CANCELLED_ERROR_MESSAGE)\n },\n }\n\n try {\n const value = await worker(...args, ctx)\n\n if (controller.isCancelled()) {\n return resultErr(makeCancelledError())\n }\n\n const normalized = normalizeWorkerReturn<A, E>(value)\n if (normalized._tag === \"Err\") {\n return resultErr(normalized.error)\n }\n\n return resultOk(normalized.value)\n } catch (cause) {\n if (controller.isCancelled() || isCancelledCause(cause)) {\n return resultErr(makeCancelledError())\n }\n return resultErr(makeWorkerExecutionError(\"Multithread worker failed during execution.\", cause))\n }\n}\n\nconst runDataFirst = <Args extends readonly unknown[], A, E>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n args: Args,\n): MultithreadOp<A, E | MultithreadError> =>\n createMultithreadOperation(async (controller, runtimeSnapshot): Promise<ResultType<A, E | MultithreadError>> => {\n if (controller.isCancelled()) {\n return resultErr(makeCancelledError())\n }\n\n const runtimeResult = await getRuntime()\n if (runtimeResult._tag === \"Err\") return resultErr(runtimeResult.error)\n\n const runtime = runtimeResult.value\n const entrypoint = createWorkerEntrypoint(worker)\n\n let joinHandle: ReturnType<MultithreadingRuntime[\"spawn\"]> | undefined\n\n try {\n const movedPayload = runtime.move(...args, controller.signal, runtimeSnapshot)\n joinHandle = runtime.spawn(movedPayload, entrypoint)\n controller.onCancel(() => {\n joinHandle?.abort()\n })\n } catch (cause) {\n if (isCallerLocationFailure(cause)) {\n return runWorkerLocally(worker, args, controller, runtimeSnapshot)\n }\n if (controller.isCancelled() || isCancelledCause(cause)) {\n return resultErr(makeCancelledError())\n }\n return resultErr(makeWorkerExecutionError(\"Failed to start multithread worker.\", cause))\n }\n\n try {\n const joined = await joinHandle.join()\n\n if (controller.isCancelled()) {\n return resultErr(makeCancelledError())\n }\n\n if (!joined.ok) {\n const joinError = joined.error ?? new Error(\"Multithread worker returned an unknown error.\")\n if (isCancelledCause(joinError)) {\n return resultErr(makeCancelledError())\n }\n return resultErr(makeWorkerExecutionError(\"Multithread worker failed during execution.\", joinError))\n }\n\n const normalized = normalizeWorkerReturn<A, E>(joined.value)\n if (normalized._tag === \"Err\") {\n return resultErr(normalized.error)\n }\n return resultOk(normalized.value)\n } catch (cause) {\n if (controller.isCancelled() || isCancelledCause(cause)) {\n return resultErr(makeCancelledError())\n }\n return resultErr(makeWorkerExecutionError(\"Failed to join multithread worker.\", cause))\n }\n })\n\nfunction runOverload<A, E = never>(\n worker: (ctx: MultithreadCtx) => WorkerReturn<A, E>,\n): MultithreadOp<A, E | MultithreadError>\nfunction runOverload<Args extends readonly unknown[], A, E = never>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n ...args: Args\n): MultithreadOp<A, E | MultithreadError>\nfunction runOverload(worker: unknown, ...args: unknown[]): MultithreadOp<unknown, unknown> {\n if (!isWorkerLike(worker)) {\n throw new TypeError(\"Multithread.run expects a worker function as first argument.\")\n }\n return runDataFirst(worker, args)\n}\n\n/**\n * Execute one worker task as a cancelable `MultithreadOp`.\n *\n * Use `run` when you need direct `result()`, `abort()`, `await op`, or explicit\n * sharing of one memoized operation.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const op = Multithread.run((input: string, ctx) => {\n * ctx.throwIfCancelled()\n * return input.toUpperCase()\n * }, \"hello\")\n *\n * const result = await op.result()\n * // => { _tag: \"Ok\", value: \"HELLO\" }\n * ```\n */\nexport const run: MultithreadRun = runOverload\n\nfunction taskOverload<A, E = never>(\n worker: (ctx: MultithreadCtx) => WorkerReturn<A, E>,\n): () => MultithreadOp<A, E | MultithreadError>\nfunction taskOverload<Args extends readonly unknown[], A, E = never>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n): (...args: Args) => MultithreadOp<A, E | MultithreadError>\nfunction taskOverload(worker: unknown): (...args: unknown[]) => MultithreadOp<unknown, unknown> {\n if (!isWorkerLike(worker)) {\n throw new TypeError(\"Multithread.task expects a worker function.\")\n }\n return (...args: unknown[]) => runDataFirst(worker, args)\n}\n\n/**\n * Create a reusable worker task factory.\n *\n * Each call to the returned function creates a fresh `MultithreadOp`.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const uppercase = Multithread.task((input: string, ctx) => {\n * ctx.throwIfCancelled()\n * return input.toUpperCase()\n * })\n *\n * const result = await uppercase(\"hello\").result()\n * // => { _tag: \"Ok\", value: \"HELLO\" }\n * ```\n */\nexport const task: MultithreadTask = taskOverload\n\nfunction fxOverload<A, E = never>(worker: (ctx: MultithreadCtx) => WorkerReturn<A, E>): AsyncFx<A, E | MultithreadError>\nfunction fxOverload<Args extends readonly unknown[], A, E = never>(\n worker: (...args: [...Args, MultithreadCtx]) => WorkerReturn<A, E>,\n ...args: Args\n): AsyncFx<A, E | MultithreadError>\nfunction fxOverload(worker: unknown, ...args: unknown[]): AsyncFx<unknown, unknown> {\n if (!isWorkerLike(worker)) {\n throw new TypeError(\"Multithread.fx expects a worker function as first argument.\")\n }\n\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown,\n _E: () => undefined as unknown,\n _R: () => undefined as never,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<unknown, never>, unknown, unknown> {\n return yield* runDataFirst(worker, args)\n },\n } as AsyncFx<unknown, unknown>\n}\n\n/**\n * Create a fresh worker-backed Fx for each execution.\n *\n * Prefer this inside reusable `Fx.gen` programs. Use `run` when you need a\n * lower-level operation handle, manual cancellation, or explicit sharing.\n *\n * @example\n * ```ts\n * import { Fx, Multithread } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(async function* () {\n * return yield* Multithread.fx((input: number, ctx) => {\n * ctx.throwIfCancelled()\n * return input * 2\n * }, 21)\n * })\n *\n * const exit = await Fx.run(program)\n * // => { _tag: \"Ok\", value: 42 }\n * ```\n */\nexport const fx: MultithreadFx = fxOverload\n\nconst executeInParallel = <A, B, E>(\n values: readonly A[],\n createItemOperation: (value: A, index: number) => MultithreadOp<B, E | MultithreadError>,\n parallelism: number,\n controller: InternalCancelController,\n): Promise<ResultType<readonly B[], E | MultithreadError>> => {\n if (values.length === 0) {\n return Promise.resolve(resultOk<readonly B[]>([]))\n }\n\n return new Promise<ResultType<readonly B[], E | MultithreadError>>((resolve) => {\n const operations = new Map<number, MultithreadOp<B, E | MultithreadError>>()\n const output: B[] = []\n\n let inFlight = 0\n let nextIndex = 0\n let completed = 0\n let settled = false\n\n const abortAll = (): void => {\n for (const operation of operations.values()) {\n operation.abort()\n }\n operations.clear()\n }\n\n const settle = (result: ResultType<readonly B[], E | MultithreadError>): void => {\n if (settled) return\n settled = true\n abortAll()\n resolve(result)\n }\n\n controller.onCancel(() => {\n settle(resultErr(makeCancelledError()))\n })\n\n const handleOperation = (index: number, operation: MultithreadOp<B, E | MultithreadError>): void => {\n void (async () => {\n try {\n const result = await operation.result()\n\n inFlight -= 1\n operations.delete(index)\n\n if (settled) return\n\n if (result._tag === \"Err\") {\n settle(resultErr(result.error))\n return\n }\n\n output[index] = result.value\n completed += 1\n\n if (completed === values.length) {\n settled = true\n resolve(resultOk(output))\n return\n }\n\n launch()\n } catch (cause) {\n inFlight -= 1\n operations.delete(index)\n\n if (settled) return\n\n if (controller.isCancelled() || isCancelledCause(cause)) {\n settle(resultErr(makeCancelledError()))\n return\n }\n\n settle(resultErr(makeWorkerExecutionError(\"Failed while executing multithread batch.\", cause)))\n }\n })()\n }\n\n const launch = (): void => {\n while (!settled && inFlight < parallelism && nextIndex < values.length) {\n const index = nextIndex\n nextIndex += 1\n\n const operation = createItemOperation(values[index]!, index)\n operations.set(index, operation)\n inFlight += 1\n\n handleOperation(index, operation)\n }\n }\n\n launch()\n })\n}\n\nconst mapDataFirst = <A, B, E>(\n values: readonly A[],\n worker: MultithreadMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly B[], E | MultithreadError> =>\n createMultithreadOperation((controller) => {\n const parallelism = normalizeParallelism(options?.parallelism, getDefaultParallelism())\n return executeInParallel(values, (value, index) => runDataFirst(worker, [value, index]), parallelism, controller)\n })\n\nfunction mapOverload<A, B, E = never>(\n values: readonly A[],\n worker: MultithreadMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly B[], E | MultithreadError>\nfunction mapOverload<A, B, E = never, InputE = never>(\n values: ResultType<readonly A[], InputE>,\n worker: MultithreadMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\nfunction mapOverload<A, B, E = never>(\n worker: MultithreadMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>\nfunction mapOverload<A, B, E = never, InputE = never>(\n valuesOrWorker: readonly A[] | ResultType<readonly A[], InputE> | MultithreadMapWorker<A, B, E>,\n workerOrOptions?: MultithreadMapWorker<A, B, E> | MultithreadParallelOptions,\n options?: MultithreadParallelOptions,\n):\n | MultithreadOp<readonly B[], E | MultithreadError>\n | Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\n | (<Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>) {\n if (typeof valuesOrWorker === \"function\") {\n const curriedOptions = resolveParallelOptions(workerOrOptions)\n return ((values: readonly A[] | ResultType<readonly A[], unknown>) =>\n runFromInputResult(values, (resolvedValues) =>\n mapDataFirst(resolvedValues as readonly A[], valuesOrWorker, curriedOptions),\n )) as <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>\n }\n\n if (typeof workerOrOptions !== \"function\") {\n throw new TypeError(\"Multithread.map(values, worker, options) requires a worker function.\")\n }\n\n return runFromInputResult(valuesOrWorker, (resolvedValues) =>\n mapDataFirst(resolvedValues as readonly A[], workerOrOptions, options),\n ) as\n | MultithreadOp<readonly B[], E | MultithreadError>\n | Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\n}\n\n/**\n * Map a collection in parallel.\n *\n * The `parallelism` option controls how many item operations this call keeps in\n * flight. Runtime execution is still bounded by the configured worker count.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const result = await Multithread.map(\n * [1, 2, 3],\n * (value, _index, ctx) => {\n * ctx.throwIfCancelled()\n * return value * 2\n * },\n * { parallelism: 2 },\n * ).result()\n * // => { _tag: \"Ok\", value: [2, 4, 6] }\n * ```\n */\nexport const map: MultithreadMap = mapOverload\n\nconst forEachDataFirst = <A, E>(\n values: readonly A[],\n worker: MultithreadMapWorker<A, unknown, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<void, E | MultithreadError> =>\n createMultithreadOperation(async (controller): Promise<ResultType<void, E | MultithreadError>> => {\n const mapped = await executeInParallel(\n values,\n (value, index) => runDataFirst(worker, [value, index]),\n normalizeParallelism(options?.parallelism, getDefaultParallelism()),\n controller,\n )\n\n if (mapped._tag === \"Err\") return resultErr(mapped.error)\n return resultOk(undefined)\n })\n\nfunction forEachOverload<A, E = never>(\n values: readonly A[],\n worker: MultithreadMapWorker<A, unknown, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<void, E | MultithreadError>\nfunction forEachOverload<A, E = never, InputE = never>(\n values: ResultType<readonly A[], InputE>,\n worker: MultithreadMapWorker<A, unknown, E>,\n options?: MultithreadParallelOptions,\n): Promise<ResultType<void, E | InputE | MultithreadError>>\nfunction forEachOverload<A, E = never>(\n worker: MultithreadMapWorker<A, unknown, E>,\n options?: MultithreadParallelOptions,\n): <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<void, E | ResultInputE | MultithreadError>>\n : MultithreadOp<void, E | MultithreadError>\nfunction forEachOverload<A, E = never, InputE = never>(\n valuesOrWorker: readonly A[] | ResultType<readonly A[], InputE> | MultithreadMapWorker<A, unknown, E>,\n workerOrOptions?: MultithreadMapWorker<A, unknown, E> | MultithreadParallelOptions,\n options?: MultithreadParallelOptions,\n):\n | MultithreadOp<void, E | MultithreadError>\n | Promise<ResultType<void, E | InputE | MultithreadError>>\n | (<Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<void, E | ResultInputE | MultithreadError>>\n : MultithreadOp<void, E | MultithreadError>) {\n if (typeof valuesOrWorker === \"function\") {\n const curriedOptions = resolveParallelOptions(workerOrOptions)\n return ((values: readonly A[] | ResultType<readonly A[], unknown>) =>\n runFromInputResult(values, (resolvedValues) =>\n forEachDataFirst(resolvedValues as readonly A[], valuesOrWorker, curriedOptions),\n )) as <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<void, E | ResultInputE | MultithreadError>>\n : MultithreadOp<void, E | MultithreadError>\n }\n\n if (typeof workerOrOptions !== \"function\") {\n throw new TypeError(\"Multithread.forEach(values, worker, options) requires a worker function.\")\n }\n\n return runFromInputResult(valuesOrWorker, (resolvedValues) =>\n forEachDataFirst(resolvedValues as readonly A[], workerOrOptions, options),\n ) as MultithreadOp<void, E | MultithreadError> | Promise<ResultType<void, E | InputE | MultithreadError>>\n}\n\n/**\n * Run side-effecting parallel work for each item.\n *\n * Use this when only completion matters. If you need collected values, use\n * `map`.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const result = await Multithread.forEach([\"a\", \"b\"], (value, _index, ctx) => {\n * ctx.throwIfCancelled()\n * return value.toUpperCase()\n * }).result()\n * // => { _tag: \"Ok\", value: undefined }\n * ```\n */\nexport const forEach: MultithreadForEach = forEachOverload\n\nconst filterDataFirst = <A, E>(\n values: readonly A[],\n worker: MultithreadFilterWorker<A, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly A[], E | MultithreadError> =>\n createMultithreadOperation(async (controller): Promise<ResultType<readonly A[], E | MultithreadError>> => {\n const decisions = await executeInParallel(\n values,\n (value, index) => runDataFirst(worker, [value, index]),\n normalizeParallelism(options?.parallelism, getDefaultParallelism()),\n controller,\n )\n\n if (decisions._tag === \"Err\") return resultErr(decisions.error)\n\n const filtered: A[] = []\n for (let index = 0; index < values.length; index += 1) {\n if (decisions.value[index] === true) {\n filtered.push(values[index]!)\n }\n }\n\n return resultOk(filtered)\n })\n\nfunction filterOverload<A, E = never>(\n values: readonly A[],\n worker: MultithreadFilterWorker<A, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly A[], E | MultithreadError>\nfunction filterOverload<A, E = never, InputE = never>(\n values: ResultType<readonly A[], InputE>,\n worker: MultithreadFilterWorker<A, E>,\n options?: MultithreadParallelOptions,\n): Promise<ResultType<readonly A[], E | InputE | MultithreadError>>\nfunction filterOverload<A, E = never>(\n worker: MultithreadFilterWorker<A, E>,\n options?: MultithreadParallelOptions,\n): <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly A[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly A[], E | MultithreadError>\nfunction filterOverload<A, E = never, InputE = never>(\n valuesOrWorker: readonly A[] | ResultType<readonly A[], InputE> | MultithreadFilterWorker<A, E>,\n workerOrOptions?: MultithreadFilterWorker<A, E> | MultithreadParallelOptions,\n options?: MultithreadParallelOptions,\n):\n | MultithreadOp<readonly A[], E | MultithreadError>\n | Promise<ResultType<readonly A[], E | InputE | MultithreadError>>\n | (<Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly A[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly A[], E | MultithreadError>) {\n if (typeof valuesOrWorker === \"function\") {\n const curriedOptions = resolveParallelOptions(workerOrOptions)\n return ((values: readonly A[] | ResultType<readonly A[], unknown>) =>\n runFromInputResult(values, (resolvedValues) =>\n filterDataFirst(resolvedValues as readonly A[], valuesOrWorker, curriedOptions),\n )) as <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly A[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly A[], E | MultithreadError>\n }\n\n if (typeof workerOrOptions !== \"function\") {\n throw new TypeError(\"Multithread.filter(values, worker, options) requires a worker function.\")\n }\n\n return runFromInputResult(valuesOrWorker, (resolvedValues) =>\n filterDataFirst(resolvedValues as readonly A[], workerOrOptions, options),\n ) as\n | MultithreadOp<readonly A[], E | MultithreadError>\n | Promise<ResultType<readonly A[], E | InputE | MultithreadError>>\n}\n\n/**\n * Filter a collection in parallel.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const result = await Multithread.filter([1, 2, 3, 4], (value, _index, ctx) => {\n * ctx.throwIfCancelled()\n * return value % 2 === 0\n * }).result()\n * // => { _tag: \"Ok\", value: [2, 4] }\n * ```\n */\nexport const filter: MultithreadFilter = filterOverload\n\nconst flatMapDataFirst = <A, B, E>(\n values: readonly A[],\n worker: MultithreadFlatMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly B[], E | MultithreadError> =>\n createMultithreadOperation(async (controller): Promise<ResultType<readonly B[], E | MultithreadError>> => {\n const chunks = await executeInParallel(\n values,\n (value, index) => runDataFirst(worker, [value, index]),\n normalizeParallelism(options?.parallelism, getDefaultParallelism()),\n controller,\n )\n\n if (chunks._tag === \"Err\") return resultErr(chunks.error)\n\n const flattened: B[] = []\n for (const chunk of chunks.value) {\n flattened.push(...chunk)\n }\n\n return resultOk(flattened)\n })\n\nfunction flatMapOverload<A, B, E = never>(\n values: readonly A[],\n worker: MultithreadFlatMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): MultithreadOp<readonly B[], E | MultithreadError>\nfunction flatMapOverload<A, B, E = never, InputE = never>(\n values: ResultType<readonly A[], InputE>,\n worker: MultithreadFlatMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\nfunction flatMapOverload<A, B, E = never>(\n worker: MultithreadFlatMapWorker<A, B, E>,\n options?: MultithreadParallelOptions,\n): <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>\nfunction flatMapOverload<A, B, E = never, InputE = never>(\n valuesOrWorker: readonly A[] | ResultType<readonly A[], InputE> | MultithreadFlatMapWorker<A, B, E>,\n workerOrOptions?: MultithreadFlatMapWorker<A, B, E> | MultithreadParallelOptions,\n options?: MultithreadParallelOptions,\n):\n | MultithreadOp<readonly B[], E | MultithreadError>\n | Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\n | (<Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>) {\n if (typeof valuesOrWorker === \"function\") {\n const curriedOptions = resolveParallelOptions(workerOrOptions)\n return ((values: readonly A[] | ResultType<readonly A[], unknown>) =>\n runFromInputResult(values, (resolvedValues) =>\n flatMapDataFirst(resolvedValues as readonly A[], valuesOrWorker, curriedOptions),\n )) as <Input extends readonly A[] | ResultType<readonly A[], unknown>>(\n values: Input,\n ) => Input extends ResultType<readonly A[], infer ResultInputE>\n ? Promise<ResultType<readonly B[], E | ResultInputE | MultithreadError>>\n : MultithreadOp<readonly B[], E | MultithreadError>\n }\n\n if (typeof workerOrOptions !== \"function\") {\n throw new TypeError(\"Multithread.flatMap(values, worker, options) requires a worker function.\")\n }\n\n return runFromInputResult(valuesOrWorker, (resolvedValues) =>\n flatMapDataFirst(resolvedValues as readonly A[], workerOrOptions, options),\n ) as\n | MultithreadOp<readonly B[], E | MultithreadError>\n | Promise<ResultType<readonly B[], E | InputE | MultithreadError>>\n}\n\n/**\n * Flat-map a collection in parallel.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const result = await Multithread.flatMap([1, 2], (value, _index, ctx) => {\n * ctx.throwIfCancelled()\n * return [value, value * 10]\n * }).result()\n * // => { _tag: \"Ok\", value: [1, 10, 2, 20] }\n * ```\n */\nexport const flatMap: MultithreadFlatMap = flatMapOverload\n\nconst raceDataFirst = <A, E>(operations: readonly MultithreadOp<A, E>[]): MultithreadOp<A, E | MultithreadError> =>\n createMultithreadOperation((controller): Promise<ResultType<A, E | MultithreadError>> => {\n if (operations.length === 0) {\n return Promise.resolve(resultErr(makeAllFailedError(\"Cannot race an empty list of operations.\", [])))\n }\n\n return new Promise<ResultType<A, E | MultithreadError>>((resolve) => {\n let settled = false\n\n const abortAll = (): void => {\n for (const operation of operations) {\n operation.abort()\n }\n }\n\n const settle = (result: ResultType<A, E | MultithreadError>): void => {\n if (settled) return\n settled = true\n abortAll()\n resolve(result)\n }\n\n controller.onCancel(() => {\n settle(resultErr(makeCancelledError()))\n })\n\n const watchOperation = (operation: MultithreadOp<A, E>): void => {\n void (async () => {\n try {\n const result = await operation.result()\n settle(result)\n } catch (cause) {\n if (controller.isCancelled() || isCancelledCause(cause)) {\n settle(resultErr(makeCancelledError()))\n return\n }\n\n settle(resultErr(makeWorkerExecutionError(\"Multithread race failed.\", cause)))\n }\n })()\n }\n\n for (const operation of operations) {\n watchOperation(operation)\n }\n })\n })\n\nfunction raceOverload<A, E>(operations: readonly MultithreadOp<A, E>[]): MultithreadOp<A, E | MultithreadError>\nfunction raceOverload<A, E, InputE = never>(\n operations: ResultType<readonly MultithreadOp<A, E>[], InputE>,\n): Promise<ResultType<A, E | InputE | MultithreadError>>\nfunction raceOverload<Ops extends readonly MultithreadOp<unknown, unknown>[]>(\n operations: Ops,\n): MultithreadOp<\n Ops[number] extends MultithreadOp<infer A, unknown> ? A : never,\n (Ops[number] extends MultithreadOp<unknown, infer OpE> ? OpE : never) | MultithreadError\n>\nfunction raceOverload<Ops extends readonly MultithreadOp<unknown, unknown>[], InputE = never>(\n operations: ResultType<Ops, InputE>,\n): Promise<\n ResultType<\n Ops[number] extends MultithreadOp<infer A, unknown> ? A : never,\n (Ops[number] extends MultithreadOp<unknown, infer OpE> ? OpE : never) | InputE | MultithreadError\n >\n>\nfunction raceOverload(\n operations:\n | readonly MultithreadOp<unknown, unknown>[]\n | ResultType<readonly MultithreadOp<unknown, unknown>[], unknown>,\n): MultithreadOp<unknown, unknown> | Promise<ResultType<unknown, unknown>> {\n return runFromInputResult(operations, (resolvedOperations) =>\n raceDataFirst(resolvedOperations as readonly MultithreadOp<unknown, unknown>[]),\n )\n}\n\n/**\n * Resolve with the first settled operation.\n *\n * The winner may be successful or failed. All remaining operations are aborted\n * after the first operation settles.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const fast = Multithread.run(() => \"fast\")\n * const slow = Multithread.run(async () => {\n * await new Promise((resolve) => {\n * setTimeout(resolve, 50)\n * })\n * return \"slow\"\n * })\n *\n * const result = await Multithread.race([fast, slow]).result()\n * // => { _tag: \"Ok\", value: \"fast\" }\n * ```\n */\nexport const race: MultithreadRace = raceOverload\n\nconst firstSuccessDataFirst = <A, E>(\n operations: readonly MultithreadOp<A, E>[],\n): MultithreadOp<A, E | MultithreadError> =>\n createMultithreadOperation((controller): Promise<ResultType<A, E | MultithreadError>> => {\n if (operations.length === 0) {\n return Promise.resolve(\n resultErr(makeAllFailedError(\"Cannot select a first success from an empty list of operations.\", [])),\n )\n }\n\n return new Promise<ResultType<A, E | MultithreadError>>((resolve) => {\n const failures: unknown[] = Array.from({ length: operations.length })\n let pending = operations.length\n let settled = false\n\n const abortAll = (): void => {\n for (const operation of operations) {\n operation.abort()\n }\n }\n\n const settle = (result: ResultType<A, E | MultithreadError>): void => {\n if (settled) return\n settled = true\n abortAll()\n resolve(result)\n }\n\n controller.onCancel(() => {\n settle(resultErr(makeCancelledError()))\n })\n\n const watchOperation = (operation: MultithreadOp<A, E>, index: number): void => {\n void (async () => {\n try {\n const result = await operation.result()\n\n if (settled) return\n\n if (result._tag === \"Ok\") {\n settle(resultOk(result.value))\n return\n }\n\n failures[index] = result.error\n pending -= 1\n\n if (pending === 0) {\n settle(\n resultErr(\n makeAllFailedError(\n \"All multithread operations failed before any success was produced.\",\n failures.filter((failure) => failure !== undefined),\n ),\n ),\n )\n }\n } catch (cause) {\n if (settled) return\n\n if (controller.isCancelled() || isCancelledCause(cause)) {\n settle(resultErr(makeCancelledError()))\n return\n }\n\n failures[index] = makeWorkerExecutionError(\"Multithread operation rejected unexpectedly.\", cause)\n pending -= 1\n\n if (pending === 0) {\n settle(\n resultErr(\n makeAllFailedError(\n \"All multithread operations failed before any success was produced.\",\n failures.filter((failure) => failure !== undefined),\n ),\n ),\n )\n }\n }\n })()\n }\n\n operations.forEach((operation, index) => {\n watchOperation(operation, index)\n })\n })\n })\n\nfunction firstSuccessOverload<A, E>(operations: readonly MultithreadOp<A, E>[]): MultithreadOp<A, E | MultithreadError>\nfunction firstSuccessOverload<A, E, InputE = never>(\n operations: ResultType<readonly MultithreadOp<A, E>[], InputE>,\n): Promise<ResultType<A, E | InputE | MultithreadError>>\nfunction firstSuccessOverload<Ops extends readonly MultithreadOp<unknown, unknown>[]>(\n operations: Ops,\n): MultithreadOp<\n Ops[number] extends MultithreadOp<infer A, unknown> ? A : never,\n (Ops[number] extends MultithreadOp<unknown, infer OpE> ? OpE : never) | MultithreadError\n>\nfunction firstSuccessOverload<Ops extends readonly MultithreadOp<unknown, unknown>[], InputE = never>(\n operations: ResultType<Ops, InputE>,\n): Promise<\n ResultType<\n Ops[number] extends MultithreadOp<infer A, unknown> ? A : never,\n (Ops[number] extends MultithreadOp<unknown, infer OpE> ? OpE : never) | InputE | MultithreadError\n >\n>\nfunction firstSuccessOverload(\n operations:\n | readonly MultithreadOp<unknown, unknown>[]\n | ResultType<readonly MultithreadOp<unknown, unknown>[], unknown>,\n): MultithreadOp<unknown, unknown> | Promise<ResultType<unknown, unknown>> {\n return runFromInputResult(operations, (resolvedOperations) =>\n firstSuccessDataFirst(resolvedOperations as readonly MultithreadOp<unknown, unknown>[]),\n )\n}\n\n/**\n * Return the first successful operation, aggregating failures if none succeed.\n *\n * @example\n * ```ts\n * import { Multithread, Result } from \"@nicolastoulemont/std\"\n *\n * const fail = Multithread.run(() => Result.err(\"boom\"))\n * const pass = Multithread.run(() => Result.ok(1))\n *\n * const result = await Multithread.firstSuccess([fail, pass]).result()\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n */\nexport const firstSuccess: MultithreadFirstSuccess = firstSuccessOverload\n\n/**\n * Configure max worker count used by the underlying runtime.\n *\n * Must be called before first multithread operation starts.\n * Use `layer` instead when the worker runtime should follow an `Fx` scope.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const configured = Multithread.configure({ maxWorkers: 4 })\n * // => { _tag: \"Ok\", value: undefined }\n * ```\n */\nexport const configure = (config: { maxWorkers: number }): ResultType<void, MultithreadError> => {\n if (runtimeInitialized) {\n return resultErr(makeRuntimeAlreadyInitializedError())\n }\n\n runtimeConfig = {\n maxWorkers: normalizeParallelism(config.maxWorkers, 1),\n }\n\n return resultOk(undefined)\n}\n\nconst makeShutdownDefect = (cause: MultithreadError): Error => {\n const defect = new Error(\"Failed to shutdown multithread runtime while closing scope.\") as Error & { cause?: unknown }\n defect.cause = cause\n return defect\n}\n\n/**\n * Create an Fx layer that configures and shuts down the shared worker runtime.\n *\n * The underlying `multithreading` runtime is process-global, so the layer makes\n * that lifecycle visible to `Fx` scopes rather than creating a per-fiber pool.\n *\n * @example\n * ```ts\n * import { Fx, Multithread, Provide } from \"@nicolastoulemont/std\"\n *\n * const program = Provide.layer(Multithread.layer({ maxWorkers: 2 }))(\n * Fx.gen(async function* () {\n * return yield* Multithread.fx(() => 42)\n * }),\n * )\n *\n * const exit = await Fx.run(program)\n * // => { _tag: \"Ok\", value: 42 }\n * ```\n */\nexport const layer: MultithreadLayer = (config) => ({\n _tag: \"Layer\",\n _ROut: undefined as never,\n _E: undefined as unknown as MultithreadError,\n _RIn: undefined as never,\n _Sync: undefined as unknown as false,\n build: (_memoMap, scope): AsyncFx<Context.Context, MultithreadError> => ({\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as Context.Context,\n _E: () => undefined as unknown as MultithreadError,\n _R: () => undefined as never,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<MultithreadError, never>, Context.Context, unknown> {\n const configured = configure(config)\n if (configured._tag === \"Err\") {\n yield configured.error\n throw new Error(\"Unreachable: Fx runtime should short-circuit on yielded Multithread layer errors.\")\n }\n\n const runtimeResult = await getRuntime()\n if (runtimeResult._tag === \"Err\") {\n yield runtimeResult.error\n throw new Error(\"Unreachable: Fx runtime should short-circuit on yielded Multithread layer errors.\")\n }\n\n yield* scope.addFinalizer(() => ({\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<never, never>, void, unknown> {\n const result = await shutdown()\n if (result._tag === \"Err\") {\n throw makeShutdownDefect(result.error)\n }\n },\n }))\n\n return Context.empty()\n },\n }),\n})\n\n/**\n * Shutdown worker runtime.\n *\n * This function is idempotent.\n * Direct users can call it in test cleanup or process teardown. `layer` calls it\n * automatically when the owning scope closes.\n *\n * @example\n * ```ts\n * import { Multithread } from \"@nicolastoulemont/std\"\n *\n * const result = await Multithread.shutdown()\n * // => { _tag: \"Ok\", value: undefined }\n * ```\n */\nexport const shutdown = async (): Promise<ResultType<void, MultithreadError>> => {\n if (!runtimeInitialized) {\n return resultOk(undefined)\n }\n\n const runtimeResult = await loadRuntimeModule()\n if (runtimeResult._tag === \"Err\") {\n runtimeInitialized = false\n return resultErr(runtimeResult.error)\n }\n\n try {\n runtimeResult.value.shutdown()\n return resultOk(undefined)\n } catch (cause) {\n return resultErr(makeWorkerExecutionError(\"Failed to shutdown multithreading runtime.\", cause))\n } finally {\n runtimeInitialized = false\n }\n}\n"],"mappings":"qYA8IA,MAAM,EAA0B,8CAEhC,IAAI,EACA,EAAqB,GACrB,EAEJ,MAAM,EAAwB,IAAI,QAE5B,OAA0D,CAC9D,QAAS,IAAA,GACT,UAAW,EAAE,CACb,MAAO,IAAA,GACR,EAEK,EACJ,GAEA,OAAO,GAAU,YACjB,GACA,YAAa,GACb,OAAO,EAAM,SAAY,UACzB,WAAY,GACZ,OAAO,EAAM,QAAW,SAEpB,EAAwB,GAAuD,CAC/E,YAAO,GAAS,WAAY,GAIhC,IAAI,YAAa,GAAQ,EAAc,EAAK,QAAQ,CAClD,MAAO,CACL,QAAS,EAAK,QAAQ,QACtB,OAAQ,EAAK,QAAQ,OACrB,GAAI,EAAK,QAAQ,aAAe,IAAA,GAAY,EAAE,CAAG,CAAE,WAAY,EAAK,QAAQ,WAAY,CACzF,CAGH,GAAI,EAAc,EAAK,CACrB,MAAO,CACL,QAAS,EAAK,QACd,OAAQ,EAAK,OACb,GAAI,EAAK,aAAe,IAAA,GAAY,EAAE,CAAG,CAAE,WAAY,EAAK,WAAY,CACzE,GAMC,EAA4B,IAAqD,CACrF,QAAS,EAAM,QACf,UAAW,CAAE,GAAG,EAAM,UAAW,CACjC,MAAO,EAAqB,EAAM,YAAY,CAC/C,EAEK,IACJ,EACA,EAAU,mGAC8B,CACxC,KAAM,qCACN,UACA,QACD,EAEK,IACJ,EAAU,iFACqC,CAC/C,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
1
- import { t as option_d_exports } from "../index-BqJ1GWAF.mjs";
1
+ import { t as option_d_exports } from "../index-pC80zLHb.mjs";
2
2
  export { option_d_exports as Option };
@@ -1 +1 @@
1
- import{r as e}from"../option-C2iCxAuJ.mjs";export{e as Option};
1
+ import{r as e}from"../option-BlyP5LA2.mjs";export{e as Option};
@@ -1,2 +1,2 @@
1
- import{t as e}from"./chunk-oQKkju2G.mjs";import{t}from"./fx.types-DyQVgTS8.mjs";import{t as n}from"./dual-fN6OUwN_.mjs";import{n as r}from"./flow-CNyLsPGb.mjs";import{t as i}from"./pipeable-Dp1_23zH.mjs";import{t as a}from"./option.types-CbY_swma.mjs";var o=e({NoSuchElementError:()=>s,all:()=>_,filter:()=>g,flatMap:()=>p,fromNullable:()=>S,fromTry:()=>C,isNone:()=>d,isSome:()=>u,map:()=>f,match:()=>b,none:()=>l,orElse:()=>h,some:()=>c,tap:()=>m,unwrapOr:()=>v,unwrapOrElse:()=>y});const s=a,c=e=>({_tag:`Some`,value:e,[t]:{_A:()=>e,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){return e}}),l=()=>({_tag:`None`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){throw yield new s,Error(`Unreachable: Fx.gen should short-circuit on NoSuchElementError`)}}),u=e=>e._tag===`Some`,d=e=>e._tag===`None`,f=n(2,(e,t)=>{if(e._tag===`None`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(c):c(n)}),p=n(2,(e,t)=>e._tag===`Some`?t(e.value):e),m=n(2,(e,t)=>{if(e._tag===`None`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),h=n(2,(e,t)=>e._tag===`Some`?e:t()),g=n(2,(e,t)=>e._tag===`None`||t(e.value)?e:l()),_=e=>{if(Array.isArray(e)){let t=[];for(let n of e){if(n._tag===`None`)return n;t.push(n.value)}return c(t)}let t={};for(let[n,r]of Object.entries(e)){let e=r;if(e._tag===`None`)return r;t[n]=e.value}return c(t)},v=n(2,(e,t)=>e._tag===`Some`?e.value:t),y=n(2,(e,t)=>e._tag===`Some`?e.value:t()),b=n(2,(e,t)=>e._tag===`Some`?t.Some(e.value):t.None()),x=e=>e!=null,S=e=>x(e)?c(e):l(),C=e=>{try{let t=e();return r(t)?Promise.resolve(t).then(c).catch(()=>l()):c(t)}catch{return l()}};export{c as i,l as n,o as r,S as t};
2
- //# sourceMappingURL=option-C2iCxAuJ.mjs.map
1
+ import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{t as n}from"./dual-CZhzZslG.mjs";import{n as r}from"./flow-D8_tllWl.mjs";import{t as i}from"./pipeable-COGyGMUV.mjs";import{t as a}from"./option.types-bFFSErJ-.mjs";var o=e({NoSuchElementError:()=>s,all:()=>_,filter:()=>g,flatMap:()=>p,fromNullable:()=>S,fromTry:()=>C,isNone:()=>d,isSome:()=>u,map:()=>f,match:()=>b,none:()=>l,orElse:()=>h,some:()=>c,tap:()=>m,unwrapOr:()=>v,unwrapOrElse:()=>y});const s=a,c=e=>({_tag:`Some`,value:e,[t]:{_A:()=>e,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){return e}}),l=()=>({_tag:`None`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){throw yield new s,Error(`Unreachable: Fx.gen should short-circuit on NoSuchElementError`)}}),u=e=>e._tag===`Some`,d=e=>e._tag===`None`,f=n(2,(e,t)=>{if(e._tag===`None`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(c):c(n)}),p=n(2,(e,t)=>e._tag===`Some`?t(e.value):e),m=n(2,(e,t)=>{if(e._tag===`None`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),h=n(2,(e,t)=>e._tag===`Some`?e:t()),g=n(2,(e,t)=>e._tag===`None`||t(e.value)?e:l()),_=e=>{if(Array.isArray(e)){let t=[];for(let n of e){if(n._tag===`None`)return n;t.push(n.value)}return c(t)}let t={};for(let[n,r]of Object.entries(e)){let e=r;if(e._tag===`None`)return r;t[n]=e.value}return c(t)},v=n(2,(e,t)=>e._tag===`Some`?e.value:t),y=n(2,(e,t)=>e._tag===`Some`?e.value:t()),b=n(2,(e,t)=>e._tag===`Some`?t.Some(e.value):t.None()),x=e=>e!=null,S=e=>x(e)?c(e):l(),C=e=>{try{let t=e();return r(t)?Promise.resolve(t).then(c).catch(()=>l()):c(t)}catch{return l()}};export{c as i,l as n,o as r,S as t};
2
+ //# sourceMappingURL=option-BlyP5LA2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"option-C2iCxAuJ.mjs","names":["NoSuchElementErrorCtor","values"],"sources":["../src/option/option.ts"],"sourcesContent":["/**\n * Optional value primitives for modeling presence (`Some`) and absence (`None`).\n *\n * **Mental model**\n * - `Option<A>` is either a value or no value.\n * - Prefer `Option` when missing data is expected and not exceptional.\n *\n * **Common tasks**\n * - Construct with `Option.some`, `Option.none`, `Option.fromNullable`.\n * - Transform with `Option.map`, `Option.flatMap`, `Option.filter`.\n * - Extract with `Option.unwrapOr`, `Option.match`.\n *\n * **Gotchas**\n * - `Option.none` short-circuits in `Fx.gen`.\n * - Use `Option.match` for exhaustive branch handling.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const name = Option.fromNullable(\"Ada\")\n * const upper = Option.map(name, (value) => value.toUpperCase())\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport { dual } from \"../shared/dual\"\nimport { isPromise } from \"../shared/is-promise\"\nimport { pipeable } from \"../shared/pipeable\"\nimport { NoSuchElementError as NoSuchElementErrorCtor } from \"./option.types\"\nimport type {\n Option as OptionType,\n OptionAll,\n OptionFlatMap,\n OptionMap,\n OptionMatch,\n OptionTap,\n OptionOrElse,\n OptionFilter,\n OptionUnwrapOr,\n OptionUnwrapOrElse,\n FromTryReturn,\n} from \"./option.types\"\n\n/**\n * Re-exported error type used when yielding `Option.none()` in `Fx.gen`.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const error = new Option.NoSuchElementError()\n * // => error.name === \"NoSuchElementError\"\n * ```\n */\nexport const NoSuchElementError = NoSuchElementErrorCtor\n\n/**\n * Re-exported `NoSuchElementError` instance type.\n *\n * @example\n * ```ts\n * import type { Option } from \"@nicolastoulemont/std\"\n *\n * type Example = Option.NoSuchElementError\n * ```\n */\nexport type NoSuchElementError = InstanceType<typeof NoSuchElementErrorCtor>\n\n/**\n * Re-exported `Option` type.\n *\n * @example\n * ```ts\n * import type { Option } from \"@nicolastoulemont/std\"\n *\n * type Example = Option.Option<unknown>\n * ```\n */\nexport type Option<T> = OptionType<T>\n\n/* oxlint-disable no-unsafe-type-assertion -- Option runtime values carry erased Fx phantom channels that require explicit marker assertions. */\n\n// ============================================================================\n// Constructors\n// ============================================================================\n\n/**\n * Create an Option with a value.\n *\n * @param value - The value to wrap\n * @returns An Option with `_tag: \"Some\"`\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.some(42)\n * // => { _tag: \"Some\", value: 42 }\n * ```\n */\nexport const some = <T>(value: T): OptionType<T> => ({\n _tag: \"Some\",\n value,\n [FxTypeId]: {\n _A: () => value,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<NoSuchElementError, T, unknown> {\n return value\n },\n})\n\n/**\n * Create an Option with no value.\n *\n * @returns An Option with `_tag: \"None\"`\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.none<number>()\n * // => { _tag: \"None\" }\n * ```\n */\nexport const none = <T = never>(): OptionType<T> => ({\n _tag: \"None\",\n [FxTypeId]: {\n _A: () => undefined as never,\n _E: () => undefined as unknown as NoSuchElementError,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n *[Symbol.iterator](): Generator<NoSuchElementError, never, unknown> {\n yield new NoSuchElementError()\n throw new Error(\"Unreachable: Fx.gen should short-circuit on NoSuchElementError\")\n },\n})\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Check if an Option has a value.\n *\n * @param option - The Option to check\n * @returns true if the Option is some\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.isSome(Option.some(1))\n * // => true\n * ```\n */\nexport const isSome = <T>(option: OptionType<T>): option is Extract<OptionType<T>, { _tag: \"Some\" }> =>\n option._tag === \"Some\"\n\n/**\n * isNone utility.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.isNone(Option.none())\n * // => true\n * ```\n */\nexport const isNone = <T>(option: OptionType<T>): option is Extract<OptionType<T>, { _tag: \"None\" }> =>\n option._tag === \"None\"\n\n// ============================================================================\n// Transformations (curried for pipe)\n// ============================================================================\n\n/**\n * Transform the value of an Option.\n * If the Option is none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `map(option, fn)`\n * - Data-last: `pipe(option, map(fn))`\n *\n * Supports both sync and async callbacks:\n * - Sync fn: returns U\n * - Async fn: returns Promise<U>\n *\n * @param fn - Function that transforms the contained value\n * @returns The mapped Option in data-first form, or a function that maps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.map(input, (n) => n + 1)\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.map((n: number) => n + 1)(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const map: OptionMap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) => {\n if (option._tag === \"None\") return option as any\n const mapped = fn(option.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(some) as any\n }\n return some(mapped) as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n\n/**\n * Chain operations that return Options.\n * If the Option is none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `flatMap(option, fn)`\n * - Data-last: `pipe(option, flatMap(fn))`\n *\n * Supports both sync and async functions:\n * - Sync fn: returns Option<U>\n * - Async fn: returns Promise<Option<U>>\n *\n * @param fn - Function that takes a value and returns an Option (or Promise<Option>)\n * @returns The resulting Option in data-first form, or a function that flatMaps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.flatMap(input, (n) => Option.some(n + 1))\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.flatMap((n: number) => Option.some(n + 1))(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\n// oxlint-disable-next-line no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types\nexport const flatMap: OptionFlatMap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) =>\n option._tag === \"Some\" ? fn(option.value) : option,\n)\n\n/**\n * Perform a side effect on the value without modifying the Option.\n * Useful for debugging, logging, or other side effects in a pipeline.\n * If the Option is none, the function is not called.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `tap(option, fn)`\n * - Data-last: `pipe(option, tap(fn))`\n *\n * Supports both sync and async side effects:\n * - Sync fn: returns any value (ignored)\n * - Async fn: returns Promise<unknown>\n *\n * @param fn - Function to call with the value (return value is ignored)\n * @returns The original Option in data-first form, or a function that taps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * let seen = 0\n * const input = Option.some(2)\n * const dataFirst = Option.tap(input, (n) => {\n * seen = n\n * })\n * // => { _tag: \"Some\", value: 2 }\n *\n * const dataLast = Option.tap((n: number) => {\n * seen = n\n * })(input)\n * // => { _tag: \"Some\", value: 2 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const tap: OptionTap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) => {\n if (option._tag === \"None\") return option as any\n const sideEffect = fn(option.value)\n if (isPromise(sideEffect)) {\n return Promise.resolve(sideEffect).then(() => option) as any\n }\n return option as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n\n/**\n * Recover from none by providing an alternative Option.\n * If the Option is some, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `orElse(option, fn)`\n * - Data-last: `pipe(option, orElse(fn))`\n *\n * Supports both sync and async fallback functions:\n * - Sync fn: returns Option<U>\n * - Async fn: returns Promise<Option<U>>\n *\n * @param fn - Function that returns an alternative Option\n * @returns The original or fallback Option in data-first form, or a function that recovers from none in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.orElse(input, () => Option.some(0))\n * // => { _tag: \"Some\", value: 0 }\n *\n * const dataLast = Option.orElse(() => Option.some(0))(input)\n * // => { _tag: \"Some\", value: 0 }\n * ```\n */\n// oxlint-disable-next-line no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types\nexport const orElse: OptionOrElse = dual(2, (option: OptionType<unknown>, fn: () => unknown) =>\n option._tag === \"Some\" ? option : fn(),\n)\n\n/**\n * Filter an Option based on a predicate.\n * If the predicate returns false, converts to none.\n * If the Option is already none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `filter(option, predicate)`\n * - Data-last: `pipe(option, filter(predicate))`\n *\n * @param predicate - Function that returns true to keep the value\n * @returns The filtered Option in data-first form, or a function that filters an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(3)\n * const dataFirst = Option.filter(input, (n) => n > 0)\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.filter((n: number) => n > 0)(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\nexport const filter: OptionFilter = dual(2, (option: OptionType<unknown>, predicate: (value: unknown) => boolean) => {\n if (option._tag === \"None\") return option\n return predicate(option.value) ? option : none()\n})\n\n// ============================================================================\n// Combinators\n// ============================================================================\n\n/**\n * Combine multiple Options into a single Option.\n * Supports both array and object inputs.\n *\n * - If all Options are some, returns some with all values\n * - If any Option is none, returns none (short-circuits)\n *\n * For arrays of 1-6 elements, tuple types are inferred automatically.\n * For longer arrays, use `as const` to preserve tuple structure.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const combined = Option.all([Option.some(1), Option.some(2)] as const)\n * // => { _tag: \"Some\", value: [1, 2] }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-type-assertion, no-unsafe-argument -- Required for handling union types in overloaded function */\nexport const all: OptionAll = (options: any): any => {\n if (Array.isArray(options)) {\n const values: unknown[] = []\n for (const option of options) {\n if (option._tag === \"None\") return option\n values.push(option.value)\n }\n return some(values)\n }\n\n const values: Record<string, unknown> = {}\n for (const [key, option] of Object.entries(options)) {\n const o = option as OptionType<unknown>\n if (o._tag === \"None\") return option\n values[key] = o.value\n }\n return some(values)\n}\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-type-assertion */\n\n// ============================================================================\n// Extraction\n// ============================================================================\n\n/**\n * Get the value or a default value.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOr(option, defaultValue)`\n * - Data-last: `pipe(option, unwrapOr(defaultValue))`\n *\n * Uses NoInfer to prevent type inference from the default value.\n *\n * @param defaultValue - Value to return if the Option is none\n * @returns The unwrapped value in data-first form, or a function that unwraps an Option with a default in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.unwrapOr(input, 0)\n * // => 0\n *\n * const dataLast = Option.unwrapOr(0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOr: OptionUnwrapOr = dual(\n 2,\n <T>(option: OptionType<T>, defaultValue: NoInfer<T>): T => (option._tag === \"Some\" ? option.value : defaultValue),\n)\n\n/**\n * Get the value or compute a value.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOrElse(option, fn)`\n * - Data-last: `pipe(option, unwrapOrElse(fn))`\n *\n * @param fn - Function to compute a value\n * @returns The unwrapped value in data-first form, or a function that unwraps an Option lazily in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.unwrapOrElse(input, () => 0)\n * // => 0\n *\n * const dataLast = Option.unwrapOrElse(() => 0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOrElse: OptionUnwrapOrElse = dual(\n 2,\n <T>(option: OptionType<T>, fn: () => T): T => (option._tag === \"Some\" ? option.value : fn()),\n)\n\n/**\n * Pattern match on an Option, handling both some and none cases.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `match(option, { Some: ..., None: ... })`\n * - Data-last: `pipe(option, match({ Some: ..., None: ... }))`\n *\n * @param handlers - Object with `Some` and `None` handlers\n * @returns The handler result in data-first form, or a function that matches an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.match(input, {\n * Some: (value) => `some:${value}` ,\n * None: () => \"none\" ,\n * })\n * // => \"some:2\"\n *\n * const dataLast = Option.match({\n * Some: (value: number) => `some:${value}` ,\n * None: () => \"none\" ,\n * })(input)\n * // => \"some:2\"\n * ```\n */\nexport const match: OptionMatch = dual(\n 2,\n <T, U>(option: OptionType<T>, handlers: { Some: (value: T) => U; None: () => U }): U =>\n option._tag === \"Some\" ? handlers.Some(option.value) : handlers.None(),\n)\n\n// ============================================================================\n// Conversions\n// ============================================================================\n\n/**\n * Convert a nullable value to an Option.\n * `null` and `undefined` become `Option.none()`, other values become `Option.some(value)`.\n * The return type narrows to `Option<NonNullable<T>>`.\n *\n * @param value - The value to convert\n * @returns An Option\n *\n * @example\n * ```ts\n * fromNullable(42) // { _tag: \"Some\", value: 42 }\n * fromNullable(null) // { _tag: \"None\" }\n * fromNullable(undefined) // { _tag: \"None\" }\n *\n * const maybeName = \"Alice\" as string | undefined\n * const option = fromNullable(maybeName) // Option<string>\n * ```\n */\nconst isNonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined\n\n/**\n * fromNullable utility.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.fromNullable(\"Ada\")\n * // => { _tag: \"Some\", value: \"Ada\" }\n * ```\n */\nexport const fromNullable = <T>(value: T): OptionType<NonNullable<T>> => (isNonNullable(value) ? some(value) : none())\n\n/**\n * Wrap a function that might throw into an Option.\n * Supports both sync and async functions with automatic type inference.\n *\n * - Sync fn: returns Option<T>\n * - Async fn: returns Promise<Option<T>>\n *\n * **Note on `any` return types:** If your function returns `any` (e.g., `JSON.parse`),\n * you should add an explicit return type annotation. This is because TypeScript's\n * conditional types cannot determine if `any` is a Promise or not, resulting in a\n * union type `Promise<Option<unknown>> | Option<any>` that won't work\n * with Option utilities like `isSome` or `isNone`.\n *\n * @param fn - Function that might throw (sync or async)\n * @returns An Option with the return value or none\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const parsed = Option.fromTry(() => Number.parseInt(\"42\", 10))\n * // => { _tag: \"Some\", value: 42 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-type-assertion -- Required for conditional return type */\nexport const fromTry = <T>(fn: () => T): FromTryReturn<T> => {\n try {\n const result = fn()\n if (isPromise(result)) {\n return Promise.resolve(result)\n .then(some)\n .catch(() => none()) as unknown as FromTryReturn<T>\n }\n return some(result) as unknown as FromTryReturn<T>\n } catch {\n return none() as unknown as FromTryReturn<T>\n }\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"qeA0DA,MAAa,EAAqBA,EA8CrB,EAAW,IAA6B,CACnD,KAAM,OACN,SACC,GAAW,CACV,OAAU,EACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EAEN,EAAE,OAAO,WAAuD,CAC9D,OAAO,GAEV,EAeY,OAAwC,CACnD,KAAM,QACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EACN,EAAE,OAAO,WAA2D,CAElE,MADA,MAAM,IAAI,EACA,MAAM,iEAAiE,EAEpF,EAoBY,EAAa,GACxB,EAAO,OAAS,OAaL,EAAa,GACxB,EAAO,OAAS,OAkCL,EAAiB,EAAK,GAAI,EAA6B,IAAoC,CACtG,GAAI,EAAO,OAAS,OAAQ,OAAO,EACnC,IAAM,EAAS,EAAG,EAAO,MAAM,CAI/B,OAHI,EAAU,EAAO,CACZ,QAAQ,QAAQ,EAAO,CAAC,KAAK,EAAK,CAEpC,EAAK,EAAO,EACnB,CA+BW,EAAyB,EAAK,GAAI,EAA6B,IAC1E,EAAO,OAAS,OAAS,EAAG,EAAO,MAAM,CAAG,EAC7C,CAoCY,EAAiB,EAAK,GAAI,EAA6B,IAAoC,CACtG,GAAI,EAAO,OAAS,OAAQ,OAAO,EACnC,IAAM,EAAa,EAAG,EAAO,MAAM,CAInC,OAHI,EAAU,EAAW,CAChB,QAAQ,QAAQ,EAAW,CAAC,SAAW,EAAO,CAEhD,GACP,CA+BW,EAAuB,EAAK,GAAI,EAA6B,IACxE,EAAO,OAAS,OAAS,EAAS,GAAI,CACvC,CA0BY,EAAuB,EAAK,GAAI,EAA6B,IACpE,EAAO,OAAS,QACb,EAAU,EAAO,MAAM,CADK,EACO,GAAM,CAChD,CAyBW,EAAkB,GAAsB,CACnD,GAAI,MAAM,QAAQ,EAAQ,CAAE,CAC1B,IAAMC,EAAoB,EAAE,CAC5B,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,EAAO,OAAS,OAAQ,OAAO,EACnC,EAAO,KAAK,EAAO,MAAM,CAE3B,OAAO,EAAKA,EAAO,CAGrB,IAAM,EAAkC,EAAE,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACnD,IAAM,EAAI,EACV,GAAI,EAAE,OAAS,OAAQ,OAAO,EAC9B,EAAO,GAAO,EAAE,MAElB,OAAO,EAAK,EAAO,EAgCR,EAA2B,EACtC,GACI,EAAuB,IAAiC,EAAO,OAAS,OAAS,EAAO,MAAQ,EACrG,CAwBY,EAAmC,EAC9C,GACI,EAAuB,IAAoB,EAAO,OAAS,OAAS,EAAO,MAAQ,GAAI,CAC5F,CA8BY,EAAqB,EAChC,GACO,EAAuB,IAC5B,EAAO,OAAS,OAAS,EAAS,KAAK,EAAO,MAAM,CAAG,EAAS,MAAM,CACzE,CAwBK,EAAoB,GAAsC,GAAU,KAa7D,EAAmB,GAA0C,EAAc,EAAM,CAAG,EAAK,EAAM,CAAG,GAAM,CA2BxG,EAAc,GAAkC,CAC3D,GAAI,CACF,IAAM,EAAS,GAAI,CAMnB,OALI,EAAU,EAAO,CACZ,QAAQ,QAAQ,EAAO,CAC3B,KAAK,EAAK,CACV,UAAY,GAAM,CAAC,CAEjB,EAAK,EAAO,MACb,CACN,OAAO,GAAM"}
1
+ {"version":3,"file":"option-BlyP5LA2.mjs","names":["NoSuchElementErrorCtor","values"],"sources":["../src/option/option.ts"],"sourcesContent":["/**\n * Optional value primitives for modeling presence (`Some`) and absence (`None`).\n *\n * **Mental model**\n * - `Option<A>` is either a value or no value.\n * - Prefer `Option` when missing data is expected and not exceptional.\n *\n * **Common tasks**\n * - Construct with `Option.some`, `Option.none`, `Option.fromNullable`.\n * - Transform with `Option.map`, `Option.flatMap`, `Option.filter`.\n * - Extract with `Option.unwrapOr`, `Option.match`.\n *\n * **Gotchas**\n * - `Option.none` short-circuits in `Fx.gen`.\n * - Use `Option.match` for exhaustive branch handling.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const name = Option.fromNullable(\"Ada\")\n * const upper = Option.map(name, (value) => value.toUpperCase())\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport { dual } from \"../shared/dual\"\nimport { isPromise } from \"../shared/is-promise\"\nimport { pipeable } from \"../shared/pipeable\"\nimport { NoSuchElementError as NoSuchElementErrorCtor } from \"./option.types\"\nimport type {\n Option as OptionType,\n OptionAll,\n OptionFlatMap,\n OptionMap,\n OptionMatch,\n OptionTap,\n OptionOrElse,\n OptionFilter,\n OptionUnwrapOr,\n OptionUnwrapOrElse,\n FromTryReturn,\n} from \"./option.types\"\n\n/**\n * Re-exported error type used when yielding `Option.none()` in `Fx.gen`.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const error = new Option.NoSuchElementError()\n * // => error.name === \"NoSuchElementError\"\n * ```\n */\nexport const NoSuchElementError = NoSuchElementErrorCtor\n\n/**\n * Re-exported `NoSuchElementError` instance type.\n *\n * @example\n * ```ts\n * import type { Option } from \"@nicolastoulemont/std\"\n *\n * type Example = Option.NoSuchElementError\n * ```\n */\nexport type NoSuchElementError = InstanceType<typeof NoSuchElementErrorCtor>\n\n/**\n * Re-exported `Option` type.\n *\n * @example\n * ```ts\n * import type { Option } from \"@nicolastoulemont/std\"\n *\n * type Example = Option.Option<unknown>\n * ```\n */\nexport type Option<T> = OptionType<T>\n\n/* oxlint-disable no-unsafe-type-assertion -- Option runtime values carry erased Fx phantom channels that require explicit marker assertions. */\n\n// ============================================================================\n// Constructors\n// ============================================================================\n\n/**\n * Create an Option with a value.\n *\n * @param value - The value to wrap\n * @returns An Option with `_tag: \"Some\"`\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.some(42)\n * // => { _tag: \"Some\", value: 42 }\n * ```\n */\nexport const some = <T>(value: T): OptionType<T> => ({\n _tag: \"Some\",\n value,\n [FxTypeId]: {\n _A: () => value,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<NoSuchElementError, T, unknown> {\n return value\n },\n})\n\n/**\n * Create an Option with no value.\n *\n * @returns An Option with `_tag: \"None\"`\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.none<number>()\n * // => { _tag: \"None\" }\n * ```\n */\nexport const none = <T = never>(): OptionType<T> => ({\n _tag: \"None\",\n [FxTypeId]: {\n _A: () => undefined as never,\n _E: () => undefined as unknown as NoSuchElementError,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n *[Symbol.iterator](): Generator<NoSuchElementError, never, unknown> {\n yield new NoSuchElementError()\n throw new Error(\"Unreachable: Fx.gen should short-circuit on NoSuchElementError\")\n },\n})\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Check if an Option has a value.\n *\n * @param option - The Option to check\n * @returns true if the Option is some\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.isSome(Option.some(1))\n * // => true\n * ```\n */\nexport const isSome = <T>(option: OptionType<T>): option is Extract<OptionType<T>, { _tag: \"Some\" }> =>\n option._tag === \"Some\"\n\n/**\n * isNone utility.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.isNone(Option.none())\n * // => true\n * ```\n */\nexport const isNone = <T>(option: OptionType<T>): option is Extract<OptionType<T>, { _tag: \"None\" }> =>\n option._tag === \"None\"\n\n// ============================================================================\n// Transformations (curried for pipe)\n// ============================================================================\n\n/**\n * Transform the value of an Option.\n * If the Option is none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `map(option, fn)`\n * - Data-last: `pipe(option, map(fn))`\n *\n * Supports both sync and async callbacks:\n * - Sync fn: returns U\n * - Async fn: returns Promise<U>\n *\n * @param fn - Function that transforms the contained value\n * @returns The mapped Option in data-first form, or a function that maps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.map(input, (n) => n + 1)\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.map((n: number) => n + 1)(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const map: OptionMap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) => {\n if (option._tag === \"None\") return option as any\n const mapped = fn(option.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(some) as any\n }\n return some(mapped) as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n\n/**\n * Chain operations that return Options.\n * If the Option is none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `flatMap(option, fn)`\n * - Data-last: `pipe(option, flatMap(fn))`\n *\n * Supports both sync and async functions:\n * - Sync fn: returns Option<U>\n * - Async fn: returns Promise<Option<U>>\n *\n * @param fn - Function that takes a value and returns an Option (or Promise<Option>)\n * @returns The resulting Option in data-first form, or a function that flatMaps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.flatMap(input, (n) => Option.some(n + 1))\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.flatMap((n: number) => Option.some(n + 1))(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\n// oxlint-disable-next-line no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types\nexport const flatMap: OptionFlatMap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) =>\n option._tag === \"Some\" ? fn(option.value) : option,\n)\n\n/**\n * Perform a side effect on the value without modifying the Option.\n * Useful for debugging, logging, or other side effects in a pipeline.\n * If the Option is none, the function is not called.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `tap(option, fn)`\n * - Data-last: `pipe(option, tap(fn))`\n *\n * Supports both sync and async side effects:\n * - Sync fn: returns any value (ignored)\n * - Async fn: returns Promise<unknown>\n *\n * @param fn - Function to call with the value (return value is ignored)\n * @returns The original Option in data-first form, or a function that taps an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * let seen = 0\n * const input = Option.some(2)\n * const dataFirst = Option.tap(input, (n) => {\n * seen = n\n * })\n * // => { _tag: \"Some\", value: 2 }\n *\n * const dataLast = Option.tap((n: number) => {\n * seen = n\n * })(input)\n * // => { _tag: \"Some\", value: 2 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const tap: OptionTap = dual(2, (option: OptionType<unknown>, fn: (value: unknown) => unknown) => {\n if (option._tag === \"None\") return option as any\n const sideEffect = fn(option.value)\n if (isPromise(sideEffect)) {\n return Promise.resolve(sideEffect).then(() => option) as any\n }\n return option as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n\n/**\n * Recover from none by providing an alternative Option.\n * If the Option is some, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `orElse(option, fn)`\n * - Data-last: `pipe(option, orElse(fn))`\n *\n * Supports both sync and async fallback functions:\n * - Sync fn: returns Option<U>\n * - Async fn: returns Promise<Option<U>>\n *\n * @param fn - Function that returns an alternative Option\n * @returns The original or fallback Option in data-first form, or a function that recovers from none in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.orElse(input, () => Option.some(0))\n * // => { _tag: \"Some\", value: 0 }\n *\n * const dataLast = Option.orElse(() => Option.some(0))(input)\n * // => { _tag: \"Some\", value: 0 }\n * ```\n */\n// oxlint-disable-next-line no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types\nexport const orElse: OptionOrElse = dual(2, (option: OptionType<unknown>, fn: () => unknown) =>\n option._tag === \"Some\" ? option : fn(),\n)\n\n/**\n * Filter an Option based on a predicate.\n * If the predicate returns false, converts to none.\n * If the Option is already none, it passes through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `filter(option, predicate)`\n * - Data-last: `pipe(option, filter(predicate))`\n *\n * @param predicate - Function that returns true to keep the value\n * @returns The filtered Option in data-first form, or a function that filters an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(3)\n * const dataFirst = Option.filter(input, (n) => n > 0)\n * // => { _tag: \"Some\", value: 3 }\n *\n * const dataLast = Option.filter((n: number) => n > 0)(input)\n * // => { _tag: \"Some\", value: 3 }\n * ```\n */\nexport const filter: OptionFilter = dual(2, (option: OptionType<unknown>, predicate: (value: unknown) => boolean) => {\n if (option._tag === \"None\") return option\n return predicate(option.value) ? option : none()\n})\n\n// ============================================================================\n// Combinators\n// ============================================================================\n\n/**\n * Combine multiple Options into a single Option.\n * Supports both array and object inputs.\n *\n * - If all Options are some, returns some with all values\n * - If any Option is none, returns none (short-circuits)\n *\n * For arrays of 1-6 elements, tuple types are inferred automatically.\n * For longer arrays, use `as const` to preserve tuple structure.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const combined = Option.all([Option.some(1), Option.some(2)] as const)\n * // => { _tag: \"Some\", value: [1, 2] }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-type-assertion, no-unsafe-argument -- Required for handling union types in overloaded function */\nexport const all: OptionAll = (options: any): any => {\n if (Array.isArray(options)) {\n const values: unknown[] = []\n for (const option of options) {\n if (option._tag === \"None\") return option\n values.push(option.value)\n }\n return some(values)\n }\n\n const values: Record<string, unknown> = {}\n for (const [key, option] of Object.entries(options)) {\n const o = option as OptionType<unknown>\n if (o._tag === \"None\") return option\n values[key] = o.value\n }\n return some(values)\n}\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-type-assertion */\n\n// ============================================================================\n// Extraction\n// ============================================================================\n\n/**\n * Get the value or a default value.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOr(option, defaultValue)`\n * - Data-last: `pipe(option, unwrapOr(defaultValue))`\n *\n * Uses NoInfer to prevent type inference from the default value.\n *\n * @param defaultValue - Value to return if the Option is none\n * @returns The unwrapped value in data-first form, or a function that unwraps an Option with a default in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.unwrapOr(input, 0)\n * // => 0\n *\n * const dataLast = Option.unwrapOr(0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOr: OptionUnwrapOr = dual(\n 2,\n <T>(option: OptionType<T>, defaultValue: NoInfer<T>): T => (option._tag === \"Some\" ? option.value : defaultValue),\n)\n\n/**\n * Get the value or compute a value.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOrElse(option, fn)`\n * - Data-last: `pipe(option, unwrapOrElse(fn))`\n *\n * @param fn - Function to compute a value\n * @returns The unwrapped value in data-first form, or a function that unwraps an Option lazily in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.none<number>()\n * const dataFirst = Option.unwrapOrElse(input, () => 0)\n * // => 0\n *\n * const dataLast = Option.unwrapOrElse(() => 0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOrElse: OptionUnwrapOrElse = dual(\n 2,\n <T>(option: OptionType<T>, fn: () => T): T => (option._tag === \"Some\" ? option.value : fn()),\n)\n\n/**\n * Pattern match on an Option, handling both some and none cases.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `match(option, { Some: ..., None: ... })`\n * - Data-last: `pipe(option, match({ Some: ..., None: ... }))`\n *\n * @param handlers - Object with `Some` and `None` handlers\n * @returns The handler result in data-first form, or a function that matches an Option in data-last form\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const input = Option.some(2)\n * const dataFirst = Option.match(input, {\n * Some: (value) => `some:${value}` ,\n * None: () => \"none\" ,\n * })\n * // => \"some:2\"\n *\n * const dataLast = Option.match({\n * Some: (value: number) => `some:${value}` ,\n * None: () => \"none\" ,\n * })(input)\n * // => \"some:2\"\n * ```\n */\nexport const match: OptionMatch = dual(\n 2,\n <T, U>(option: OptionType<T>, handlers: { Some: (value: T) => U; None: () => U }): U =>\n option._tag === \"Some\" ? handlers.Some(option.value) : handlers.None(),\n)\n\n// ============================================================================\n// Conversions\n// ============================================================================\n\n/**\n * Convert a nullable value to an Option.\n * `null` and `undefined` become `Option.none()`, other values become `Option.some(value)`.\n * The return type narrows to `Option<NonNullable<T>>`.\n *\n * @param value - The value to convert\n * @returns An Option\n *\n * @example\n * ```ts\n * fromNullable(42) // { _tag: \"Some\", value: 42 }\n * fromNullable(null) // { _tag: \"None\" }\n * fromNullable(undefined) // { _tag: \"None\" }\n *\n * const maybeName = \"Alice\" as string | undefined\n * const option = fromNullable(maybeName) // Option<string>\n * ```\n */\nconst isNonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined\n\n/**\n * fromNullable utility.\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Option.fromNullable(\"Ada\")\n * // => { _tag: \"Some\", value: \"Ada\" }\n * ```\n */\nexport const fromNullable = <T>(value: T): OptionType<NonNullable<T>> => (isNonNullable(value) ? some(value) : none())\n\n/**\n * Wrap a function that might throw into an Option.\n * Supports both sync and async functions with automatic type inference.\n *\n * - Sync fn: returns Option<T>\n * - Async fn: returns Promise<Option<T>>\n *\n * **Note on `any` return types:** If your function returns `any` (e.g., `JSON.parse`),\n * you should add an explicit return type annotation. This is because TypeScript's\n * conditional types cannot determine if `any` is a Promise or not, resulting in a\n * union type `Promise<Option<unknown>> | Option<any>` that won't work\n * with Option utilities like `isSome` or `isNone`.\n *\n * @param fn - Function that might throw (sync or async)\n * @returns An Option with the return value or none\n *\n * @example\n * ```ts\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const parsed = Option.fromTry(() => Number.parseInt(\"42\", 10))\n * // => { _tag: \"Some\", value: 42 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-type-assertion -- Required for conditional return type */\nexport const fromTry = <T>(fn: () => T): FromTryReturn<T> => {\n try {\n const result = fn()\n if (isPromise(result)) {\n return Promise.resolve(result)\n .then(some)\n .catch(() => none()) as unknown as FromTryReturn<T>\n }\n return some(result) as unknown as FromTryReturn<T>\n } catch {\n return none() as unknown as FromTryReturn<T>\n }\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"qeA0DA,MAAa,EAAqBA,EA8CrB,EAAW,IAA6B,CACnD,KAAM,OACN,SACC,GAAW,CACV,OAAU,EACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EAEN,EAAE,OAAO,WAAuD,CAC9D,OAAO,GAEV,EAeY,OAAwC,CACnD,KAAM,QACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EACN,EAAE,OAAO,WAA2D,CAElE,MADA,MAAM,IAAI,EACA,MAAM,iEAAiE,EAEpF,EAoBY,EAAa,GACxB,EAAO,OAAS,OAaL,EAAa,GACxB,EAAO,OAAS,OAkCL,EAAiB,EAAK,GAAI,EAA6B,IAAoC,CACtG,GAAI,EAAO,OAAS,OAAQ,OAAO,EACnC,IAAM,EAAS,EAAG,EAAO,MAAM,CAI/B,OAHI,EAAU,EAAO,CACZ,QAAQ,QAAQ,EAA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c,EAAM,CAAG,EAAK,EAAM,CAAG,GAAM,CA2BxG,EAAc,GAAkC,CAC3D,GAAI,CACF,IAAM,EAAS,GAAI,CAMnB,OALI,EAAU,EAAO,CACZ,QAAQ,QAAQ,EAAO,CAC3B,KAAK,EAAK,CACV,UAAY,GAAM,CAAC,CAEjB,EAAK,EAAO,MACb,CACN,OAAO,GAAM"}
@@ -1,5 +1,5 @@
1
- import { i as Fx } from "./fx.types-BdN1EWxr.mjs";
2
- import { t as Pipeable } from "./pipeable-BIrevC0D.mjs";
1
+ import { i as Fx } from "./fx.types-CpFKa-Jj.mjs";
2
+ import { t as Pipeable } from "./pipeable-BY9yPsNK.mjs";
3
3
 
4
4
  //#region src/option/option.types.d.ts
5
5
 
@@ -154,4 +154,4 @@ type OptionMatch = {
154
154
  };
155
155
  //#endregion
156
156
  export { OptionFilter as a, OptionMatch as c, OptionUnwrapOr as d, OptionUnwrapOrElse as f, OptionAll as i, OptionOrElse as l, NoSuchElementError as n, OptionFlatMap as o, Option as r, OptionMap as s, FromTryReturn as t, OptionTap as u };
157
- //# sourceMappingURL=option.types-D9hrKcfa.d.mts.map
157
+ //# sourceMappingURL=option.types-DLp3QpFE.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"option.types-D9hrKcfa.d.mts","names":[],"sources":["../src/option/option.types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkBA;AAOC;AAWkB;AA0BnB;;;;AACK,cA7CQ,kBAAA,SAA2B,KAAA,CA6CnC;EAAG,SAAA,IAAA,GAAA,oBAAA;EAAN,WAAA,CAAA;;;;;KA7BG,IA+B6B,CAAA,CAAA,CAAA,GAAA;EAQtB,SAAA,IAAA,EAAA,MAAa;EAAM,SAAA,KAAA,EArCb,CAqCa;CAAU;;;;KA/BpC,IAAA,GA+BmF;EAAP,SAAA,IAAA,EAAA,MAAA;CAAM;AAAG;AAgB1F;;;;;;;;;;;AAGoD,KA9BxC,MA8BwC,CAAA,CAAA,CAAA,GAAA,CA9B3B,I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oC;EAAqB,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA,MAAA,EAoFpD,MApFoD,CAoF7C,CApF6C,CAAA,EAAA,QAAA,EAAA;IAAP,IAAA,EAAA,CAAA,KAAA,EAoFR,CApFQ,EAAA,GAoFF,GApFE;IAAM,IAAA,EAAA,GAAA,GAoFO,GApFP;EAQxD,CAAA,CAAA,EA4EqE,GA5ErE;EAEY,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA,QAAA,EAAA;IAAP,IAAA,EAAA,CAAA,KAAA,EA4EkB,CA5ElB,EAAA,GA4EwB,GA5ExB;IAAuB,IAAA,EAAA,GAAA,GA4EgB,GA5EhB;EAAc,CAAA,CAAA,EAAA,CAAA,MAAA,EA4EiB,MA5EjB,CA4EwB,CA5ExB,CAAA,EAAA,GA4E+B,GA5E/B;CAAR"}
@@ -1,2 +1,2 @@
1
1
  var e=class extends Error{_tag=`NoSuchElementError`;constructor(){super(`Option is None - no element present`),this.name=`NoSuchElementError`}};export{e as t};
2
- //# sourceMappingURL=option.types-CbY_swma.mjs.map
2
+ //# sourceMappingURL=option.types-bFFSErJ-.mjs.map