import type { Result } from './types.js' import { success, failure } from './result-helpers.js' import { isPromise, getErrorMessage } from './internals.js' /** * Executes a function, promise, or value and returns a Result type. * If an error occurs, it returns a Failure with the error message as a string. * * @template T The type of the successful result * @param {T | Promise | (() => T | Promise)} value - The value, promise, or function to execute * @returns {Result | Promise>} A Result type or a Promise of a Result type * * @example * // With a value * const [err, result] = goTry(42); * * @example * // With a function * const [err, result] = goTry(() => JSON.parse('{"key": "value"}')); * * @example * // With a promise * const [err, result] = await goTry(fetch('https://api.example.com/data')); */ export function goTry(fn: () => never): Result export function goTry(fn: () => Promise): Promise> export function goTry(promise: Promise): Promise> export function goTry(fn: () => T): Result export function goTry(value: T): Result export function goTry( value: T | Promise | (() => T | Promise), ): Result | Promise> { try { const result = typeof value === 'function' ? (value as () => T | Promise)() : value if (isPromise(result)) { return result .then((resolvedValue) => success(resolvedValue)) .catch((err) => failure(getErrorMessage(err))) } return success(result) } catch (err) { return failure(getErrorMessage(err)) } }