All files Result.ts

100% Statements 152/152
100% Branches 74/74
100% Functions 60/60
100% Lines 121/121

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830    6x 6x   6x                     399x           399x         399x                                 205x                                 133x                                     10x                                                               5x 5x 3x 1x   2x   2x                                                 2x                                                               7x 4x 4x 10x 8x   2x   3x 3x 6x 6x 5x   2x                                                     6x 6x 3x 3x 3x 8x   3x       3x 3x 6x 4x 2x     3x                                   19x                               43x                                   6x                                           14x 10x 10x 2x                                             3x 2x 2x 1x                                               7x 6x 6x 5x 3x                                         5x 4x 4x 3x 2x                                                     5x 4x 4x 2x 2x     2x                                               5x 4x 3x   2x 1x 1x   1x                                             16x 13x 13x                                       101x                                 2x                             2x                           2x                             13x 2x                           4x 2x                           4x 2x                           4x 2x                                                 171x                                 2x                                         3x 2x 2x 1x                                           5x 3x   2x                                         3x 2x 2x 1x                                           3x 2x 2x 1x                                     5x 4x 1x               3x 2x 2x             3x 2x 2x             7x         2x         2x                                     16x     6x  
// Result.ts
 
import { Option } from './Option'
import { ResultAsync } from './ResultAsync'
import { CombineOks, CombineOksObject, FlattenResult, MaybePromise, ResultErrType, ResultLike } from './types'
import { display } from './utils'
 
/**
 * A class representing a value that is either a success (`Ok`) with a value of type `T` or a failure (`Err`) with an error of type `E`.
 * Useful for handling operations that may fail in a type-safe way.
 *
 * @template T The type of the success value.
 * @template E The type of the error value.
 */
class Result<T, E> {
  private constructor(
    private readonly isOkFlag: boolean,
    /**
     * The success value. Present (`T`) when the `Result` is `Ok`, `undefined` when `Err`.
     * Prefer narrowing with {@link Result.isOk} (which refines this to `T`) or
     * {@link Result.match}/{@link Result.unwrapOr} over reading it directly.
     */
    readonly value?: T,
    /**
     * The error value. Present (`E`) when the `Result` is `Err`, `undefined` when `Ok`.
     * Prefer narrowing with {@link Result.isErr} (which refines this to `E`).
     */
    readonly error?: E
  ) {}
 
  /**
   * Creates a `Result` representing a successful outcome (`Ok`) with a value.
   *
   * @template T The type of the success value.
   * @template E The type of the potential error.
   * @param value The value to wrap in an `Ok` Result.
   * @returns A `Result` containing the provided value as `Ok`.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.isOk()); // true
   * console.log(ok.unwrapOr(0)); // 42
   */
  static ok<T, E>(value: T): Result<T, E> {
    return new Result<T, E>(true, value, undefined)
  }
 
  /**
   * Creates a `Result` representing a failed outcome (`Err`) with an error.
   *
   * @template T The type of the potential success value.
   * @template E The type of the error.
   * @param error The error to wrap in an `Err` Result.
   * @returns A `Result` containing the provided error as `Err`.
   *
   * @example
   * const err = Result.err<number, string>("Failed");
   * console.log(err.isErr()); // true
   * console.log(err.unwrapOr(0)); // 0
   */
  static err<T, E>(error: E): Result<T, E> {
    return new Result<T, E>(false, undefined, error)
  }
 
  /**
   * Creates a `Result` from a potentially null or undefined value.
   * Returns `Ok` if the value is neither null nor undefined, otherwise `Err` with the provided error.
   *
   * @template T The type of the success value.
   * @template E The type of the error.
   * @param value The value to convert to a `Result`.
   * @param error The error to use if the value is null or undefined.
   * @returns A `Result` containing the value as `Ok` or the error as `Err`.
   *
   * @example
   * const ok = Result.from(42, "Value missing"); // Ok(42)
   * const err = Result.from(null, "Value missing"); // Err("Value missing")
   * const undefinedErr = Result.from(undefined, "Value missing"); // Err("Value missing")
   */
  static from<T, E>(value: T | null | undefined, error: E): Result<T, E> {
    return value == null ? new Result<T, E>(false, undefined, error) : new Result<T, E>(true, value, undefined)
  }
 
