@railway-ts/pipelines 0.1.30 → 0.2.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.
@@ -0,0 +1,909 @@
1
+ // src/result/result.ts
2
+ /**
3
+ * Symbol used to identify Result objects.
4
+ *
5
+ * Not meant to be used directly, but it must stay in the published type
6
+ * declarations: `Result` refers to it, and without it a plain
7
+ * `{ ok: true, value }` object would type-check as a `Result`.
8
+ *
9
+ * `Symbol.for` makes every copy of this module (each entry point, or a second
10
+ * installed copy of the package) share one symbol, so Results compare equal no
11
+ * matter which copy created them.
12
+ */
13
+ const RESULT_BRAND = Symbol.for("@railway-ts/pipelines/RESULT_BRAND");
14
+ /**
15
+ * Creates a Result containing a value.
16
+ *
17
+ * @example
18
+ * const result: Result<number, string> = ok(123);
19
+ *
20
+ * @param value - The value to contain
21
+ * @returns A Result containing the value
22
+ */
23
+ function ok(value) {
24
+ return {
25
+ ok: true,
26
+ value,
27
+ [RESULT_BRAND]: "ok"
28
+ };
29
+ }
30
+ /**
31
+ * Creates a Result containing an error.
32
+ *
33
+ * @example
34
+ * const error: Result<number, string> = err("An error occurred");
35
+ *
36
+ * @param error - The error to contain
37
+ * @returns A Result containing the error
38
+ */
39
+ function err(error) {
40
+ return {
41
+ ok: false,
42
+ error,
43
+ [RESULT_BRAND]: "error"
44
+ };
45
+ }
46
+ /**
47
+ * Type guard that checks if a Result is an Ok variant containing a value.
48
+ *
49
+ * @example
50
+ * const result: Result<number, string> = ok(123);
51
+ * if (isOk(result)) {
52
+ * // TypeScript knows result.value exists here
53
+ * console.log(result.value);
54
+ * }
55
+ *
56
+ * @param result - The result to check
57
+ * @returns A type predicate indicating if the result is an Ok variant
58
+ */
59
+ function isOk(result) {
60
+ return result.ok;
61
+ }
62
+ /**
63
+ * Type guard that checks if a Result is an Error variant.
64
+ *
65
+ * @example
66
+ * const result: Result<number, string> = err("error");
67
+ * if (isErr(result)) {
68
+ * // TypeScript knows result.error exists here
69
+ * console.log(result.error);
70
+ * }
71
+ *
72
+ * @param result - The result to check
73
+ * @returns A type predicate indicating if the result is an Error variant
74
+ */
75
+ function isErr(result) {
76
+ return !result.ok;
77
+ }
78
+ /**
79
+ * Maps the value inside a Result using a transformation function.
80
+ *
81
+ * @example
82
+ * const result: Result<number, string> = ok(123);
83
+ * const transformed: Result<string, string> = map(result, (value) => value.toString());
84
+ *
85
+ * @param result - The Result to transform
86
+ * @param fn - The function to apply to the contained value
87
+ * @returns A new Result containing the transformed value, or the original error if the input was an error
88
+ */
89
+ function map$1(result, fn) {
90
+ return result.ok ? ok(fn(result.value)) : result;
91
+ }
92
+ /**
93
+ * Maps the value inside a Result using a transformation function that returns a Result.
94
+ *
95
+ * @example
96
+ * const result: Result<number, string> = ok(123);
97
+ * const transformed: Result<string, string> = flatMap(result, (value) => ok(value.toString()));
98
+ *
99
+ * @param result - The Result to transform
100
+ * @param fn - The function to apply to the contained value, returning a Result
101
+ * @returns The Result returned by the transformation function, or the original error if the input was an error
102
+ */
103
+ function flatMap$1(result, fn) {
104
+ return result.ok ? fn(result.value) : result;
105
+ }
106
+ /**
107
+ * Maps the error inside a Result using a transformation function.
108
+ *
109
+ * @example
110
+ * const result: Result<number, string> = err("error");
111
+ * const transformed: Result<number, Error> = mapErr(result, (err) => new Error(err));
112
+ *
113
+ * @param result - The Result to transform
114
+ * @param fn - The function to apply to the contained error
115
+ * @returns A new Result containing the transformed error, or the original value if the input was ok
116
+ */
117
+ function mapErr(result, fn) {
118
+ return result.ok ? result : err(fn(result.error));
119
+ }
120
+ /**
121
+ * Maps both the value and error of a Result using separate transformation functions.
122
+ * This is equivalent to chaining map and mapErr, but more concise.
123
+ *
124
+ * @example
125
+ * const result: Result<number, string> = ok(123);
126
+ * const transformed = bimap(
127
+ * result,
128
+ * (value) => value.toString(),
129
+ * (error) => new Error(error)
130
+ * ); // ok("123")
131
+ *
132
+ * const error: Result<number, string> = err("failed");
133
+ * const transformed2 = bimap(
134
+ * error,
135
+ * (value) => value.toString(),
136
+ * (error) => new Error(error)
137
+ * ); // err(Error("failed"))
138
+ *
139
+ * @param result - The Result to transform
140
+ * @param okFn - The function to apply to the contained value if Ok
141
+ * @param errFn - The function to apply to the contained error if Err
142
+ * @returns A new Result with both branches transformed
143
+ */
144
+ function bimap$1(result, okFn, errFn) {
145
+ return result.ok ? ok(okFn(result.value)) : err(errFn(result.error));
146
+ }
147
+ /**
148
+ * Filters a Result based on a predicate function.
149
+ *
150
+ * @example
151
+ * const result: Result<number, string> = ok(123);
152
+ * const filtered: Result<number, string> = filter(result, value => value > 100, "Value too small"); // still Ok(123)
153
+ * const filtered2: Result<number, string> = filter(result, value => value > 200, "Value too small"); // Err("Value too small")
154
+ *
155
+ * @param result - The Result to filter
156
+ * @param predicate - A function that determines if the value should be kept
157
+ * @param error - The error to return if the predicate fails
158
+ * @returns The original Result if it contains a value that satisfies the predicate, otherwise an Error
159
+ */
160
+ function filter$1(result, predicate, error) {
161
+ if (!result.ok) return result;
162
+ return predicate(result.value) ? result : err(error);
163
+ }
164
+ /**
165
+ * Executes a callback with the value if the Result is Ok, without changing the Result.
166
+ * Useful for side effects like logging while maintaining a processing chain.
167
+ *
168
+ * @example
169
+ * const finalResult = pipe(
170
+ * ok(123),
171
+ * r => map(r, x => x * 2),
172
+ * r => tap(r, x => console.log(`Value: ${x}`)), // Logs but doesn't change the Result
173
+ * r => filter(r, x => x > 200, "Value too small")
174
+ * );
175
+ *
176
+ * @param result - The Result to tap into
177
+ * @param fn - The function to execute with the value if Ok
178
+ * @returns The original Result unchanged
179
+ */
180
+ function tap$1(result, fn) {
181
+ if (isOk(result)) fn(result.value);
182
+ return result;
183
+ }
184
+ /**
185
+ * Executes a callback with the error if the Result is an Error, without changing the Result.
186
+ * Useful for side effects like logging while maintaining a processing chain.
187
+ *
188
+ * @example
189
+ * const finalResult = pipe(
190
+ * err("something went wrong"),
191
+ * r => tapErr(r, e => console.error(`Error: ${e}`)), // Logs but doesn't change the Result
192
+ * r => mapErr(r, e => new Error(e))
193
+ * );
194
+ *
195
+ * @param result - The Result to tap into
196
+ * @param fn - The function to execute with the error if Error
197
+ * @returns The original Result unchanged
198
+ */
199
+ function tapErr(result, fn) {
200
+ if (isErr(result)) fn(result.error);
201
+ return result;
202
+ }
203
+ /**
204
+ * Recovers from an Err by applying `fn` to the error value. Returns the original Ok unchanged.
205
+ * This is the error-channel equivalent of `flatMap`.
206
+ *
207
+ * @example
208
+ * const result: Result<number, string> = err("not found");
209
+ * const recovered = orElse(result, (e) => ok(e.length)); // ok(9)
210
+ *
211
+ * const okResult: Result<number, string> = ok(42);
212
+ * const kept = orElse(okResult, (e) => ok(e.length)); // ok(42)
213
+ *
214
+ * @param result - The Result to recover from
215
+ * @param fn - A function that receives the Err value and returns a fallback Result
216
+ * @returns The original Ok, or the Result of applying fn to the error
217
+ */
218
+ function orElse(result, fn) {
219
+ return result.ok ? result : fn(result.error);
220
+ }
221
+ /**
222
+ * Pattern matches on a Result to handle both Ok and Error cases.
223
+ *
224
+ * @example
225
+ * const result = ok(42);
226
+ * const message = match(result, {
227
+ * ok: (value) => `Got value: ${value}`,
228
+ * err: (error) => `Got error: ${error}`
229
+ * }); // "Got value: 42"
230
+ *
231
+ * @param result - The Result to match against
232
+ * @param patterns - An object containing handler functions for Ok and Error cases
233
+ * @returns The result of calling the appropriate handler function
234
+ */
235
+ function match$1(result, patterns) {
236
+ if (isOk(result)) return (0, patterns.ok)(result.value);
237
+ return (0, patterns.err)(result.error);
238
+ }
239
+ /**
240
+ * Unwraps the value inside a Result, throwing an error if the Result is an error.
241
+ *
242
+ * @remarks
243
+ * This function is intended for prototyping only and should not be used in production.
244
+ * In production code, prefer using pattern matching or `unwrapOr` to handle both Ok and Error cases safely.
245
+ *
246
+ * @example
247
+ * const result: Result<number, string> = ok(123);
248
+ * const value: number = unwrap(result);
249
+ *
250
+ * // With custom error message
251
+ * try {
252
+ * const badResult: Result<number, string> = err("Invalid data");
253
+ * unwrap(badResult, "Custom error message");
254
+ * } catch (error) {
255
+ * // Error will contain "Custom error message" instead of the default
256
+ * }
257
+ *
258
+ * @param result - The Result to unwrap
259
+ * @param errorMsg - Optional custom error message to use if Result is an error
260
+ * @returns The contained value
261
+ * @throws If the Result is an error
262
+ */
263
+ function unwrap$1(result, errorMsg) {
264
+ if (result.ok) return result.value;
265
+ throw new Error(errorMsg || `Cannot unwrap an error Result: ${String(result.error)}`);
266
+ }
267
+ /**
268
+ * Unwraps the value inside a Result, providing a default value if the Result is an error.
269
+ *
270
+ * @example
271
+ * const result: Result<number, string> = err("error");
272
+ * const value: number = unwrapOr(result, 123);
273
+ *
274
+ * @param result - The Result to unwrap
275
+ * @param defaultValue - The value to return if the Result is an error
276
+ * @returns The contained value, or the default value if the Result is an error
277
+ */
278
+ function unwrapOr$1(result, defaultValue) {
279
+ return result.ok ? result.value : defaultValue;
280
+ }
281
+ /**
282
+ * Unwraps the value inside a Result, calling a function to generate a default value if the Result is an error.
283
+ * Unlike unwrapOr, this only computes the default when needed.
284
+ *
285
+ * @example
286
+ * const result: Result<number, string> = err("error");
287
+ * const value = unwrapOrElse(result, () => expensiveComputation());
288
+ *
289
+ * @param result - The Result to unwrap
290
+ * @param defaultFn - A function that returns a default value if the Result is an error
291
+ * @returns The contained value, or the result of calling defaultFn if the Result is an error
292
+ */
293
+ function unwrapOrElse$1(result, defaultFn) {
294
+ return result.ok ? result.value : defaultFn();
295
+ }
296
+ function combine$1(results) {
297
+ const values = [];
298
+ for (const result of results) {
299
+ if (!result.ok) return result;
300
+ values.push(result.value);
301
+ }
302
+ return ok(values);
303
+ }
304
+ function combineAll(results) {
305
+ const errors = [];
306
+ const values = [];
307
+ for (const result of results) if (result.ok) values.push(result.value);
308
+ else errors.push(result.error);
309
+ return errors.length > 0 ? err(errors) : ok(values);
310
+ }
311
+ /**
312
+ * Separates an array of Results into successes and failures.
313
+ * Unlike `combineAll` which is all-or-nothing, `partition` preserves both sides —
314
+ * useful for batch processing where partial success is meaningful.
315
+ *
316
+ * @example
317
+ * const results = [ok(1), err('bad'), ok(3), err('worse')];
318
+ * partition(results);
319
+ * // { successes: [1, 3], failures: ['bad', 'worse'] }
320
+ */
321
+ const partition = (results) => ({
322
+ successes: results.filter((r) => isOk(r)).map((r) => r.value),
323
+ failures: results.filter((r) => isErr(r)).map((r) => r.error)
324
+ });
325
+ /**
326
+ * Converts a Result to an Option.
327
+ * If the Result is Ok, returns a Some variant with the value.
328
+ * If the Result is an Error, returns a None variant.
329
+ *
330
+ * @example
331
+ * import { some, none } from "@/option";
332
+ *
333
+ * const option1 = mapToOption(ok(123)); // some(123)
334
+ * const option2 = mapToOption(err("error")); // none()
335
+ *
336
+ * @param result - The Result to convert
337
+ * @returns An Option containing the value if Ok, or None if Error
338
+ */
339
+ function mapToOption(result) {
340
+ return result.ok ? some(result.value) : none();
341
+ }
342
+ /**
343
+ * Safely executes a function that might throw and converts the result into a Result type.
344
+ * If the function executes successfully, returns an Ok variant with the return value.
345
+ * If the function throws an error, returns an Error variant containing the error message as a string.
346
+ *
347
+ * @example
348
+ * const parseJson = (str: string) => fromTry(() => JSON.parse(str));
349
+ *
350
+ * const validResult = parseJson('{"name":"John"}'); // ok({ name: 'John' })
351
+ * const invalidResult = parseJson('invalid json'); // err("Unexpected token...")
352
+ *
353
+ * @param f - The function to execute
354
+ * @returns A Result containing either the function's return value or the error message
355
+ */
356
+ function fromTry(f) {
357
+ try {
358
+ return ok(f());
359
+ } catch (error) {
360
+ return err(error instanceof Error ? error.message : String(error));
361
+ }
362
+ }
363
+ /**
364
+ * Safely executes a function that might throw and converts the result into a Result type.
365
+ * Unlike fromTry, this preserves the full Error object instead of just the message.
366
+ * Use this when you need access to error stack traces or custom error properties.
367
+ *
368
+ * @example
369
+ * const result = fromTryWithError(() => JSON.parse('invalid'));
370
+ * if (isErr(result)) {
371
+ * console.log(result.error.stack); // Access to full stack trace
372
+ * }
373
+ *
374
+ * @param f - The function to execute
375
+ * @returns A Result containing either the function's return value or the full Error object
376
+ */
377
+ function fromTryWithError(f) {
378
+ try {
379
+ return ok(f());
380
+ } catch (error) {
381
+ return err(error instanceof Error ? error : new Error(String(error)));
382
+ }
383
+ }
384
+ /**
385
+ * Converts a Promise to a Result, capturing any errors that occur during promise resolution.
386
+ * Returns error messages as strings for simplicity.
387
+ *
388
+ * @example
389
+ * const result = await fromPromise(fetch('https://api.example.com/data'));
390
+ * if (isErr(result)) {
391
+ * console.log(result.error); // Error message as string
392
+ * }
393
+ *
394
+ * @param promise - The Promise to convert
395
+ * @returns A Promise that resolves to a Result with string error messages
396
+ */
397
+ async function fromPromise(promise) {
398
+ try {
399
+ return ok(await promise);
400
+ } catch (error) {
401
+ return err(error instanceof Error ? error.message : String(error));
402
+ }
403
+ }
404
+ /**
405
+ * Converts a Promise to a Result, preserving the full error object or custom error type.
406
+ * Use this when you need access to error stack traces, custom properties, or specific error types.
407
+ *
408
+ * @example
409
+ * // With default error handling (preserves full error)
410
+ * const result = await fromPromiseWithError(fetch('https://api.example.com/data'));
411
+ *
412
+ * @example
413
+ * // With specific error type and transformer
414
+ * type ApiError = { code: number; message: string };
415
+ *
416
+ * const result = await fromPromiseWithError<Response, ApiError>(
417
+ * fetch('https://api.example.com/data'),
418
+ * (error) => ({
419
+ * code: error instanceof Error ? 500 : 400,
420
+ * message: error instanceof Error ? error.message : String(error)
421
+ * })
422
+ * );
423
+ *
424
+ * @param promise - The Promise to convert
425
+ * @param errorFn - Optional function to transform caught errors to the expected error type
426
+ * @returns A Promise that resolves to a Result
427
+ */
428
+ async function fromPromiseWithError(promise, errorFn = (error) => error) {
429
+ try {
430
+ return ok(await promise);
431
+ } catch (error) {
432
+ return err(errorFn(error));
433
+ }
434
+ }
435
+ /**
436
+ * Converts a Result to a Promise.
437
+ *
438
+ * @example
439
+ * const result = ok(123);
440
+ * const promise = toPromise(result);
441
+ * const value = await promise; // 123
442
+ *
443
+ * @param result - The Result to convert
444
+ * @returns A Promise that resolves to the value if Ok, or rejects with the error if Error
445
+ */
446
+ function toPromise(result) {
447
+ return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);
448
+ }
449
+ /**
450
+ * Curried version of `map`. Returns a function that transforms the Ok value using `fn`,
451
+ * passing through any Err unchanged.
452
+ *
453
+ * @example
454
+ * const double = mapWith((n: number) => n * 2);
455
+ *
456
+ * const result: Result<number, string> = ok(5);
457
+ * const doubled: Result<number, string> = double(result); // ok(10)
458
+ *
459
+ * const errResult: Result<number, string> = err("fail");
460
+ * const stillErr: Result<number, string> = double(errResult); // err("fail")
461
+ *
462
+ * // Point-free in a pipe
463
+ * const result2 = pipe(ok(3), mapWith((n: number) => n + 1)); // ok(4)
464
+ *
465
+ * @param fn - The function to apply to the Ok value
466
+ * @returns A function that takes a Result and returns a new Result with the Ok value transformed
467
+ */
468
+ function mapWith$1(fn) {
469
+ return (result) => map$1(result, fn);
470
+ }
471
+ function flatMapWith$1(fn) {
472
+ return (result) => {
473
+ if (!result.ok) return result;
474
+ return fn(result.value);
475
+ };
476
+ }
477
+ /**
478
+ * Curried version of `mapErr`. Returns a function that transforms the Err value using `fn`,
479
+ * passing through any Ok unchanged.
480
+ *
481
+ * @example
482
+ * const wrapError = mapErrWith((msg: string) => new Error(msg));
483
+ *
484
+ * const result: Result<number, string> = err("fail");
485
+ * const wrapped: Result<number, Error> = wrapError(result); // err(Error("fail"))
486
+ *
487
+ * const okResult: Result<number, string> = ok(42);
488
+ * const stillOk: Result<number, Error> = wrapError(okResult); // ok(42)
489
+ *
490
+ * // Point-free in a pipe
491
+ * const result2 = pipe(err("oops"), mapErrWith((s: string) => s.toUpperCase())); // err("OOPS")
492
+ *
493
+ * @param fn - The function to apply to the Err value
494
+ * @returns A function that takes a Result and returns a new Result with the Err value transformed
495
+ */
496
+ function mapErrWith(fn) {
497
+ return (result) => mapErr(result, fn);
498
+ }
499
+ /**
500
+ * Curried version of `filter`. Returns a function that keeps an Ok value matching the predicate,
501
+ * or returns the provided error if the predicate fails.
502
+ *
503
+ * @example
504
+ * const isPositive = filterWith((n: number) => n > 0, "must be positive");
505
+ *
506
+ * const result: Result<number, string> = ok(5);
507
+ * const filtered: Result<number, string> = isPositive(result); // ok(5)
508
+ *
509
+ * const zero: Result<number, string> = ok(-1);
510
+ * const failed: Result<number, string> = isPositive(zero); // err("must be positive")
511
+ *
512
+ * // Point-free in a pipe
513
+ * const result2 = pipe(ok(10), filterWith((n: number) => n < 100, "too large")); // ok(10)
514
+ *
515
+ * @param predicate - A function that determines if the Ok value should be kept
516
+ * @param error - The error to return if the predicate fails
517
+ * @returns A function that takes a Result and returns the original Result or an Err
518
+ */
519
+ function filterWith$1(predicate, error) {
520
+ return (result) => filter$1(result, predicate, error);
521
+ }
522
+ function tapWith$1(fn) {
523
+ return (result) => {
524
+ if (!result.ok) return result;
525
+ const out = fn(result.value);
526
+ if (out instanceof Promise) return out.then(() => result);
527
+ return result;
528
+ };
529
+ }
530
+ function tapErrWith(fn) {
531
+ return (result) => {
532
+ if (result.ok) return result;
533
+ const out = fn(result.error);
534
+ if (out instanceof Promise) return out.then(() => result);
535
+ return result;
536
+ };
537
+ }
538
+ /**
539
+ * Curried version of `orElse`. Recovers from an Err by applying `fn` to the error value;
540
+ * passes through Ok unchanged.
541
+ *
542
+ * @example
543
+ * const recover = orElseWith((msg: string) => ok(msg.length));
544
+ *
545
+ * const errResult: Result<number, string> = err("fail");
546
+ * const recovered: Result<number, string> = recover(errResult); // ok(4)
547
+ *
548
+ * const okResult: Result<number, string> = ok(42);
549
+ * const kept: Result<number, string> = recover(okResult); // ok(42)
550
+ *
551
+ * // Point-free in a pipe — recover using the error
552
+ * const result = pipe(
553
+ * err("not found"),
554
+ * orElseWith((e: string) => ok(`recovered from: ${e}`))
555
+ * ); // ok("recovered from: not found")
556
+ *
557
+ * @param fn - A function that receives the Err value and returns a fallback Result
558
+ * @returns A function that takes a Result and returns either the original Ok or the result of calling fn
559
+ */
560
+ function orElseWith(fn) {
561
+ return (result) => orElse(result, fn);
562
+ }
563
+ // src/option/option.ts
564
+ /**
565
+ * Symbol used to identify Option objects.
566
+ *
567
+ * Not meant to be used directly, but it must stay in the published type
568
+ * declarations: `Option` refers to it, and without it a plain
569
+ * `{ some: true, value }` object would type-check as an `Option`.
570
+ *
571
+ * `Symbol.for` makes every copy of this module (each entry point, or a second
572
+ * installed copy of the package) share one symbol, so Options compare equal no
573
+ * matter which copy created them.
574
+ */
575
+ const OPTION_BRAND = Symbol.for("@railway-ts/pipelines/OPTION_BRAND");
576
+ /**
577
+ * Creates an Option containing a value.
578
+ *
579
+ * @param value - The value to contain
580
+ * @returns An Option containing the value
581
+ */
582
+ function some(value) {
583
+ return {
584
+ some: true,
585
+ value,
586
+ [OPTION_BRAND]: "some"
587
+ };
588
+ }
589
+ /**
590
+ * Creates an Option containing nothing.
591
+ *
592
+ * @example
593
+ * const some: Option<number> = some(123);
594
+ * const none: Option<number> = none();
595
+ *
596
+ * @returns An Option containing nothing
597
+ */
598
+ function none() {
599
+ return {
600
+ some: false,
601
+ [OPTION_BRAND]: "none"
602
+ };
603
+ }
604
+ /**
605
+ * Type guard that checks if an Option is a Some variant containing a value.
606
+ *
607
+ * @example
608
+ * const option: Option<number> = some(123);
609
+ * if (isSome(option)) {
610
+ * // TypeScript knows option.value exists here
611
+ * console.log(option.value);
612
+ * }
613
+ *
614
+ * @param option - The option to check
615
+ * @returns A type predicate indicating if the option is a Some variant
616
+ */
617
+ function isSome(option) {
618
+ return option.some;
619
+ }
620
+ /**
621
+ * Type guard that checks if an Option is a None variant containing no value.
622
+ *
623
+ * @example
624
+ * const option: Option<number> = none();
625
+ * if (isNone(option)) {
626
+ * // TypeScript knows this option has no value
627
+ * // Attempting to access option.value would be a type error
628
+ * }
629
+ *
630
+ * @param option - The option to check
631
+ * @returns A type predicate indicating if the option is a None variant
632
+ */
633
+ function isNone(option) {
634
+ return !option.some;
635
+ }
636
+ /**
637
+ * Maps the value inside an Option using a transformation function.
638
+ *
639
+ * @example
640
+ * const option: Option<number> = some(123);
641
+ * const transformed: Option<string> = map(option, (value) => value.toString());
642
+ *
643
+ * @param option - The Option to transform
644
+ * @param fn - The function to apply to the contained value
645
+ * @returns A new Option containing the transformed value, or none if the input was none
646
+ */
647
+ function map(option, fn) {
648
+ return option.some ? some(fn(option.value)) : none();
649
+ }
650
+ /**
651
+ * Maps the value inside an Option using a transformation function that returns an Option.
652
+ *
653
+ * @example
654
+ * const option: Option<number> = some(123);
655
+ * const transformed: Option<string> = flatMap(option, (value) => some(value.toString()));
656
+ *
657
+ * @param option - The Option to transform
658
+ * @param fn - The function to apply to the contained value, returning an Option
659
+ * @returns The Option returned by the transformation function, or none if the input was none
660
+ */
661
+ function flatMap(option, fn) {
662
+ return option.some ? fn(option.value) : none();
663
+ }
664
+ /**
665
+ * Maps both the Some and None branches of an Option using separate transformation functions.
666
+ * This is similar to combining a match with flatMap: it lets you decide the resulting Option in both cases.
667
+ *
668
+ * @example
669
+ * const o1 = some(123);
670
+ * const r1 = bimap(o1, (n) => some(n.toString()), () => none()); // some("123")
671
+ *
672
+ * const o2 = none<number>();
673
+ * const r2 = bimap(o2, (n) => some(n.toString()), () => some('fallback')); // some("fallback")
674
+ *
675
+ * @param option - The Option to transform
676
+ * @param someFn - The function to apply if the Option is Some, returning a new Option
677
+ * @param noneFn - The function to apply if the Option is None, returning a new Option
678
+ * @returns The Option returned by the appropriate transformation function
679
+ */
680
+ function bimap(option, someFn, noneFn) {
681
+ return option.some ? someFn(option.value) : noneFn();
682
+ }
683
+ /**
684
+ * Filters an Option based on a predicate function.
685
+ *
686
+ * @example
687
+ * const option: Option<number> = some(123);
688
+ * const filtered: Option<number> = filter(option, value => value > 100); // still Some(123)
689
+ * const filtered2: Option<number> = filter(option, value => value < 100); // None
690
+ *
691
+ * @param option - The Option to filter
692
+ * @param predicate - A function that determines if the value should be kept
693
+ * @returns The original Option if it contains a value that satisfies the predicate, otherwise None
694
+ */
695
+ function filter(option, predicate) {
696
+ return option.some && predicate(option.value) ? option : none();
697
+ }
698
+ /**
699
+ * Executes a callback with the value if the Option is Some, without changing the Option.
700
+ * Useful for side effects like logging while maintaining a processing chain.
701
+ *
702
+ * @example
703
+ * const result = pipe(
704
+ * some(123),
705
+ * opt => map(opt, x => x * 2),
706
+ * opt => tap(opt, x => console.log(`Value: ${x}`)), // Logs but doesn't change the Option
707
+ * opt => filter(opt, x => x > 200)
708
+ * );
709
+ *
710
+ * @param option - The Option to tap into
711
+ * @param fn - The function to execute with the value if Some
712
+ * @returns The original Option unchanged
713
+ */
714
+ function tap(option, fn) {
715
+ if (isSome(option)) fn(option.value);
716
+ return option;
717
+ }
718
+ /**
719
+ * Pattern matches on an Option to handle both Some and None cases.
720
+ *
721
+ * @example
722
+ * const option = some(42);
723
+ * const result = match(option, {
724
+ * some: (value) => `Got value: ${value}`,
725
+ * none: () => "Got nothing"
726
+ * }); // "Got value: 42"
727
+ *
728
+ * const empty = none<number>();
729
+ * const result2 = match(empty, {
730
+ * some: (value) => `Got value: ${value}`,
731
+ * none: () => "Got nothing"
732
+ * }); // "Got nothing"
733
+ *
734
+ * @param option - The Option to match against
735
+ * @param patterns - An object containing handler functions for Some and None cases
736
+ * @returns The result of calling the appropriate handler function
737
+ */
738
+ function match(option, patterns) {
739
+ if (isSome(option)) return (0, patterns.some)(option.value);
740
+ return (0, patterns.none)();
741
+ }
742
+ /**
743
+ * Unwraps the value inside an Option, throwing an error if the Option is none.
744
+ *
745
+ * @remarks
746
+ * This function is intended for prototyping only and should not be used in production.
747
+ * In production code, prefer using pattern matching or `unwrapOr` to handle both Some and None cases safely.
748
+ *
749
+ * @example
750
+ * const option: Option<number> = some(123);
751
+ * const value: number = unwrap(option);
752
+ *
753
+ * @param option - The Option to unwrap
754
+ * @param [errorMsg] - Optional custom error message to throw when the Option is none
755
+ * @returns The contained value
756
+ */
757
+ function unwrap(option, errorMsg) {
758
+ if (option.some) return option.value;
759
+ throw new Error(errorMsg || "Cannot unwrap a none Option");
760
+ }
761
+ /**
762
+ * Unwraps the value inside an Option, providing a default value if the Option is none.
763
+ *
764
+ * @example
765
+ * const option: Option<number> = none();
766
+ * const value: number = unwrapOr(option, 123);
767
+ *
768
+ * @param option - The Option to unwrap
769
+ * @param defaultValue - The value to return if the Option is none
770
+ * @returns The contained value, or the default value if the Option is none
771
+ */
772
+ function unwrapOr(option, defaultValue) {
773
+ return option.some ? option.value : defaultValue;
774
+ }
775
+ /**
776
+ * Unwraps the value inside an Option, calling a function to generate a default value if the Option is none.
777
+ * Unlike unwrapOr, this only computes the default when needed.
778
+ *
779
+ * @example
780
+ * const option: Option<number> = none();
781
+ * const value = unwrapOrElse(option, () => expensiveComputation());
782
+ *
783
+ * @param option - The Option to unwrap
784
+ * @param defaultFn - A function that returns a default value if the Option is none
785
+ * @returns The contained value, or the result of calling defaultFn if the Option is none
786
+ */
787
+ function unwrapOrElse(option, defaultFn) {
788
+ return option.some ? option.value : defaultFn();
789
+ }
790
+ function combine(options) {
791
+ const values = [];
792
+ for (const option of options) {
793
+ if (!option.some) return none();
794
+ values.push(option.value);
795
+ }
796
+ return some(values);
797
+ }
798
+ /**
799
+ * Creates an Option from a nullable value.
800
+ *
801
+ * @example
802
+ * const option = fromNullable(123); // some(123)
803
+ * const option = fromNullable(null); // none()
804
+ *
805
+ * @param value - The value to wrap in the Some variant
806
+ * @returns An Option containing the value (Some) if the value is not null or undefined, or None if the value is null or undefined
807
+ */
808
+ const fromNullable = (value) => {
809
+ return value === null || value === void 0 ? none() : some(value);
810
+ };
811
+ /**
812
+ * Converts an Option to a Result.
813
+ * If the Option is Some, returns an Ok variant with the value.
814
+ * If the Option is None, returns an Err variant with the provided error.
815
+ *
816
+ * @example
817
+ * const result = mapToResult(some(123), 'Some error message');
818
+ * if (isOk(result)) {
819
+ * console.log('Value:', result.value);
820
+ * } else {
821
+ * console.error('Error:', result.error);
822
+ * }
823
+ *
824
+ * @param option - The Option to convert
825
+ * @param error - The error to return if the Option is None
826
+ * @returns A Result containing either the value (Ok) or the error (Err)
827
+ */
828
+ function mapToResult(option, error) {
829
+ return option.some ? ok(option.value) : err(error);
830
+ }
831
+ /**
832
+ * Curried version of `map`. Returns a function that transforms the Some value using `fn`,
833
+ * passing through None unchanged.
834
+ *
835
+ * @example
836
+ * const double = mapWith((n: number) => n * 2);
837
+ *
838
+ * const option: Option<number> = some(5);
839
+ * const doubled: Option<number> = double(option); // some(10)
840
+ *
841
+ * const empty: Option<number> = none();
842
+ * const stillNone: Option<number> = double(empty); // none()
843
+ *
844
+ * // Point-free in a pipe
845
+ * const result = pipe(some(3), mapWith((n: number) => n + 1)); // some(4)
846
+ *
847
+ * @param fn - The function to apply to the Some value
848
+ * @returns A function that takes an Option and returns a new Option with the Some value transformed
849
+ */
850
+ function mapWith(fn) {
851
+ return (option) => map(option, fn);
852
+ }
853
+ function flatMapWith(fn) {
854
+ return (option) => {
855
+ if (!option.some) return option;
856
+ return fn(option.value);
857
+ };
858
+ }
859
+ /**
860
+ * Curried version of `filter`. Returns a function that keeps a Some value matching the predicate,
861
+ * or returns None if the predicate fails.
862
+ *
863
+ * @example
864
+ * const isPositive = filterWith((n: number) => n > 0);
865
+ *
866
+ * const option: Option<number> = some(5);
867
+ * const filtered: Option<number> = isPositive(option); // some(5)
868
+ *
869
+ * const negative: Option<number> = some(-1);
870
+ * const gone: Option<number> = isPositive(negative); // none()
871
+ *
872
+ * // Point-free in a pipe
873
+ * const result = pipe(some(10), filterWith((n: number) => n < 100)); // some(10)
874
+ *
875
+ * @param predicate - A function that determines if the Some value should be kept
876
+ * @returns A function that takes an Option and returns the original Option or None
877
+ */
878
+ function filterWith(predicate) {
879
+ return (option) => filter(option, predicate);
880
+ }
881
+ function tapWith(fn) {
882
+ return (option) => {
883
+ if (!option.some) return option;
884
+ const out = fn(option.value);
885
+ if (out instanceof Promise) return out.then(() => option);
886
+ return option;
887
+ };
888
+ }
889
+ /**
890
+ * Curried version of `mapToResult`. Returns a function that converts an Option
891
+ * to a Result, using the provided error if the Option is None.
892
+ *
893
+ * @example
894
+ * const toResult = mapToResultWith('not found');
895
+ * toResult(some(42)); // ok(42)
896
+ * toResult(none()); // err('not found')
897
+ *
898
+ * // Point-free in a pipe
899
+ * pipe(fromNullable(value), mapToResultWith('missing'));
900
+ *
901
+ * @param error - The error to return if the Option is None
902
+ * @returns A function that takes an Option and returns a Result
903
+ */
904
+ function mapToResultWith(error) {
905
+ return (option) => mapToResult(option, error);
906
+ }
907
+ export { unwrap$1 as $, flatMap$1 as A, mapErrWith as B, RESULT_BRAND as C, err as D, combineAll as E, fromTryWithError as F, orElse as G, mapWith$1 as H, isErr as I, tap$1 as J, orElseWith as K, isOk as L, fromPromise as M, fromPromiseWithError as N, filter$1 as O, fromTry as P, toPromise as Q, map$1 as R, unwrapOrElse as S, combine$1 as T, match$1 as U, mapToOption as V, ok as W, tapErrWith as X, tapErr as Y, tapWith$1 as Z, some as _, filterWith as a, unwrap as b, fromNullable as c, map as d, unwrapOr$1 as et, mapToResult as f, none as g, match as h, filter as i, flatMapWith$1 as j, filterWith$1 as k, isNone as l, mapWith as m, bimap as n, flatMap as o, mapToResultWith as p, partition as q, combine as r, flatMapWith as s, OPTION_BRAND as t, unwrapOrElse$1 as tt, isSome as u, tap as v, bimap$1 as w, unwrapOr as x, tapWith as y, mapErr as z };
908
+
909
+ //# sourceMappingURL=option-BQCaaEBP.mjs.map