@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,244 @@
|
|
|
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
|
|
7
|
+
* - Mixing Result (fallible) and Option (nullable) types
|
|
8
|
+
* - Using Flow.asyncGenAdapter for clean, declarative control flow
|
|
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
|
+
// 1. Domain Types & Errors
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
type UserID = number
|
|
23
|
+
|
|
24
|
+
interface User {
|
|
25
|
+
id: UserID
|
|
26
|
+
username: string
|
|
27
|
+
email: string
|
|
28
|
+
isActive: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface UserPreferences {
|
|
32
|
+
theme: "light" | "dark" | "system"
|
|
33
|
+
notificationsEnabled: boolean
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Order {
|
|
37
|
+
id: string
|
|
38
|
+
total: number
|
|
39
|
+
status: "pending" | "completed"
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface EnrichedUser {
|
|
43
|
+
user: User
|
|
44
|
+
preferences: UserPreferences
|
|
45
|
+
recentOrders: Order[]
|
|
46
|
+
lifetimeValue: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Custom Errors
|
|
50
|
+
class NotFoundError extends Error {
|
|
51
|
+
readonly _tag = "NotFoundError"
|
|
52
|
+
constructor(message: string) {
|
|
53
|
+
super(message)
|
|
54
|
+
this.name = "NotFoundError"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class ValidationError extends Error {
|
|
59
|
+
readonly _tag = "ValidationError"
|
|
60
|
+
constructor(message: string) {
|
|
61
|
+
super(message)
|
|
62
|
+
this.name = "ValidationError"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
class ServiceUnavailableError extends Error {
|
|
67
|
+
readonly _tag = "ServiceUnavailableError"
|
|
68
|
+
constructor(service: string) {
|
|
69
|
+
super(`${service} unavailable`)
|
|
70
|
+
this.name = "ServiceUnavailableError"
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ============================================================================
|
|
75
|
+
// 2. Mock Services
|
|
76
|
+
// ============================================================================
|
|
77
|
+
|
|
78
|
+
const DB = {
|
|
79
|
+
users: new Map<UserID, User>([
|
|
80
|
+
[
|
|
81
|
+
1,
|
|
82
|
+
{
|
|
83
|
+
id: 1,
|
|
84
|
+
username: "alice_w",
|
|
85
|
+
email: "alice@example.com",
|
|
86
|
+
isActive: true,
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
[
|
|
90
|
+
2,
|
|
91
|
+
{
|
|
92
|
+
id: 2,
|
|
93
|
+
username: "bob_builder",
|
|
94
|
+
email: "bob@example.com",
|
|
95
|
+
isActive: false,
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
]),
|
|
99
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
100
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
101
|
+
]),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const UserRepository = {
|
|
105
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
106
|
+
// Simulate DB latency
|
|
107
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
108
|
+
|
|
109
|
+
const user = DB.users.get(id)
|
|
110
|
+
return user
|
|
111
|
+
? Result.Ok(user)
|
|
112
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const PreferencesService = {
|
|
117
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
118
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
119
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const OrderService = {
|
|
124
|
+
getRecentOrders: async (
|
|
125
|
+
id: UserID,
|
|
126
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
127
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
128
|
+
|
|
129
|
+
// Simulate random service failure for demo
|
|
130
|
+
if (Math.random() < 0.1) {
|
|
131
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (id === 1) {
|
|
135
|
+
return Result.Ok([
|
|
136
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
137
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
138
|
+
])
|
|
139
|
+
}
|
|
140
|
+
return Result.Ok([])
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ============================================================================
|
|
145
|
+
// 3. Main Logic: Enriched User Fow
|
|
146
|
+
// ============================================================================
|
|
147
|
+
|
|
148
|
+
// Default preferences if none found
|
|
149
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
150
|
+
theme: "system",
|
|
151
|
+
notificationsEnabled: false,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const enrichUser = (userId: number) =>
|
|
155
|
+
Flow.asyncGenAdapter(async function* ($) {
|
|
156
|
+
// 1. Validation Logic (Synchronous Result)
|
|
157
|
+
if (userId <= 0) {
|
|
158
|
+
yield* $(Result.Err(new ValidationError("User ID must be positive")))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 2. Fetch User (Async Result)
|
|
162
|
+
// The adapter automatically awaits the Promise and unwraps the Result
|
|
163
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
164
|
+
const user = yield* $(UserRepository.findById(userId))
|
|
165
|
+
|
|
166
|
+
// 3. Early exit if inactive
|
|
167
|
+
if (!user.isActive) {
|
|
168
|
+
yield* $(Result.Err(new ValidationError("User is inactive")))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// 4. Fetch Preferences (Async Option) & Orders (Async Result) in parallel
|
|
172
|
+
// We can use Promise.all to fetch them concurrently, then yield* to unwrap
|
|
173
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
174
|
+
|
|
175
|
+
const [prefsOpt, ordersRes] = await Promise.all([
|
|
176
|
+
PreferencesService.getPreferences(user.id),
|
|
177
|
+
OrderService.getRecentOrders(user.id),
|
|
178
|
+
])
|
|
179
|
+
|
|
180
|
+
// Unwrap Orders (Result) - will bubble up ServiceUnavailableError if failed
|
|
181
|
+
const orders = yield* $(ordersRes)
|
|
182
|
+
|
|
183
|
+
// Unwrap Preferences (Option) - we want to provide a default if None,
|
|
184
|
+
// rather than halting the flow (which yielding a None would do).
|
|
185
|
+
// So we DON'T use yield* on the Option directly here.
|
|
186
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
187
|
+
|
|
188
|
+
// 5. Aggregate Data
|
|
189
|
+
const lifetimeValue = orders.reduce(
|
|
190
|
+
(sum, ord) => (ord.status === "completed" ? sum + ord.total : sum),
|
|
191
|
+
0,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
const enriched: EnrichedUser = {
|
|
195
|
+
user,
|
|
196
|
+
preferences,
|
|
197
|
+
recentOrders: orders,
|
|
198
|
+
lifetimeValue,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return enriched
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
// ============================================================================
|
|
205
|
+
// 4. Execution Examples
|
|
206
|
+
// ============================================================================
|
|
207
|
+
|
|
208
|
+
const errorMessage = (error: unknown): string =>
|
|
209
|
+
error instanceof Error ? error.message : String(error)
|
|
210
|
+
|
|
211
|
+
async function runDemo() {
|
|
212
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
213
|
+
const res1 = await enrichUser(1)
|
|
214
|
+
/*
|
|
215
|
+
* We can match on the final result to handle success/failure
|
|
216
|
+
*/
|
|
217
|
+
res1.match({
|
|
218
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
219
|
+
Err: (err) => console.error("FAILURE:", errorMessage(err)),
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
223
|
+
const res2 = await enrichUser(99)
|
|
224
|
+
console.log(
|
|
225
|
+
"Result:",
|
|
226
|
+
res2.isErr() ? `Left(${errorMessage(res2.unwrapErr())})` : "Ok",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
230
|
+
const res3 = await enrichUser(-5)
|
|
231
|
+
console.log(
|
|
232
|
+
"Result:",
|
|
233
|
+
res3.isErr() ? `Left(${errorMessage(res3.unwrapErr())})` : "Ok",
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
237
|
+
const res4 = await enrichUser(2)
|
|
238
|
+
console.log(
|
|
239
|
+
"Result:",
|
|
240
|
+
res4.isErr() ? `Left(${errorMessage(res4.unwrapErr())})` : "Ok",
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
runDemo().catch(console.error)
|
|
@@ -0,0 +1,229 @@
|
|
|
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 ExperimentalOption and ExperimentalResult
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ExperimentalFlow as Flow,
|
|
14
|
+
ExperimentalFlowError as FlowError,
|
|
15
|
+
ExperimentalOption as Option,
|
|
16
|
+
ExperimentalResult as Result,
|
|
17
|
+
} from "../../src/index.js"
|
|
18
|
+
|
|
19
|
+
// ============================================================================
|
|
20
|
+
// 1. Domain Types & Errors
|
|
21
|
+
// ============================================================================
|
|
22
|
+
|
|
23
|
+
type UserID = number
|
|
24
|
+
|
|
25
|
+
interface User {
|
|
26
|
+
id: UserID
|
|
27
|
+
username: string
|
|
28
|
+
email: string
|
|
29
|
+
isActive: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface UserPreferences {
|
|
33
|
+
theme: "light" | "dark" | "system"
|
|
34
|
+
notificationsEnabled: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Order {
|
|
38
|
+
id: string
|
|
39
|
+
total: number
|
|
40
|
+
status: "pending" | "completed"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface EnrichedUser {
|
|
44
|
+
user: User
|
|
45
|
+
preferences: UserPreferences
|
|
46
|
+
recentOrders: Order[]
|
|
47
|
+
lifetimeValue: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Custom Errors - extend FlowError for direct yielding in Flow generators
|
|
51
|
+
class NotFoundError extends FlowError {
|
|
52
|
+
readonly _tag = "NotFoundError"
|
|
53
|
+
constructor(message: string) {
|
|
54
|
+
super(message)
|
|
55
|
+
Object.defineProperty(this, "name", { value: "NotFoundError" })
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
class ValidationError extends FlowError {
|
|
60
|
+
readonly _tag = "ValidationError"
|
|
61
|
+
constructor(message: string) {
|
|
62
|
+
super(message)
|
|
63
|
+
Object.defineProperty(this, "name", { value: "ValidationError" })
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
class ServiceUnavailableError extends FlowError {
|
|
68
|
+
readonly _tag = "ServiceUnavailableError"
|
|
69
|
+
constructor(service: string) {
|
|
70
|
+
super(`${service} unavailable`)
|
|
71
|
+
Object.defineProperty(this, "name", { value: "ServiceUnavailableError" })
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// 2. Mock Services
|
|
77
|
+
// ============================================================================
|
|
78
|
+
|
|
79
|
+
const DB = {
|
|
80
|
+
users: new Map<UserID, User>([
|
|
81
|
+
[
|
|
82
|
+
1,
|
|
83
|
+
{
|
|
84
|
+
id: 1,
|
|
85
|
+
username: "alice_w",
|
|
86
|
+
email: "alice@example.com",
|
|
87
|
+
isActive: true,
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
[
|
|
91
|
+
2,
|
|
92
|
+
{
|
|
93
|
+
id: 2,
|
|
94
|
+
username: "bob_builder",
|
|
95
|
+
email: "bob@example.com",
|
|
96
|
+
isActive: false,
|
|
97
|
+
},
|
|
98
|
+
],
|
|
99
|
+
]),
|
|
100
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
101
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
102
|
+
]),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const UserRepository = {
|
|
106
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
107
|
+
// Simulate DB latency
|
|
108
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
109
|
+
|
|
110
|
+
const user = DB.users.get(id)
|
|
111
|
+
return user
|
|
112
|
+
? Result.Ok(user)
|
|
113
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const PreferencesService = {
|
|
118
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
119
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
120
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const OrderService = {
|
|
125
|
+
getRecentOrders: async (
|
|
126
|
+
id: UserID,
|
|
127
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
128
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
129
|
+
|
|
130
|
+
// Simulate random service failure for demo
|
|
131
|
+
if (Math.random() < 0.1) {
|
|
132
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (id === 1) {
|
|
136
|
+
return Result.Ok([
|
|
137
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
138
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
139
|
+
])
|
|
140
|
+
}
|
|
141
|
+
return Result.Ok([])
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ============================================================================
|
|
146
|
+
// 3. Main Logic: Enriched User Fow
|
|
147
|
+
// ============================================================================
|
|
148
|
+
|
|
149
|
+
// Default preferences if none found
|
|
150
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
151
|
+
theme: "system",
|
|
152
|
+
notificationsEnabled: false,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const enrichUser = async (userId: number) => {
|
|
156
|
+
return await Flow.asyncGen(async function* () {
|
|
157
|
+
// Direct error yielding with FlowError - no Result.Err wrapper needed!
|
|
158
|
+
if (userId <= 0) {
|
|
159
|
+
yield* new ValidationError("UserID must be positive")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
163
|
+
const user = yield* await UserRepository.findById(userId)
|
|
164
|
+
|
|
165
|
+
if (!user.isActive) {
|
|
166
|
+
yield* new ValidationError("User account is inactive")
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
170
|
+
|
|
171
|
+
const orders = yield* await OrderService.getRecentOrders(user.id)
|
|
172
|
+
|
|
173
|
+
const prefsOpt = await PreferencesService.getPreferences(user.id)
|
|
174
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
175
|
+
|
|
176
|
+
const lifetimeValue = orders.reduce(
|
|
177
|
+
(sum, order) => (order.status === "completed" ? sum + order.total : sum),
|
|
178
|
+
0,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
const enrichedUser: EnrichedUser = {
|
|
182
|
+
user,
|
|
183
|
+
preferences,
|
|
184
|
+
recentOrders: orders,
|
|
185
|
+
lifetimeValue,
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return enrichedUser
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ============================================================================
|
|
193
|
+
// 4. Execution Examples
|
|
194
|
+
// ============================================================================
|
|
195
|
+
|
|
196
|
+
async function runDemo() {
|
|
197
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
198
|
+
const res1 = await enrichUser(1)
|
|
199
|
+
/*
|
|
200
|
+
* We can match on the final result to handle success/failure
|
|
201
|
+
*/
|
|
202
|
+
res1.match({
|
|
203
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
204
|
+
Err: (err) => console.error("FAILURE:", (err as Error).message),
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
208
|
+
const res2 = await enrichUser(99)
|
|
209
|
+
console.log(
|
|
210
|
+
"Result:",
|
|
211
|
+
res2.isErr() ? `Left(${(res2.unwrapErr() as Error).message})` : "Ok",
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
215
|
+
const res3 = await enrichUser(-5)
|
|
216
|
+
console.log(
|
|
217
|
+
"Result:",
|
|
218
|
+
res3.isErr() ? `Left(${(res3.unwrapErr() as Error).message})` : "Ok",
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
222
|
+
const res4 = await enrichUser(2)
|
|
223
|
+
console.log(
|
|
224
|
+
"Result:",
|
|
225
|
+
res4.isErr() ? `Left(${(res4.unwrapErr() as Error).message})` : "Ok",
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
runDemo().catch(console.error)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ExperimentalFlow Examples Index
|
|
3
|
+
*
|
|
4
|
+
* These examples use the experimental Flow API with
|
|
5
|
+
* ExperimentalOption and ExperimentalResult.
|
|
6
|
+
* Run examples with:
|
|
7
|
+
* bun run examples/flow-experimental/01-basics.ts
|
|
8
|
+
* bun run examples/flow-experimental/02-async.ts
|
|
9
|
+
* bun run examples/flow-experimental/03-recovery.ts
|
|
10
|
+
* bun run examples/flow-experimental/04-complex-backend.ts
|
|
11
|
+
* bun run examples/flow-experimental/05-complex-backend-asyncGen.ts
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export {}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* match() API examples for stable Option/Result.
|
|
3
|
+
*
|
|
4
|
+
* This file demonstrates:
|
|
5
|
+
* - String-tag matching
|
|
6
|
+
* - Pattern helpers (P.Some/P.Ok/etc)
|
|
7
|
+
* - Guards and fallthrough
|
|
8
|
+
* - Generic discriminated unions
|
|
9
|
+
* - How to handle Option<Promise<T>> / Result<Promise<T>, E>
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { match, P } from "../../dist/match.mjs"
|
|
13
|
+
import { Option } from "../../dist/option.mjs"
|
|
14
|
+
import { Result } from "../../dist/result.mjs"
|
|
15
|
+
|
|
16
|
+
console.log("=== Stable match() examples ===\n")
|
|
17
|
+
|
|
18
|
+
// -----------------------------------------------------------------------------
|
|
19
|
+
// 1) Basic Option/Result matching
|
|
20
|
+
// -----------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
const maybeScore = Option.Some(82)
|
|
23
|
+
const grade = match(maybeScore)
|
|
24
|
+
.with("Some", (value) => (value >= 90 ? "A" : "B"))
|
|
25
|
+
.with("None", () => "N/A")
|
|
26
|
+
.exhaustive()
|
|
27
|
+
console.log("grade:", grade)
|
|
28
|
+
|
|
29
|
+
const apiResult = Result.Err("rate-limited") as Result<number, string>
|
|
30
|
+
const label = match(apiResult)
|
|
31
|
+
.with("Ok", (value) => `value=${value}`)
|
|
32
|
+
.with("Err", (error) => `error=${error}`)
|
|
33
|
+
.exhaustive()
|
|
34
|
+
console.log("result label:", label)
|
|
35
|
+
|
|
36
|
+
// -----------------------------------------------------------------------------
|
|
37
|
+
// 2) P helpers + guards
|
|
38
|
+
// -----------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
const guarded = match(Option.Some(74))
|
|
41
|
+
.with(
|
|
42
|
+
P.Some((x: number) => x >= 90),
|
|
43
|
+
() => "A",
|
|
44
|
+
)
|
|
45
|
+
.with(
|
|
46
|
+
P.Some((x: number) => x >= 80),
|
|
47
|
+
() => "B",
|
|
48
|
+
)
|
|
49
|
+
.with(
|
|
50
|
+
P.Some((x: number) => x >= 70),
|
|
51
|
+
() => "C",
|
|
52
|
+
)
|
|
53
|
+
.with(P.Some(), () => "D")
|
|
54
|
+
.with(P.None(), () => "N/A")
|
|
55
|
+
.exhaustive()
|
|
56
|
+
console.log("guarded grade:", guarded)
|
|
57
|
+
|
|
58
|
+
const retryPolicy = match(Result.Err("fatal") as Result<number, string>)
|
|
59
|
+
.with(P.Ok(), () => "none")
|
|
60
|
+
.with(P.Err(P.oneOf("timeout", "offline")), () => "retry")
|
|
61
|
+
.with(P.Err(P.not(P.oneOf("timeout", "offline"))), () => "do-not-retry")
|
|
62
|
+
.exhaustive()
|
|
63
|
+
console.log("retry policy:", retryPolicy)
|
|
64
|
+
|
|
65
|
+
const stateByPredicates = match(Result.Ok(1) as Result<number, string>)
|
|
66
|
+
.when(P.IsErr, () => "err")
|
|
67
|
+
.when(P.IsOk, () => "ok")
|
|
68
|
+
.otherwise(() => "other")
|
|
69
|
+
console.log("state by predicates:", stateByPredicates)
|
|
70
|
+
|
|
71
|
+
const combinedPredicates = match(Result.Ok(42) as Result<number, string>)
|
|
72
|
+
.with(P.Ok(P.all(P.not(P.eq(0)), P.any(P.eq(42), P.eq(43)))), () => "hit")
|
|
73
|
+
.with(P.Ok(), () => "miss")
|
|
74
|
+
.with(P.Err(), () => "err")
|
|
75
|
+
.exhaustive()
|
|
76
|
+
console.log("combined predicates:", combinedPredicates)
|
|
77
|
+
|
|
78
|
+
const exactValueHandler = match(Result.Ok(42) as Result<number, string>)
|
|
79
|
+
.with(P.Ok(P.eq(42)), (value) => `exact:${value}`)
|
|
80
|
+
.with(P.Ok(), (value) => `other-ok:${value}`)
|
|
81
|
+
.with(P.Err(), (error) => `err:${error}`)
|
|
82
|
+
.exhaustive()
|
|
83
|
+
console.log("exact value handler:", exactValueHandler)
|
|
84
|
+
|
|
85
|
+
// -----------------------------------------------------------------------------
|
|
86
|
+
// 3) when() + otherwise() + wildcard
|
|
87
|
+
// -----------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
const status = match(Result.Ok({ attempts: 4, user: "alice" }))
|
|
90
|
+
.when(
|
|
91
|
+
(r) => r.isOk() && r.unwrap().attempts > 3,
|
|
92
|
+
() => "needs-review",
|
|
93
|
+
)
|
|
94
|
+
.with(P._, () => "ok")
|
|
95
|
+
.exhaustive()
|
|
96
|
+
console.log("status:", status)
|
|
97
|
+
|
|
98
|
+
const fallbackStatus = match(Result.Err("boom") as Result<number, string>)
|
|
99
|
+
.with(P.Ok(P.not(P.eq(42))), () => "ok-not-42")
|
|
100
|
+
.with(P.Ok(P.eq(42)), () => "ok-42")
|
|
101
|
+
.otherwise(() => "fallback")
|
|
102
|
+
console.log("fallback status:", fallbackStatus)
|
|
103
|
+
|
|
104
|
+
// -----------------------------------------------------------------------------
|
|
105
|
+
// 4) Generic discriminated union support
|
|
106
|
+
// -----------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
type JobEvent =
|
|
109
|
+
| { readonly _tag: "queued"; id: string }
|
|
110
|
+
| { readonly _tag: "running"; id: string; progress: number }
|
|
111
|
+
| { readonly _tag: "failed"; id: string; reason: string }
|
|
112
|
+
|
|
113
|
+
const asJobEvent = (value: JobEvent): JobEvent => value
|
|
114
|
+
const event = asJobEvent({ _tag: "running", id: "job-1", progress: 55 })
|
|
115
|
+
const eventText = match(event)
|
|
116
|
+
.with("queued", (e) => `queued:${e.id}`)
|
|
117
|
+
.with("running", (e) => `running:${e.id}:${e.progress}%`)
|
|
118
|
+
.with("failed", (e) => `failed:${e.id}:${e.reason}`)
|
|
119
|
+
.exhaustive()
|
|
120
|
+
console.log("event:", eventText)
|
|
121
|
+
|
|
122
|
+
// -----------------------------------------------------------------------------
|
|
123
|
+
// 5) Async-inner stable values: settle first, then match
|
|
124
|
+
// -----------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
async function runAsyncInnerExamples(): Promise<void> {
|
|
127
|
+
// IMPORTANT:
|
|
128
|
+
// match() intentionally rejects Result<Promise<T>, E> and Option<Promise<T>>.
|
|
129
|
+
// For stable variants, convert them first with toPromise():
|
|
130
|
+
// Result<Promise<T>, E> -> Promise<Result<T, E>>
|
|
131
|
+
// Option<Promise<T>> -> Promise<Option<T>>
|
|
132
|
+
|
|
133
|
+
const asyncStableResult = Result.Ok(Promise.resolve(21))
|
|
134
|
+
const settledResult = await asyncStableResult.toPromise()
|
|
135
|
+
|
|
136
|
+
const settledResultText = match(settledResult)
|
|
137
|
+
.with("Ok", (value) => `settled-ok:${value * 2}`)
|
|
138
|
+
.with("Err", (error) => `settled-err:${String(error)}`)
|
|
139
|
+
.exhaustive()
|
|
140
|
+
console.log("settled result:", settledResultText)
|
|
141
|
+
|
|
142
|
+
const asyncStableOption = Option.Some(Promise.resolve("token-123"))
|
|
143
|
+
const settledOption = await asyncStableOption.toPromise()
|
|
144
|
+
|
|
145
|
+
const settledOptionText = match(settledOption)
|
|
146
|
+
.with("Some", (value) => `settled-some:${value}`)
|
|
147
|
+
.with("None", () => "settled-none")
|
|
148
|
+
.exhaustive()
|
|
149
|
+
console.log("settled option:", settledOptionText)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
await runAsyncInnerExamples()
|
|
153
|
+
|
|
154
|
+
console.log("\n=== stable match() examples complete ===")
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* match() Examples Index (Stable)
|
|
3
|
+
*
|
|
4
|
+
* Run:
|
|
5
|
+
* bun run examples/match/01-stable-match.ts
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 01-stable-match.ts
|
|
10
|
+
*
|
|
11
|
+
* Topics covered:
|
|
12
|
+
* - match() with stable Option/Result
|
|
13
|
+
* - P helpers and guarded cases
|
|
14
|
+
* - wildcard/when/otherwise
|
|
15
|
+
* - generic discriminated unions
|
|
16
|
+
* - async-inner stable values via toPromise()
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export {}
|