  /**
   * Creates a `Result` or `ResultAsync` by executing a function and catching any errors.
   * Returns `Ok` with the result if the function succeeds, or `Err` with the mapped error if it throws.
   * Handles both synchronous and asynchronous functions.
   *
   * @template T The type of the success value.
   * @template E The type of the error.
   * @param fn The function to execute, which may return a value or Promise.
   * @param onError The function to map any caught error to the error type `E`.
   * @returns A `Result<T, E>` for synchronous functions or `ResultAsync<T, E>` for asynchronous functions.
   *
   * @example
   * // Synchronous function
   * const safeParse = Result.try(() => JSON.parse('{"key": "value"}'), e => `Parse error: ${e}`);
   * console.log(safeParse.unwrapOr({})); // { key: "value" }
   *
   * const failedParse = Result.try(() => JSON.parse('invalid'), e => `Parse error: ${e}`);
   * console.log(failedParse.unwrapOr({})); // {}
   *
   * // Asynchronous function
   * const asyncFetch = Result.try(
   *   () => fetch('https://api.example.com/data').then(res => res.json()),
   *   e => `Fetch error: ${e}`
   * );
   * const data = await asyncFetch.unwrapOr({ error: "Failed to fetch" });
   */
  static try<T, E>(fn: () => T, onError: (e: unknown) => E): Result<T, E>
  static try<T, E>(fn: () => Promise<T>, onError: (e: unknown) => E): ResultAsync<T, E>
  static try<T, E>(fn: () => MaybePromise<T>, onError: (e: unknown) => E): Result<T, E> | ResultAsync<T, E> {
    try {
      const result = fn()
      if (result instanceof Promise) {
        return ResultAsync.try(() => result, onError) // Treat as async
      }
      return new Result<T, E>(true, result, undefined)
    } catch (e) {
      return new Result<T, E>(false, undefined, onError(e))
    }
  }
 
  /**
   * Wraps a throwing function into a reusable safe version that returns a `Result` instead of
   * throwing. Unlike {@link Result.try} (one-shot), this returns a new function you can call
   * many times.
   *
   * @template A The argument types of the function.
   * @template T The success type.
   * @template E The error type.
   * @param fn The (synchronous) function that may throw.
   * @param onError Maps a thrown value to the error type `E`.
   * @returns A function with the same arguments that returns `Result<T, E>`.
   *
   * @example
   * const safeParse = Result.fromThrowable(JSON.parse, (e) => `bad json: ${e}`);
   * safeParse('{"a":1}'); // Ok({ a: 1 })
   * safeParse('nope');    // Err('bad json: ...')
   */
  static fromThrowable<A extends readonly unknown[], T, E>(
    fn: (...args: A) => T,
    onError: (e: unknown) => E
  ): (...args: A) => Result<T, E> {
    return (...args: A) => Result.try(() => fn(...args), onError) as Result<T, E>
  }
 
  /**
   * Combines an array of `Result`s into a single `Result` of an array.
   * Returns the first `Err` encountered, otherwise `Ok` with every value in order.
   *
   * @template T The type of the success values.
   * @template E The type of the error values.
   * @param results The array of `Result`s to combine.
   * @returns `Ok` with all values, or the first `Err`.
   *
   * Accepts either a tuple/array of `Result`s (tuple element types are preserved) or a record
   * of `Result`s keyed by name.
   *
   * @example
   * // Tuple — positional types preserved:
   * Result.combine([Result.ok(1), Result.ok('a')]); // Result<[number, string], never>
   * // Record — keys preserved:
   * Result.combine({ id: Result.ok(1), name: Result.ok('a') }); // Result<{ id: number; name: string }, never>
   * // First Err short-circuits:
   * Result.combine([Result.ok<number, string>(1), Result.err<number, string>('x')]); // Err('x')
   */
  static combine<T extends readonly Result<unknown, unknown>[] | []>(
    results: T
  ): Result<CombineOks<T>, ResultErrType<T[number]>>
  static combine<T extends Record<string, Result<unknown, unknown>>>(
    results: T
  ): Result<CombineOksObject<T>, ResultErrType<T[keyof T]>>
  static combine(
    results: ReadonlyArray<Result<unknown, unknown>> | Record<string, Result<unknown, unknown>>
  ): Result<unknown, unknown> {
    if (Array.isArray(results)) {
      const values: unknown[] = []
      for (const result of results) {
        if (result.isErr()) return new Result(false, undefined, result.error)
        values.push(result.value)
      }
      return new Result(true, values, undefined)
    }
    const out: Record<string, unknown> = {}
    for (const key of Object.keys(results)) {
      const result = (results as Record<string, Result<unknown, unknown>>)[key]
      if (result.isErr()) return new Result(false, undefined, result.error)
      out[key] = result.value
    }
    return new Result(true, out, undefined)
  }
 
