resultar 1.4.5 → 2.0.0-beta.2

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