@carbonteq/fp 0.9.1 → 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.
- package/README.md +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +286 -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 +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1266 -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 +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +46 -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 +237 -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 +241 -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 +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -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 +50 -18
package/dist/result.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
1
2
|
const require_errors = require('./errors.cjs');
|
|
2
3
|
const require_unit = require('./unit.cjs');
|
|
3
4
|
const require_utils = require('./utils.cjs');
|
|
@@ -10,6 +11,40 @@ const ERR_VAL = Symbol("Result::Err");
|
|
|
10
11
|
const NO_ERR = Symbol("Result::NoErr");
|
|
11
12
|
/** Internal symbol for accessing private factory - not exported */
|
|
12
13
|
const RESULT_INTERNAL = Symbol("Result::Internal");
|
|
14
|
+
/**
|
|
15
|
+
* Wrapper that makes Result yieldable with proper type tracking.
|
|
16
|
+
* The Generator signature ensures TypeScript tracks the inner type T.
|
|
17
|
+
*
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
var ResultYieldWrap = class {
|
|
21
|
+
constructor(result) {
|
|
22
|
+
this.result = result;
|
|
23
|
+
}
|
|
24
|
+
*[Symbol.iterator]() {
|
|
25
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
26
|
+
return yield new require_utils.CapturedTrace(this, trace);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Wrapper that makes Result yieldable in async generators with proper type tracking.
|
|
31
|
+
* Supports Promise<Result<T, E>> for async result chaining.
|
|
32
|
+
*
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
var AsyncResultYieldWrap = class {
|
|
36
|
+
constructor(result) {
|
|
37
|
+
this.result = result;
|
|
38
|
+
}
|
|
39
|
+
async *[Symbol.asyncIterator]() {
|
|
40
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
41
|
+
return yield new require_utils.CapturedTrace(this, trace);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Represents a computation that can succeed (`Ok<T>`) or fail (`Err<E>`).
|
|
46
|
+
* Provides composable transformations with explicit error propagation.
|
|
47
|
+
*/
|
|
13
48
|
var Result = class Result {
|
|
14
49
|
/** Discriminant tag for type-level identification */
|
|
15
50
|
_tag;
|
|
@@ -35,26 +70,57 @@ var Result = class Result {
|
|
|
35
70
|
}
|
|
36
71
|
/** Singleton UNIT_RESULT for void-success operations */
|
|
37
72
|
static UNIT_RESULT = new Result(require_unit.UNIT, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
38
|
-
/**
|
|
73
|
+
/**
|
|
74
|
+
* Creates an Ok containing the given value.
|
|
75
|
+
*
|
|
76
|
+
* @template T - Success value type
|
|
77
|
+
* @template E - Error type (defaults to never)
|
|
78
|
+
* @param val - Success value
|
|
79
|
+
* @returns Result in the Ok state
|
|
80
|
+
*/
|
|
39
81
|
static Ok(val) {
|
|
40
82
|
return new Result(val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
41
83
|
}
|
|
42
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* Creates an Err containing the given error.
|
|
86
|
+
*
|
|
87
|
+
* @template E - Error type
|
|
88
|
+
* @template T - Success value type (defaults to never)
|
|
89
|
+
* @param err - Error value
|
|
90
|
+
* @returns Result in the Err state
|
|
91
|
+
*/
|
|
43
92
|
static Err(err) {
|
|
44
93
|
return new Result(ERR_VAL, err, { asyncErr: NO_ERR }, "Err");
|
|
45
94
|
}
|
|
46
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Type guard for Ok state.
|
|
97
|
+
*
|
|
98
|
+
* @returns true if this Result is Ok
|
|
99
|
+
*/
|
|
47
100
|
isOk() {
|
|
48
101
|
return this._tag === "Ok" && this.#ctx.asyncErr === NO_ERR;
|
|
49
102
|
}
|
|
50
|
-
/**
|
|
103
|
+
/**
|
|
104
|
+
* Type guard for Err state.
|
|
105
|
+
*
|
|
106
|
+
* @returns true if this Result is Err
|
|
107
|
+
*/
|
|
51
108
|
isErr() {
|
|
52
109
|
return this._tag === "Err" || this.#ctx.asyncErr !== NO_ERR || this._tag === "Ok" && this.#val === ERR_VAL;
|
|
53
110
|
}
|
|
54
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* Type guard for Ok containing UNIT.
|
|
113
|
+
*
|
|
114
|
+
* @returns true if the Ok value is UNIT
|
|
115
|
+
*/
|
|
55
116
|
isUnit() {
|
|
56
117
|
return this.#val === require_unit.UNIT;
|
|
57
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Returns a string representation of the Result.
|
|
121
|
+
*
|
|
122
|
+
* @returns "Result::Ok<value>" or "Result::Err<error>"
|
|
123
|
+
*/
|
|
58
124
|
toString() {
|
|
59
125
|
if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
|
|
60
126
|
return `Result::Err<${String(this.getErr())}>`;
|
|
@@ -119,7 +185,13 @@ var Result = class Result {
|
|
|
119
185
|
});
|
|
120
186
|
return curr === ERR_VAL ? null : curr;
|
|
121
187
|
}
|
|
122
|
-
/**
|
|
188
|
+
/**
|
|
189
|
+
* Exhaustive pattern match on Result state.
|
|
190
|
+
*
|
|
191
|
+
* @template U - Result type of the handlers
|
|
192
|
+
* @param cases - Handlers for Ok and Err
|
|
193
|
+
* @returns Result of the matching handler
|
|
194
|
+
*/
|
|
123
195
|
match(cases) {
|
|
124
196
|
if (this.isErr()) return cases.Err(this.getErr());
|
|
125
197
|
return cases.Ok(this.#val);
|
|
@@ -131,13 +203,24 @@ var Result = class Result {
|
|
|
131
203
|
if (require_utils.isPromiseLike(curr)) {
|
|
132
204
|
const p = curr;
|
|
133
205
|
const newCtx = { asyncErr: NO_ERR };
|
|
134
|
-
|
|
135
|
-
return new Result(out, parentErr, newCtx, "Ok");
|
|
206
|
+
return new Result(Result.safeMap(p, fn, newCtx, this.#ctx), parentErr, newCtx, "Ok");
|
|
136
207
|
}
|
|
137
208
|
const next = fn(curr);
|
|
138
209
|
if (require_utils.isPromiseLike(next)) return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
139
210
|
return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
140
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* Safely maps a promised Ok value while propagating async errors.
|
|
214
|
+
*
|
|
215
|
+
* @template In - Input value type
|
|
216
|
+
* @template U - Output value type
|
|
217
|
+
* @template E - Error type
|
|
218
|
+
* @param p - Promise of Ok value or ERR sentinel
|
|
219
|
+
* @param mapper - Transform function
|
|
220
|
+
* @param ctx - New async context to populate on error
|
|
221
|
+
* @param parentCtx - Parent async context to read error from
|
|
222
|
+
* @returns Promise of transformed value or ERR sentinel
|
|
223
|
+
*/
|
|
141
224
|
static safeMap(p, mapper, ctx, parentCtx) {
|
|
142
225
|
return p.then((v) => {
|
|
143
226
|
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
@@ -147,6 +230,27 @@ var Result = class Result {
|
|
|
147
230
|
return mapper(v);
|
|
148
231
|
});
|
|
149
232
|
}
|
|
233
|
+
/**
|
|
234
|
+
* Transforms the error value while preserving the success value.
|
|
235
|
+
*
|
|
236
|
+
* If the Result is Err, applies the function to the error. If Ok, returns
|
|
237
|
+
* the Ok unchanged without calling the function.
|
|
238
|
+
*
|
|
239
|
+
* @param fn - Function to transform the error
|
|
240
|
+
* @returns Result<T, E2> with transformed error or original Ok
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* ```ts
|
|
244
|
+
* Result.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
|
|
245
|
+
* Result.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
|
|
246
|
+
*
|
|
247
|
+
* // Add context to errors
|
|
248
|
+
* fetchData()
|
|
249
|
+
* .mapErr((e) => new ContextualError("Failed to fetch data", e));
|
|
250
|
+
* ```
|
|
251
|
+
*
|
|
252
|
+
* @see mapBoth
|
|
253
|
+
*/
|
|
150
254
|
mapErr(fn) {
|
|
151
255
|
if (this._tag === "Err") {
|
|
152
256
|
const mappedErr = fn(this.getErr());
|
|
@@ -156,18 +260,15 @@ var Result = class Result {
|
|
|
156
260
|
const parentCtx = this.#ctx;
|
|
157
261
|
if (require_utils.isPromiseLike(curr)) {
|
|
158
262
|
const newCtx = { asyncErr: NO_ERR };
|
|
159
|
-
|
|
263
|
+
return new Result(curr.then((v) => {
|
|
160
264
|
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) newCtx.asyncErr = fn(parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err);
|
|
161
265
|
return v;
|
|
162
|
-
});
|
|
163
|
-
return new Result(p, void 0, newCtx, "Ok");
|
|
266
|
+
}), void 0, newCtx, "Ok");
|
|
164
267
|
}
|
|
165
268
|
return new Result(this.#val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
166
269
|
}
|
|
167
270
|
mapBoth(fnOk, fnErr) {
|
|
168
|
-
|
|
169
|
-
if (require_utils.isPromiseLike(this.#val)) return this.map(fnOk);
|
|
170
|
-
return this.map(fnOk);
|
|
271
|
+
return this.map(fnOk).mapErr(fnErr);
|
|
171
272
|
}
|
|
172
273
|
flatMap(fn) {
|
|
173
274
|
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
@@ -175,31 +276,48 @@ var Result = class Result {
|
|
|
175
276
|
const parentErr = this.#err;
|
|
176
277
|
const parentCtx = this.#ctx;
|
|
177
278
|
const newCtx = { asyncErr: NO_ERR };
|
|
178
|
-
if (require_utils.isPromiseLike(curr)) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
});
|
|
189
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
190
|
-
}
|
|
279
|
+
if (require_utils.isPromiseLike(curr)) return new Result(new Promise((resolve, reject) => {
|
|
280
|
+
curr.then((v) => {
|
|
281
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
282
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
283
|
+
return resolve(ERR_VAL);
|
|
284
|
+
}
|
|
285
|
+
const mapped = fn(v);
|
|
286
|
+
resolve(Result.flatMapHelper(newCtx, mapped));
|
|
287
|
+
}, reject);
|
|
288
|
+
}), parentErr, newCtx, "Ok");
|
|
191
289
|
const mapped = fn(curr);
|
|
192
|
-
if (require_utils.isPromiseLike(mapped))
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return new Result(mapped.#val, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
290
|
+
if (require_utils.isPromiseLike(mapped)) return new Result(mapped.then((r) => Result.flatMapInnerHelper(newCtx, r)), parentErr, newCtx, "Ok");
|
|
291
|
+
const normalized = Result.flatMapInnerHelper(newCtx, mapped);
|
|
292
|
+
if (require_utils.isPromiseLike(normalized)) return new Result(normalized, parentErr, newCtx, "Ok");
|
|
293
|
+
if (normalized === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
|
|
294
|
+
return new Result(normalized, parentErr, newCtx, "Ok");
|
|
198
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* Normalizes sync/async flatMap outputs to a value or Promise.
|
|
298
|
+
*
|
|
299
|
+
* @template U - Success value type
|
|
300
|
+
* @template E - Original error type
|
|
301
|
+
* @template E2 - Mapped error type
|
|
302
|
+
* @template T - Input value type
|
|
303
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
304
|
+
* @param mapped - FlatMap output (sync or async Result)
|
|
305
|
+
* @returns Value, Promise, or ERR sentinel
|
|
306
|
+
*/
|
|
199
307
|
static flatMapHelper(mutableCtx, mapped) {
|
|
200
308
|
if (require_utils.isPromiseLike(mapped)) return mapped.then((r) => Result.flatMapInnerHelper(mutableCtx, r));
|
|
201
309
|
return Result.flatMapInnerHelper(mutableCtx, mapped);
|
|
202
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Extracts the inner value from a Result, updating error context on failure.
|
|
313
|
+
*
|
|
314
|
+
* @template U - Success value type
|
|
315
|
+
* @template E - Original error type
|
|
316
|
+
* @template E2 - Mapped error type
|
|
317
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
318
|
+
* @param r - Inner Result to unwrap
|
|
319
|
+
* @returns Value, Promise, or ERR sentinel
|
|
320
|
+
*/
|
|
203
321
|
static flatMapInnerHelper(mutableCtx, r) {
|
|
204
322
|
if (r._tag === "Err") {
|
|
205
323
|
mutableCtx.asyncErr = r.getErr();
|
|
@@ -222,23 +340,17 @@ var Result = class Result {
|
|
|
222
340
|
const parentErr = this.#err;
|
|
223
341
|
const parentCtx = this.#ctx;
|
|
224
342
|
const newCtx = { asyncErr: NO_ERR };
|
|
225
|
-
if (require_utils.isPromiseLike(curr)) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
});
|
|
235
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
236
|
-
}
|
|
343
|
+
if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
344
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
345
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
346
|
+
return ERR_VAL;
|
|
347
|
+
}
|
|
348
|
+
const u = fn(v);
|
|
349
|
+
if (require_utils.isPromiseLike(u)) return u.then((uu) => [v, uu]);
|
|
350
|
+
return [v, u];
|
|
351
|
+
}), parentErr, newCtx, "Ok");
|
|
237
352
|
const u = fn(curr);
|
|
238
|
-
if (require_utils.isPromiseLike(u)) {
|
|
239
|
-
const p = u.then((uu) => [curr, uu]);
|
|
240
|
-
return new Result(p, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
241
|
-
}
|
|
353
|
+
if (require_utils.isPromiseLike(u)) return new Result(u.then((uu) => [curr, uu]), parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
242
354
|
return new Result([curr, u], parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
243
355
|
}
|
|
244
356
|
flatZip(fn) {
|
|
@@ -247,27 +359,48 @@ var Result = class Result {
|
|
|
247
359
|
const parentErr = this.#err;
|
|
248
360
|
const parentCtx = this.#ctx;
|
|
249
361
|
const newCtx = { asyncErr: NO_ERR };
|
|
250
|
-
if (require_utils.isPromiseLike(curr)) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
});
|
|
259
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
260
|
-
}
|
|
362
|
+
if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
363
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
364
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
365
|
+
return ERR_VAL;
|
|
366
|
+
}
|
|
367
|
+
const mapped = fn(v);
|
|
368
|
+
return Result.flatZipHelper(newCtx, v, mapped);
|
|
369
|
+
}), parentErr, newCtx, "Ok");
|
|
261
370
|
const mapped = fn(curr);
|
|
262
371
|
const p = Result.flatZipHelper(newCtx, curr, mapped);
|
|
263
372
|
if (require_utils.isPromiseLike(p)) return new Result(p, parentErr, newCtx, "Ok");
|
|
264
373
|
if (p === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
|
|
265
374
|
return new Result(p, parentErr, newCtx, "Ok");
|
|
266
375
|
}
|
|
376
|
+
/**
|
|
377
|
+
* Normalizes sync/async flatZip outputs to a tuple or ERR sentinel.
|
|
378
|
+
*
|
|
379
|
+
* @template U - Derived value type
|
|
380
|
+
* @template E - Original error type
|
|
381
|
+
* @template E2 - Mapped error type
|
|
382
|
+
* @template In - Original value type
|
|
383
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
384
|
+
* @param originalVal - Original value to preserve
|
|
385
|
+
* @param mapped - FlatZip output (sync or async Result)
|
|
386
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
387
|
+
*/
|
|
267
388
|
static flatZipHelper(mutableCtx, originalVal, mapped) {
|
|
268
389
|
if (require_utils.isPromiseLike(mapped)) return mapped.then((r) => Result.flatZipInnerHelper(mutableCtx, originalVal, r));
|
|
269
390
|
return Result.flatZipInnerHelper(mutableCtx, originalVal, mapped);
|
|
270
391
|
}
|
|
392
|
+
/**
|
|
393
|
+
* Extracts the inner value for flatZip, updating error context on failure.
|
|
394
|
+
*
|
|
395
|
+
* @template U - Derived value type
|
|
396
|
+
* @template E - Original error type
|
|
397
|
+
* @template E2 - Mapped error type
|
|
398
|
+
* @template In - Original value type
|
|
399
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
400
|
+
* @param originalVal - Original value to preserve
|
|
401
|
+
* @param r - Inner Result to unwrap
|
|
402
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
403
|
+
*/
|
|
271
404
|
static flatZipInnerHelper(mutableCtx, originalVal, r) {
|
|
272
405
|
if (r._tag === "Err") {
|
|
273
406
|
mutableCtx.asyncErr = r.getErr();
|
|
@@ -293,31 +426,51 @@ var Result = class Result {
|
|
|
293
426
|
const parentErr = this.#err;
|
|
294
427
|
const parentCtx = this.#ctx;
|
|
295
428
|
const newCtx = { asyncErr: NO_ERR };
|
|
296
|
-
if (require_utils.isPromiseLike(curr)) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
});
|
|
305
|
-
return new Result(newP$1, parentErr, newCtx, "Ok");
|
|
306
|
-
}
|
|
429
|
+
if (require_utils.isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
430
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
431
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
432
|
+
return ERR_VAL;
|
|
433
|
+
}
|
|
434
|
+
const r = fn(v);
|
|
435
|
+
return Result.zipErrHelper(v, r, newCtx);
|
|
436
|
+
}), parentErr, newCtx, "Ok");
|
|
307
437
|
const r = fn(curr);
|
|
308
438
|
const newP = Result.zipErrHelper(curr, r, newCtx);
|
|
309
439
|
if (require_utils.isPromiseLike(newP)) return new Result(newP, parentErr, newCtx, "Ok");
|
|
310
440
|
if (newCtx.asyncErr !== NO_ERR) return new Result(ERR_VAL, newCtx.asyncErr, newCtx, "Err");
|
|
311
441
|
return new Result(newP, parentErr, newCtx, "Ok");
|
|
312
442
|
}
|
|
443
|
+
/**
|
|
444
|
+
* Tracks errors from a Result while preserving the original value.
|
|
445
|
+
*
|
|
446
|
+
* @template In - Original value type
|
|
447
|
+
* @template E - Error type
|
|
448
|
+
* @param v - Original value to preserve
|
|
449
|
+
* @param r - Result to inspect for errors
|
|
450
|
+
* @param newCtx - Context to populate on error
|
|
451
|
+
* @returns Original value or Promise of value
|
|
452
|
+
*/
|
|
313
453
|
static zipErrHelper(v, r, newCtx) {
|
|
314
454
|
if (require_utils.isPromiseLike(r)) return r.then((newResult) => {
|
|
315
|
-
|
|
455
|
+
const maybeAwaited = Result.captureZipErr(newResult, newCtx);
|
|
456
|
+
if (require_utils.isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
316
457
|
return v;
|
|
317
458
|
});
|
|
318
|
-
|
|
459
|
+
const maybeAwaited = Result.captureZipErr(r, newCtx);
|
|
460
|
+
if (require_utils.isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
319
461
|
return v;
|
|
320
462
|
}
|
|
463
|
+
static captureZipErr(result, newCtx) {
|
|
464
|
+
if (result._tag === "Err") {
|
|
465
|
+
newCtx.asyncErr = result.getErr();
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const innerVal = result.#val;
|
|
469
|
+
if (require_utils.isPromiseLike(innerVal)) return innerVal.then((resolved) => {
|
|
470
|
+
if (resolved === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
|
|
471
|
+
});
|
|
472
|
+
if (innerVal === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
|
|
473
|
+
}
|
|
321
474
|
validate(validators) {
|
|
322
475
|
if (this.isErr()) return this;
|
|
323
476
|
const currVal = this.#val;
|
|
@@ -330,8 +483,8 @@ var Result = class Result {
|
|
|
330
483
|
return ERR_VAL;
|
|
331
484
|
}
|
|
332
485
|
const awaitedVal = c;
|
|
333
|
-
const results
|
|
334
|
-
return Promise.all(results
|
|
486
|
+
const results = validators.map((v) => v(awaitedVal));
|
|
487
|
+
return Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, awaitedVal));
|
|
335
488
|
}), parentErr, mutableCtx, "Ok");
|
|
336
489
|
const baseVal = currVal;
|
|
337
490
|
const results = validators.map((v) => v(baseVal));
|
|
@@ -341,6 +494,16 @@ var Result = class Result {
|
|
|
341
494
|
const combinedRes = Result.all(...syncResults);
|
|
342
495
|
return combinedRes.isErr() ? combinedRes : this;
|
|
343
496
|
}
|
|
497
|
+
/**
|
|
498
|
+
* Collapses validator Results into a single value or ERR sentinel.
|
|
499
|
+
*
|
|
500
|
+
* @template Val - Success value type
|
|
501
|
+
* @template Err - Error type
|
|
502
|
+
* @param results - Validator Results to combine
|
|
503
|
+
* @param currCtx - Context to populate on error
|
|
504
|
+
* @param currVal - Original value to return on success
|
|
505
|
+
* @returns Original value, Promise of value, or ERR sentinel
|
|
506
|
+
*/
|
|
344
507
|
static validateHelper(results, currCtx, currVal) {
|
|
345
508
|
const combinedRes = Result.all(...results);
|
|
346
509
|
if (require_utils.isPromiseLike(combinedRes.#val)) return combinedRes.#val.then((v) => {
|
|
@@ -359,27 +522,89 @@ var Result = class Result {
|
|
|
359
522
|
static all(...results) {
|
|
360
523
|
const vals = results.map((r) => r.#val);
|
|
361
524
|
const newCtx = { asyncErr: NO_ERR };
|
|
362
|
-
if (vals.some(require_utils.isPromiseLike)) {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
});
|
|
372
|
-
return new Result(p, [], newCtx, "Ok");
|
|
373
|
-
}
|
|
525
|
+
if (vals.some(require_utils.isPromiseLike)) return new Result(Promise.all(vals).then((resolvedVals) => {
|
|
526
|
+
const errs = [];
|
|
527
|
+
for (let i = 0; i < results.length; i++) if (results[i]._tag === "Err" || results[i].#ctx.asyncErr !== NO_ERR || resolvedVals[i] === ERR_VAL) errs.push(results[i].getErr());
|
|
528
|
+
if (errs.length > 0) {
|
|
529
|
+
newCtx.asyncErr = errs;
|
|
530
|
+
return ERR_VAL;
|
|
531
|
+
}
|
|
532
|
+
return resolvedVals;
|
|
533
|
+
}), [], newCtx, "Ok");
|
|
374
534
|
const errs = [];
|
|
375
535
|
for (const r of results) if (r._tag === "Err") errs.push(r.getErr());
|
|
376
536
|
if (errs.length > 0) return Result.Err(errs);
|
|
377
537
|
return Result.Ok(vals);
|
|
378
538
|
}
|
|
379
|
-
/**
|
|
539
|
+
/**
|
|
540
|
+
* Returns the first Ok, or collects all errors if all are Err.
|
|
541
|
+
*
|
|
542
|
+
* Useful for fallback chains where you want the first success, but want
|
|
543
|
+
* to collect all errors if everything fails.
|
|
544
|
+
*
|
|
545
|
+
* - First Ok → Returns that Ok immediately
|
|
546
|
+
* - All Err → `Err([...all errors])`
|
|
547
|
+
*
|
|
548
|
+
* For async Ok values, this waits for settlement and selects the first
|
|
549
|
+
* successful candidate in input order (not fastest-to-resolve order).
|
|
550
|
+
*
|
|
551
|
+
* @param results - Variable number of Results to check
|
|
552
|
+
* @returns First Ok found, or Err with array of all errors
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
* ```ts
|
|
556
|
+
* Result.any(
|
|
557
|
+
* Result.Err("Error 1"),
|
|
558
|
+
* Result.Ok("First success"),
|
|
559
|
+
* Result.Ok("Second success"),
|
|
560
|
+
* ); // Ok("First success")
|
|
561
|
+
*
|
|
562
|
+
* Result.any(
|
|
563
|
+
* Result.Err("Error 1"),
|
|
564
|
+
* Result.Err("Error 2"),
|
|
565
|
+
* Result.Err("Error 3"),
|
|
566
|
+
* ); // Err(["Error 1", "Error 2", "Error 3"])
|
|
567
|
+
*
|
|
568
|
+
* // Fallback chain
|
|
569
|
+
* Result.any(
|
|
570
|
+
* fetchFromCache(key),
|
|
571
|
+
* fetchFromDb(key),
|
|
572
|
+
* fetchFromRemote(key),
|
|
573
|
+
* );
|
|
574
|
+
* ```
|
|
575
|
+
*
|
|
576
|
+
* @see all
|
|
577
|
+
*/
|
|
380
578
|
static any(...results) {
|
|
381
|
-
|
|
382
|
-
|
|
579
|
+
const errs = [];
|
|
580
|
+
const pending = [];
|
|
581
|
+
for (const r of results) {
|
|
582
|
+
if (r.isOk()) {
|
|
583
|
+
if (require_utils.isPromiseLike(r.#val)) {
|
|
584
|
+
pending.push(r);
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
return r;
|
|
588
|
+
}
|
|
589
|
+
errs.push(r.getErr());
|
|
590
|
+
}
|
|
591
|
+
if (pending.length === 0) return Result.Err(errs);
|
|
592
|
+
const ctx = { asyncErr: NO_ERR };
|
|
593
|
+
return new Result(Promise.all(pending.map(async (r) => {
|
|
594
|
+
const val = await r.#val;
|
|
595
|
+
return {
|
|
596
|
+
failed: r.#ctx.asyncErr !== NO_ERR || val === ERR_VAL,
|
|
597
|
+
val,
|
|
598
|
+
err: r.getErr()
|
|
599
|
+
};
|
|
600
|
+
})).then((settled) => {
|
|
601
|
+
for (const item of settled) {
|
|
602
|
+
if (!item.failed) return item.val;
|
|
603
|
+
errs.push(item.err);
|
|
604
|
+
}
|
|
605
|
+
ctx.asyncErr = errs;
|
|
606
|
+
return ERR_VAL;
|
|
607
|
+
}), void 0, ctx, "Ok");
|
|
383
608
|
}
|
|
384
609
|
tap(fn) {
|
|
385
610
|
if (this.isErr()) return this;
|
|
@@ -387,62 +612,179 @@ var Result = class Result {
|
|
|
387
612
|
const parentCtx = this.#ctx;
|
|
388
613
|
if (require_utils.isPromiseLike(curr)) {
|
|
389
614
|
const newCtx = { asyncErr: NO_ERR };
|
|
390
|
-
|
|
615
|
+
return new Result(curr.then((v) => {
|
|
391
616
|
if (v !== ERR_VAL && parentCtx.asyncErr === NO_ERR) fn(v);
|
|
392
617
|
else newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err;
|
|
393
618
|
return v;
|
|
394
|
-
});
|
|
395
|
-
return new Result(newPromise, this.#err, newCtx, "Ok");
|
|
619
|
+
}), this.#err, newCtx, "Ok");
|
|
396
620
|
}
|
|
397
621
|
fn(curr);
|
|
398
622
|
return this;
|
|
399
623
|
}
|
|
400
|
-
/**
|
|
624
|
+
/**
|
|
625
|
+
* Executes a side effect function for Err values, then returns self.
|
|
626
|
+
*
|
|
627
|
+
* Useful for logging errors or executing cleanup without breaking the chain.
|
|
628
|
+
* The function is only called if the Result is Err.
|
|
629
|
+
*
|
|
630
|
+
* @param fn - Function to execute with the error (sync or async)
|
|
631
|
+
* @returns The same Result (chainable)
|
|
632
|
+
*
|
|
633
|
+
* @example
|
|
634
|
+
* ```ts
|
|
635
|
+
* Result.Err("Connection failed")
|
|
636
|
+
* .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
|
|
637
|
+
* .orElse((e) => Result.Ok(defaultValue));
|
|
638
|
+
* // Logs error timestamp
|
|
639
|
+
* // Returns: Ok(defaultValue)
|
|
640
|
+
*
|
|
641
|
+
* // Ok - tapErr does nothing
|
|
642
|
+
* Result.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
|
|
643
|
+
* ```
|
|
644
|
+
*
|
|
645
|
+
* @see tap
|
|
646
|
+
*/
|
|
401
647
|
tapErr(fn) {
|
|
402
648
|
if (this.isErr()) fn(this.getErr());
|
|
403
649
|
return this;
|
|
404
650
|
}
|
|
405
|
-
/**
|
|
651
|
+
/**
|
|
652
|
+
* Swaps the Ok and Err states, turning success into failure and vice versa.
|
|
653
|
+
*
|
|
654
|
+
* Useful for inverting the meaning of a Result, such as converting
|
|
655
|
+
* validation errors to successes and valid values to errors.
|
|
656
|
+
*
|
|
657
|
+
* @returns Result<E, T> with swapped states
|
|
658
|
+
*
|
|
659
|
+
* @example
|
|
660
|
+
* ```ts
|
|
661
|
+
* Result.Ok("Success value").flip(); // Err("Success value")
|
|
662
|
+
* Result.Err("Error value").flip(); // Ok("Error value")
|
|
663
|
+
*
|
|
664
|
+
* // Invert validation (fail if value is in blacklist)
|
|
665
|
+
* const blacklist = ["admin", "root"];
|
|
666
|
+
* const isBlacklisted = (name: string) =>
|
|
667
|
+
* Result.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
|
|
668
|
+
* .flip(); // Ok if blacklisted, Err if not
|
|
669
|
+
* ```
|
|
670
|
+
*/
|
|
406
671
|
flip() {
|
|
407
672
|
if (this.isErr()) return new Result(this.getErr(), void 0, { asyncErr: NO_ERR }, "Ok");
|
|
408
673
|
return new Result(ERR_VAL, this.#val, { asyncErr: NO_ERR }, "Err");
|
|
409
674
|
}
|
|
410
|
-
/**
|
|
675
|
+
/**
|
|
676
|
+
* Converts Result to Option, discarding error information.
|
|
677
|
+
*
|
|
678
|
+
* - Ok(value) → Some(value)
|
|
679
|
+
* - Err(error) → None
|
|
680
|
+
*
|
|
681
|
+
* Use when you only care about presence/absence of a value, not the error.
|
|
682
|
+
*
|
|
683
|
+
* @returns Option<T> - Some if Ok, None if Err
|
|
684
|
+
*
|
|
685
|
+
* @example
|
|
686
|
+
* ```ts
|
|
687
|
+
* Result.Ok(42).toOption(); // Some(42)
|
|
688
|
+
* Result.Err("fail").toOption(); // None
|
|
689
|
+
*
|
|
690
|
+
* // Safe user lookup
|
|
691
|
+
* const userOpt = fetchUser(id).toOption();
|
|
692
|
+
* // User or None, regardless of why fetch failed
|
|
693
|
+
* ```
|
|
694
|
+
*
|
|
695
|
+
* @see Option.toResult
|
|
696
|
+
*/
|
|
411
697
|
toOption() {
|
|
412
698
|
if (this.isErr()) return require_option.Option.None;
|
|
413
699
|
return require_option.Option.Some(this.#val);
|
|
414
700
|
}
|
|
415
|
-
/**
|
|
701
|
+
/**
|
|
702
|
+
* Resolves the inner promise while preserving Result structure.
|
|
703
|
+
*
|
|
704
|
+
* @returns Promise of Result with awaited value or Err
|
|
705
|
+
*/
|
|
416
706
|
async toPromise() {
|
|
417
707
|
const v = await this.#val;
|
|
418
|
-
if (v === ERR_VAL || this.#ctx.asyncErr !== NO_ERR) {
|
|
419
|
-
const errVal = this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err;
|
|
420
|
-
return new Result(ERR_VAL, errVal, { asyncErr: NO_ERR }, "Err");
|
|
421
|
-
}
|
|
708
|
+
if (v === ERR_VAL || this.#ctx.asyncErr !== NO_ERR) return new Result(ERR_VAL, this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err, { asyncErr: NO_ERR }, "Err");
|
|
422
709
|
return new Result(v, this.#err, { asyncErr: NO_ERR }, "Ok");
|
|
423
710
|
}
|
|
424
|
-
/**
|
|
711
|
+
/**
|
|
712
|
+
* Maps over array elements inside a Result<Array<T>, E>.
|
|
713
|
+
*
|
|
714
|
+
* Applies the mapper function to each element if the Result is Ok and
|
|
715
|
+
* contains an array. Propagates Err unchanged.
|
|
716
|
+
*
|
|
717
|
+
* @param mapper - Function to map over each array element
|
|
718
|
+
* @returns Result<Array<Out>, E> with mapped array or propagated error
|
|
719
|
+
* @throws Error if the Result is Ok but value is not an array
|
|
720
|
+
*
|
|
721
|
+
* @example
|
|
722
|
+
* ```ts
|
|
723
|
+
* Result.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
|
|
724
|
+
* Result.Err("fail").innerMap((x) => x * 2); // Err("fail")
|
|
725
|
+
* ```
|
|
726
|
+
*/
|
|
425
727
|
innerMap(mapper) {
|
|
426
728
|
if (this.isErr()) return this;
|
|
427
729
|
if (Array.isArray(this.#val)) return new Result(this.#val.map(mapper), this.#err, this.#ctx, "Ok");
|
|
428
730
|
throw new Error("Can only be called for Result<Array<T>, E>");
|
|
429
731
|
}
|
|
430
|
-
/**
|
|
732
|
+
/**
|
|
733
|
+
* Recovers from Err by providing a fallback Result.
|
|
734
|
+
*
|
|
735
|
+
* If Ok, returns self unchanged.
|
|
736
|
+
*
|
|
737
|
+
* @template T2 - Fallback success type
|
|
738
|
+
* @template E2 - Fallback error type
|
|
739
|
+
* @param fn - Function to produce a fallback Result from the error
|
|
740
|
+
* @returns Original Ok or fallback Result
|
|
741
|
+
*/
|
|
431
742
|
orElse(fn) {
|
|
432
743
|
if (this.isOk()) return this;
|
|
433
744
|
return fn(this.getErr());
|
|
434
745
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
746
|
+
/**
|
|
747
|
+
* Creates a Result from a nullable value.
|
|
748
|
+
*
|
|
749
|
+
* Returns Err when the value is null or undefined, otherwise Ok.
|
|
750
|
+
*
|
|
751
|
+
* @template T - Input value type
|
|
752
|
+
* @template E - Error type
|
|
753
|
+
* @param val - Value to wrap
|
|
754
|
+
* @param error - Error value for null/undefined
|
|
755
|
+
* @returns Ok with value or Err with error
|
|
756
|
+
*/
|
|
757
|
+
static fromNullable(val, error) {
|
|
438
758
|
return val === null || val === void 0 ? Result.Err(error) : Result.Ok(val);
|
|
439
759
|
}
|
|
440
|
-
|
|
441
|
-
|
|
760
|
+
/**
|
|
761
|
+
* Creates a Result based on a predicate.
|
|
762
|
+
*
|
|
763
|
+
* Returns Ok when predicate passes, otherwise Err.
|
|
764
|
+
*
|
|
765
|
+
* @template T - Input value type
|
|
766
|
+
* @template E - Error type
|
|
767
|
+
* @param val - Value to test
|
|
768
|
+
* @param pred - Predicate to decide Ok vs Err
|
|
769
|
+
* @param error - Error value for predicate failure
|
|
770
|
+
* @returns Ok with value or Err with error
|
|
771
|
+
*/
|
|
772
|
+
static fromPredicate(val, pred, error) {
|
|
442
773
|
return pred(val) ? Result.Ok(val) : Result.Err(error);
|
|
443
774
|
}
|
|
444
|
-
|
|
445
|
-
|
|
775
|
+
/**
|
|
776
|
+
* Wraps a Promise<Result<T, E>> as Result<Promise<T>, E>.
|
|
777
|
+
*
|
|
778
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the inner promise fails later,
|
|
779
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
780
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
781
|
+
*
|
|
782
|
+
* @template U - Success value type
|
|
783
|
+
* @template F - Error type
|
|
784
|
+
* @param promise - Promise resolving to a Result
|
|
785
|
+
* @returns Result containing a Promise of the success value
|
|
786
|
+
*/
|
|
787
|
+
static fromPromise(promise) {
|
|
446
788
|
const ctx = { asyncErr: NO_ERR };
|
|
447
789
|
const p = promise.then((innerResult) => {
|
|
448
790
|
if (innerResult.isErr()) {
|
|
@@ -455,16 +797,36 @@ var Result = class Result {
|
|
|
455
797
|
});
|
|
456
798
|
return Result[RESULT_INTERNAL].create(p, void 0, ctx, "Ok");
|
|
457
799
|
}
|
|
458
|
-
|
|
459
|
-
|
|
800
|
+
/**
|
|
801
|
+
* Catches synchronous exceptions and converts them to Err.
|
|
802
|
+
*
|
|
803
|
+
* @template T - Success value type
|
|
804
|
+
* @template E - Error type
|
|
805
|
+
* @param fn - Function that may throw
|
|
806
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
807
|
+
* @returns Ok with return value or Err with mapped error
|
|
808
|
+
*/
|
|
809
|
+
static tryCatch(fn, errorMapper) {
|
|
460
810
|
try {
|
|
461
811
|
return Result.Ok(fn());
|
|
462
812
|
} catch (e) {
|
|
463
813
|
return Result.Err(errorMapper ? errorMapper(e) : e);
|
|
464
814
|
}
|
|
465
815
|
}
|
|
466
|
-
|
|
467
|
-
|
|
816
|
+
/**
|
|
817
|
+
* Catches async exceptions and converts them to Err.
|
|
818
|
+
*
|
|
819
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the async work fails later,
|
|
820
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
821
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
822
|
+
*
|
|
823
|
+
* @template T - Success value type
|
|
824
|
+
* @template E - Error type
|
|
825
|
+
* @param fn - Async function that may throw
|
|
826
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
827
|
+
* @returns Result containing a Promise of the success value
|
|
828
|
+
*/
|
|
829
|
+
static tryAsyncCatch(fn, errorMapper) {
|
|
468
830
|
const ctx = { asyncErr: NO_ERR };
|
|
469
831
|
const pWithErr = fn().then((v) => v).catch((e) => {
|
|
470
832
|
ctx.asyncErr = errorMapper ? errorMapper(e) : e;
|
|
@@ -472,14 +834,245 @@ var Result = class Result {
|
|
|
472
834
|
});
|
|
473
835
|
return Result[RESULT_INTERNAL].create(pWithErr, void 0, ctx, "Ok");
|
|
474
836
|
}
|
|
475
|
-
|
|
476
|
-
|
|
837
|
+
/**
|
|
838
|
+
* Makes Result iterable for use with generator-based syntax.
|
|
839
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
840
|
+
*
|
|
841
|
+
* @example
|
|
842
|
+
* ```ts
|
|
843
|
+
* const result = Result.gen(function* () {
|
|
844
|
+
* const value = yield* Result.Ok(42);
|
|
845
|
+
* return value * 2;
|
|
846
|
+
* });
|
|
847
|
+
* ```
|
|
848
|
+
*/
|
|
849
|
+
*[Symbol.iterator]() {
|
|
850
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
851
|
+
return yield new require_utils.CapturedTrace(this, trace);
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Makes Result iterable for use with async generator-based syntax.
|
|
855
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
856
|
+
*
|
|
857
|
+
* @example
|
|
858
|
+
* ```ts
|
|
859
|
+
* const result = await Result.asyncGen(async function* () {
|
|
860
|
+
* const value = yield* $(Result.Ok(42));
|
|
861
|
+
* return value * 2;
|
|
862
|
+
* });
|
|
863
|
+
* ```
|
|
864
|
+
*/
|
|
865
|
+
async *[Symbol.asyncIterator]() {
|
|
866
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
867
|
+
return yield new require_utils.CapturedTrace(this, trace);
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
871
|
+
* Provides imperative-style code while maintaining functional error handling.
|
|
872
|
+
*
|
|
873
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
874
|
+
* recursion to avoid stack overflow on deep chains.
|
|
875
|
+
*
|
|
876
|
+
* @example
|
|
877
|
+
* ```ts
|
|
878
|
+
* const result = Result.gen(function* () {
|
|
879
|
+
* const a = yield* Result.Ok(1);
|
|
880
|
+
* const b = yield* Result.Ok(2);
|
|
881
|
+
* return a + b;
|
|
882
|
+
* });
|
|
883
|
+
* // Result<number, never>
|
|
884
|
+
* ```
|
|
885
|
+
*/
|
|
886
|
+
static gen(genFn) {
|
|
887
|
+
const iterator = genFn();
|
|
888
|
+
let nextArg;
|
|
889
|
+
let currentResult;
|
|
890
|
+
while (true) {
|
|
891
|
+
const next = iterator.next(nextArg);
|
|
892
|
+
if (next.done) {
|
|
893
|
+
currentResult = Result.Ok(next.value);
|
|
894
|
+
break;
|
|
895
|
+
}
|
|
896
|
+
let yielded = next.value;
|
|
897
|
+
let stack;
|
|
898
|
+
if (require_utils.isCapturedTrace(yielded)) {
|
|
899
|
+
stack = yielded.stack;
|
|
900
|
+
yielded = yielded.value;
|
|
901
|
+
}
|
|
902
|
+
if (yielded.isErr()) {
|
|
903
|
+
const err = yielded.unwrapErr();
|
|
904
|
+
if (stack && err instanceof Error) {
|
|
905
|
+
const stackLines = stack.split("\n");
|
|
906
|
+
if (stackLines.length > 2) {
|
|
907
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
908
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
currentResult = yielded;
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
nextArg = yielded.unwrap();
|
|
915
|
+
}
|
|
916
|
+
return currentResult;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Generator-based syntax for chaining Result operations (with adapter).
|
|
920
|
+
* Uses an adapter function ($) for improved type inference.
|
|
921
|
+
*
|
|
922
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
923
|
+
* recursion to avoid stack overflow on deep chains.
|
|
924
|
+
*
|
|
925
|
+
* @example
|
|
926
|
+
* ```ts
|
|
927
|
+
* const result = Result.genAdapter(function* ($) {
|
|
928
|
+
* const a = yield* $(Result.Ok(1));
|
|
929
|
+
* const b = yield* $(Result.Ok(2));
|
|
930
|
+
* return a + b;
|
|
931
|
+
* });
|
|
932
|
+
* // Result<number, never>
|
|
933
|
+
* ```
|
|
934
|
+
*/
|
|
935
|
+
static genAdapter(genFn) {
|
|
936
|
+
const adapter = (result) => new ResultYieldWrap(result);
|
|
937
|
+
const iterator = genFn(adapter);
|
|
938
|
+
let nextArg;
|
|
939
|
+
let currentResult;
|
|
940
|
+
while (true) {
|
|
941
|
+
const next = iterator.next(nextArg);
|
|
942
|
+
if (next.done) {
|
|
943
|
+
currentResult = Result.Ok(next.value);
|
|
944
|
+
break;
|
|
945
|
+
}
|
|
946
|
+
const wrapped = next.value;
|
|
947
|
+
let result = wrapped.result;
|
|
948
|
+
let stack;
|
|
949
|
+
if (require_utils.isCapturedTrace(wrapped)) {
|
|
950
|
+
stack = wrapped.stack;
|
|
951
|
+
result = wrapped.value.result;
|
|
952
|
+
}
|
|
953
|
+
if (result.isErr()) {
|
|
954
|
+
const err = result.unwrapErr();
|
|
955
|
+
if (stack && err instanceof Error) {
|
|
956
|
+
const stackLines = stack.split("\n");
|
|
957
|
+
if (stackLines.length > 2) {
|
|
958
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
959
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
currentResult = result;
|
|
963
|
+
break;
|
|
964
|
+
}
|
|
965
|
+
nextArg = result.unwrap();
|
|
966
|
+
}
|
|
967
|
+
return currentResult;
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Async generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
971
|
+
* Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
|
|
972
|
+
*
|
|
973
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
974
|
+
* recursion to avoid stack overflow on deep chains.
|
|
975
|
+
*
|
|
976
|
+
* @example
|
|
977
|
+
* ```ts
|
|
978
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
979
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
980
|
+
* const result = await Result.asyncGen(async function* () {
|
|
981
|
+
* const a = yield* Result.Ok(1);
|
|
982
|
+
* const dataResult = yield* await fetchData(a);
|
|
983
|
+
* return a + dataResult.id;
|
|
984
|
+
* });
|
|
985
|
+
* // Result<number, never>
|
|
986
|
+
* ```
|
|
987
|
+
*/
|
|
988
|
+
static async asyncGen(genFn) {
|
|
989
|
+
const iterator = genFn();
|
|
990
|
+
let nextArg;
|
|
991
|
+
let currentResult;
|
|
992
|
+
while (true) {
|
|
993
|
+
const next = await iterator.next(nextArg);
|
|
994
|
+
if (next.done) {
|
|
995
|
+
currentResult = Result.Ok(next.value);
|
|
996
|
+
break;
|
|
997
|
+
}
|
|
998
|
+
let result = next.value;
|
|
999
|
+
let stack;
|
|
1000
|
+
if (require_utils.isCapturedTrace(result)) {
|
|
1001
|
+
stack = result.stack;
|
|
1002
|
+
result = result.value;
|
|
1003
|
+
}
|
|
1004
|
+
if (result.isErr()) {
|
|
1005
|
+
const err = result.unwrapErr();
|
|
1006
|
+
if (stack && err instanceof Error) {
|
|
1007
|
+
const stackLines = stack.split("\n");
|
|
1008
|
+
if (stackLines.length > 2) {
|
|
1009
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
1010
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
currentResult = result;
|
|
1014
|
+
break;
|
|
1015
|
+
}
|
|
1016
|
+
nextArg = result.unwrap();
|
|
1017
|
+
}
|
|
1018
|
+
return currentResult;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Async generator-based syntax for chaining Result operations (with adapter).
|
|
1022
|
+
* Uses an adapter function ($) for improved type inference.
|
|
1023
|
+
* Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
|
|
1024
|
+
*
|
|
1025
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
1026
|
+
* recursion to avoid stack overflow on deep chains.
|
|
1027
|
+
*
|
|
1028
|
+
* @example
|
|
1029
|
+
* ```ts
|
|
1030
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
1031
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
1032
|
+
* const result = await Result.asyncGenAdapter(async function* ($) {
|
|
1033
|
+
* const a = yield* $(Result.Ok(1));
|
|
1034
|
+
* const data = yield* $(fetchData(a));
|
|
1035
|
+
* return a + data.id;
|
|
1036
|
+
* });
|
|
1037
|
+
* // Result<number, never>
|
|
1038
|
+
* ```
|
|
1039
|
+
*/
|
|
1040
|
+
static async asyncGenAdapter(genFn) {
|
|
1041
|
+
const adapter = (result) => new AsyncResultYieldWrap(Promise.resolve(result));
|
|
1042
|
+
const iterator = genFn(adapter);
|
|
1043
|
+
let nextArg;
|
|
1044
|
+
let currentResult;
|
|
1045
|
+
while (true) {
|
|
1046
|
+
const next = await iterator.next(nextArg);
|
|
1047
|
+
if (next.done) {
|
|
1048
|
+
currentResult = Result.Ok(next.value);
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
const wrapped = next.value;
|
|
1052
|
+
let result;
|
|
1053
|
+
let stack;
|
|
1054
|
+
if (require_utils.isCapturedTrace(wrapped)) {
|
|
1055
|
+
stack = wrapped.stack;
|
|
1056
|
+
result = await wrapped.value.result;
|
|
1057
|
+
} else result = await wrapped.result;
|
|
1058
|
+
if (result.isErr()) {
|
|
1059
|
+
const err = result.unwrapErr();
|
|
1060
|
+
if (stack && err instanceof Error) {
|
|
1061
|
+
const stackLines = stack.split("\n");
|
|
1062
|
+
if (stackLines.length > 2) {
|
|
1063
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
1064
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
currentResult = result;
|
|
1068
|
+
break;
|
|
1069
|
+
}
|
|
1070
|
+
nextArg = result.unwrap();
|
|
1071
|
+
}
|
|
1072
|
+
return currentResult;
|
|
1073
|
+
}
|
|
1074
|
+
};
|
|
477
1075
|
|
|
478
1076
|
//#endregion
|
|
479
|
-
|
|
480
|
-
enumerable: true,
|
|
481
|
-
get: function () {
|
|
482
|
-
return Result;
|
|
483
|
-
}
|
|
484
|
-
});
|
|
1077
|
+
exports.Result = Result;
|
|
485
1078
|
//# sourceMappingURL=result.cjs.map
|