  /**
   * Like {@link Result.combine}, but accumulates every `Err` instead of stopping at the first.
   * Returns `Ok` with all values when every `Result` is `Ok`, otherwise `Err` with all errors.
   *
   * @template T The type of the success values.
   * @template E The type of the error values.
   * @param results The array of `Result`s to combine.
   * @returns `Ok` with all values, or `Err` with an array of all errors.
   *
   * Accepts a tuple/array or a record of `Result`s, mirroring {@link Result.combine}.
   *
   * @example
   * const r = Result.combineWithAllErrors([Result.ok<number, string>(1), Result.err<number, string>('a'), Result.err<number, string>('b')]);
   * console.log(r.match({ ok: () => [], err: (e) => e })); // ['a', 'b']
   */
  static combineWithAllErrors<T extends readonly Result<unknown, unknown>[] | []>(
    results: T
  ): Result<CombineOks<T>, ResultErrType<T[number]>[]>
  static combineWithAllErrors<T extends Record<string, Result<unknown, unknown>>>(
    results: T
  ): Result<CombineOksObject<T>, ResultErrType<T[keyof T]>[]>
  static combineWithAllErrors(
    results: ReadonlyArray<Result<unknown, unknown>> | Record<string, Result<unknown, unknown>>
  ): Result<unknown, unknown[]> {
    const errors: unknown[] = []
    if (Array.isArray(results)) {
      const arr = results as ReadonlyArray<Result<unknown, unknown>>
      const values: unknown[] = []
      for (const result of arr) {
        result.match({ ok: (v) => void values.push(v), err: (e) => void errors.push(e) })
      }
      return errors.length > 0
        ? new Result<unknown, unknown[]>(false, undefined, errors)
        : new Result<unknown, unknown[]>(true, values, undefined)
    }
    const out: Record<string, unknown> = {}
    for (const key of Object.keys(results)) {
      ;(results as Record<string, Result<unknown, unknown>>)[key].match({
        ok: (v) => void (out[key] = v),
        err: (e) => void errors.push(e),
      })
    }
    return errors.length > 0
      ? new Result<unknown, unknown[]>(false, undefined, errors)
      : new Result<unknown, unknown[]>(true, out, undefined)
  }
 
  /**
   * Checks if the `Result` is `Ok` (contains a value).
   *
   * @returns `true` if the `Result` is `Ok`, `false` if it is `Err`.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.isOk()); // true
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.isOk()); // false
   */
  isOk(): this is Result<T, E> & { readonly value: T } {
    return this.isOkFlag
  }
 
  /**
   * Checks if the `Result` is `Err` (contains an error).
   *
   * @returns `true` if the `Result` is `Err`, `false` if it is `Ok`.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.isErr()); // false
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.isErr()); // true
   */
  isErr(): this is Result<T, E> & { readonly error: E } {
    return !this.isOkFlag
  }
 
  /**
   * Checks if the `Result` is `Ok` and contains a specific value.
   *
   * @param value The value to compare against.
   * @returns `true` if the `Result` is `Ok` and its value equals the provided value, `false` otherwise.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.contains(42)); // true
   * console.log(ok.contains(43)); // false
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.contains(42)); // false
   */
  contains(value: T): boolean {
    return this.isOkFlag && this.value === value
  }
 
