@nicolastoulemont/std 0.5.1 → 0.7.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 (207) hide show
  1. package/README.md +546 -0
  2. package/dist/adt/index.d.mts +2 -2
  3. package/dist/adt/index.mjs +1 -1
  4. package/dist/adt-DajUZvJe.mjs +2 -0
  5. package/dist/adt-DajUZvJe.mjs.map +1 -0
  6. package/dist/brand/index.d.mts +2 -2
  7. package/dist/brand/index.mjs +1 -1
  8. package/dist/brand-Bia3Vj6l.mjs +2 -0
  9. package/dist/brand-Bia3Vj6l.mjs.map +1 -0
  10. package/dist/chunk-C934ptG5.mjs +1 -0
  11. package/dist/context/index.d.mts +2 -0
  12. package/dist/context/index.mjs +1 -0
  13. package/dist/context-CCHj1nab.mjs +2 -0
  14. package/dist/context-CCHj1nab.mjs.map +1 -0
  15. package/dist/context-r8ESJiFn.d.mts +176 -0
  16. package/dist/context-r8ESJiFn.d.mts.map +1 -0
  17. package/dist/data/index.d.mts +2 -2
  18. package/dist/data/index.mjs +1 -1
  19. package/dist/data-CJxw6al9.mjs +2 -0
  20. package/dist/data-CJxw6al9.mjs.map +1 -0
  21. package/dist/data.tagged-error.types-CLlJJ3n5.d.mts +50 -0
  22. package/dist/data.tagged-error.types-CLlJJ3n5.d.mts.map +1 -0
  23. package/dist/{discriminator.types-DkThfvNE.d.mts → discriminator.types-CTURejXz.d.mts} +1 -1
  24. package/dist/discriminator.types-CTURejXz.d.mts.map +1 -0
  25. package/dist/dual-CZhzZslG.mjs +2 -0
  26. package/dist/dual-CZhzZslG.mjs.map +1 -0
  27. package/dist/either/index.d.mts +2 -2
  28. package/dist/either/index.mjs +1 -1
  29. package/dist/either-6BwadiFj.mjs +2 -0
  30. package/dist/either-6BwadiFj.mjs.map +1 -0
  31. package/dist/equality-CoyUHWh9.mjs +2 -0
  32. package/dist/equality-CoyUHWh9.mjs.map +1 -0
  33. package/dist/flow-D8_tllWl.mjs +2 -0
  34. package/dist/flow-D8_tllWl.mjs.map +1 -0
  35. package/dist/functions/index.d.mts +2 -0
  36. package/dist/functions/index.mjs +1 -0
  37. package/dist/functions-BkevX2Dw.mjs +2 -0
  38. package/dist/functions-BkevX2Dw.mjs.map +1 -0
  39. package/dist/fx/index.d.mts +2 -3
  40. package/dist/fx/index.mjs +1 -1
  41. package/dist/fx-BzxLbf1Q.mjs +2 -0
  42. package/dist/fx-BzxLbf1Q.mjs.map +1 -0
  43. package/dist/fx.runtime-BcC6yMSy.mjs +2 -0
  44. package/dist/fx.runtime-BcC6yMSy.mjs.map +1 -0
  45. package/dist/{fx.types-CXTwEa1G.mjs → fx.types-Bg-Mmdm5.mjs} +1 -1
  46. package/dist/fx.types-Bg-Mmdm5.mjs.map +1 -0
  47. package/dist/{fx.types-DO-8yG4c.d.mts → fx.types-DeEWEltG.d.mts} +3 -8
  48. package/dist/{fx.types-DO-8yG4c.d.mts.map → fx.types-DeEWEltG.d.mts.map} +1 -1
  49. package/dist/index-7Lv982Om.d.mts +217 -0
  50. package/dist/index-7Lv982Om.d.mts.map +1 -0
  51. package/dist/index-B_iY5tq0.d.mts +241 -0
  52. package/dist/index-B_iY5tq0.d.mts.map +1 -0
  53. package/dist/index-B_wWGszy.d.mts +129 -0
  54. package/dist/index-B_wWGszy.d.mts.map +1 -0
  55. package/dist/index-BiiE8NS7.d.mts +108 -0
  56. package/dist/index-BiiE8NS7.d.mts.map +1 -0
  57. package/dist/index-By6dNRc4.d.mts +277 -0
  58. package/dist/index-By6dNRc4.d.mts.map +1 -0
  59. package/dist/index-CCo85AdC.d.mts +121 -0
  60. package/dist/index-CCo85AdC.d.mts.map +1 -0
  61. package/dist/index-CUZn-ohG.d.mts +490 -0
  62. package/dist/index-CUZn-ohG.d.mts.map +1 -0
  63. package/dist/index-CugDqdx6.d.mts +464 -0
  64. package/dist/index-CugDqdx6.d.mts.map +1 -0
  65. package/dist/index-DEAWPlcI.d.mts +405 -0
  66. package/dist/index-DEAWPlcI.d.mts.map +1 -0
  67. package/dist/index-DKS1g1oC.d.mts +449 -0
  68. package/dist/index-DKS1g1oC.d.mts.map +1 -0
  69. package/dist/index-DSsDFLGw.d.mts +777 -0
  70. package/dist/index-DSsDFLGw.d.mts.map +1 -0
  71. package/dist/{index-DjjJIDaA.d.mts → index-DXbYlSnB.d.mts} +66 -103
  72. package/dist/index-DXbYlSnB.d.mts.map +1 -0
  73. package/dist/{index-DtAPrec7.d.mts → index-DaTvFhZ8.d.mts} +167 -52
  74. package/dist/index-DaTvFhZ8.d.mts.map +1 -0
  75. package/dist/index-Dm2dFysv.d.mts +415 -0
  76. package/dist/index-Dm2dFysv.d.mts.map +1 -0
  77. package/dist/index.d.mts +23 -16
  78. package/dist/index.mjs +1 -1
  79. package/dist/layer/index.d.mts +2 -0
  80. package/dist/layer/index.mjs +1 -0
  81. package/dist/layer-BttmtDrs.mjs +2 -0
  82. package/dist/layer-BttmtDrs.mjs.map +1 -0
  83. package/dist/layer.types-DgpCIsk_.d.mts +100 -0
  84. package/dist/layer.types-DgpCIsk_.d.mts.map +1 -0
  85. package/dist/multithread/index.d.mts +2 -0
  86. package/dist/multithread/index.mjs +1 -0
  87. package/dist/multithread-xUUh4eLn.mjs +19 -0
  88. package/dist/multithread-xUUh4eLn.mjs.map +1 -0
  89. package/dist/option/index.d.mts +2 -3
  90. package/dist/option/index.mjs +1 -1
  91. package/dist/option-Qt1H-u7c.mjs +2 -0
  92. package/dist/option-Qt1H-u7c.mjs.map +1 -0
  93. package/dist/option.types-DRUm2QiI.mjs +2 -0
  94. package/dist/option.types-DRUm2QiI.mjs.map +1 -0
  95. package/dist/{option.types-Cluybn30.d.mts → option.types-DlAb6Sr0.d.mts} +6 -11
  96. package/dist/option.types-DlAb6Sr0.d.mts.map +1 -0
  97. package/dist/order/index.d.mts +2 -0
  98. package/dist/order/index.mjs +1 -0
  99. package/dist/order-D5c4QChk.mjs +2 -0
  100. package/dist/order-D5c4QChk.mjs.map +1 -0
  101. package/dist/pipeable-COGyGMUV.mjs +2 -0
  102. package/dist/pipeable-COGyGMUV.mjs.map +1 -0
  103. package/dist/{pipeable-KHu4D8ol.d.mts → pipeable-rfqacPxZ.d.mts} +2 -9
  104. package/dist/{pipeable-KHu4D8ol.d.mts.map → pipeable-rfqacPxZ.d.mts.map} +1 -1
  105. package/dist/predicate/index.d.mts +2 -2
  106. package/dist/predicate/index.mjs +1 -1
  107. package/dist/predicate-DUhhQqWY.mjs +2 -0
  108. package/dist/predicate-DUhhQqWY.mjs.map +1 -0
  109. package/dist/provide/index.d.mts +2 -0
  110. package/dist/provide/index.mjs +1 -0
  111. package/dist/provide-B_SqJpCd.mjs +2 -0
  112. package/dist/provide-B_SqJpCd.mjs.map +1 -0
  113. package/dist/queue/index.d.mts +2 -0
  114. package/dist/queue/index.mjs +1 -0
  115. package/dist/queue-CG5izEBS.mjs +2 -0
  116. package/dist/queue-CG5izEBS.mjs.map +1 -0
  117. package/dist/queue.types-CD2LOu37.d.mts +36 -0
  118. package/dist/queue.types-CD2LOu37.d.mts.map +1 -0
  119. package/dist/result/index.d.mts +2 -3
  120. package/dist/result/index.mjs +1 -1
  121. package/dist/result-B5WbPg8C.mjs +1 -0
  122. package/dist/result-BEzV0DYC.mjs +2 -0
  123. package/dist/result-BEzV0DYC.mjs.map +1 -0
  124. package/dist/{result.types-fIbuBwVQ.d.mts → result.types-_xDAei3-.d.mts} +31 -109
  125. package/dist/result.types-_xDAei3-.d.mts.map +1 -0
  126. package/dist/schedule/index.d.mts +2 -0
  127. package/dist/schedule/index.mjs +1 -0
  128. package/dist/schedule-C6tjcJ1O.mjs +2 -0
  129. package/dist/schedule-C6tjcJ1O.mjs.map +1 -0
  130. package/dist/schedule-DlX2Dg69.d.mts +144 -0
  131. package/dist/schedule-DlX2Dg69.d.mts.map +1 -0
  132. package/dist/scope/index.d.mts +2 -0
  133. package/dist/scope/index.mjs +1 -0
  134. package/dist/scope-CZdp4wKX.d.mts +79 -0
  135. package/dist/scope-CZdp4wKX.d.mts.map +1 -0
  136. package/dist/scope-qwL1VUh2.mjs +2 -0
  137. package/dist/scope-qwL1VUh2.mjs.map +1 -0
  138. package/dist/service/index.d.mts +2 -0
  139. package/dist/service/index.mjs +1 -0
  140. package/dist/service-3PYQTUdH.mjs +2 -0
  141. package/dist/service-3PYQTUdH.mjs.map +1 -0
  142. package/dist/service-DrXU7KJG.d.mts +69 -0
  143. package/dist/service-DrXU7KJG.d.mts.map +1 -0
  144. package/dist/service-resolution-C19smeaO.mjs +2 -0
  145. package/dist/service-resolution-C19smeaO.mjs.map +1 -0
  146. package/package.json +52 -13
  147. package/dist/adt-DZmVJG4P.mjs +0 -2
  148. package/dist/adt-DZmVJG4P.mjs.map +0 -1
  149. package/dist/apply-fn.types-CMgY6WQe.d.mts +0 -8
  150. package/dist/apply-fn.types-CMgY6WQe.d.mts.map +0 -1
  151. package/dist/brand-BUqMmkzC.mjs +0 -2
  152. package/dist/brand-BUqMmkzC.mjs.map +0 -1
  153. package/dist/data-DzqKBCQg.mjs +0 -2
  154. package/dist/data-DzqKBCQg.mjs.map +0 -1
  155. package/dist/discriminator.types-DkThfvNE.d.mts.map +0 -1
  156. package/dist/either-BDY9T5oz.mjs +0 -2
  157. package/dist/either-BDY9T5oz.mjs.map +0 -1
  158. package/dist/equality-D2EJvZm4.mjs +0 -2
  159. package/dist/equality-D2EJvZm4.mjs.map +0 -1
  160. package/dist/err/index.d.mts +0 -2
  161. package/dist/err/index.mjs +0 -1
  162. package/dist/err-CYs4b1RV.mjs +0 -2
  163. package/dist/err-CYs4b1RV.mjs.map +0 -1
  164. package/dist/flow/index.d.mts +0 -2
  165. package/dist/flow/index.mjs +0 -1
  166. package/dist/flow-CxKQ5yac.mjs +0 -2
  167. package/dist/flow-CxKQ5yac.mjs.map +0 -1
  168. package/dist/fx-C4UuWCqP.mjs +0 -2
  169. package/dist/fx-C4UuWCqP.mjs.map +0 -1
  170. package/dist/fx.types-CXTwEa1G.mjs.map +0 -1
  171. package/dist/index-78LWwTds.d.mts +0 -288
  172. package/dist/index-78LWwTds.d.mts.map +0 -1
  173. package/dist/index-BQ5wVDSP.d.mts +0 -441
  174. package/dist/index-BQ5wVDSP.d.mts.map +0 -1
  175. package/dist/index-BahMvQpA.d.mts +0 -80
  176. package/dist/index-BahMvQpA.d.mts.map +0 -1
  177. package/dist/index-Bs5TTFlK.d.mts +0 -882
  178. package/dist/index-Bs5TTFlK.d.mts.map +0 -1
  179. package/dist/index-BuLJRX1e.d.mts +0 -476
  180. package/dist/index-BuLJRX1e.d.mts.map +0 -1
  181. package/dist/index-CDio8mJY.d.mts +0 -225
  182. package/dist/index-CDio8mJY.d.mts.map +0 -1
  183. package/dist/index-DLlx9jiG.d.mts +0 -389
  184. package/dist/index-DLlx9jiG.d.mts.map +0 -1
  185. package/dist/index-DjjJIDaA.d.mts.map +0 -1
  186. package/dist/index-DtAPrec7.d.mts.map +0 -1
  187. package/dist/index-IdejL485.d.mts +0 -79
  188. package/dist/index-IdejL485.d.mts.map +0 -1
  189. package/dist/index-UYodvXes.d.mts +0 -846
  190. package/dist/index-UYodvXes.d.mts.map +0 -1
  191. package/dist/option-Qiv7Ls7L.mjs +0 -2
  192. package/dist/option-Qiv7Ls7L.mjs.map +0 -1
  193. package/dist/option.types-By5UOfC2.mjs +0 -2
  194. package/dist/option.types-By5UOfC2.mjs.map +0 -1
  195. package/dist/option.types-Cluybn30.d.mts.map +0 -1
  196. package/dist/pipe/index.d.mts +0 -2
  197. package/dist/pipe/index.mjs +0 -1
  198. package/dist/pipe-BROILDeC.mjs +0 -2
  199. package/dist/pipe-BROILDeC.mjs.map +0 -1
  200. package/dist/pipeable-rQvolRqh.mjs +0 -2
  201. package/dist/pipeable-rQvolRqh.mjs.map +0 -1
  202. package/dist/predicate-DvXnfmeJ.mjs +0 -2
  203. package/dist/predicate-DvXnfmeJ.mjs.map +0 -1
  204. package/dist/result-B68pxC7l.mjs +0 -2
  205. package/dist/result-B68pxC7l.mjs.map +0 -1
  206. package/dist/result.types-fIbuBwVQ.d.mts.map +0 -1
  207. /package/dist/{result-uRORQlAQ.mjs → option-CBCwzF0L.mjs} +0 -0
