resultar 1.4.4 → 2.0.0-beta.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.
@@ -1,717 +0,0 @@
1
- import {
2
- createResultarError
3
- } from "./chunk-VBI3T5VS.js";
4
-
5
- // src/result.ts
6
- var Ok = class {
7
- constructor(value) {
8
- this.value = value;
9
- }
10
- ok = true;
11
- };
12
- var Err = class {
13
- constructor(error) {
14
- this.error = error;
15
- }
16
- ok = false;
17
- };
18
- var Result = class _Result {
19
- constructor(state) {
20
- this.state = state;
21
- if (state.ok) {
22
- this.value = state.value;
23
- this.error = void 0;
24
- } else {
25
- this.error = state.error;
26
- this.value = void 0;
27
- }
28
- }
29
- /**
30
- * Creates a `Result` by running a function that might throw.
31
- * If the function throws, the error will be caught and returned as an `Err`.
32
- * If the function succeeds, the value will be wrapped in an `Ok`.
33
- *
34
- * @param fn - The function to execute, which might throw an error
35
- * @param errorFn - Optional function to transform the thrown error before wrapping in `Err`
36
- * @returns A `Result` containing either the function's return value or the caught error
37
- */
38
- static tryCatch(fn, errorFn) {
39
- try {
40
- return ok(fn());
41
- } catch (error) {
42
- if (errorFn) {
43
- return err(errorFn(error));
44
- }
45
- return err(error);
46
- }
47
- }
48
- /**
49
- * Wraps a function with a try catch, creating a new function with the same
50
- * arguments but returning `Ok` if successful, `Err` if the function throws
51
- *
52
- * @param fn function to wrap with ok on success or err on failure
53
- * @param errorFn when an error is thrown, this will wrap the error result if provided
54
- */
55
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
- static fromThrowable(fn, errorFn) {
57
- return (...args) => {
58
- try {
59
- const result = fn(...args);
60
- return ok(result);
61
- } catch (error) {
62
- if (errorFn) {
63
- return err(errorFn(error));
64
- }
65
- return err(error);
66
- }
67
- };
68
- }
69
- static ok(value) {
70
- return new _Result(new Ok(value));
71
- }
72
- /**
73
- * Creates a new `Result` instance representing a successful operation with an undefined value.
74
- *
75
- * @return {Result<undefined, E>} A new `Result` instance with an undefined value.
76
- */
77
- static unit() {
78
- return new _Result(new Ok(void 0));
79
- }
80
- static err(error) {
81
- return new _Result(new Err(error));
82
- }
83
- static combine(resultList) {
84
- return combineResultList(resultList);
85
- }
86
- static combineWithAllErrors(resultList) {
87
- return combineResultListWithAllErrors(
88
- resultList
89
- );
90
- }
91
- value;
92
- error;
93
- /**
94
- * Used to check if a `Result` is an `OK`
95
- *
96
- * @returns `true` if the result is an `OK` variant of Result
97
- */
98
- isOk() {
99
- return this.state.ok;
100
- }
101
- /**
102
- * Used to check if a `Result` is an `Err`
103
- *
104
- * @returns `true` if the result is an `Err` variant of Result
105
- */
106
- isErr() {
107
- return !this.state.ok;
108
- }
109
- /**
110
- * Maps a `Result<T, E>` to `Result<U, E>`
111
- * by applying a function to a contained `Ok` value, leaving an `Err` value
112
- * untouched.
113
- *
114
- * @param f The function to apply an `OK` value
115
- * @returns the result of applying `f` or an `Err` untouched
116
- */
117
- map(f) {
118
- if (this.state.ok) {
119
- const value = f(this.value);
120
- return ok(value);
121
- }
122
- return err(this.error);
123
- }
124
- /**
125
- * Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
126
- * contained `Err` value, leaving an `Ok` value untouched.
127
- *
128
- * This function can be used to pass through a successful result while
129
- * handling an error.
130
- *
131
- * @param f a function to apply to the error `Err` value
132
- */
133
- mapErr(fn) {
134
- if (this.state.ok) {
135
- return ok(this.value);
136
- }
137
- return err(fn(this.error));
138
- }
139
- /**
140
- * Similar to `map` Except you must return a new `Result`.
141
- *
142
- * This is useful for when you need to do a subsequent computation using the
143
- * inner `T` value, but that computation might fail.
144
- * Additionally, `andThen` is really useful as a tool to flatten a
145
- * `Result<Result<A, E2>, E1>` into a `Result<A, E2>` (see example below).
146
- *
147
- * @param f The function to apply to the current value
148
- */
149
- andThen(f) {
150
- if (this.state.ok) {
151
- return f(this.value);
152
- }
153
- return err(this.error);
154
- }
155
- if(fCondition) {
156
- return {
157
- true: (fTrue) => ({
158
- false: (fFalse) => {
159
- if (this.state.ok) {
160
- const condition = fCondition(this.value);
161
- return condition ? fTrue(this.value) : fFalse(this.value);
162
- }
163
- return err(this.error);
164
- }
165
- })
166
- };
167
- }
168
- orElse(f) {
169
- if (this.state.ok) {
170
- return ok(this.value);
171
- }
172
- return f(this.error);
173
- }
174
- asyncAndThen(f) {
175
- if (this.state.ok) {
176
- return f(this.value);
177
- }
178
- return errAsync(this.error);
179
- }
180
- /**
181
- * Maps a `Result<T, E>` to `ResultAsync<U, E>`
182
- * by applying an async function to a contained `Ok` value, leaving an `Err`
183
- * value untouched.
184
- *
185
- * @param f An async function to apply an `OK` value
186
- */
187
- asyncMap(f) {
188
- if (this.state.ok) {
189
- return ResultAsync.fromSafePromise(f(this.value));
190
- }
191
- return errAsync(this.error);
192
- }
193
- /**
194
- * Unwrap the `Ok` value, or return the default if there is an `Err`
195
- *
196
- * @param v the default value to return if there is an `Err`
197
- */
198
- unwrapOr(defaultValue) {
199
- if (this.state.ok) {
200
- return this.value;
201
- }
202
- return defaultValue;
203
- }
204
- /**
205
- * Given 2 functions (one for the `Ok` variant and one for the `Err` variant)
206
- * execute the function that matches the `Result` variant.
207
- *
208
- * Match callbacks do not necessitate to return a `Result`, however you can
209
- * return a `Result` if you want to.
210
- *
211
- * `match` is like chaining `map` and `mapErr`, with the distinction that
212
- * with `match` both functions must have the same return type.
213
- *
214
- * @param ok
215
- * @param err
216
- */
217
- match(fnOk, fnErr) {
218
- if (this.state.ok) {
219
- return fnOk(this.value);
220
- }
221
- return fnErr(this.error);
222
- }
223
- /**
224
- * Performs a side effect for the `Ok` or `Err` variant of `Result`.
225
- *
226
- * @param fn The function to apply an `OK` value
227
- * @returns the result of applying `f` or an `Err` untouched
228
- */
229
- log(fn) {
230
- try {
231
- fn(this.value, this.error);
232
- } catch {
233
- }
234
- return this;
235
- }
236
- /**
237
- * Performs a side effect for the `Ok` variant of `Result`.
238
- *
239
- * @param fn The function to apply an `OK` value
240
- * @returns the result of applying `f` or an `Err` untouched
241
- */
242
- tap(fn) {
243
- if (this.state.ok) {
244
- try {
245
- fn(this.value);
246
- } catch {
247
- }
248
- }
249
- return this;
250
- }
251
- /**
252
- * Performs a side effect for the `Err` variant of `Result`.
253
- *
254
- * @param fn The function to apply an `Err` value
255
- * @returns the result of applying `f` or an `Ok` untouched
256
- */
257
- tapError(fn) {
258
- if (!this.state.ok) {
259
- try {
260
- fn(this.error);
261
- } catch {
262
- }
263
- }
264
- return this;
265
- }
266
- finally(f) {
267
- const resultDisposable = new DisposableResult(this, f);
268
- try {
269
- return resultDisposable;
270
- } finally {
271
- resultDisposable[Symbol.dispose]();
272
- }
273
- }
274
- unwrapOrThrow() {
275
- if (this.state.ok) {
276
- return this.value;
277
- }
278
- throw this.error;
279
- }
280
- /**
281
- * **This method is unsafe, and should only be used in a test environments**
282
- *
283
- * Takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.
284
- *
285
- * @param config
286
- */
287
- _unsafeUnwrap(config) {
288
- if (this.state.ok) {
289
- return this.value;
290
- }
291
- throw createResultarError("Called `_unsafeUnwrap` on an Err", this, config);
292
- }
293
- /**
294
- * **This method is unsafe, and should only be used in a test environments**
295
- *
296
- * takes a `Result<T, E>` and returns a `E` when the result is an `Err`,
297
- * otherwise it throws a custom object.
298
- *
299
- * @param config
300
- */
301
- _unsafeUnwrapErr(config) {
302
- if (this.state.ok) {
303
- throw createResultarError(
304
- "Called `_unsafeUnwrapErr` on an Ok",
305
- this,
306
- config
307
- );
308
- }
309
- return this.error;
310
- }
311
- *[Symbol.iterator]() {
312
- if (this.state.ok) {
313
- return this.value;
314
- }
315
- const self = this;
316
- yield self;
317
- return self;
318
- }
319
- safeUnwrap() {
320
- if (this.state.ok) {
321
- const { value } = this;
322
- return function* () {
323
- return value;
324
- }();
325
- }
326
- const { error } = this;
327
- return function* () {
328
- yield err(error);
329
- throw new Error("Do not use this generator out of `safeTry`");
330
- }();
331
- }
332
- };
333
- var DisposableResult = class {
334
- constructor(result, finalizer) {
335
- this.result = result;
336
- this.finalizer = finalizer;
337
- }
338
- get value() {
339
- return this.result.value;
340
- }
341
- get error() {
342
- return this.result.error;
343
- }
344
- _unsafeUnwrap(config) {
345
- return this.result._unsafeUnwrap(config);
346
- }
347
- _unsafeUnwrapErr(config) {
348
- return this.result._unsafeUnwrapErr(config);
349
- }
350
- isOk() {
351
- return this.result.isOk();
352
- }
353
- isErr() {
354
- return this.result.isErr();
355
- }
356
- unwrapOr(defaultValue) {
357
- return this.result.unwrapOr(defaultValue);
358
- }
359
- [Symbol.dispose]() {
360
- this.finalizer(this.result.value, this.result.error);
361
- }
362
- };
363
- function safeTry(body) {
364
- const n = body().next();
365
- if (n instanceof Promise) {
366
- return new ResultAsync(n.then((r) => r.value));
367
- }
368
- return n.value;
369
- }
370
- var ok = Result.ok;
371
- var err = Result.err;
372
- var fromThrowable = Result.fromThrowable;
373
- var unit = Result.unit;
374
- var tryCatch = Result.tryCatch;
375
-
376
- // src/result-async.ts
377
- var DisposableResultAsync = class {
378
- innerPromise;
379
- constructor(res) {
380
- this.innerPromise = res;
381
- }
382
- then(successCallback, failureCallback) {
383
- return this.innerPromise.then(successCallback, failureCallback);
384
- }
385
- };
386
- var ResultAsync = class _ResultAsync {
387
- static okAsync(value) {
388
- return new _ResultAsync(Promise.resolve(Result.ok(value)));
389
- }
390
- /**
391
- * Returns a ResultAsync that is immediately resolved with a Result.ok(undefined) value.
392
- *
393
- * @return {ResultAsync<undefined, E>} A ResultAsync instance with undefined as the value type and E as the error type.
394
- */
395
- static unitAsync() {
396
- return new _ResultAsync(Promise.resolve(Result.unit()));
397
- }
398
- static errAsync(error) {
399
- return new _ResultAsync(Promise.resolve(Result.err(error)));
400
- }
401
- /**
402
- * Creates a ResultAsync from a Promise, catching any errors that occur during its execution.
403
- *
404
- * @param fn - The Promise to be wrapped in a ResultAsync.
405
- * @param errorFn - Optional function to transform the caught error into a specific error type.
406
- * If not provided, the original error will be used.
407
- * @returns A ResultAsync that will resolve to Ok with the promise's value if successful,
408
- * or Err with either the transformed error (if errorFn is provided) or the original error.
409
- *
410
- * @example
411
- * ```typescript
412
- * // Without error transformer
413
- * const result = ResultAsync.tryCatch(Promise.resolve(42));
414
- *
415
- * // With error transformer
416
- * const result = ResultAsync.tryCatch(
417
- * fetch('https://api.example.com'),
418
- * (error) => new CustomError('API request failed')
419
- * );
420
- * ```
421
- */
422
- static tryCatch(fn, errorFn) {
423
- const newPromise = fn.then((value) => Result.ok(value)).catch((error) => {
424
- if (errorFn) {
425
- return Result.err(errorFn(error));
426
- }
427
- return Result.err(error);
428
- });
429
- return new _ResultAsync(newPromise);
430
- }
431
- static fromSafePromise(promise) {
432
- const newPromise = promise.then((value) => Result.ok(value));
433
- return new _ResultAsync(newPromise);
434
- }
435
- static fromPromise(promise, errorFn) {
436
- const newPromise = promise.then((value) => Result.ok(value)).catch((error) => Result.err(errorFn(error)));
437
- return new _ResultAsync(newPromise);
438
- }
439
- static combine(asyncResultList) {
440
- return combineResultAsyncList(asyncResultList);
441
- }
442
- static combineWithAllErrors(asyncResultList) {
443
- return combineResultAsyncListWithAllErrors(
444
- asyncResultList
445
- );
446
- }
447
- /**
448
- * Wraps a async function with a try catch, creating a new function with the same
449
- * arguments but returning `Ok` if successful, `Err` if the function throws
450
- *
451
- * @param fn function to wrap with ok on success or err on failure
452
- * @param errorFn when an error is thrown, this will wrap the error result if provided
453
- * @returns a new function that returns a `ResultAsync`
454
- */
455
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
456
- static fromThrowable(fn, errorFn) {
457
- return (...args) => new _ResultAsync(
458
- (async () => {
459
- try {
460
- const v = await fn(...args);
461
- return Result.ok(v);
462
- } catch (error) {
463
- const e = errorFn ? errorFn(error) : error;
464
- return Result.err(e);
465
- }
466
- })()
467
- );
468
- }
469
- innerPromise;
470
- constructor(res) {
471
- this.innerPromise = res;
472
- }
473
- then(successCallback, failureCallback) {
474
- return this.innerPromise.then(successCallback, failureCallback);
475
- }
476
- mapErr(f) {
477
- return new _ResultAsync(this.innerPromise.then(async (res) => {
478
- if (res.isOk()) {
479
- return okAsync(res.value);
480
- }
481
- return errAsync(await f(res.error));
482
- }));
483
- }
484
- map(f) {
485
- const x = new _ResultAsync(
486
- this.innerPromise.then(async (res) => {
487
- if (res.isErr()) {
488
- return errAsync(res.error);
489
- }
490
- return okAsync(await f(res.value));
491
- })
492
- );
493
- return x;
494
- }
495
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
496
- andThen(f) {
497
- return new _ResultAsync(
498
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
499
- this.innerPromise.then(async (res) => {
500
- if (res.isErr()) {
501
- return errAsync(res.error);
502
- }
503
- const newValue = f(res.value);
504
- return newValue instanceof _ResultAsync ? newValue.innerPromise : newValue;
505
- })
506
- );
507
- }
508
- if(fCondition) {
509
- return {
510
- true: (fTrue) => ({
511
- false: (fFalse) => new _ResultAsync(this.innerPromise.then(async (res) => {
512
- if (res.isOk()) {
513
- const condition = fCondition(res.value);
514
- return condition ? fTrue(res.value) : fFalse(res.value);
515
- }
516
- return errAsync(res.error);
517
- }))
518
- })
519
- };
520
- }
521
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
522
- orElse(f) {
523
- return new _ResultAsync(
524
- this.innerPromise.then(async (res) => {
525
- if (res.isErr()) {
526
- return f(res.error);
527
- }
528
- return okAsync(res.value);
529
- })
530
- );
531
- }
532
- async match(ok2, fnErr) {
533
- return this.innerPromise.then((res) => res.match(ok2, fnErr));
534
- }
535
- async unwrapOr(t) {
536
- return this.innerPromise.then((res) => res.unwrapOr(t));
537
- }
538
- async unwrapOrThrow() {
539
- return this.innerPromise.then((res) => res.unwrapOrThrow());
540
- }
541
- /**
542
- * Performs a side effect for the `Ok` variant of `ResultAsync`.
543
- * This function can be used for control flow based on result values.
544
- * @param f The function to call if the result is `Ok`
545
- * @returns `self` if the result is `Err`, otherwise the result of `f`
546
- */
547
- log(f) {
548
- return new _ResultAsync(
549
- this.innerPromise.then(async (res) => {
550
- if (res.isOk()) {
551
- try {
552
- await f(res.value);
553
- } catch {
554
- }
555
- return okAsync(res.value);
556
- }
557
- try {
558
- await f(void 0, res.error);
559
- } catch {
560
- }
561
- return errAsync(res.error);
562
- })
563
- );
564
- }
565
- /**
566
- * Performs a side effect for the `Ok` variant of `ResultAsync`.
567
- * This function can be used for control flow based on result values.
568
- * @param f The function to call if the result is `Ok`
569
- * @returns `self` if the result is `Err`, otherwise the result of `f`
570
- */
571
- tap(f) {
572
- return new _ResultAsync(
573
- this.innerPromise.then(async (res) => {
574
- if (res.isErr()) {
575
- return errAsync(res.error);
576
- }
577
- try {
578
- await f(res.value);
579
- } catch {
580
- }
581
- return okAsync(res.value);
582
- })
583
- );
584
- }
585
- /**
586
- * Performs a side effect for the `Err` variant of `ResultAsync`.
587
- * This function can be used for control flow based on result values.
588
- * @param f The function to call if the result is `Err`
589
- * @returns `self` if the result is `Ok`, otherwise the result of `f`
590
- * @example
591
- */
592
- tapError(f) {
593
- return new _ResultAsync(
594
- this.innerPromise.then(async (res) => {
595
- if (res.isErr()) {
596
- try {
597
- await f(res.error);
598
- } catch {
599
- }
600
- return errAsync(res.error);
601
- }
602
- return okAsync(res.value);
603
- })
604
- );
605
- }
606
- finally(f) {
607
- return new DisposableResultAsync(
608
- // eslint-disable-next-line @typescript-eslint/require-await
609
- this.innerPromise.then(async (res) => {
610
- try {
611
- res.finally(f);
612
- } catch {
613
- }
614
- return res;
615
- })
616
- );
617
- }
618
- async *[Symbol.asyncIterator]() {
619
- const result = await this.innerPromise;
620
- if (result.isErr()) {
621
- yield errAsync(result.error);
622
- }
623
- return result.value;
624
- }
625
- /**
626
- * @deprecated will be removed in 2.0.0.
627
- *
628
- * You can use `safeTry` without this method.
629
- * @example
630
- * ```typescript
631
- * safeTry(async function* () {
632
- * const okValue = yield* yourResult
633
- * })
634
- * ```
635
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
636
- */
637
- async *safeUnwrap() {
638
- return yield* await this.innerPromise.then((res) => res.safeUnwrap());
639
- }
640
- };
641
- function safeTryAsync(body) {
642
- return new ResultAsync(
643
- (async () => {
644
- const n = await body().next();
645
- if (n.value.isOk()) {
646
- return okAsync(n.value.value);
647
- }
648
- return errAsync(n.value.error);
649
- })()
650
- );
651
- }
652
- var okAsync = ResultAsync.okAsync;
653
- var errAsync = ResultAsync.errAsync;
654
- var fromPromise = ResultAsync.fromPromise;
655
- var fromSafePromise = ResultAsync.fromSafePromise;
656
- var unitAsync = ResultAsync.unitAsync;
657
- var fromThrowableAsync = ResultAsync.fromThrowable;
658
- var tryCatchAsync = ResultAsync.tryCatch;
659
-
660
- // src/utils.ts
661
- var combineResultList = (resultList) => {
662
- let acc = ok([]);
663
- for (const result of resultList) {
664
- if (result.isErr()) {
665
- acc = err(result.error);
666
- break;
667
- } else {
668
- acc.map((list) => list.push(result.value));
669
- }
670
- }
671
- return acc;
672
- };
673
- var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(
674
- combineResultList
675
- );
676
- var combineResultListWithAllErrors = (resultList) => {
677
- let acc = ok([]);
678
- for (const result of resultList) {
679
- if (result.isErr() && acc.isErr()) {
680
- acc.error.push(result.error);
681
- } else if (result.isErr() && acc.isOk()) {
682
- acc = err([result.error]);
683
- } else if (result.isOk() && acc.isOk()) {
684
- acc.value.push(result.value);
685
- }
686
- }
687
- return acc;
688
- };
689
- var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(
690
- combineResultListWithAllErrors
691
- );
692
-
693
- export {
694
- combineResultList,
695
- combineResultAsyncList,
696
- combineResultListWithAllErrors,
697
- combineResultAsyncListWithAllErrors,
698
- Result,
699
- DisposableResult,
700
- safeTry,
701
- ok,
702
- err,
703
- fromThrowable,
704
- unit,
705
- tryCatch,
706
- DisposableResultAsync,
707
- ResultAsync,
708
- safeTryAsync,
709
- okAsync,
710
- errAsync,
711
- fromPromise,
712
- fromSafePromise,
713
- unitAsync,
714
- fromThrowableAsync,
715
- tryCatchAsync
716
- };
717
- //# sourceMappingURL=chunk-G4XXW6QA.js.map