  /**
   * Transforms the value in an `Ok` `Result` using the provided function.
   * Returns the original `Err` if the `Result` is `Err`.
   *
   * @template U The type of the transformed value.
   * @param fn The function to transform the value.
   * @returns A `Result` containing the transformed value or the original error.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const mapped = ok.map(x => x * 2);
   * console.log(mapped.unwrapOr(0)); // 84
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.map(x => x * 2).unwrapOr(0)); // 0
   */
  map<U>(fn: (value: T) => Promise<U>): ResultAsync<U, E>
  map<U>(fn: (value: T) => U): Result<U, E>
  map<U>(fn: (value: T) => MaybePromise<U>): Result<U, E> | ResultAsync<U, E> {
    if (!this.isOkFlag) return new Result<U, E>(false, undefined, this.error)
    const out = fn(this.value!)
    return out instanceof Promise
      ? ResultAsync._fromPromise(out.then((v) => Result.ok<U, E>(v)))
      : new Result<U, E>(true, out, undefined)
  }
 
  /**
   * Transforms the error in an `Err` `Result` using the provided function.
   * Returns the original `Ok` if the `Result` is `Ok`.
   *
   * @template F The type of the transformed error.
   * @param fn The function to transform the error.
   * @returns A `Result` containing the original value or the transformed error.
   *
   * @example
   * const err = Result.err<number, string>("Failed");
   * const mappedErr = err.mapErr(e => `Error: ${e}`);
   * console.log(mappedErr.unwrapOrElse(e => e)); // "Error: Failed"
   *
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.mapErr(e => `Error: ${e}`).unwrapOr(0)); // 42
   */
  mapErr<F>(fn: (error: E) => Promise<F>): ResultAsync<T, F>
  mapErr<F>(fn: (error: E) => F): Result<T, F>
  mapErr<F>(fn: (error: E) => MaybePromise<F>): Result<T, F> | ResultAsync<T, F> {
    if (this.isOkFlag) return new Result<T, F>(true, this.value, undefined)
    const out = fn(this.error!)
    return out instanceof Promise
      ? ResultAsync._fromPromise(out.then((e) => Result.err<T, F>(e)))
      : new Result<T, F>(false, undefined, out)
  }
 
  /**
   * Chains a `Result` by applying a function that returns another `Result`.
   * Returns the original `Err` if the `Result` is `Err`.
   *
   * @template U The type of the value in the resulting `Result`.
   * @template F The type of the error in the resulting `Result`.
   * @param fn The function that returns a `Result`.
   * @returns A `Result` containing the result of the function or the original error.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const chained = ok.andThen(x => Result.ok<string, string>(`Value: ${x}`));
   * console.log(chained.unwrapOr("None")); // "Value: 42"
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.andThen(x => Result.ok<string, string>(`Value: ${x}`)).unwrapOr("None")); // "None"
   */
  andThen<U, F>(fn: (value: T) => ResultAsync<U, F> | Promise<Result<U, F>>): ResultAsync<U, E | F>
  andThen<U, F>(fn: (value: T) => Result<U, F>): Result<U, E | F>
  andThen<U, F>(fn: (value: T) => ResultLike<U, F>): Result<U, E | F> | ResultAsync<U, E | F> {
    if (!this.isOkFlag) return new Result<U, E | F>(false, undefined, this.error)
    const next = fn(this.value!)
    if (next instanceof ResultAsync) return next as ResultAsync<U, E | F>
    if (next instanceof Promise) return ResultAsync._fromPromise(next as Promise<Result<U, E | F>>)
    return next as Result<U, E | F>
  }
 
  /**
   * Returns the current `Result` if it is `Ok`, otherwise returns the result of the provided function.
   *
   * @template F The type of the error in the fallback `Result`.
   * @param fn The function returning a `Result` as a fallback.
   * @returns A `Result` containing the original value or the fallback result.
   *
   * @example
   * const err = Result.err<number, string>("Failed");
   * const fallback = err.orElse(e => Result.ok<number, string>(0));
   * console.log(fallback.unwrapOr(-1)); // 0
   *
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.orElse(e => Result.ok<number, string>(0)).unwrapOr(-1)); // 42
   */
  orElse<F>(fn: (error: E) => Result<T, F>): Result<T, E | F>
  orElse<F>(fn: (error: E) => ResultAsync<T, F> | Promise<Result<T, F>>): ResultAsync<T, E | F>
  orElse<F>(fn: (error: E) => ResultLike<T, F>): Result<T, E | F> | ResultAsync<T, E | F> {
    if (this.isOkFlag) return new Result<T, E | F>(true, this.value!, undefined)
    const next = fn(this.error!)
    if (next instanceof ResultAsync) return next as ResultAsync<T, E | F>
    if (next instanceof Promise) return ResultAsync._fromPromise(next as Promise<Result<T, E | F>>)
    return next as Result<T, E | F>
  }
 
