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