@carbonteq/fp 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 (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +237 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
@@ -0,0 +1,312 @@
1
+ /**
2
+ * ExperimentalResult Examples Index
3
+ *
4
+ * This file lists all available examples and demonstrates different
5
+ * patterns for working with ExperimentalResult types.
6
+ *
7
+ * NOTE: These examples are experimental-only and may change.
8
+ * For stable Result examples, see README.md.
9
+ *
10
+ * Run examples with:
11
+ * bun run examples/result-experimental/01-map.ts
12
+ * bun run examples/result-experimental/02-flatMap.ts
13
+ * etc.
14
+ */
15
+
16
+ // ============================================================================
17
+ // BASIC OPERATIONS (files 01-04)
18
+ // ============================================================================
19
+
20
+ /**
21
+ * 01-map.ts - Transform success values
22
+ *
23
+ * Topics covered:
24
+ * - Basic map usage
25
+ * - Map on Err (mapper not called)
26
+ * - Chaining multiple maps
27
+ * - Map with object transformation
28
+ * - Map with async functions (returns Result<Promise<T>, E>)
29
+ * - Map with array operations
30
+ * - Type transformations
31
+ *
32
+ * Run: bun run examples/result-experimental/01-map.ts
33
+ */
34
+
35
+ /**
36
+ * 02-flatMap.ts - Chain Result-returning functions
37
+ *
38
+ * Topics covered:
39
+ * - Basic flatMap chains
40
+ * - Short-circuit on errors
41
+ * - Chaining multiple flatMaps
42
+ * - Dependent lookups (user → posts)
43
+ * - Error type unions
44
+ * - Async flatMap
45
+ * - Validation pipelines
46
+ * - flatMap vs map comparison
47
+ * - Real-world user registration flow
48
+ *
49
+ * Run: bun run examples/result-experimental/02-flatMap.ts
50
+ */
51
+
52
+ /**
53
+ * 03-zip.ts - Pair original with derived value
54
+ *
55
+ * Topics covered:
56
+ * - Basic zip usage
57
+ * - Zip on Err
58
+ * - Async zip
59
+ * - Validation with context
60
+ * - Multiple zips
61
+ * - Audit trail patterns
62
+ * - Before/after comparisons
63
+ * - Error context preservation
64
+ * - Transformation history
65
+ * - Async API call patterns
66
+ *
67
+ * Run: bun run examples/result-experimental/03-zip.ts
68
+ */
69
+
70
+ /**
71
+ * 04-flatZip.ts - Pair original with Result-returning function
72
+ *
73
+ * Topics covered:
74
+ * - Basic flatZip usage
75
+ * - Short-circuit on errors
76
+ * - Chaining flatZips
77
+ * - Async flatZip
78
+ * - User and posts pattern
79
+ * - Dependent lookups
80
+ * - Validation with context
81
+ * - Complex object building
82
+ * - Sequential API calls
83
+ * - flatZip vs flatMap comparison
84
+ * - Audit log patterns
85
+ * - Context preservation
86
+ * - Multi-step validation
87
+ *
88
+ * Run: bun run examples/result-experimental/04-flatZip.ts
89
+ */
90
+
91
+ // ============================================================================
92
+ // GENERATOR-BASED SYNTAX (files 05-08)
93
+ // ============================================================================
94
+
95
+ /**
96
+ * 05-gen.ts - Imperative-style sync Result composition
97
+ *
98
+ * Topics covered:
99
+ * - Simple gen with single/multiple yields
100
+ * - Short-circuit on errors
101
+ * - Function calls in gen
102
+ * - Validation pipelines
103
+ * - gen vs flatMap readability
104
+ * - Complex object building
105
+ * - Intermediate processing
106
+ * - Array operations
107
+ * - Dependent operations
108
+ * - No yields case
109
+ * - Error context collection
110
+ * - Stack overflow prevention (many yields)
111
+ * - Conditional logic
112
+ * - Type information preservation
113
+ * - Error recovery with orElse
114
+ * - Sequential API patterns
115
+ * - Accumulator patterns
116
+ *
117
+ * Run: bun run examples/result-experimental/05-gen.ts
118
+ */
119
+
120
+ /**
121
+ * 06-genAdapter.ts - Generator with adapter for better type inference
122
+ *
123
+ * Topics covered:
124
+ * - Adapter function ($) usage
125
+ * - Improved type inference with different error types
126
+ * - Rich validation error types
127
+ * - Method calls on objects
128
+ * - API composition
129
+ * - Conditional logic
130
+ * - Parallel-like operations (sequential but clean)
131
+ * - Error type narrowing
132
+ * - Complex state building
133
+ * - Try-catch patterns (safeParseInt, safeDivide)
134
+ * - Array iteration
135
+ * - Multi-step validation
136
+ * - Nested genAdapter calls
137
+ * - Accumulator patterns
138
+ * - Transaction-like operations
139
+ * - gen vs genAdapter comparison
140
+ *
141
+ * Run: bun run examples/result-experimental/06-genAdapter.ts
142
+ */
143
+
144
+ /**
145
+ * 07-asyncGen.ts - Imperative-style async Result composition
146
+ *
147
+ * Topics covered:
148
+ * - Simple asyncGen with sync/async Results
149
+ * - Multiple yields with mixed sync/async
150
+ * - Short-circuit on errors
151
+ * - Async operations with delays
152
+ * - Fetching data patterns (user → posts)
153
+ * - Auto-awaiting Result<Promise<T>, E>
154
+ * - Async validation pipelines
155
+ * - Error recovery
156
+ * - Sequential API calls
157
+ * - Async map chains
158
+ * - Complex workflows (order → payment → receipt)
159
+ * - toPromise conversion
160
+ * - Retry-like patterns
161
+ * - Array processing
162
+ * - Conditional async operations
163
+ * - Batch operations
164
+ *
165
+ * Run: bun run examples/result-experimental/07-asyncGen.ts
166
+ */
167
+
168
+ /**
169
+ * 08-asyncGenAdapter.ts - Async generator with adapter
170
+ *
171
+ * Topics covered:
172
+ * - Adapter function ($) in async context
173
+ * - Promise<Result<T,E>> handling
174
+ * - Improved type inference
175
+ * - API composition
176
+ * - Auto-awaiting Result<Promise<T>, E>
177
+ * - Complex async validation
178
+ * - Transaction workflows
179
+ * - Retry logic with fallbacks
180
+ * - Data processing pipelines
181
+ * - Array operations
182
+ * - Conditional logic
183
+ * - Batch operations
184
+ * - Parallel-like patterns (sequential)
185
+ * - toPromise usage
186
+ * - Complex workflows (order → payment → shipment → invoice)
187
+ * - Error aggregation
188
+ * - Nested operations
189
+ * - Streaming-like patterns
190
+ *
191
+ * Run: bun run examples/result-experimental/08-asyncGenAdapter.ts
192
+ */
193
+
194
+ // ============================================================================
195
+ // WORKFLOW EXAMPLES (files 09-10)
196
+ // ============================================================================
197
+
198
+ /**
199
+ * 09-workflow-simple-sync.ts - Real-world sync workflow
200
+ *
201
+ * Domain: Grocery list management
202
+ *
203
+ * Comparisons shown:
204
+ * - flatMap chain style
205
+ * - Result.gen style
206
+ * - Result.genAdapter style
207
+ *
208
+ * Workflow steps:
209
+ * - Ensure ownership
210
+ * - Validate list is active
211
+ * - Validate items
212
+ * - Calculate stats
213
+ * - Serialize data
214
+ *
215
+ * Also covers:
216
+ * - Multi-step validation comparison
217
+ * - Fetching and chaining
218
+ * - Readability comparison
219
+ *
220
+ * Run: bun run examples/result-experimental/09-workflow-simple-sync.ts
221
+ */
222
+
223
+ /**
224
+ * 10-workflow-async.ts - Real-world async workflow
225
+ *
226
+ * Domain: Grocery list management with async operations
227
+ *
228
+ * Styles shown:
229
+ * - Result.asyncGen
230
+ * - Result.asyncGenAdapter
231
+ * - Auto-awaiting Result<Promise<T>, E>
232
+ * - Complex multi-step async validation
233
+ *
234
+ * Workflow steps:
235
+ * - Fetch list and owner (async)
236
+ * - Ensure ownership
237
+ * - Async permission validation
238
+ * - Validate list is active
239
+ * - Fetch items (async)
240
+ * - Validate items
241
+ * - Serialize (async)
242
+ * - Calculate stats (async)
243
+ *
244
+ * Also covers:
245
+ * - Error handling comparison
246
+ * - Sequential fetch patterns
247
+ * - toPromise conversion
248
+ * - Readability comparison
249
+ *
250
+ * Run: bun run examples/result-experimental/10-workflow-async.ts
251
+ */
252
+
253
+ // ============================================================================
254
+ // SHARED DOMAIN (for workflow examples)
255
+ // ============================================================================
256
+
257
+ /**
258
+ * shared-domain.ts - Domain models used in workflow examples
259
+ *
260
+ * Contains:
261
+ * - UserEntity, ItemEntity, GroceryListEntity classes
262
+ * - Error types (GroceryListOwnershipError, ValidationError)
263
+ * - Helper functions (calculateDetailedStats)
264
+ * - Mock data
265
+ * - Repository methods (sync and async)
266
+ *
267
+ * Imported by: 09-workflow-simple-sync.ts, 10-workflow-async.ts
268
+ */
269
+
270
+ // ============================================================================
271
+ // QUICK REFERENCE
272
+ // ============================================================================
273
+
274
+ /**
275
+ * WHEN TO USE EACH METHOD:
276
+ *
277
+ * map():
278
+ * - Transform success value
279
+ * - Error bypasses mapper
280
+ *
281
+ * flatMap():
282
+ * - Chain Result-returning functions
283
+ * - Stop on first error
284
+ *
285
+ * zip():
286
+ * - Keep original value along with transformed value
287
+ * - Returns [original, derived] tuple
288
+ *
289
+ * flatZip():
290
+ * - Like zip, but function returns Result
291
+ * - Stop on first error
292
+ *
293
+ * gen():
294
+ * - Imperative-style sync code
295
+ * - Multiple yields with automatic threading
296
+ * - Short-circuits on errors
297
+ *
298
+ * genAdapter():
299
+ * - Same as gen, with adapter function ($)
300
+ * - Better type inference for complex errors
301
+ *
302
+ * asyncGen():
303
+ * - Imperative-style async code
304
+ * - Handles Promise<Result<T,E>> and Result<Promise<T>,E>
305
+ * - Auto-awaits inner promises
306
+ *
307
+ * asyncGenAdapter():
308
+ * - Same as asyncGen, with adapter ($)
309
+ * - Best type inference for async workflows
310
+ */
311
+
312
+ export {}
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Shared domain models for workflow examples
3
+ */
4
+
5
+ import { ExperimentalResult as Result } from "../../dist/result-experimental.mjs"
6
+
7
+ // ============================================================================
8
+ // DOMAIN MODELS
9
+ // ============================================================================
10
+
11
+ type UserId = string
12
+ type GroceryListId = string
13
+ type ItemId = string
14
+
15
+ // User Entity
16
+ export class UserEntity {
17
+ constructor(
18
+ readonly id: UserId,
19
+ readonly name: string,
20
+ readonly email: string,
21
+ ) {}
22
+
23
+ serialize() {
24
+ return {
25
+ id: this.id,
26
+ name: this.name,
27
+ email: this.email,
28
+ }
29
+ }
30
+ }
31
+
32
+ // Item Entity
33
+ export class ItemEntity {
34
+ constructor(
35
+ readonly id: ItemId,
36
+ readonly name: string,
37
+ readonly quantity: number,
38
+ readonly isBought: boolean,
39
+ ) {}
40
+
41
+ serialize() {
42
+ return {
43
+ id: this.id,
44
+ name: this.name,
45
+ quantity: this.quantity,
46
+ isBought: this.isBought,
47
+ }
48
+ }
49
+ }
50
+
51
+ // Grocery List Entity
52
+ export class GroceryListEntity {
53
+ constructor(
54
+ readonly id: GroceryListId,
55
+ readonly name: string,
56
+ readonly description: string,
57
+ readonly active: boolean,
58
+ readonly ownerId: UserId,
59
+ ) {}
60
+
61
+ serialize() {
62
+ return {
63
+ id: this.id,
64
+ name: this.name,
65
+ description: this.description,
66
+ active: this.active,
67
+ ownerId: this.ownerId,
68
+ }
69
+ }
70
+
71
+ ensureIsOwner(user: UserEntity): Result<this, GroceryListOwnershipError> {
72
+ if (this.ownerId !== user.id) {
73
+ return Result.Err(new GroceryListOwnershipError(this.id))
74
+ }
75
+ return Result.Ok(this)
76
+ }
77
+ }
78
+
79
+ // Stats
80
+ export interface GroceryListStats {
81
+ totalItems: number
82
+ pendingItems: number
83
+ completedItems: number
84
+ completionPercentage: number
85
+ }
86
+
87
+ // Details output
88
+ export interface GroceryListDetails {
89
+ id: GroceryListId
90
+ name: string
91
+ description: string
92
+ active: boolean
93
+ owner: ReturnType<UserEntity["serialize"]>
94
+ items: ReturnType<ItemEntity["serialize"]>[]
95
+ stats: GroceryListStats
96
+ }
97
+
98
+ // Error types
99
+ export class GroceryListOwnershipError {
100
+ readonly _tag = "GroceryListOwnershipError"
101
+ constructor(readonly listId: GroceryListId) {}
102
+ }
103
+
104
+ export class ValidationError {
105
+ readonly _tag = "ValidationError"
106
+ constructor(readonly message: string) {}
107
+ }
108
+
109
+ export type GroceryListError = GroceryListOwnershipError | ValidationError
110
+
111
+ // ============================================================================
112
+ // HELPER FUNCTIONS
113
+ // ============================================================================
114
+
115
+ export function calculateDetailedStats(items: ItemEntity[]): GroceryListStats {
116
+ const totalItems = items.length
117
+ const pendingItems = items.filter((item) => !item.isBought).length
118
+ const completedItems = items.filter((item) => item.isBought).length
119
+
120
+ const completionPercentage =
121
+ totalItems > 0 ? (completedItems / totalItems) * 100 : 0
122
+
123
+ return {
124
+ totalItems,
125
+ pendingItems,
126
+ completedItems,
127
+ completionPercentage: Math.round(completionPercentage * 100) / 100,
128
+ }
129
+ }
130
+
131
+ // ============================================================================
132
+ // MOCK DATA
133
+ // ============================================================================
134
+
135
+ export const mockUser = new UserEntity("user-123", "Alice", "alice@example.com")
136
+
137
+ export const mockDifferentUser = new UserEntity(
138
+ "user-999",
139
+ "Bob",
140
+ "bob@example.com",
141
+ )
142
+
143
+ export const mockGroceryList = new GroceryListEntity(
144
+ "list-456",
145
+ "Weekly Shopping",
146
+ "Weekly grocery list",
147
+ true,
148
+ "user-123",
149
+ )
150
+
151
+ export const mockItems: ItemEntity[] = [
152
+ new ItemEntity("item-1", "Milk", 2, true),
153
+ new ItemEntity("item-2", "Eggs", 12, false),
154
+ new ItemEntity("item-3", "Bread", 1, false),
155
+ ]
156
+
157
+ // ============================================================================
158
+ // REPOSITORY/WORKFLOW METHODS
159
+ // ============================================================================
160
+
161
+ // SYNC methods returning Result
162
+ export function fetchUserById(id: UserId): Result<UserEntity, ValidationError> {
163
+ if (id === "user-123") {
164
+ return Result.Ok(mockUser)
165
+ }
166
+ return Result.Err(new ValidationError(`User not found: ${id}`))
167
+ }
168
+
169
+ export function ensureListIsActive(
170
+ list: GroceryListEntity,
171
+ ): Result<GroceryListEntity, ValidationError> {
172
+ if (list.active) {
173
+ return Result.Ok(list)
174
+ }
175
+ return Result.Err(new ValidationError("List is not active"))
176
+ }
177
+
178
+ export function validateItems(
179
+ items: ItemEntity[],
180
+ ): Result<ItemEntity[], ValidationError> {
181
+ if (items.length === 0) {
182
+ return Result.Err(new ValidationError("Items cannot be empty"))
183
+ }
184
+ const hasInvalidQuantity = items.some((item) => item.quantity <= 0)
185
+ if (hasInvalidQuantity) {
186
+ return Result.Err(
187
+ new ValidationError("All items must have positive quantity"),
188
+ )
189
+ }
190
+ return Result.Ok(items)
191
+ }
192
+
193
+ export function filterActiveItems(
194
+ items: ItemEntity[],
195
+ ): Result<ItemEntity[], ValidationError> {
196
+ const filtered = items.filter((item) => !item.isBought)
197
+ if (filtered.length === 0) {
198
+ return Result.Err(new ValidationError("No active items found"))
199
+ }
200
+ return Result.Ok(filtered)
201
+ }
202
+
203
+ // ASYNC methods returning Promise<Result>
204
+ export async function fetchUserByIdAsync(
205
+ id: UserId,
206
+ ): Promise<Result<UserEntity, ValidationError>> {
207
+ await new Promise((resolve) => setTimeout(resolve, 10))
208
+ return fetchUserById(id)
209
+ }
210
+
211
+ export async function fetchItemsForListAsync(
212
+ listId: GroceryListId,
213
+ ): Promise<Result<ItemEntity[], ValidationError>> {
214
+ await new Promise((resolve) => setTimeout(resolve, 10))
215
+ if (listId === "list-456") {
216
+ return Result.Ok(mockItems)
217
+ }
218
+ return Result.Err(new ValidationError(`Items not found for list: ${listId}`))
219
+ }
220
+
221
+ // ASYNC methods returning Promise (for use as mappers)
222
+ export async function serializeItemsAsync(
223
+ items: ItemEntity[],
224
+ ): Promise<ReturnType<ItemEntity["serialize"]>[]> {
225
+ await new Promise((resolve) => setTimeout(resolve, 5))
226
+ return items.map((item) => item.serialize())
227
+ }
228
+
229
+ export async function calculateDetailedStatsAsync(
230
+ items: ItemEntity[],
231
+ ): Promise<GroceryListStats> {
232
+ await new Promise((resolve) => setTimeout(resolve, 5))
233
+ return calculateDetailedStats(items)
234
+ }
235
+
236
+ export async function validateUserPermissionsAsync(
237
+ user: UserEntity,
238
+ list: GroceryListEntity,
239
+ ): Promise<Result<UserEntity, ValidationError>> {
240
+ await new Promise((resolve) => setTimeout(resolve, 5))
241
+ if (user.id === list.ownerId) {
242
+ return Result.Ok(user)
243
+ }
244
+ return Result.Err(new ValidationError("User lacks permission"))
245
+ }
246
+
247
+ export async function fetchListWithOwnerAsync(
248
+ listId: GroceryListId,
249
+ userId: UserId,
250
+ ): Promise<
251
+ Result<{ list: GroceryListEntity; owner: UserEntity }, ValidationError>
252
+ > {
253
+ const owner = await fetchUserByIdAsync(userId)
254
+ if (owner.isErr()) {
255
+ return Result.Err(owner.unwrapErr())
256
+ }
257
+
258
+ if (listId !== "list-456") {
259
+ return Result.Err(new ValidationError(`List not found: ${listId}`))
260
+ }
261
+
262
+ return Result.Ok({ list: mockGroceryList, owner: owner.unwrap() })
263
+ }