  /**
   * Filters the `Result` based on a predicate. Returns the original `Ok` if the predicate is true, otherwise `Err` with the provided error.
   *
   * @param predicate The function to test the value.
   * @param error The error to use if the predicate fails.
   * @returns The original `Result` if the predicate passes, otherwise `Err` with the provided error.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const filtered = ok.filter(x => x > 40, "Too small");
   * console.log(filtered.unwrapOr(0)); // 42
   *
   * const failedFilter = ok.filter(x => x < 40, "Too small");
   * console.log(failedFilter.unwrapOr(0)); // 0
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.filter(x => x > 40, "Too small").unwrapOr(0)); // 0
   */
  filter(predicate: (value: T) => Promise<boolean>, error: MaybePromise<E>): ResultAsync<T, E>
  filter(predicate: (value: T) => boolean, error: E): Result<T, E>
  filter(
    predicate: (value: T) => MaybePromise<boolean>,
    error: MaybePromise<E>
  ): Result<T, E> | ResultAsync<T, E> {
    if (!this.isOkFlag) return this
    const verdict = predicate(this.value!)
    if (verdict instanceof Promise) {
      return ResultAsync._fromPromise(
        verdict.then(async (ok) => (ok ? (this as Result<T, E>) : Result.err<T, E>(await Promise.resolve(error))))
      )
    }
    return verdict ? this : new Result<T, E>(false, undefined, error as E)
  }
 
  /**
   * Combines two `Result`s into a single `Result` containing a tuple of their values.
   * Returns `Err` if either `Result` is `Err`.
   *
   * @template U The type of the value in the other `Result`.
   * @template F The type of the error in the other `Result`.
   * @param other The other `Result` to combine with.
   * @returns A `Result` containing a tuple of values or the first error encountered.
   *
   * @example
   * const ok1 = Result.ok<number, string>(42);
   * const ok2 = Result.ok<string, string>("hello");
   * const zipped = ok1.zip(ok2);
   * console.log(zipped.unwrapOr([0, ""])); // [42, "hello"]
   *
   * const err = Result.err<string, string>("Failed");
   * console.log(ok1.zip(err).unwrapOr([0, ""])); // [0, ""]
   */
  zip<U, F>(other: ResultAsync<U, F> | Promise<Result<U, F>>): ResultAsync<[T, U], E | F>
  zip<U, F>(other: Result<U, F>): Result<[T, U], E | F>
  zip<U, F>(other: ResultLike<U, F>): Result<[T, U], E | F> | ResultAsync<[T, U], E | F> {
    if (other instanceof ResultAsync) return this.toAsync().zip(other)
    if (other instanceof Promise) return this.toAsync().zip(ResultAsync._fromPromise(other))
    return this.match({
      ok: (value1) =>
        other.match({
          ok: (value2) => Result.ok<[T, U], E | F>([value1, value2]),
          err: (error) => Result.err<[T, U], E | F>(error),
        }),
      err: (error) => Result.err<[T, U], E | F>(error),
    })
  }
 
  /**
   * Flattens a nested `Result` into a single `Result`.
   * If the `Result` is `Ok` and contains another `Result`, it recursively flattens it.
   *
   * Nested errors are preserved: flattening a `Result<Result<T, F>, E>` yields `Result<T, E | F>`.
   *
   * @returns A flattened `Result`.
   *
   * @example
   * const nested = Result.ok<Result<number, string>, string>(Result.ok<number, string>(42));
   * console.log(nested.flatten().unwrapOr(0)); // 42
   *
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.flatten().unwrapOr(0)); // 42
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.flatten().unwrapOr(0)); // 0
   */
  flatten(): FlattenResult<T, E> {
    if (!this.isOkFlag) return new Result<unknown, E>(false, undefined, this.error) as FlattenResult<T, E>
    const inner = this.value
    return (inner instanceof Result ? inner.flatten() : new Result<unknown, E>(true, inner, undefined)) as FlattenResult<
      T,
      E
    >
  }
 
