@carbonteq/fp 0.9.1 → 0.11.1
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.
- package/README.md +326 -97
- package/dist/errors.cjs +2 -3
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -5
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts +2 -5
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs +1 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +332 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +330 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +340 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +77 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +77 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +338 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +29 -14
- package/dist/index.d.cts +10 -5
- package/dist/index.d.mts +10 -5
- package/dist/index.mjs +10 -5
- package/dist/match.cjs +376 -3
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +467 -8
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +467 -8
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +371 -3
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1547 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1380 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1380 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1545 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +650 -71
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +528 -39
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +528 -39
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +648 -70
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1346 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1345 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +746 -81
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +799 -104
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +799 -104
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +742 -73
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +5 -4
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +9 -7
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +9 -7
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +4 -3
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +3 -3
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +4 -5
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +4 -5
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +2 -2
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +50 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +14 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +14 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +46 -3
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +60 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +240 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +244 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +154 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +157 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +54 -31
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Complex Backend Example - User Enrichment Service
|
|
3
|
+
*
|
|
4
|
+
* Demonstrates:
|
|
5
|
+
* - Orchestrating multiple async services (Database, External APIs)
|
|
6
|
+
* - Error handling with custom typed errors using FlowError
|
|
7
|
+
* - Mixing Result (fallible) and Option (nullable) types
|
|
8
|
+
* - Using Flow.asyncGen with direct error yielding via FlowError
|
|
9
|
+
* - Uses stable Option and Result
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Flow, FlowError, Option, Result } from "../../src/index.js"
|
|
13
|
+
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// 1. Domain Types & Errors
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
type UserID = number
|
|
19
|
+
|
|
20
|
+
interface User {
|
|
21
|
+
id: UserID
|
|
22
|
+
username: string
|
|
23
|
+
email: string
|
|
24
|
+
isActive: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface UserPreferences {
|
|
28
|
+
theme: "light" | "dark" | "system"
|
|
29
|
+
notificationsEnabled: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface Order {
|
|
33
|
+
id: string
|
|
34
|
+
total: number
|
|
35
|
+
status: "pending" | "completed"
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface EnrichedUser {
|
|
39
|
+
user: User
|
|
40
|
+
preferences: UserPreferences
|
|
41
|
+
recentOrders: Order[]
|
|
42
|
+
lifetimeValue: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Custom Errors - extend FlowError for direct yielding in Flow generators
|
|
46
|
+
class NotFoundError extends FlowError {
|
|
47
|
+
readonly _tag = "NotFoundError"
|
|
48
|
+
constructor(message: string) {
|
|
49
|
+
super(message)
|
|
50
|
+
Object.defineProperty(this, "name", { value: "NotFoundError" })
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class ValidationError extends FlowError {
|
|
55
|
+
readonly _tag = "ValidationError"
|
|
56
|
+
constructor(message: string) {
|
|
57
|
+
super(message)
|
|
58
|
+
Object.defineProperty(this, "name", { value: "ValidationError" })
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class ServiceUnavailableError extends FlowError {
|
|
63
|
+
readonly _tag = "ServiceUnavailableError"
|
|
64
|
+
constructor(service: string) {
|
|
65
|
+
super(`${service} unavailable`)
|
|
66
|
+
Object.defineProperty(this, "name", { value: "ServiceUnavailableError" })
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ============================================================================
|
|
71
|
+
// 2. Mock Services
|
|
72
|
+
// ============================================================================
|
|
73
|
+
|
|
74
|
+
const DB = {
|
|
75
|
+
users: new Map<UserID, User>([
|
|
76
|
+
[
|
|
77
|
+
1,
|
|
78
|
+
{
|
|
79
|
+
id: 1,
|
|
80
|
+
username: "alice_w",
|
|
81
|
+
email: "alice@example.com",
|
|
82
|
+
isActive: true,
|
|
83
|
+
},
|
|
84
|
+
],
|
|
85
|
+
[
|
|
86
|
+
2,
|
|
87
|
+
{
|
|
88
|
+
id: 2,
|
|
89
|
+
username: "bob_builder",
|
|
90
|
+
email: "bob@example.com",
|
|
91
|
+
isActive: false,
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
]),
|
|
95
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
96
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
97
|
+
]),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const UserRepository = {
|
|
101
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
102
|
+
// Simulate DB latency
|
|
103
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
104
|
+
|
|
105
|
+
const user = DB.users.get(id)
|
|
106
|
+
return user
|
|
107
|
+
? Result.Ok(user)
|
|
108
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const PreferencesService = {
|
|
113
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
114
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
115
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const OrderService = {
|
|
120
|
+
getRecentOrders: async (
|
|
121
|
+
id: UserID,
|
|
122
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
123
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
124
|
+
|
|
125
|
+
// Simulate random service failure for demo
|
|
126
|
+
if (Math.random() < 0.1) {
|
|
127
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (id === 1) {
|
|
131
|
+
return Result.Ok([
|
|
132
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
133
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
134
|
+
])
|
|
135
|
+
}
|
|
136
|
+
return Result.Ok([])
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ============================================================================
|
|
141
|
+
// 3. Main Logic: Enriched User Fow
|
|
142
|
+
// ============================================================================
|
|
143
|
+
|
|
144
|
+
// Default preferences if none found
|
|
145
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
146
|
+
theme: "system",
|
|
147
|
+
notificationsEnabled: false,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const enrichUser = async (userId: number) => {
|
|
151
|
+
return await Flow.asyncGen(async function* () {
|
|
152
|
+
// Direct error yielding with FlowError - no Result.Err wrapper needed!
|
|
153
|
+
if (userId <= 0) {
|
|
154
|
+
yield* new ValidationError("UserID must be positive")
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
158
|
+
const user = yield* await UserRepository.findById(userId)
|
|
159
|
+
|
|
160
|
+
if (!user.isActive) {
|
|
161
|
+
yield* new ValidationError("User account is inactive")
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
165
|
+
|
|
166
|
+
const orders = yield* await OrderService.getRecentOrders(user.id)
|
|
167
|
+
|
|
168
|
+
const prefsOpt = await PreferencesService.getPreferences(user.id)
|
|
169
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
170
|
+
|
|
171
|
+
const lifetimeValue = orders.reduce(
|
|
172
|
+
(sum, order) => (order.status === "completed" ? sum + order.total : sum),
|
|
173
|
+
0,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
const enrichedUser: EnrichedUser = {
|
|
177
|
+
user,
|
|
178
|
+
preferences,
|
|
179
|
+
recentOrders: orders,
|
|
180
|
+
lifetimeValue,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return enrichedUser
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ============================================================================
|
|
188
|
+
// 4. Execution Examples
|
|
189
|
+
// ============================================================================
|
|
190
|
+
|
|
191
|
+
async function runDemo() {
|
|
192
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
193
|
+
const res1 = await enrichUser(1)
|
|
194
|
+
/*
|
|
195
|
+
* We can match on the final result to handle success/failure
|
|
196
|
+
*/
|
|
197
|
+
res1.match({
|
|
198
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
199
|
+
Err: (err) => console.error("FAILURE:", (err as Error).message),
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
203
|
+
const res2 = await enrichUser(99)
|
|
204
|
+
console.log(
|
|
205
|
+
"Result:",
|
|
206
|
+
res2.isErr() ? `Left(${(res2.unwrapErr() as Error).message})` : "Ok",
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
210
|
+
const res3 = await enrichUser(-5)
|
|
211
|
+
console.log(
|
|
212
|
+
"Result:",
|
|
213
|
+
res3.isErr() ? `Left(${(res3.unwrapErr() as Error).message})` : "Ok",
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
217
|
+
const res4 = await enrichUser(2)
|
|
218
|
+
console.log(
|
|
219
|
+
"Result:",
|
|
220
|
+
res4.isErr() ? `Left(${(res4.unwrapErr() as Error).message})` : "Ok",
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
runDemo().catch(console.error)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow Examples Index (Stable)
|
|
3
|
+
*
|
|
4
|
+
* These examples use the stable Flow API with stable Option and Result.
|
|
5
|
+
* Run examples with:
|
|
6
|
+
* bun run examples/flow/01-basics.ts
|
|
7
|
+
* bun run examples/flow/02-async.ts
|
|
8
|
+
* bun run examples/flow/03-recovery.ts
|
|
9
|
+
* bun run examples/flow/04-complex-backend.ts
|
|
10
|
+
* bun run examples/flow/05-complex-backend-asyncGen.ts
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export {}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow - Unified Generator for Option and Result
|
|
3
|
+
*
|
|
4
|
+
* Flow allows you to yield both Option and Result types in the same generator.
|
|
5
|
+
* It automatically handles short-circuiting:
|
|
6
|
+
* - If Option.None is yielded -> returns Result.Err(UnwrappedNone)
|
|
7
|
+
* - If Result.Err(e) is yielded -> returns Result.Err(e)
|
|
8
|
+
*
|
|
9
|
+
* Uses ExperimentalOption and ExperimentalResult.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ExperimentalFlow as Flow,
|
|
14
|
+
ExperimentalOption as Option,
|
|
15
|
+
ExperimentalResult as Result,
|
|
16
|
+
} from "../../dist/index.mjs"
|
|
17
|
+
|
|
18
|
+
// ============================================================================
|
|
19
|
+
// Flow.gen - Direct usage (simpler, good for simple chains)
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
const basicGen = Flow.gen(function* () {
|
|
23
|
+
console.log("Start Flow.gen")
|
|
24
|
+
|
|
25
|
+
// 1. Yield Option -> Unwraps value or error
|
|
26
|
+
const a = yield* Option.Some(10)
|
|
27
|
+
|
|
28
|
+
// 2. Yield Result -> Unwraps value or error
|
|
29
|
+
const b = yield* Result.Ok(20)
|
|
30
|
+
|
|
31
|
+
// 3. Helper to convert nullable to Option -> Then yield
|
|
32
|
+
const c = yield* Option.fromNullable(30)
|
|
33
|
+
|
|
34
|
+
return a + b + c
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
console.log("Basic Gen:", basicGen.safeUnwrap()) // 60
|
|
38
|
+
|
|
39
|
+
// Error Handling: Option.None
|
|
40
|
+
const noneError = Flow.gen(function* () {
|
|
41
|
+
const a = yield* Option.Some(1)
|
|
42
|
+
yield* Option.None // Stops here
|
|
43
|
+
|
|
44
|
+
return a + 10
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
console.log("None Error:", noneError.isErr()) // true
|
|
48
|
+
console.log("Error Type:", noneError.unwrapErr()) // UnwrappedNone
|
|
49
|
+
|
|
50
|
+
// Error Handling: Result.Err
|
|
51
|
+
const resultError = Flow.gen(function* () {
|
|
52
|
+
const a = yield* Result.Ok(1)
|
|
53
|
+
yield* Result.Err("Something went wrong") // Stops here
|
|
54
|
+
return a + 10
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
console.log("Result Error:", resultError.unwrapErr()) // "Something went wrong"
|
|
58
|
+
|
|
59
|
+
// ============================================================================
|
|
60
|
+
// Flow.genAdapter - Adapter usage (better type inference)
|
|
61
|
+
// ============================================================================
|
|
62
|
+
|
|
63
|
+
// The `$` adapter function helps TypeScript infer types correctly,
|
|
64
|
+
// especially in more complex expressions or chains.
|
|
65
|
+
|
|
66
|
+
const adapterGen = Flow.genAdapter(function* ($) {
|
|
67
|
+
const val1 = yield* $(Option.Some(100))
|
|
68
|
+
const val2 = yield* $(Result.Ok(200))
|
|
69
|
+
|
|
70
|
+
// You can wrap complex expressions
|
|
71
|
+
const val3 = yield* $(
|
|
72
|
+
Option.fromPredicate(val1 + val2, (v) => v > 100).map((v) => v / 10),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return val3
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
console.log("Adapter Gen:", adapterGen.unwrap()) // 30
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async Flow - Unified Async Generator
|
|
3
|
+
*
|
|
4
|
+
* Handles Promise<Option>, Promise<Result>, and async operations.
|
|
5
|
+
* Uses ExperimentalOption and ExperimentalResult.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ExperimentalFlow as Flow,
|
|
10
|
+
ExperimentalOption as Option,
|
|
11
|
+
ExperimentalResult as Result,
|
|
12
|
+
} from "../../dist/index.mjs"
|
|
13
|
+
|
|
14
|
+
type User = { id: number; name: string }
|
|
15
|
+
|
|
16
|
+
// Mock async functions
|
|
17
|
+
const fetchUser = async (id: number): Promise<Result<User, string>> => {
|
|
18
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
19
|
+
return id === 1
|
|
20
|
+
? Result.Ok({ id, name: "Alice" })
|
|
21
|
+
: Result.Err("User not found")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fetchSettings = async (_userId: number) => {
|
|
25
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
26
|
+
return Option.Some({ theme: "dark" })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// Flow.asyncGen - Direct usage (requires explicit awaits)
|
|
31
|
+
// ============================================================================
|
|
32
|
+
|
|
33
|
+
const asyncDirect = await Flow.asyncGen(async function* () {
|
|
34
|
+
// 1. Await async Result function, then yield*
|
|
35
|
+
const user = yield* await fetchUser(1)
|
|
36
|
+
|
|
37
|
+
// 2. Await async Option function, then yield*
|
|
38
|
+
const settings = yield* await fetchSettings(user.id)
|
|
39
|
+
|
|
40
|
+
// 3. Sync yield works too
|
|
41
|
+
const bonus = yield* Option.Some(50)
|
|
42
|
+
|
|
43
|
+
return `${user.name} prefers ${settings.theme} theme (Bonus: ${bonus})`
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
console.log("Async Direct:", asyncDirect.unwrap())
|
|
47
|
+
|
|
48
|
+
// ============================================================================
|
|
49
|
+
// Flow.asyncGenAdapter - Adapter usage (cleaner syntax)
|
|
50
|
+
// ============================================================================
|
|
51
|
+
|
|
52
|
+
const asyncAdapter = await Flow.asyncGenAdapter(async function* ($) {
|
|
53
|
+
// 1. Wrap promise - adapter handles await automatically!
|
|
54
|
+
const user = yield* $(fetchUser(1))
|
|
55
|
+
|
|
56
|
+
// 2. Wrap another promise
|
|
57
|
+
const settings = yield* $(fetchSettings(user.id))
|
|
58
|
+
|
|
59
|
+
// 3. Wrap sync values
|
|
60
|
+
const multiplier = yield* $(Result.Ok<number, Error>(2))
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
user,
|
|
64
|
+
settings,
|
|
65
|
+
score: 100 * multiplier,
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
console.log("Async Adapter:", asyncAdapter.safeUnwrap())
|
|
70
|
+
|
|
71
|
+
// Error propagation in Async
|
|
72
|
+
const asyncError = await Flow.asyncGenAdapter(async function* ($) {
|
|
73
|
+
const user = yield* $(fetchUser(999)) // Returns Err
|
|
74
|
+
return user // Not reached
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
console.log("Async Error:", asyncError.unwrapErr()) // "User not found"
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow - Error Recovery Patterns
|
|
3
|
+
*
|
|
4
|
+
* Examples of how to handle errors and perform recovery (orElse) within Flow generators.
|
|
5
|
+
* Uses ExperimentalResult.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ExperimentalFlow as Flow,
|
|
10
|
+
ExperimentalResult as Result,
|
|
11
|
+
} from "../../dist/index.mjs"
|
|
12
|
+
|
|
13
|
+
// Mock operations
|
|
14
|
+
const mayFail = (id: number): Result<number, string> =>
|
|
15
|
+
id > 0 ? Result.Ok(id) : Result.Err("Invalid ID")
|
|
16
|
+
|
|
17
|
+
const recover = (_err: string): Result<number, string> => Result.Ok(0) // Default to 0
|
|
18
|
+
|
|
19
|
+
const complexRecovery = async (
|
|
20
|
+
_err: string,
|
|
21
|
+
): Promise<Result<number, string>> => {
|
|
22
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
23
|
+
return Result.Ok(100)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ============================================================================
|
|
27
|
+
// Pattern 1: Simple recovery using .orElse()
|
|
28
|
+
// Best when the recovery logic is simple and synchronous/atomic.
|
|
29
|
+
// ============================================================================
|
|
30
|
+
|
|
31
|
+
const simpleRecovery = Flow.gen(function* () {
|
|
32
|
+
// Try to clean 5, if fail, recover is not called
|
|
33
|
+
const a = yield* mayFail(5).orElse(recover)
|
|
34
|
+
|
|
35
|
+
// Try to clean -1, fails -> recovers (returns Ok(0))
|
|
36
|
+
// The 'yield*' sees the *recovered* Ok value.
|
|
37
|
+
const b = yield* mayFail(-1).orElse(recover)
|
|
38
|
+
|
|
39
|
+
return a + b // 5 + 0 = 5
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
console.log("Simple Recovery:", simpleRecovery.unwrap())
|
|
43
|
+
|
|
44
|
+
// ============================================================================
|
|
45
|
+
// Pattern 2: Manual branching for complex flows
|
|
46
|
+
// Necessary when recovery involves multiple yield steps or generators.
|
|
47
|
+
// ============================================================================
|
|
48
|
+
|
|
49
|
+
const manualRecovery = Flow.gen(function* () {
|
|
50
|
+
// const result = mayFail(-1); // Don't yield yet!
|
|
51
|
+
//
|
|
52
|
+
// let val: number;
|
|
53
|
+
// if (result.isOk()) {
|
|
54
|
+
// val = result.unwrap();
|
|
55
|
+
// } else {
|
|
56
|
+
// // Perform complex recovery logic here
|
|
57
|
+
// const fallback = yield* Option.Some(99);
|
|
58
|
+
// val = fallback + 1; // 100
|
|
59
|
+
// }
|
|
60
|
+
|
|
61
|
+
const val = yield* mayFail(-1).orElse(() => {
|
|
62
|
+
console.log("Failed, recovering...")
|
|
63
|
+
|
|
64
|
+
return Result.Ok(100)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
return val
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
console.log("Manual Recovery:", manualRecovery.unwrap())
|
|
71
|
+
|
|
72
|
+
// ============================================================================
|
|
73
|
+
// Pattern 3: Async recovery using .orElseAsync() (if available on Result)
|
|
74
|
+
// or manual branching for async logic.
|
|
75
|
+
// ============================================================================
|
|
76
|
+
|
|
77
|
+
const asyncRecovery = await Flow.asyncGen(async function* () {
|
|
78
|
+
// const res = mayFail(-5);
|
|
79
|
+
//
|
|
80
|
+
// let val: number;
|
|
81
|
+
// if (res.isOk()) {
|
|
82
|
+
// val = res.unwrap();
|
|
83
|
+
// } else {
|
|
84
|
+
// // You can yield async recovery operations here
|
|
85
|
+
// val = yield* await complexRecovery(res.unwrapErr());
|
|
86
|
+
// }
|
|
87
|
+
|
|
88
|
+
const val = yield* await mayFail(-5).orElseAsync(complexRecovery)
|
|
89
|
+
|
|
90
|
+
return val
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
console.log("Async Recovery:", asyncRecovery.unwrap()) // 100
|