import { DecorationError, DeserializationError, InvalidStateError, UnwrapCustomError } from "./errors"; import { bind, combine, identity, isWrappedFunction, noop, throwValue } from "./runtime"; import type { MaybePromiseLike, Pair, Mapper, AnyParameters, AsyncMonad, Alternative, Container, Pipe, AsyncTap, Zip } from "./types"; export const enum EitherType { Left = "Left", Right = "Right" } const name = "Either"; function right(right: R): Either { return Right.create(right); } right.void = function rightVoid(): Either { // eslint-disable-next-line @typescript-eslint/no-invalid-void-type, unicorn/no-useless-undefined return Right.create(undefined); }; function left(value: L): Either { return Left.create(value); } export { right, right as Ok, left, left as Err }; function cast(constructor: EitherConstructor): Either { if (isEither(constructor)) { return constructor; } /* istanbul ignore next */ throw new InvalidStateError(); } class EitherConstructor implements AsyncMonad, Alternative, Container, Pipe, AsyncTap, Zip { //#region Functor mapLeft( map: Mapper, ...parameters: P ): Either { return this.biMap(bind(map, parameters), identity); } map( map: Mapper, ...parameters: P ): Either { return this.mapRight(map, ...parameters); } mapRight( map: Mapper, ...parameters: P ): Either { return this.biMap(identity, bind(map, parameters)); } biMap(mapLeft: Mapper, mapRight: Mapper): Either { return this.fold(combine(mapLeft, left), combine(mapRight, right)); } async asyncMap( map: Mapper, P>, ...parameters: P ): Promise> { return await this.map(map, ...parameters).await(); } //#endregion //#region Applicative pure(value: R): Either { return right(value); } apply( this: Either>, argument: Either, ...parameters: P ): Either; apply( this: Either, map: Either>, ...parameters: P ): Either; apply( this: Either>, argument: Either>, ...parameters: P ): Either { return this.zip(argument).map(([current, argument]): B => { if (isWrappedFunction(current)) { return current(argument as A, ...parameters); } if (isWrappedFunction(argument)) { return argument(current as A, ...parameters); } throw new InvalidStateError( InvalidStateError.Messages.APPLY_SHOULD_BE_FUNCTION ); }); } asyncApply( this: Either, P>>, argument: Either, ...parameters: P ): Promise>; asyncApply( this: Either, map: Either, P>>, ...parameters: P ): Promise>; async asyncApply( this: Either, P>>, argument: Either, P>>, ...parameters: P ): Promise> { return await this.zip(argument) .map(([current, argument]): B => { if (isWrappedFunction(current)) { return current(argument as A, ...parameters); } if (isWrappedFunction(argument)) { return argument(current as A, ...parameters); } throw new InvalidStateError( InvalidStateError.Messages.APPLY_SHOULD_BE_FUNCTION ); }) .await(); } //#endregion //#region Monad chain( map: Mapper, P>, ...parameters: P ): Either { return this.fold(left, bind(map, parameters)); } chainLeft( map: Mapper, P>, ...parameters: P ): Either { return this.fold(bind(map, parameters), right); } async asyncChain( map: Mapper>, P>, ...parameters: P ): Promise> { const result = await this.asyncMap, P>(map, ...parameters); return result.join(); } async await(this: Either>): Promise> { return await this.fold>>( left, async (value) => right(await value) ); } join(this: Either>): Either { return this.chain(identity); } //#endregion //#region Alternative default(value: R): Either { return this.or(right(value)); } or(x: Either): Either { return this.orLazy(() => x); } orLazy(factory: () => Either): Either { return this.fold(factory, () => cast(this)); } async orAsync( factory: () => MaybePromiseLike> ): Promise> { return await this.fold(factory, () => cast(this)); } //#endregion //#region Tap tap

( callback: Mapper, ...parameters: P ): Either { this.map(callback, ...parameters); return cast(this); } async asyncTap

( callback: Mapper, P>, ...parameters: P ): Promise> { await this.asyncMap(callback, ...parameters); return cast(this); } tapLeft

( callback: Mapper, ...parameters: P ): Either { this.mapLeft(callback, ...parameters); return cast(this); } //#endregion // Pipe pipe( pipe: Mapper, T, P>, ...parameters: P ): T { return bind(pipe, parameters)(cast(this)); } //#region Matching isLeft(predicate: (left: L) => left is T): this is Left; isLeft(predicate?: (left: L) => boolean): this is Left; isLeft(predicate?: (left: L) => boolean): this is Left { return isLeft(this) && (!predicate || predicate(this.getLeft())); } isError(predicate: (left: L) => left is T): this is Left; isError(predicate?: (left: L) => boolean): this is Left; isError(predicate?: (left: L) => boolean): this is Left { return isLeft(this) && (!predicate || predicate(this.getLeft())); } isRight( predicate?: (right: R) => right is T ): this is Right; isRight(predicate?: (right: R) => boolean): this is Right; isRight(predicate?: (right: R) => boolean): this is Right { return isRight(this) && (!predicate || predicate(this.getRight())); } isOk(predicate?: (right: R) => right is T): this is Right; isOk(predicate?: (right: R) => boolean): this is Right; isOk(predicate?: (right: R) => boolean): this is Right { return isRight(this) && (!predicate || predicate(this.getRight())); } /** * * @param {Mapper} mapLeft * @param {Mapper} mapRight * @return {A|B} * @throws {InvalidStateError} - {@link InvalidStateError} if Either state is neither Left neither Right, this probably should never happen */ fold(mapLeft: Mapper, mapRight: Mapper): A | B { if (this.isLeft()) { return mapLeft(this.left); } if (this.isRight()) { return mapRight(this.right); } /* istanbul ignore next */ throw new InvalidStateError(); } match(matcher: { readonly left: (left: L) => A; readonly right: (value: R) => B; }): A | B { return this.fold(matcher.left, matcher.right); } //#endregion //#region Container unwrapOrElse(fallback: (value: L) => T): T | R { return this.fold(fallback, identity); } unwrapOr(value: T): T | R { return this.unwrapOrElse(() => value); } /** * @deprecated - **If Left value is Error use {@link throw} instead** * * * @param {string} [message] - Error message, if either is left. By default "Either state is Left" * @return {R} - Right value of Either, if right * @throws {UnwrapCustomError} - {@link UnwrapCustomError} is Left with provided {@link message} */ unwrap(message: string = UnwrapCustomError.Messages.EITHER_IS_LEFT): R { return this.fold(() => UnwrapCustomError.inlineThrow(message), identity); } //#endregion // Zip zip(either: Either): Either> { return this.chain((value) => either.map((right) => [value, right])); } // Either specific swap(): Either { return this.fold(right, left); } async promise(): Promise { return this.throw(); } /** * * @return {R} - Right value if current state is Right, * @throws {L} - {@link L} if current state is Left */ throw(): R { return this.fold(throwValue, identity); } /** * Return value of Either independent if it is Right or Left * * @deprecated - probably should not be used, please refactor code or use {@link fold} * @see {@link fold} * @return {L|R} */ value(): L | R { return this.fold(identity, identity); } any(this: Either): T { return this.value(); } } Object.freeze(EitherConstructor); Object.freeze(EitherConstructor.prototype); type SerializedLeft = Readonly<{ name: typeof name; type: EitherType.Left; left: L; }>; class Left extends EitherConstructor implements SerializedLeft { static create(left: L): Left { return new Left(left); } /** * @deprecated Should not be used directly, public only for serialization & type check use {@link getLeft} * @see {@link getLeft} * * @type {L} * @memberof Left */ public readonly left: L; get [Symbol.toStringTag](): EitherType.Left { return EitherType.Left; } get name(): typeof name { return name; } getRight(): undefined { return; } getValue(): undefined { return; } getLeft(): L { return this.left; } getError(): L { return this.left; } /** * Should be used instead of * ```js * return left(result.getLeft()) * ``` * * Makes types correct without copying * * @template T * @return {Left} * * @example * return result.move() */ move(): Left { return cast(this) as Left; } get type(): EitherType.Left { return EitherType.Left; } private constructor(left: L) { super(); this.left = left; Object.freeze(this); } toJSON(): SerializedLeft { return { name: this.name, type: this.type, left: this.left }; } } Object.freeze(Left); Object.freeze(Left.prototype); type SerializedRight = Readonly<{ name: typeof name; type: EitherType.Right; right: R; }>; class Right extends EitherConstructor implements SerializedRight { static create(right: R): Right { return new Right(right); } /** * @deprecated Should not be used directly, public only for serialization & type check use {@link getRight} * @see {@link getRight} * * @type {R} * @memberof Right */ public readonly right: R; get [Symbol.toStringTag](): EitherType.Right { return EitherType.Right; } get name(): typeof name { return name; } get type(): EitherType.Right { return EitherType.Right; } getRight(): R { return this.right; } getValue(): R { return this.right; } getLeft(): undefined { return; } getError(): undefined { return; } /** * Should be used instead of * ```js * return right(result.getRight()) * ``` * * Makes types correct without copying * * @template T * @return {Right} * * @example * return result.move() */ move(): Right { return cast(this) as Right; } private constructor(right: R) { super(); this.right = right; Object.freeze(this); } toJSON(): SerializedRight { return { name: this.name, type: this.type, right: this.right }; } } Object.freeze(Right); Object.freeze(Right.prototype); export type Either = Right | Left; export type SerializedEither = SerializedRight | SerializedLeft; export const isLeft = ( value: unknown | Either ): value is Left => value instanceof Left; export const isRight = ( value: unknown | Either ): value is Right => value instanceof Right; export const isEither = ( value: unknown | Either ): value is Either => isLeft(value) || isRight(value); export function chain( map: (value: R, ...parameters: P) => MaybePromiseLike>, ...parameters: P ): (either: Either, ...parameters: P) => Promise>; export function chain( map: (value: R, ...parameters: P) => MaybePromiseLike>, ...parameters: P ): (either: Either, ...parameters: P) => Promise>; export function chain( map: (value: R, ...parameters: P) => MaybePromiseLike>, ...parameters: P ): (either: Either, ...parameters: P) => Promise>; export function chain< L = never, R = never, NL = never, NR = never, P extends AnyParameters = [] >( map: (value: R, ...parameters: P) => MaybePromiseLike>, ...parameters: P ): (either: Either) => Promise> { return (either) => either.asyncChain(bind(map, parameters)); } /** * * @template L * @template R * * @throws {DeserializationError} - {@link DeserializationError} * @param {SerializedEither} serialized * @return {Either} */ export function fromJSON( serialized: SerializedEither ): Either { if (serialized.name !== name) { throw new DeserializationError( DeserializationError.Messages.EXPECTED_EITHER ); } if (serialized.type === EitherType.Left) { return left(serialized.left); } if (serialized.type === EitherType.Right) { return right(serialized.right); } throw new DeserializationError( DeserializationError.Messages.EITHER_INVALID_STATE ); } export function mergeInOne(values: [Either]): Either; export function mergeInOne( values: [Either, Either] ): Either; export function mergeInOne( values: [Either, Either, Either] ): Either; export function mergeInOne( values: [Either, Either, Either, Either] ): Either; export function mergeInOne( values: [ Either, Either, Either, Either, Either ] ): Either; export function mergeInOne( values: [ Either, Either, Either, Either, Either, Either ] ): Either; export function mergeInOne(values: Either[]): Either; export function mergeInOne(values: Either[]) { return mergeInMany(values).mapLeft((errors) => errors[0]); } export const merge = mergeInOne; export const from = right; export function mergeInMany( values: [Either] ): Either; export function mergeInMany( values: [Either, Either] ): Either<(L1 | L2)[], [R1, R2]>; export function mergeInMany( values: [Either, Either, Either] ): Either<(L1 | L2 | L3)[], [R1, R2, R3]>; export function mergeInMany( values: [Either, Either, Either, Either] ): Either<(L1 | L2 | L3 | L4)[], [R1, R2, R3, R4]>; export function mergeInMany( values: [ Either, Either, Either, Either, Either ] ): Either<(L1 | L2 | L3 | L4 | L5)[], [R1, R2, R3, R4, R5]>; export function mergeInMany( values: [ Either, Either, Either, Either, Either, Either ] ): Either<(L1 | L2 | L3 | L4 | L5 | L6)[], [R1, R2, R3, R4, R5, R6]>; export function mergeInMany(values: Either[]): Either; export function mergeInMany( values: Either[] ): Either { if (allRights(values)) { return right(values.map((either) => either.getRight())); } const results: unknown[] = []; for (const value of values) { if (value.isLeft()) { results.push(value.getLeft()); } } return left(results); } function allRights(array: Either[]): array is Right[] { return array.every((value) => value.isRight()); } export function aggregateError( values: Either[], message: string | undefined | ((lefts: T[]) => string | undefined) ): AggregateError | undefined { const joined = mergeInMany(values); if (joined.isRight()) { return; } return joined.fold( (errors) => new AggregateError( errors, typeof message === "string" ? message : message?.(errors) ), noop ); } function eraseType(value: unknown): any { return value; } export type MapCaught = Mapper; type LegacyMethodDecorator = ( target: CallableFunction, property: any, descriptor: PropertyDescriptor ) => void; type ModernMethodDecorator = < T extends (...parameters: AnyParameters) => R >( method: T, context: any ) => T; export function DecorateLegacy(): LegacyMethodDecorator { /* istanbul ignore next */ return function decorate(_target, _property, descriptor) { descriptor.value = wrap(descriptor.value); }; } export function DecorateAsyncLegacy(): LegacyMethodDecorator { /* istanbul ignore next */ return function decorateAsync(_target, _property, descriptor) { descriptor.value = wrapAsync(descriptor.value); }; } function requireDecorationMethod( context: ClassMemberDecoratorContext ): asserts context is ClassMethodDecoratorContext { /* istanbul ignore next */ if (context.kind !== "method") { throw new DecorationError(); } } export function Decorate(): ModernMethodDecorator { /* istanbul ignore next */ return function decorate( method: any, context: ClassMemberDecoratorContext ): any { /* istanbul ignore next */ requireDecorationMethod(context); return wrap(method); }; } export function DecorateAsync(): ModernMethodDecorator> { /* istanbul ignore next */ return function decorate( method: any, context: ClassMemberDecoratorContext ): any { /* istanbul ignore next */ requireDecorationMethod(context); return wrapAsync(method); }; } export function wrap( method: (...parameters: P) => Either, mapCaught?: MapCaught ): (this: any, ...parameters: P) => Either { return function eitherWrap(this: any, ...parameters: P): Either { return catchSync(() => method.call(this, ...parameters), mapCaught); }; } export function wrapAsync( method: (...parameters: P) => MaybePromiseLike> ): (this: any, ...parameters: P) => Promise> { return function eitherWrap( this: any, ...parameters: P ): Promise> { return catchAsync(() => method.call(this, ...parameters)); }; } export function catchSync( method: () => Either, mapCaught?: MapCaught ): Either { return fromTry>(method, mapCaught).join(); } export async function catchAsync( method: PromiseLike> | (() => MaybePromiseLike>), mapCaught?: MapCaught ): Promise> { const caught = await fromTryAsync>(method, mapCaught); return caught.join(); } export async function fromPromise( promise: MaybePromiseLike, mapCaught?: MapCaught ): Promise> { return fromTryAsync(() => promise, mapCaught); } export function fromTry( callback: () => T, mapCaught: MapCaught = eraseType ): Either { try { return right(callback()); } catch (error) { return left(mapCaught(error)); } } export async function fromTryAsync( callback: PromiseLike | (() => MaybePromiseLike), mapCaught: MapCaught = eraseType ): Promise> { try { const result = await (typeof callback === "function" ? callback() : callback); return right(result); } catch (error) { return left(mapCaught(error)); } } export function fromPromiseSettledResult( result: PromiseSettledResult ): Either { return result.status === "fulfilled" ? right(result.value) : left(result.reason); }