  /**
   * Returns the value if the `Result` is `Ok`, otherwise returns the provided default value.
   *
   * @param defaultValue The value to return if the `Result` is `Err`.
   * @returns The value of `Ok` or the default value.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.unwrapOr(0)); // 42
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.unwrapOr(0)); // 0
   */
  unwrapOr(defaultValue: T): T {
    return this.isOkFlag ? this.value! : defaultValue
  }
 
  /**
   * Returns the value if the `Result` is `Ok`, otherwise returns the result of the provided function.
   *
   * @param fn The function to compute the default value based on the error.
   * @returns The value of `Ok` or the computed default value.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.unwrapOrElse(e => 0)); // 42
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.unwrapOrElse(e => e.length)); // 6
   */
  unwrapOrElse(fn: (error: E) => T): T {
    return this.isOkFlag ? this.value! : fn(this.error!)
  }
 
  /**
   * Applies `fn` to the `Ok` value, or returns `defaultValue` if `Err` — in one step.
   *
   * @template U The result type.
   * @param defaultValue The value to return when `Err`.
   * @param fn Maps the `Ok` value to `U`.
   *
   * @example
   * Result.ok<number, string>(2).mapOr(0, (x) => x * 10); // 20
   * Result.err<number, string>('e').mapOr(0, (x) => x * 10); // 0
   */
  mapOr<U>(defaultValue: U, fn: (value: T) => U): U {
    return this.isOkFlag ? fn(this.value!) : defaultValue
  }
 
  /**
   * Applies `fn` to the `Ok` value, or `onError` to the error if `Err` — in one step.
   *
   * @template U The result type.
   * @param onError Maps the error to `U` when `Err`.
   * @param fn Maps the `Ok` value to `U`.
   *
   * @example
   * Result.err<number, string>('boom').mapOrElse((e) => e.length, (x) => x * 10); // 4
   */
  mapOrElse<U>(onError: (error: E) => U, fn: (value: T) => U): U {
    return this.isOkFlag ? fn(this.value!) : onError(this.error!)
  }
 
  /**
   * Unsafe escape hatch: returns the `Ok` value, or throws if the `Result` is `Err`.
   * Prefer {@link Result.unwrapOr}/{@link Result.match} in production code.
   *
   * @returns The contained `Ok` value.
   * @throws If the `Result` is `Err`.
   *
   * @example
   * console.log(Result.ok(42).unwrap()); // 42
   * Result.err('boom').unwrap(); // throws
   */
  unwrap(): T {
    if (this.isOkFlag) return this.value!
    throw new Error(`Called unwrap() on an Err value: ${String(this.error)}`)
  }
 
  /**
   * Unsafe escape hatch: returns the `Err` value, or throws if the `Result` is `Ok`.
   *
   * @returns The contained `Err` value.
   * @throws If the `Result` is `Ok`.
   *
   * @example
   * console.log(Result.err('boom').unwrapErr()); // "boom"
   * Result.ok(42).unwrapErr(); // throws
   */
  unwrapErr(): E {
    if (!this.isOkFlag) return this.error!
    throw new Error(`Called unwrapErr() on an Ok value: ${String(this.value)}`)
  }
 
  /**
   * Unsafe escape hatch: returns the `Ok` value, or throws an `Error` with `message` if `Err`.
   *
   * @param message The error message to throw with when the `Result` is `Err`.
   * @returns The contained `Ok` value.
   * @throws If the `Result` is `Err`.
   *
   * @example
   * console.log(Result.ok(42).expect('must have a value')); // 42
   */
  expect(message: string): T {
    if (this.isOkFlag) return this.value!
    throw new Error(message)
  }
 
  /**
   * Unsafe escape hatch: returns the `Err` value, or throws an `Error` with `message` if `Ok`.
   *
   * @param message The error message to throw with when the `Result` is `Ok`.
   * @returns The contained `Err` value.
   * @throws If the `Result` is `Ok`.
   *
   * @example
   * console.log(Result.err('boom').expectErr('must be an error')); // "boom"
   */
  expectErr(message: string): E {
    if (!this.isOkFlag) return this.error!
    throw new Error(message)
  }
 