package/README.md CHANGED
@@ -1 +1,547 @@
1
1
  # @nicolastoulemont/std
2
+
3
+ ## Introduction
4
+
5
+ `@nicolastoulemont/std` is a functional TypeScript toolkit for modeling domain data, handling failures explicitly, and composing sync or async workflows.
6
+ It is designed for application code where clear control flow, predictable typing, and dependency-aware orchestration matter.
7
+ The API is small, pipe-friendly, and built around practical primitives you can combine incrementally.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pnpm add @nicolastoulemont/std
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```ts
18
+ import { Result, Data, pipe } from "@nicolastoulemont/std"
19
+
20
+ class InvalidPortError extends Data.TaggedError("InvalidPortError")<{ input: string }> {}
21
+
22
+ const parsePort = (input: string) =>
23
+ pipe(
24
+ Result.try(() => Number.parseInt(input, 10)),
25
+ Result.filter(
26
+ (n) => Number.isInteger(n) && n > 0,
27
+ () => new InvalidPortError({ input }),
28
+ ),
29
+ )
30
+ ```
31
+
32
+ ```ts
33
+ import { Fx, Layer, Provide, Service, pipe } from "@nicolastoulemont/std"
34
+
35
+ const Config = Service.tag<{ baseUrl: string }>("Config")
36
+
37
+ const ConfigLive = Layer.ok(Config, { baseUrl: "https://api.example.com" })
38
+
39
+ const program = Fx.gen(function* () {
40
+ const config = yield* Config
41
+ return config.baseUrl
42
+ })
43
+
44
+ const exit = Fx.run(pipe(program, Provide.layer(ConfigLive)))
45
+
46
+ const response = Fx.match(exit, {
47
+ Ok: (ok) => ({ status: 200, body: ok.value }),
48
+ Err: (err) => ({ status: 400, body: err.error }),
49
+ Defect: (defect) => ({ status: 500, body: String(defect.defect) }),
50
+ })
51
+ ```
52
+
53
+ ## Main Modules
54
+
55
+ ### Result
56
+
57
+ Result models success/failure with typed errors so transformations stay explicit and composable.
58
+
59
+ #### Abstract Example
60
+
61
+ ```ts
62
+ import { Result, Data, pipe } from "@nicolastoulemont/std"
63
+
64
+ class NotPositiveIntegerError extends Data.TaggedError("NotPositiveIntegerError")<{ input: string }> {}
65
+
66
+ const parsePositiveInt = (input: string) => {
67
+ const parsed = Number.parseInt(input, 10)
68
+ return pipe(
69
+ Result.ok(parsed),
70
+ Result.filter(
71
+ (n) => Number.isInteger(n) && n > 0,
72
+ () => new NotPositiveIntegerError({ input }),
73
+ ),
74
+ )
75
+ }
76
+ ```
77
+
78
+ #### Real-World Example
79
+
80
+ ```ts
81
+ import { Result, Data, pipe } from "@nicolastoulemont/std"
82
+
83
+ class ValidationError extends Data.TaggedError("ValidationError")<{ message: string }> {}
84
+ class ConflictError extends Data.TaggedError("ConflictError")<{ message: string }> {}
85
+ type SignupError = ValidationError | ConflictError
86
+
87
+ const validateEmail = (email: string) =>
88
+ email.includes("@") ? Result.ok(email) : Result.err<SignupError>(new ValidationError({ message: "Invalid email" }))
89
+
90
+ const createUser = (email: string) =>
91
+ email === "taken@example.com"
92
+ ? Result.err<SignupError>(new ConflictError({ message: "Email already used" }))
93
+ : Result.ok({ id: "u_123", email })
94
+
95
+ const signup = (email: string) => pipe(validateEmail(email), Result.flatMap(createUser))
96
+ ```
97
+
98
+ ### Option
99
+
100
+ Option models optional presence/absence when missing data is expected and not an error condition.
101
+
102
+ #### Abstract Example
103
+
104
+ ```ts
105
+ import { Option, pipe } from "@nicolastoulemont/std"
106
+
107
+ const normalizedName = (value: string | undefined) =>
108
+ pipe(
109
+ Option.fromNullable(value),
110
+ Option.map((name) => name.trim()),
111
+ Option.filter((name) => name.length > 0),
112
+ Option.unwrapOr("Anonymous"),
113
+ )
114
+ ```
115
+
116
+ #### Real-World Example
117
+
118
+ ```ts
119
+ import { Option, pipe } from "@nicolastoulemont/std"
120
+
121
+ const readPagination = (query: URLSearchParams) => ({
122
+ page: pipe(
123
+ Option.fromNullable(query.get("page")),
124
+ Option.map((raw) => Number.parseInt(raw, 10)),
125
+ Option.filter((n) => Number.isInteger(n) && n > 0),
126
+ Option.unwrapOr(1),
127
+ ),
128
+ limit: pipe(
129
+ Option.fromNullable(query.get("limit")),
130
+ Option.map((raw) => Number.parseInt(raw, 10)),
131
+ Option.filter((n) => Number.isInteger(n) && n > 0 && n <= 100),
132
+ Option.unwrapOr(20),
133
+ ),
134
+ })
135
+ ```
136
+
137
+ ### Either
138
+
139
+ Either models two valid branches where both sides are meaningful outcomes rather than success versus failure.
140
+
141
+ #### Abstract Example
142
+
143
+ ```ts
144
+ import { Either } from "@nicolastoulemont/std"
145
+
146
+ const parseSource = (input: "local" | "remote") => (input === "local" ? Either.left("LOCAL") : Either.right("REMOTE"))
147
+
148
+ const label = Either.match(parseSource("local"), {
149
+ Left: (source) => `Source: ${source}`,
150
+ Right: (source) => `Source: ${source}`,
151
+ })
152
+ ```
153
+
154
+ #### Real-World Example
155
+
156
+ ```ts
157
+ import { Either, pipe } from "@nicolastoulemont/std"
158
+
159
+ type Source = "cache" | "database"
160
+ type User = { id: string; name: string }
161
+
162
+ const findUser = (id: string) =>
163
+ id.startsWith("cached:") ? Either.left<Source, User>("cache") : Either.right<Source, User>({ id, name: "Ada" })
164
+
165
+ const responseMeta = (id: string) =>
166
+ pipe(
167
+ findUser(id),
168
+ Either.match({
169
+ Left: (source) => ({ source, stale: true }),
170
+ Right: (user) => ({ source: "database" as const, stale: false, user }),
171
+ }),
172
+ )
173
+ ```
174
+
175
+ ### Fx
176
+
177
+ Fx models generator-based effects with typed dependencies and short-circuiting typed failures.
178
+
179
+ #### Abstract Example
180
+
181
+ ```ts
182
+ import { Fx, Layer, Provide, Service, pipe } from "@nicolastoulemont/std"
183
+
184
+ const Clock = Service.tag<{ now: () => number }>("Clock")
185
+ const ClockLive = Layer.ok(Clock, { now: () => Date.now() })
186
+
187
+ const program = Fx.gen(function* () {
188
+ const clock = yield* Clock
189
+ return clock.now()
190
+ })
191
+
192
+ const exit = Fx.run(pipe(program, Provide.layer(ClockLive)))
193
+
194
+ const timestamp = Fx.match(exit, {
195
+ Ok: (ok) => ok.value,
196
+ Err: () => 0,
197
+ Defect: () => 0,
198
+ })
199
+ ```
200
+
201
+ #### Real-World Example
202
+
203
+ ```ts
204
+ import { Fx, Layer, Result, Data, Provide, Service, pipe } from "@nicolastoulemont/std"
205
+
206
+ const Api = Service.tag<{ postOrder: (input: { sku: string; qty: number }) => Promise<{ orderId: string }> }>("Api")
207
+ const ApiLive = Layer.ok(Api, {
208
+ postOrder: async () => ({ orderId: "ord_42" }),
209
+ })
210
+
211
+ class InvalidQuantityError extends Data.TaggedError("InvalidQuantityError")<{ qty: number }> {}
212
+
213
+ const submitOrder = Fx.gen(function* (payload: { sku?: string; qty: number }) {
214
+ const api = yield* Api
215
+ const sku = yield* Fx.option(payload.sku)
216
+ const validQty = yield* Result.filter(
217
+ Result.ok(payload.qty),
218
+ (qty) => qty > 0,
219
+ (qty) => new InvalidQuantityError({ qty }),
220
+ )
221
+ return yield* Fx.try(() => api.postOrder({ sku, qty: validQty }))
222
+ })
223
+
224
+ const exit = Fx.run(pipe(submitOrder({ sku: "book-1", qty: 2 }), Provide.layer(ApiLive)))
225
+
226
+ const httpResponse = Fx.match(exit, {
227
+ Ok: (ok) => ({ status: 201, body: ok.value }),
228
+ Err: (err) => ({ status: 400, body: String(err.error) }),
229
+ Defect: () => ({ status: 500, body: "Unexpected defect" }),
230
+ })
231
+ ```
232
+
233
+ #### Retry Example
234
+
235
+ ```ts
236
+ import { Fx, Result, Schedule } from "@nicolastoulemont/std"
237
+
238
+ let attempts = 0
239
+
240
+ const flaky = Fx.gen(function* () {
241
+ attempts += 1
242
+ if (attempts < 3) {
243
+ return yield* Result.err("temporary" as const)
244
+ }
245
+ return "ok"
246
+ })
247
+
248
+ const exit = Fx.run(Fx.retry(flaky, Schedule.recurs(5)))
249
+ ```
250
+
251
+ #### Nested Retry with Dependencies
252
+
253
+ ```ts
254
+ import { Fx, Layer, Result, Schedule, pipe, Provide, Service } from "@nicolastoulemont/std"
255
+
256
+ type ConfigService = { baseUrl: string }
257
+ const Config = Service.tag<ConfigService>("Config")
258
+ const ConfigLive = Layer.ok(Config, { baseUrl: "https://api.example.com" })
259
+
260
+ let attempts = 0
261
+
262
+ const inner = Fx.retry(
263
+ Fx.gen(function* () {
264
+ const config = yield* Config
265
+ attempts += 1
266
+ if (attempts < 2) {
267
+ return yield* Result.err("temporary" as const)
268
+ }
269
+ return config.baseUrl
270
+ }),
271
+ Schedule.recurs(2),
272
+ )
273
+
274
+ const program = Fx.gen(function* () {
275
+ const baseUrl = yield* inner
276
+ return `ready:${baseUrl}`
277
+ })
278
+
279
+ const exit = Fx.run(pipe(program, Provide.layer(ConfigLive)))
280
+ ```
281
+
282
+ #### Concurrent Traversal with Fx.forEach
283
+
284
+ ```ts
285
+ import { Fx } from "@nicolastoulemont/std"
286
+
287
+ const loadUsers = Fx.forEach(
288
+ ["u1", "u2", "u3"],
289
+ (id) =>
290
+ Fx.gen(async function* () {
291
+ const response = await fetch(`/api/users/${id}`)
292
+ return yield* Fx.try(() => response.json())
293
+ }),
294
+ { concurrency: 2 },
295
+ )
296
+
297
+ const exit = await Fx.run(loadUsers)
298
+ ```
299
+
300
+ ### Queue
301
+
302
+ Queue provides a standalone FIFO task queue with configurable concurrency, backpressure (bounded mode), and lifecycle controls.
303
+
304
+ #### Abstract Example
305
+
306
+ ```ts
307
+ import { Queue } from "@nicolastoulemont/std"
308
+
309
+ const queue = Queue.make({ concurrency: 2 })
310
+
311
+ const first = queue.enqueue(() => 1)
312
+ const second = queue.enqueue(async () => 2)
313
+
314
+ await queue.awaitIdle()
315
+ await queue.shutdown({ mode: "drain" })
316
+ ```
317
+
318
+ #### Real-World Example
319
+
320
+ ```ts
321
+ import { Queue } from "@nicolastoulemont/std"
322
+
323
+ const imageQueue = Queue.bounded(100, { concurrency: 4 })
324
+
325
+ const tasks = imageUrls.map((url) =>
326
+ imageQueue.enqueue(async ({ signal }) => {
327
+ const response = await fetch(url, { signal })
328
+ return response.arrayBuffer()
329
+ }),
330
+ )
331
+
332
+ const buffers = await Promise.all(tasks)
333
+ await imageQueue.shutdown({ mode: "drain" })
334
+ ```
335
+
336
+ ### Multithread
337
+
338
+ Multithread runs self-contained callbacks in worker threads using a Result-first API while remaining yieldable in `Fx.gen`.
339
+
340
+ #### Abstract Example
341
+
342
+ ```ts
343
+ import { Multithread } from "@nicolastoulemont/std"
344
+
345
+ const op = Multithread.run((input: string, ctx) => {
346
+ ctx.throwIfCancelled()
347
+ return input.toUpperCase()
348
+ }, "hello")
349
+
350
+ const result = await op.result()
351
+ ```
352
+
353
+ #### Real-World Example
354
+
355
+ ```ts
356
+ import { Fx, Multithread } from "@nicolastoulemont/std"
357
+
358
+ const program = Fx.gen(async function* () {
359
+ const records = yield* Multithread.map(
360
+ ['{"id":"1","email":"a@example.com"}', '{"id":"2","email":"b@example.com"}'],
361
+ (line, _index, ctx) => {
362
+ ctx.throwIfCancelled()
363
+ try {
364
+ return JSON.parse(line) as { id: string; email: string }
365
+ } catch {
366
+ return { _tag: "Err" as const, error: { _tag: "ParseError" as const, line } }
367
+ }
368
+ },
369
+ { parallelism: 4 },
370
+ )
371
+
372
+ const preferred = yield* Multithread.firstSuccess([Multithread.run(() => "cache"), Multithread.run(() => "database")])
373
+
374
+ return { records, preferred }
375
+ })
376
+
377
+ const exit = await Fx.run(program)
378
+ ```
379
+
380
+ Multithread cancellation is cooperative. `abort()` always cancels logically, and worker code can stop early by calling `ctx.throwIfCancelled()`.
381
+
382
+ ### Adt
383
+
384
+ Adt provides schema-backed tagged variants so you can model domain state with exhaustive pattern matching.
385
+
386
+ #### Abstract Example
387
+
388
+ ```ts
389
+ import { Adt, type AdtInfer } from "@nicolastoulemont/std"
390
+ import { z } from "zod"
391
+
392
+ const Shape = Adt.union("Shape", {
393
+ Circle: z.object({ radius: z.number() }),
394
+ Square: z.object({ side: z.number() }),
395
+ })
396
+ type Shape = AdtInfer<typeof Shape>
397
+
398
+ const describeShape = (shape: Shape) =>
399
+ Adt.match(shape, {
400
+ Circle: (value) => `circle(${value.radius})`,
401
+ Square: (value) => `square(${value.side})`,
402
+ })
403
+ ```
404
+
405
+ #### Real-World Example
406
+
407
+ ```ts
408
+ import { Adt, type AdtInfer } from "@nicolastoulemont/std"
409
+ import { z } from "zod"
410
+
411
+ const OrderState = Adt.union("OrderState", {
412
+ Draft: z.object({ id: z.string() }),
413
+ Confirmed: z.object({ id: z.string(), paymentId: z.string() }),
414
+ Shipped: z.object({ id: z.string(), trackingId: z.string() }),
415
+ })
416
+ type OrderState = AdtInfer<typeof OrderState>
417
+
418
+ const badgeLabel = (state: OrderState) =>
419
+ Adt.match(state, {
420
+ Draft: () => "Waiting for payment",
421
+ Confirmed: () => "Preparing shipment",
422
+ Shipped: (value) => `Shipped: ${value.trackingId}`,
423
+ })
424
+ ```
425
+
426
+ ### Data
427
+
428
+ Data creates immutable structural value objects (`Data.struct`, `Data.tuple`, `Data.array`, `Data.tagged`) with stable equality and hashing semantics.
429
+
430
+ #### Abstract Example
431
+
432
+ ```ts
433
+ import { Data } from "@nicolastoulemont/std"
434
+
435
+ const a = Data.struct({ env: "prod", retries: 3 })
436
+ const b = Data.struct({ env: "prod", retries: 3 })
437
+
438
+ const same = a.equals(b) // true
439
+ ```
440
+
441
+ #### Real-World Example
442
+
443
+ ```ts
444
+ import { Data } from "@nicolastoulemont/std"
445
+
446
+ const previous = Data.struct({ search: "books", sort: "price-asc" })
447
+ const next = Data.struct({ search: "books", sort: "price-asc" })
448
+
449
+ if (previous.equals(next)) {
450
+ // Skip redundant fetch because filter state is structurally identical
451
+ }
452
+ ```
453
+
454
+ ### Order
455
+
456
+ Order provides composable comparators and immutable sorting helpers.
457
+
458
+ #### Abstract Example
459
+
460
+ ```ts
461
+ import { Order, pipe } from "@nicolastoulemont/std"
462
+
463
+ type User = { name: string; age: number }
464
+
465
+ const byAge = Order.by(Order.number, (user: User) => user.age)
466
+ const byName = Order.by(Order.string, (user: User) => user.name)
467
+
468
+ const userOrder = Order.merge(byAge, byName)
469
+ const sameOrder = pipe(byAge, Order.merge(byName))
470
+ const allOrders = Order.merge([byAge, byName])
471
+
472
+ const sorted = Order.sort(
473
+ [
474
+ { name: "bob", age: 30 },
475
+ { name: "alice", age: 30 },
476
+ { name: "zoe", age: 25 },
477
+ ],
478
+ allOrders,
479
+ )
480
+ ```
481
+
482
+ #### Real-World Example
483
+
484
+ ```ts
485
+ import { Order } from "@nicolastoulemont/std"
486
+
487
+ type Product = {
488
+ id: string
489
+ category: string
490
+ price: number
491
+ rating: number
492
+ }
493
+
494
+ const byCategory = Order.by(Order.string, (product: Product) => product.category)
495
+ const byPrice = Order.by(Order.number, (product: Product) => product.price)
496
+ const byRatingDesc = Order.reverse(Order.by(Order.number, (product: Product) => product.rating))
497
+
498
+ const sortProducts = Order.sortBy(byCategory, byPrice, byRatingDesc)
499
+
500
+ const products: Product[] = [
501
+ { id: "a", category: "books", price: 20, rating: 4.8 },
502
+ { id: "b", category: "books", price: 20, rating: 4.5 },
503
+ { id: "c", category: "games", price: 60, rating: 4.7 },
504
+ ]
505
+
506
+ const sorted = sortProducts(products)
507
+ ```
508
+
509
+ ### pipe / flow
510
+
511
+ pipe and flow compose sync/async transformations into readable, type-inferred data pipelines.
512
+
513
+ #### Abstract Example
514
+
515
+ ```ts
516
+ import { pipe, flow } from "@nicolastoulemont/std"
517
+
518
+ const toLabel = flow(
519
+ (n: number) => n * 2,
520
+ (n) => n.toString(),
521
+ (s) => `value:${s}`,
522
+ )
523
+
524
+ const result = pipe(10, (n) => n + 1, toLabel) // "value:22"
525
+ ```
526
+
527
+ #### Real-World Example
528
+
529
+ ```ts
530
+ import { pipe } from "@nicolastoulemont/std"
531
+
532
+ type RawProfile = { name?: string; age?: string }
533
+
534
+ const normalizeProfile = (input: RawProfile) =>
535
+ pipe(
536
+ input,
537
+ (p) => ({ name: p.name?.trim() ?? "", age: Number.parseInt(p.age ?? "0", 10) }),
538
+ (p) => ({ ...p, age: Number.isNaN(p.age) ? 0 : p.age }),
539
+ (p) => ({ ...p, isAdult: p.age >= 18 }),
540
+ )
541
+ ```
542
+
543
+ ## Documentation
544
+
545
+ - Usage examples: `EXAMPLES.md`
546
+ - Fx integration notes: `docs/fx-react-integration.md`
547
+ - JSDoc conventions: `docs/jsdoc-style.md`
@@ -1,2 +1,2 @@
1
- import { _ as VariantNames, a as record, c as CodecDef, d as Infer, f as InferInput, g as ValidationError, h as RecordObject, i as data, l as CodecError, m as RecordDef, n as MatchHandlers, o as ADT, p as InferOutput, r as match, s as CodecConstraint, t as createCodecError, u as ExtractSchema, v as VariantOf } from "../index-DLlx9jiG.mjs";
2
- export { ADT, CodecConstraint, CodecDef, CodecError, ExtractSchema, Infer, InferInput, InferOutput, MatchHandlers, RecordDef, RecordObject, ValidationError, VariantNames, VariantOf, createCodecError, data, match, record };
1
+ import { t as adt_d_exports } from "../index-DKS1g1oC.mjs";
2
+ export { adt_d_exports as Adt };
@@ -1 +1 @@
1
- import{i as e,n as t,r as n,t as r}from"../adt-DZmVJG4P.mjs";export{e as createCodecError,t as data,r as match,n as record};
1
+ import{t as e}from"../adt-DajUZvJe.mjs";export{e as Adt};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-C934ptG5.mjs";import{i as t,n,r,t as i}from"./equality-CoyUHWh9.mjs";import{n as a}from"./flow-D8_tllWl.mjs";import{r as o,t as s}from"./result-BEzV0DYC.mjs";function c(e,t){let n=t[e._tag];return n(e)}function l(e){return typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===Object.prototype}function u(e){return typeof e==`function`&&`_variant`in e&&e._variant===!0}function d(e){return e.issues?s({issues:e.issues.map(e=>({message:e.message,path:e.path?.map(e=>typeof e==`object`&&`key`in e?e.key:e)}))}):o(e.value)}function f(e,t,n){let r=e[`~standard`].validate(t);if(a(r))throw Error(`Async validation not supported. Schema for "${n}" returned a Promise. Use a synchronous schema or handle async validation separately.`);return d(r)}function p(e){return t=>l(t)&&`_tag`in t&&t._tag===e}function m(e){let t=new Set(e);return e=>l(e)&&`_tag`in e&&typeof e._tag==`string`&&t.has(e._tag)}function h(e,t,n,r){return n!==void 0&&r!==void 0?{kind:e,message:t,cause:n,validationIssues:r}:n===void 0?r===void 0?{kind:e,message:t}:{kind:e,message:t,validationIssues:r}:{kind:e,message:t,cause:n}}function g(e){return{to:e=>JSON.stringify(e),from:e=>{try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`_tag`in t){let{_tag:e,...n}=t;return n}return t}catch{return null}}}}function _(e,t,n){let r=g(e),i={json:n=>{let i=f(t,{...n,_tag:e},e);if(i._tag===`Err`)return s(h(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return o(r.to(i.value))}catch(e){return s(h(`EncodingError`,`JSON encoding failed: ${e instanceof Error?e.message:String(e)}`,e))}}};if(n)for(let[r,a]of Object.entries(n))i[r]=n=>{let i=f(t,{...n,_tag:e},e);if(i._tag===`Err`)return s(h(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return o(a.to(i.value))}catch(e){return s(h(`EncodingError`,`Encoding with codec '${r}' failed: ${e instanceof Error?e.message:String(e)}`,e))}};return i}function v(e,t,n){let r=g(e),i={json:n=>{let i=r.from(n);if(i===null)return s(h(`DecodingError`,`Invalid JSON format`));let a=f(t,{...i,_tag:e},e);return a._tag===`Err`?s(h(`ValidationError`,`Decoded data failed schema validation`,void 0,a.error.issues)):o({...a.value,_tag:e})}};if(n)for(let[r,a]of Object.entries(n))i[r]=n=>{let i;try{i=a.from(n)}catch(e){return s(h(`DecodingError`,`Decoding with codec '${r}' threw an error`,e))}if(i===null)return s(h(`DecodingError`,`Codec '${r}' failed to decode input`));let c=f(t,{...i,_tag:e},e);return c._tag===`Err`?s(h(`ValidationError`,`Decoded data failed schema validation`,void 0,c.error.issues)):o({...c.value,_tag:e})};return i}function y(e,n,i){let a=p(e),c=_(e,n,i),l=v(e,n,i),u=r(e),d=t(e),m=t=>{let r=f(n,{...t,_tag:e},e);return r._tag===`Err`?s(r.error):o({...r.value,_tag:e})};return m._variant=!0,m._tag=e,m.schema=n,i&&(m.codecs=i),m.is=a,m.to=c,m.from=l,m.equals=u,m.hash=d,m}function b(e,t){let r=Object.keys(t),a={};for(let[e,n]of Object.entries(t))u(n)?n._tag===e?a[e]=n:n.codecs?a[e]=y(e,n.schema,n.codecs):a[e]=y(e,n.schema):a[e]=y(e,n);return{_name:e,is:m(r),equals:i(r),hash:n(r),...a}}var x=e({match:()=>w,union:()=>S,variant:()=>C});const S=b,C=y,w=c;export{x as t};
2
+ //# sourceMappingURL=adt-DajUZvJe.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adt-DajUZvJe.mjs","names":["match","variant","union","variant","unionImpl","variantImpl","matchImpl"],"sources":["../src/adt/adt.match.ts","../src/shared/is-plain-object.ts","../src/adt/adt.utils.ts","../src/adt/adt.codec.ts","../src/adt/adt.variant.ts","../src/adt/adt.union.ts","../src/adt/adt.ts"],"sourcesContent":["/**\n * Handler functions for each variant in a discriminated union.\n * Each key maps to a function that receives the variant value and returns TResult.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n */\ntype AdtMatchHandlers<T extends { readonly _tag: string }, TResult> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { readonly _tag: K }>) => TResult\n}\n\n/**\n * Exhaustive pattern matching for discriminated unions.\n *\n * TypeScript will error if any variant is missing from handlers,\n * ensuring exhaustive handling of all cases.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n * @template Handlers - The handler object type (inferred)\n * @param value - A discriminated union value with _tag\n * @param handlers - An object with a handler function for each variant\n * @returns The result of calling the matching handler\n *\n * @see {@link union} for creating discriminated unions\n * @see {@link variant} for creating individual variant types\n *\n * @example\n * ```ts\n * const Shape = union('Shape', { Circle, Square })\n * type Shape = AdtInfer<typeof Shape>\n *\n * function describeShape(shape: Shape): string {\n * return match(shape, {\n * Circle: (c) => `Circle with radius ${c.radius}`,\n * Square: (s) => `Square with size ${s.size}`,\n * })\n * }\n * ```\n */\nexport function match<\n T extends { readonly _tag: string },\n TResult,\n Handlers extends AdtMatchHandlers<T, TResult> = AdtMatchHandlers<T, TResult>,\n>(value: T, handlers: Handlers): TResult {\n const tag = value._tag as keyof Handlers\n const handler = handlers[tag]\n // oxlint-disable-next-line no-explicit-any, no-unsafe-argument, no-unsafe-type-assertion -- Required for variant dispatch\n return handler(value as any)\n}\n","/**\n * Check if a value is a plain object.\n * A plain object is an object created with `{}`, `Object.create(null)`, or `new Object()`.\n * Arrays, functions, dates, maps, etc. are not considered plain objects.\n */\nexport function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n\n return Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport { isPromise } from \"../shared/is-promise\"\nimport type { AdtVariant, AdtValidationError } from \"./adt.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is an AdtVariant created by variant().\n * AdtVariants are callable functions with static properties.\n */\nexport function isVariant(value: unknown): value is AdtVariant {\n return typeof value === \"function\" && \"_variant\" in value && value[\"_variant\"] === true\n}\n\n/**\n * Wrap Standard Schema validation result into our Result type.\n */\nfunction wrapValidationResult<T>(result: StandardSchemaV1.Result<T>): Result<T, AdtValidationError> {\n if (result.issues) {\n return err({\n issues: result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((segment) => (typeof segment === \"object\" && \"key\" in segment ? segment.key : segment)),\n })),\n })\n }\n return ok(result.value)\n}\n\n/**\n * Validate data using a Standard Schema, enforcing sync-only validation.\n * Throws if the schema returns a Promise.\n */\nexport function validateSync<T>(\n schema: StandardSchemaV1<unknown, T>,\n data: unknown,\n _tag: string,\n): Result<T, AdtValidationError> {\n const result = schema[\"~standard\"].validate(data)\n\n if (isPromise(result)) {\n throw new Error(\n `Async validation not supported. Schema for \"${_tag}\" returned a Promise. ` +\n `Use a synchronous schema or handle async validation separately.`,\n )\n }\n\n return wrapValidationResult(result)\n}\n\n/**\n * Create a type guard function for a specific _tag.\n */\nexport function createIsGuard<Tag extends string, T>(\n _tag: Tag,\n): (value: unknown) => value is T & { readonly _tag: Tag } {\n return (value: unknown): value is T & { readonly _tag: Tag } => {\n return isPlainObject(value) && \"_tag\" in value && value[\"_tag\"] === _tag\n }\n}\n\n/**\n * Create a type guard function for multiple _tags (AdtUnion root guard).\n */\nexport function createIsAnyGuard<T>(_tags: readonly string[]): (value: unknown) => value is T {\n const _tagSet = new Set(_tags)\n return (value: unknown): value is T => {\n return isPlainObject(value) && \"_tag\" in value && typeof value[\"_tag\"] === \"string\" && _tagSet.has(value[\"_tag\"])\n }\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type {\n AdtCodecConstraint,\n AdtCodecDef,\n AdtCodecError,\n AdtInferInput,\n AdtInferOutput,\n AdtValidationError,\n ToMethods,\n FromMethods,\n} from \"./adt.types\"\nimport { validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a AdtCodecError with consistent structure.\n */\nfunction createCodecError(\n kind: AdtCodecError[\"kind\"],\n message: string,\n cause?: unknown,\n validationIssues?: AdtValidationError[\"issues\"],\n): AdtCodecError {\n if (cause !== undefined && validationIssues !== undefined) {\n return { kind, message, cause, validationIssues }\n }\n if (cause !== undefined) {\n return { kind, message, cause }\n }\n if (validationIssues !== undefined) {\n return { kind, message, validationIssues }\n }\n return { kind, message }\n}\n\n/**\n * Built-in JSON codec that works with any schema.\n * Encodes to JSON string and decodes with JSON.parse.\n */\nfunction createJsonCodec<Tag extends string, S extends StandardSchemaV1>(\n _tag: Tag,\n): AdtCodecDef<AdtInferOutput<S> & Discriminator<Tag>, string, AdtInferInput<S>> {\n return {\n to: (value) => {\n // JSON.stringify can throw for circular references, BigInt, etc.\n // We let it throw and catch it in the wrapper\n return JSON.stringify(value)\n },\n /* oxlint-disable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return -- Required for JSON parsing which returns unknown types */\n from: (input: string) => {\n try {\n const parsed = JSON.parse(input)\n // Return parsed object without _tag - it will be added during validation\n if (typeof parsed === \"object\" && parsed !== null && \"_tag\" in parsed) {\n const { _tag: _, ...rest } = parsed\n return rest as AdtInferInput<S>\n }\n return parsed\n } catch {\n return null\n }\n },\n /* oxlint-enable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return */\n }\n}\n\n/**\n * Create the \"to\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createToMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): ToMethods<S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const to: Record<string, (value: AdtInferInput<S>) => Result<any, AdtCodecError>> = {\n json: (value: AdtInferInput<S>): Result<string, AdtCodecError> => {\n // First, create a validated variant to ensure the encoded payload is well-typed.\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input into object\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(jsonCodec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\"EncodingError\", `JSON encoding failed: ${e instanceof Error ? e.message : String(e)}`, e),\n )\n }\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n to[name] = (value: AdtInferInput<S>): Result<any, AdtCodecError> => {\n // Validate input first\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(codec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\n \"EncodingError\",\n `Encoding with codec '${name}' failed: ${e instanceof Error ? e.message : String(e)}`,\n e,\n ),\n )\n }\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return to as ToMethods<S, Codecs>\n}\n\n/**\n * Create the \"from\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createFromMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): FromMethods<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const from: Record<string, (input: any) => Result<Output, AdtCodecError>> = {\n json: (input: string): Result<Output, AdtCodecError> => {\n // Decode\n const decoded = jsonCodec.from(input)\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", \"Invalid JSON format\"))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\"ValidationError\", \"Decoded data failed schema validation\", undefined, result.error.issues),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n from[name] = (input: unknown): Result<Output, AdtCodecError> => {\n // Decode\n let decoded: unknown\n try {\n decoded = codec.from(input)\n } catch (e) {\n return err(createCodecError(\"DecodingError\", `Decoding with codec '${name}' threw an error`, e))\n }\n\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", `Codec '${name}' failed to decode input`))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n \"Decoded data failed schema validation\",\n undefined,\n result.error.issues,\n ),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return from as FromMethods<Tag, S, Codecs>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport { createToMethods, createFromMethods } from \"./adt.codec\"\nimport type { AdtCodecConstraint, AdtInferInput, AdtInferOutput, AdtVariant, AdtValidationError } from \"./adt.types\"\nimport { createIsGuard, validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged variant from a Standard Schema with optional codecs.\n *\n * Variants can be used independently or composed into an AdtUnion via union().\n * All defaults should be defined at the schema level (e.g., Zod's .default()).\n *\n * @template Tag - The string literal type for the _tag discriminator\n * @template S - The Standard Schema type for validation\n * @template Codecs - Optional codec definitions for custom serialization formats\n * @param _tag - The _tag discriminator value\n * @param schema - A Standard Schema compliant validator\n * @param codecs - Optional codec definitions for custom serialization formats\n * @returns A callable AdtVariant with is(), to, and from methods\n *\n * @see {@link union} for composing variants into discriminated unions\n * @see {@link tagged} for unvalidated tagged value constructors\n *\n * @example\n * ```ts\n * const CircleSchema = z.object({\n * radius: z.number().positive(),\n * color: z.string().default('blue')\n * })\n *\n * // Basic variant with JSON codec (always included)\n * const Circle = variant('Circle', CircleSchema)\n *\n * const result = Circle({ radius: 10 })\n * // { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 10, color: \"blue\" } }\n *\n * Circle.is(someValue) // type guard\n *\n * const json = Circle.to.json({ radius: 10 }) // JSON string\n * const result2 = Circle.from.json(json) // Result<Circle, AdtCodecError>\n *\n * // Variant with custom codec\n * const Circle2 = variant('Circle', CircleSchema, {\n * graphic: {\n * to: (circle) => `(${circle.radius})`,\n * from: (input: string) => {\n * const match = input.match(/^\\((\\d+)\\)$/)\n * return match ? { radius: parseInt(match[1]!) } : null\n * }\n * }\n * })\n *\n * const graphic = Circle2.to.graphic({ radius: 10 }) // \"(10)\"\n * const result3 = Circle2.from.graphic(\"(10)\") // Result<Circle, AdtCodecError>\n * ```\n */\n// Overload: with codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1, Codecs extends AdtCodecConstraint<Tag, S>>(\n _tag: Tag,\n schema: S,\n codecs: Codecs,\n): AdtVariant<Tag, S, Codecs>\n\n// Overload: without codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): AdtVariant<Tag, S>\n\n// Implementation\nexport function variant<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined,\n>(_tag: Tag, schema: S, codecs?: Codecs): AdtVariant<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const isGuard = createIsGuard<Tag, Output>(_tag)\n const to = createToMethods(_tag, schema, codecs)\n const from = createFromMethods(_tag, schema, codecs)\n const equals = createEqualsMethod<Tag, AdtInferOutput<S>>(_tag)\n const hash = createHashMethod<Tag, AdtInferOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: AdtInferInput<S>): Result<Output, AdtValidationError> => {\n // Add _tag to the input before validation\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(input as object), _tag }\n\n // Validate using the schema\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(result.error)\n }\n\n // Ensure _tag is in the output (schema might strip unknown keys)\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n\n // Attach static properties to constructor function\n constructor._variant = true as const\n constructor._tag = _tag\n constructor.schema = schema\n if (codecs) {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Conditional assignment of codecs\n ;(constructor as { codecs?: Codecs }).codecs = codecs\n }\n constructor.is = isGuard\n constructor.to = to\n constructor.from = from\n constructor.equals = equals\n constructor.hash = hash\n\n return constructor as AdtVariant<Tag, S, Codecs>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport type { AdtUnion, AdtVariantDef, AdtVariant } from \"./adt.types\"\nimport { createIsAnyGuard, isVariant } from \"./adt.utils\"\nimport { variant } from \"./adt.variant\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (AdtUnion).\n *\n * Accepts either:\n * - Pre-built AdtVariants from variant() (codecs are preserved)\n * - Raw Standard Schema validators (will be wrapped internally)\n *\n * When using pre-built records, the object key overrides the original _tag.\n *\n * @template R - Record of variant names to AdtVariants or StandardSchema validators\n * @param name - The name of this AdtUnion (for identification)\n * @param records - An object mapping _tag names to AdtVariants or schemas\n * @returns An AdtUnion object with accessors for each variant\n *\n * @see {@link variant} for creating individual variant types\n * @see {@link match} for exhaustive pattern matching on AdtUnion values\n *\n * @example\n * ```ts\n * // From pre-built variants\n * const Circle = variant('Circle', CircleSchema)\n * const Square = variant('Square', SquareSchema)\n * const Shape = union('Shape', { Circle, Square })\n *\n * // From raw schemas (JSON codec is automatically included)\n * const Shape = union('Shape', {\n * Circle: CircleSchema,\n * Square: SquareSchema\n * })\n *\n * // JSON codec works on all variants\n * Shape.Circle.to.json({ radius: 10 })\n * Shape.Circle.from.json(jsonString)\n *\n * // Mixed\n * const Shape = union('Shape', {\n * Circle, // Pre-built variant\n * Square: SquareSchema // Raw schema\n * })\n *\n * // Usage\n * Shape.Circle({ radius: 10 })\n * Shape.is(someValue) // type guard for any variant\n * Shape.Circle.is(someValue) // type guard for Circle\n * ```\n */\nexport function union<R extends Record<string, AdtVariantDef>>(name: string, records: R): AdtUnion<R> {\n const tags = Object.keys(records)\n const variants: Record<string, AdtVariant> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isVariant(def)) {\n // Pre-built AdtVariant - key overrides original _tag\n if (def._tag === _tag) {\n // _tag matches key, use as-is (preserves codecs)\n variants[_tag] = def\n // oxlint-disable-next-line strict-boolean-expressions -- codecs can be undefined\n } else if (def.codecs) {\n // _tag differs from key - create new variant with key as _tag\n // Preserve codecs\n variants[_tag] = variant(_tag, def.schema, def.codecs)\n } else {\n // _tag differs from key and no codecs\n variants[_tag] = variant(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in variant\n // Note: Even without custom codecs, this still gets JSON codec!\n // oxlint-disable-next-line no-unsafe-type-assertion -- def is a StandardSchemaV1 in this branch\n variants[_tag] = variant(_tag, def as StandardSchemaV1)\n }\n }\n\n // Create the root type guard for any variant\n const isAnyVariant = createIsAnyGuard(tags)\n const equals = createADTEqualsMethod(tags)\n const hash = createADTHashMethod(tags)\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic AdtUnion return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as AdtUnion<R>\n}\n","/**\n * Tagged union builders and match helpers.\n *\n * **Mental model**\n * - `Adt` helps build discriminated unions with runtime validation.\n * - Use `union`, `variant`, and `match` to model algebraic data types.\n *\n * **Common tasks**\n * - Define variants with `Adt.variant`.\n * - Combine variants with `Adt.union`.\n * - Pattern-match with `Adt.match`.\n *\n * **Gotchas**\n * - `Adt` codec/type helpers are mostly type-level.\n * - Prefer namespace imports from `@nicolastoulemont/std`.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * const Shape = Adt.union(\"Shape\", {} as never)\n * // => union helper with tagged constructors\n * ```\n *\n * @module\n */\nimport { match as matchImpl } from \"./adt.match\"\nimport type {\n AdtInfer as AdtInferType,\n AdtVariantNames as AdtVariantNamesType,\n AdtVariantOf as AdtVariantOfType,\n} from \"./adt.types\"\nimport { union as unionImpl } from \"./adt.union\"\nimport { variant as variantImpl } from \"./adt.variant\"\n\n/**\n * Re-exported ADT inferred union helper.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Adt\n * ```\n *\n * @category Type-level\n */\nexport type AdtInfer<T> = AdtInferType<T>\n\n/**\n * Re-exported union variant name helper.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Adt\n * ```\n *\n * @category Type-level\n */\nexport type AdtVariantNames<T> = AdtVariantNamesType<T>\n\n/**\n * Re-exported helper to extract a specific variant from an ADT.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Adt\n * ```\n *\n * @category Type-level\n */\nexport type AdtVariantOf<T, K extends string> = AdtVariantOfType<T, K>\n\n/**\n * Build an ADT union from named variants.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * const Shape = Adt.union(\"Shape\", {} as never)\n * // => union helper with tagged constructors\n * ```\n *\n * @category Constructors\n */\nexport const union = unionImpl\n\n/**\n * Define one ADT variant with schema-backed validation.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * const Circle = Adt.variant(\"Circle\", {} as never)\n * // => callable variant constructor\n * ```\n *\n * @category Constructors\n */\nexport const variant = variantImpl\n\n/**\n * Match over ADT variants by discriminator tag.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * const label = Adt.match({ _tag: \"Circle\", radius: 2 } as const, {\n * Circle: (circle) => `r=${circle.radius}` ,\n * })\n * // => \"r=2\"\n * ```\n *\n * @category Pattern Matching\n */\nexport const match = matchImpl\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import { a as unsafeMake, c as BrandKey, d as Unbrand, i as refine, l as BrandRefinement, n as is, o as Brand$1, r as make, s as BrandError, t as Brand, u as Branded } from "../index-DjjJIDaA.mjs";
2
- export { Brand, BrandError, BrandKey, BrandRefinement, Brand$1 as BrandType, Branded, Unbrand, is, make, refine, unsafeMake };
1
+ import { t as brand_d_exports } from "../index-DXbYlSnB.mjs";
2
+ export { brand_d_exports as Brand };
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"../brand-BUqMmkzC.mjs";export{i as Brand,n as is,r as make,t as refine,e as unsafeMake};
1
+ import{t as e}from"../brand-Bia3Vj6l.mjs";export{e as Brand};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-C934ptG5.mjs";import{r as t,t as n}from"./result-BEzV0DYC.mjs";var r=e({is:()=>o,make:()=>i,refine:()=>s,unsafeMake:()=>a});const i=e=>e,a=e=>e,o=e=>t=>e(t),s=(e,r)=>i=>e(i)?t(i):n({_tag:`BrandError`,value:i,message:typeof r==`function`?r(i):r??`Brand validation failed`});export{r as t};
2
+ //# sourceMappingURL=brand-Bia3Vj6l.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brand-Bia3Vj6l.mjs","names":["Result.err","Result.ok"],"sources":["../src/brand/brand.ts"],"sourcesContent":["/**\n * Nominal branding utilities for lightweight domain types.\n *\n * **Mental model**\n * - Brands let you distinguish semantically different values with the same runtime shape.\n * - `Brand.refine` validates and returns `Result`, while `Brand.make` is unchecked.\n *\n * **Common tasks**\n * - Create branded values with `Brand.make`.\n * - Add runtime validation with `Brand.refine`.\n * - Build guards with `Brand.is`.\n *\n * **Gotchas**\n * - Branding is a type-level operation and does not change runtime representation.\n * - `unsafeMake` should be reserved for trusted sources.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type UserId = Brand.Branded<string, \"UserId\">\n * const raw = \"user_123\" as UserId\n * const userId = Brand.make<UserId>(raw)\n * // => brand-preserving cast\n * ```\n *\n * @module\n */\nimport { Result } from \"../result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport type { BrandError as BrandErrorType, Branded as BrandedType, Unbrand, Validator } from \"./brand.types\"\n\n/**\n * Re-exported nominal brand helper type.\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Brand\n * ```\n *\n * @category Type-level\n */\nexport type Branded<T, K extends string> = BrandedType<T, K>\n\n/**\n * Re-exported brand validation error type.\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Brand\n * ```\n *\n * @category Type-level\n */\nexport type BrandError<T> = BrandErrorType<T>\n\n/* oxlint-disable no-unsafe-type-assertion -- Branding is a deliberate nominal cast at the type level and requires explicit assertions. */\n\n/**\n * Create a branded value without validation.\n * This is a type-level cast with zero runtime cost.\n *\n * Use this when you trust the value source (e.g., from a database)\n * or when validation happens elsewhere.\n *\n * @template B - The branded type\n * @param value - The value to brand\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type UserId = Brand.Branded<string, \"UserId\">\n * const raw = \"user_123\" as UserId\n * const userId = Brand.make<UserId>(raw)\n * // => brand-preserving cast\n * ```\n *\n * @category Utilities\n */\nexport const make = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Alias for make() - explicitly indicates no validation occurs.\n * Prefer this when readability about the lack of validation is important.\n *\n * @template B - The branded type\n * @param value - The value to brand (unchecked)\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type UserId = Brand.Branded<string, \"UserId\">\n * const raw = \"user_123\" as UserId\n * const userId = Brand.unsafeMake<UserId>(raw)\n * // => unchecked brand cast\n * ```\n *\n * @category Utilities\n */\nexport const unsafeMake = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Create a type guard with validation for a branded type.\n * Returns a refinement predicate that narrows to the branded type.\n *\n * @template T - The base type\n * @template K - The brand key (string literal)\n * @param validator - A function that validates the base value\n * @returns A type guard that returns true if validation passes\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type UserId = Brand.Branded<string, \"UserId\">\n * const isUserId = Brand.is<string, \"UserId\">((value) => value.startsWith(\"user_\"))\n * const valid = isUserId(\"user_123\")\n * // => true\n * ```\n *\n * @category Utilities\n */\nexport const is = <T, K extends string>(validator: Validator<T>): ((value: T) => value is Branded<T, K>) => {\n return (value: T): value is Branded<T, K> => validator(value)\n}\n\n/**\n * Create a validated branded value wrapped in a Result.\n * Returns `Result.ok(brandedValue)` on success, `Result.err(BrandError)` on failure.\n *\n * The returned Result is yieldable in Fx.gen computations via `yield*`.\n *\n * @template B - The branded type\n * @param validator - A function that validates the base value\n * @param errorMessage - Optional custom error message (or function)\n * @returns A function that takes a value and returns a Result\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n *\n * type UserId = Brand.Branded<string, \"UserId\">\n * const toUserId = Brand.refine<UserId>((value) => value.startsWith(\"user_\"), \"Invalid user id\")\n * const parsed = toUserId(\"user_123\" as UserId)\n * // => { _tag: \"Ok\", value: \"user_123\" }\n * ```\n *\n * @category Utilities\n */\nexport const refine = <B extends Branded<unknown, string>>(\n validator: Validator<Unbrand<B>>,\n errorMessage?: string | ((value: Unbrand<B>) => string),\n): ((value: Unbrand<B>) => ResultType<B, BrandError<Unbrand<B>>>) => {\n return (value: Unbrand<B>) => {\n if (!validator(value)) {\n const msg = typeof errorMessage === \"function\" ? errorMessage(value) : (errorMessage ?? \"Brand validation failed\")\n return Result.err({ _tag: \"BrandError\" as const, value, message: msg })\n }\n return Result.ok(value as B)\n }\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"uJAuFA,MAAa,EAA4C,GAChD,EAuBI,EAAkD,GACtD,EAwBI,EAA2B,GAC9B,GAAqC,EAAU,EAAM,CA0BlD,GACX,EACA,IAEQ,GACD,EAAU,EAAM,CAIdC,EAAU,EAAW,CAFnBD,EAAW,CAAE,KAAM,aAAuB,QAAO,QAD5C,OAAO,GAAiB,WAAa,EAAa,EAAM,CAAI,GAAgB,0BAClB,CAAC"}
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&&e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
@@ -0,0 +1,2 @@
1
+ import { n as context_d_exports } from "../context-r8ESJiFn.mjs";
2
+ export { context_d_exports as Context };
@@ -0,0 +1 @@
1
+ import{t as e}from"../context-CCHj1nab.mjs";export{e as Context};