  /**
   * Pattern-matches the `Result`, executing the appropriate branch based on whether it is `Ok` or `Err`.
   *
   * @template U The type of the result.
   * @param branches An object with `ok` and `err` branches.
   * @returns The result of the executed branch.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const result = ok.match({
   *   ok: x => `Value: ${x}`,
   *   err: e => `Error: ${e}`,
   * });
   * console.log(result); // "Value: 42"
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.match({
   *   ok: x => `Value: ${x}`,
   *   err: e => `Error: ${e}`,
   * })); // "Error: Failed"
   */
  match<U>(branches: { ok: (value: T) => U; err: (error: E) => U }): U {
    return this.isOkFlag ? branches.ok(this.value!) : branches.err(this.error!)
  }
 
  /**
   * Converts the `Result` to an `Option`, discarding the error.
   * Returns `Some` if the `Result` is `Ok`, otherwise `None`.
   *
   * @returns An `Option` containing the value or `None`.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.toOption().unwrapOr(0)); // 42
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.toOption().unwrapOr(0)); // 0
   */
  toOption(): Option<T> {
    return this.isOkFlag ? Option.some(this.value!) : Option.none()
  }
 
  /**
   * Recovers from an `Err` `Result` by providing a fallback value.
   * Returns the original `Ok` if the `Result` is `Ok`.
   *
   * @param fn The function to compute the recovery value based on the error.
   * @returns A `Result` containing the original value or the recovery value.
   *
   * @example
   * const err = Result.err<number, string>("Failed");
   * const recovered = err.recover(e => e.length);
   * console.log(recovered.unwrapOr(0)); // 6
   *
   * const ok = Result.ok<number, string>(42);
   * console.log(ok.recover(e => e.length).unwrapOr(0)); // 42
   */
  recover(fn: (error: E) => Promise<T>): ResultAsync<T, E>
  recover(fn: (error: E) => T): Result<T, E>
  recover(fn: (error: E) => MaybePromise<T>): Result<T, E> | ResultAsync<T, E> {
    if (this.isOkFlag) return this
    const out = fn(this.error!)
    return out instanceof Promise
      ? ResultAsync._fromPromise(out.then((v) => Result.ok<T, E>(v)))
      : new Result<T, E>(true, out, undefined)
  }
 
  /**
   * Converts the `Result` to a `Result` containing an array.
   * If `Ok`, wraps the value in an array (or keeps it if already an array); if `Err`, returns an empty array.
   *
   * @returns A `Result` containing an array of values or the original error.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const sequenced = ok.sequence();
   * console.log(sequenced.unwrapOr([])); // [42]
   *
   * const arrayOk = Result.ok<number[], string>([1, 2, 3]);
   * console.log(arrayOk.sequence().unwrapOr([])); // [1, 2, 3]
   *
   * const err = Result.err<number, string>("Failed");
   * console.log(err.sequence().unwrapOr([])); // []
   */
  sequence(): Result<T[], E> {
    if (this.isOkFlag) {
      return new Result<T[], E>(true, Array.isArray(this.value) ? [...this.value] : [this.value!], undefined)
    }
    return new Result<T[], E>(false, undefined, this.error!)
  }
 
  /**
   * Performs a side effect with the value if the `Result` is `Ok`.
   * Returns the original `Result` unchanged.
   *
   * @param fn The function to execute with the value.
   * @returns The original `Result`.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const tapped = ok.tap(x => console.log(`Value: ${x}`));
   * console.log(tapped.unwrapOr(0)); // Logs "Value: 42", returns 42
   *
   * const err = Result.err<number, string>("Failed");
   * err.tap(x => console.log(`Value: ${x}`)); // No log
   */
  tap(fn: (value: T) => Promise<void>): ResultAsync<T, E>
  tap(fn: (value: T) => void): Result<T, E>
  tap(fn: (value: T) => MaybePromise<void>): Result<T, E> | ResultAsync<T, E> {
    if (!this.isOkFlag) return this
    const out = fn(this.value!)
    return out instanceof Promise
      ? ResultAsync._fromPromise(out.then(() => this as Result<T, E>))
      : this
  }
 
  /**
   * Performs a side effect with the error if the `Result` is `Err`.
   * Returns the original `Result` unchanged.
   *
   * @param fn The function to execute with the error.
   * @returns The original `Result`.
   *
   * @example
   * const err = Result.err<number, string>("Failed");
   * const tapped = err.tapErr(e => console.log(`Error: ${e}`));
   * console.log(tapped.unwrapOr(0)); // Logs "Error: Failed", returns 0
   *
   * const ok = Result.ok<number, string>(42);
   * ok.tapErr(e => console.log(`Error: ${e}`)); // No log
   */
  tapErr(fn: (error: E) => Promise<void>): ResultAsync<T, E>
  tapErr(fn: (error: E) => void): Result<T, E>
  tapErr(fn: (error: E) => MaybePromise<void>): Result<T, E> | ResultAsync<T, E> {
    if (this.isOkFlag) return this
    const out = fn(this.error!)
    return out instanceof Promise
      ? ResultAsync._fromPromise(out.then(() => this as Result<T, E>))
      : this
  }
 
  /**
   * Converts the `Result` to a `ResultAsync`, enabling asynchronous operations.
   *
   * @returns A `ResultAsync` containing the value or error.
   *
   * @example
   * const ok = Result.ok<number, string>(42);
   * const asyncOk = ok.toAsync();
   * console.log(await asyncOk.unwrapOr(0)); // 42
   *
   * const err = Result.err<number, string>("Failed");
   * const asyncErr = err.toAsync();
   * console.log(await asyncErr.unwrapOr(0)); // 0
   */
  toAsync(): ResultAsync<T, E> {
    return this.match({
      ok: (value) => ResultAsync.ok<T, E>(value),
      err: (error) => ResultAsync.err<T, E>(error),
    })
  }
 
  /** Alias for {@link Result.tap} (Rust-style naming). */
  inspect(fn: (value: T) => Promise<void>): ResultAsync<T, E>
  inspect(fn: (value: T) => void): Result<T, E>
  inspect(fn: (value: T) => MaybePromise<void>): Result<T, E> | ResultAsync<T, E> {
    if (!this.isOkFlag) return this
    const out = fn(this.value!)
    return out instanceof Promise ? ResultAsync._fromPromise(out.then(() => this as Result<T, E>)) : this
  }
 
  /** Alias for {@link Result.tapErr} (Rust-style naming). */
  inspectErr(fn: (error: E) => Promise<void>): ResultAsync<T, E>
  inspectErr(fn: (error: E) => void): Result<T, E>
  inspectErr(fn: (error: E) => MaybePromise<void>): Result<T, E> | ResultAsync<T, E> {
    if (this.isOkFlag) return this
    const out = fn(this.error!)
    return out instanceof Promise ? ResultAsync._fromPromise(out.then(() => this as Result<T, E>)) : this
  }
 
  /**
   * Returns a readable representation, e.g. `Ok(42)` or `Err("boom")`.
   */
  toString(): string {
    return this.isOkFlag ? `Ok(${display(this.value)})` : `Err(${display(this.error)})`
  }
 
  /** Node's `util.inspect` hook, so `console.log` prints `Ok(42)` instead of internal fields. */
  [Symbol.for('nodejs.util.inspect.custom')](): string {
    return this.toString()
  }
 
  /** JSON representation: `{ type: 'Ok', value }` or `{ type: 'Err', error }`. */
  toJSON(): { type: 'Ok'; value: T } | { type: 'Err'; error: E } {
    return this.isOkFlag ? { type: 'Ok', value: this.value! } : { type: 'Err', error: this.error! }
  }
}
 
/**
 * Type guard to check if a value is an instance of `Result`.
 *
 * @template T The type of the success value.
 * @template E The type of the error value.
 * @param value The value to check.
 * @returns `true` if the value is a `Result`, `false` otherwise.
 *
 * @example
 * const ok = Result.ok<number, string>(42);
 * console.log(isResult(ok)); // true
 * console.log(isResult(42)); // false
 * console.log(isResult(Option.some(42))); // false
 */
function isResult<T, E>(value: any): value is Result<T, E> {
  return value instanceof Result
}
 
export { Result, isResult }