@praha/byethrow 0.9.0 → 0.10.0

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/README.md CHANGED
@@ -46,7 +46,7 @@ const validateId = (id: string) => {
46
46
  return Result.succeed();
47
47
  };
48
48
 
49
- const findUser = Result.try({
49
+ const findUser = Result.fn({
50
50
  try: (id: string) => {
51
51
  return { id, name: 'John Doe' };
52
52
  },
@@ -24,6 +24,9 @@ var __webpack_modules__ = {
24
24
  "./functions/fail" (module) {
25
25
  module.exports = require("./functions/fail.cjs");
26
26
  },
27
+ "./functions/fn" (module) {
28
+ module.exports = require("./functions/fn.cjs");
29
+ },
27
30
  "./functions/inspect-error" (module) {
28
31
  module.exports = require("./functions/inspect-error.cjs");
29
32
  },
@@ -48,6 +51,9 @@ var __webpack_modules__ = {
48
51
  "./functions/or-else" (module) {
49
52
  module.exports = require("./functions/or-else.cjs");
50
53
  },
54
+ "./functions/or-through" (module) {
55
+ module.exports = require("./functions/or-through.cjs");
56
+ },
51
57
  "./functions/parse" (module) {
52
58
  module.exports = require("./functions/parse.cjs");
53
59
  },
@@ -152,65 +158,73 @@ var __webpack_exports__ = {};
152
158
  var __rspack_reexport = {};
153
159
  for(const __rspack_import_key in _functions_fail__rspack_import_8)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_fail__rspack_import_8[__rspack_import_key];
154
160
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
155
- var _functions_inspect__rspack_import_9 = __webpack_require__("./functions/inspect");
161
+ var _functions_fn__rspack_import_9 = __webpack_require__("./functions/fn");
162
+ var __rspack_reexport = {};
163
+ for(const __rspack_import_key in _functions_fn__rspack_import_9)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_fn__rspack_import_9[__rspack_import_key];
164
+ __webpack_require__.d(__webpack_exports__, __rspack_reexport);
165
+ var _functions_inspect__rspack_import_10 = __webpack_require__("./functions/inspect");
166
+ var __rspack_reexport = {};
167
+ for(const __rspack_import_key in _functions_inspect__rspack_import_10)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_inspect__rspack_import_10[__rspack_import_key];
168
+ __webpack_require__.d(__webpack_exports__, __rspack_reexport);
169
+ var _functions_inspect_error__rspack_import_11 = __webpack_require__("./functions/inspect-error");
156
170
  var __rspack_reexport = {};
157
- for(const __rspack_import_key in _functions_inspect__rspack_import_9)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_inspect__rspack_import_9[__rspack_import_key];
171
+ for(const __rspack_import_key in _functions_inspect_error__rspack_import_11)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_inspect_error__rspack_import_11[__rspack_import_key];
158
172
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
159
- var _functions_inspect_error__rspack_import_10 = __webpack_require__("./functions/inspect-error");
173
+ var _functions_is_failure__rspack_import_12 = __webpack_require__("./functions/is-failure");
160
174
  var __rspack_reexport = {};
161
- for(const __rspack_import_key in _functions_inspect_error__rspack_import_10)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_inspect_error__rspack_import_10[__rspack_import_key];
175
+ for(const __rspack_import_key in _functions_is_failure__rspack_import_12)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_failure__rspack_import_12[__rspack_import_key];
162
176
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
163
- var _functions_is_failure__rspack_import_11 = __webpack_require__("./functions/is-failure");
177
+ var _functions_is_result__rspack_import_13 = __webpack_require__("./functions/is-result");
164
178
  var __rspack_reexport = {};
165
- for(const __rspack_import_key in _functions_is_failure__rspack_import_11)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_failure__rspack_import_11[__rspack_import_key];
179
+ for(const __rspack_import_key in _functions_is_result__rspack_import_13)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_result__rspack_import_13[__rspack_import_key];
166
180
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
167
- var _functions_is_result__rspack_import_12 = __webpack_require__("./functions/is-result");
181
+ var _functions_is_success__rspack_import_14 = __webpack_require__("./functions/is-success");
168
182
  var __rspack_reexport = {};
169
- for(const __rspack_import_key in _functions_is_result__rspack_import_12)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_result__rspack_import_12[__rspack_import_key];
183
+ for(const __rspack_import_key in _functions_is_success__rspack_import_14)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_success__rspack_import_14[__rspack_import_key];
170
184
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
171
- var _functions_is_success__rspack_import_13 = __webpack_require__("./functions/is-success");
185
+ var _functions_map__rspack_import_15 = __webpack_require__("./functions/map");
172
186
  var __rspack_reexport = {};
173
- for(const __rspack_import_key in _functions_is_success__rspack_import_13)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_is_success__rspack_import_13[__rspack_import_key];
187
+ for(const __rspack_import_key in _functions_map__rspack_import_15)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_map__rspack_import_15[__rspack_import_key];
174
188
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
175
- var _functions_map__rspack_import_14 = __webpack_require__("./functions/map");
189
+ var _functions_map_error__rspack_import_16 = __webpack_require__("./functions/map-error");
176
190
  var __rspack_reexport = {};
177
- for(const __rspack_import_key in _functions_map__rspack_import_14)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_map__rspack_import_14[__rspack_import_key];
191
+ for(const __rspack_import_key in _functions_map_error__rspack_import_16)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_map_error__rspack_import_16[__rspack_import_key];
178
192
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
179
- var _functions_map_error__rspack_import_15 = __webpack_require__("./functions/map-error");
193
+ var _functions_or_else__rspack_import_17 = __webpack_require__("./functions/or-else");
180
194
  var __rspack_reexport = {};
181
- for(const __rspack_import_key in _functions_map_error__rspack_import_15)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_map_error__rspack_import_15[__rspack_import_key];
195
+ for(const __rspack_import_key in _functions_or_else__rspack_import_17)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_or_else__rspack_import_17[__rspack_import_key];
182
196
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
183
- var _functions_or_else__rspack_import_16 = __webpack_require__("./functions/or-else");
197
+ var _functions_or_through__rspack_import_18 = __webpack_require__("./functions/or-through");
184
198
  var __rspack_reexport = {};
185
- for(const __rspack_import_key in _functions_or_else__rspack_import_16)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_or_else__rspack_import_16[__rspack_import_key];
199
+ for(const __rspack_import_key in _functions_or_through__rspack_import_18)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_or_through__rspack_import_18[__rspack_import_key];
186
200
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
187
- var _functions_parse__rspack_import_17 = __webpack_require__("./functions/parse");
201
+ var _functions_parse__rspack_import_19 = __webpack_require__("./functions/parse");
188
202
  var __rspack_reexport = {};
189
- for(const __rspack_import_key in _functions_parse__rspack_import_17)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_parse__rspack_import_17[__rspack_import_key];
203
+ for(const __rspack_import_key in _functions_parse__rspack_import_19)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_parse__rspack_import_19[__rspack_import_key];
190
204
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
191
- var _functions_pipe__rspack_import_18 = __webpack_require__("./functions/pipe");
205
+ var _functions_pipe__rspack_import_20 = __webpack_require__("./functions/pipe");
192
206
  var __rspack_reexport = {};
193
- for(const __rspack_import_key in _functions_pipe__rspack_import_18)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_pipe__rspack_import_18[__rspack_import_key];
207
+ for(const __rspack_import_key in _functions_pipe__rspack_import_20)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_pipe__rspack_import_20[__rspack_import_key];
194
208
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
195
- var _functions_sequence__rspack_import_19 = __webpack_require__("./functions/sequence");
209
+ var _functions_sequence__rspack_import_21 = __webpack_require__("./functions/sequence");
196
210
  var __rspack_reexport = {};
197
- for(const __rspack_import_key in _functions_sequence__rspack_import_19)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_sequence__rspack_import_19[__rspack_import_key];
211
+ for(const __rspack_import_key in _functions_sequence__rspack_import_21)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_sequence__rspack_import_21[__rspack_import_key];
198
212
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
199
- var _functions_succeed__rspack_import_20 = __webpack_require__("./functions/succeed");
213
+ var _functions_succeed__rspack_import_22 = __webpack_require__("./functions/succeed");
200
214
  var __rspack_reexport = {};
201
- for(const __rspack_import_key in _functions_succeed__rspack_import_20)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_succeed__rspack_import_20[__rspack_import_key];
215
+ for(const __rspack_import_key in _functions_succeed__rspack_import_22)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_succeed__rspack_import_22[__rspack_import_key];
202
216
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
203
- var _functions_try__rspack_import_21 = __webpack_require__("./functions/try");
217
+ var _functions_try__rspack_import_23 = __webpack_require__("./functions/try");
204
218
  var __rspack_reexport = {};
205
- for(const __rspack_import_key in _functions_try__rspack_import_21)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_try__rspack_import_21[__rspack_import_key];
219
+ for(const __rspack_import_key in _functions_try__rspack_import_23)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_try__rspack_import_23[__rspack_import_key];
206
220
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
207
- var _functions_unwrap__rspack_import_22 = __webpack_require__("./functions/unwrap");
221
+ var _functions_unwrap__rspack_import_24 = __webpack_require__("./functions/unwrap");
208
222
  var __rspack_reexport = {};
209
- for(const __rspack_import_key in _functions_unwrap__rspack_import_22)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_unwrap__rspack_import_22[__rspack_import_key];
223
+ for(const __rspack_import_key in _functions_unwrap__rspack_import_24)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_unwrap__rspack_import_24[__rspack_import_key];
210
224
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
211
- var _functions_unwrap_error__rspack_import_23 = __webpack_require__("./functions/unwrap-error");
225
+ var _functions_unwrap_error__rspack_import_25 = __webpack_require__("./functions/unwrap-error");
212
226
  var __rspack_reexport = {};
213
- for(const __rspack_import_key in _functions_unwrap_error__rspack_import_23)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_unwrap_error__rspack_import_23[__rspack_import_key];
227
+ for(const __rspack_import_key in _functions_unwrap_error__rspack_import_25)if ("default" !== __rspack_import_key) __rspack_reexport[__rspack_import_key] = ()=>_functions_unwrap_error__rspack_import_25[__rspack_import_key];
214
228
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
215
229
  })();
216
230
  for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
@@ -7,6 +7,7 @@ export * from './functions/bind.js';
7
7
  export * from './functions/collect.js';
8
8
  export * from './functions/do.js';
9
9
  export * from './functions/fail.js';
10
+ export * from './functions/fn.js';
10
11
  export * from './functions/inspect.js';
11
12
  export * from './functions/inspect-error.js';
12
13
  export * from './functions/is-failure.js';
@@ -15,6 +16,7 @@ export * from './functions/is-success.js';
15
16
  export * from './functions/map.js';
16
17
  export * from './functions/map-error.js';
17
18
  export * from './functions/or-else.js';
19
+ export * from './functions/or-through.js';
18
20
  export * from './functions/parse.js';
19
21
  export * from './functions/pipe.js';
20
22
  export * from './functions/sequence.js';
@@ -1,13 +1,17 @@
1
- import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
1
+ import type { HasPromise } from '../internals/types/has-promise.js';
2
+ import type { Failure, InferFailure, ResultMaybeAsync } from '../result.js';
2
3
  /**
3
4
  * Asserts that a {@link Result} or {@link ResultAsync} is a {@link Failure} and returns it.
4
- * If the result is a {@link Success}, throws an error.
5
+ * This function requires that the result's success type is `never`, meaning the result is
6
+ * guaranteed to be a {@link Failure} at the type level.
7
+ * If the result is a {@link Success} at runtime, throws an error.
5
8
  *
6
9
  * @function
7
- * @typeParam E - The type of the error value.
10
+ * @typeParam R - The result type that extends {@link ResultMaybeAsync} with `never` as the success type.
8
11
  * @param result - The {@link Result} or {@link ResultAsync} to assert as a {@link Failure}.
9
- * @returns The {@link Failure} result or a Promise of {@link Success} result.
10
- * @throws {Error} If the result is a {@link Success}.
12
+ * The success type must be `never`.
13
+ * @returns The {@link Failure} result or a Promise of {@link Failure} result.
14
+ * @throws {Error} If the result is a {@link Success} at runtime.
11
15
  *
12
16
  * @example
13
17
  * ```ts
@@ -18,24 +22,15 @@ import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
18
22
  * // failure: { type: 'Failure', error: 'error' }
19
23
  * ```
20
24
  *
21
- * @example Throws on Success
22
- * ```ts
23
- * // @errors: 2769
24
- * import { Result } from '@praha/byethrow';
25
- *
26
- * const result = Result.succeed(42);
27
- * Result.assertFailure(result); // throws Error
28
- * ```
29
- *
30
- * @example Safe unwrap with assertFailure
25
+ * @example Type-safe usage after narrowing success type
31
26
  * ```ts
32
27
  * import { Result } from '@praha/byethrow';
33
28
  *
34
29
  * const getResult = (): Result.Result<number, string> => Result.fail('error');
35
30
  * const value = Result.pipe(
36
31
  * getResult(),
37
- * Result.andThen(() => Result.fail('die')),
38
- * Result.assertFailure,
32
+ * Result.andThen(() => Result.fail('die')), // Success type becomes never
33
+ * Result.assertFailure, // Type-safe: success type is now never
39
34
  * Result.unwrapError(), // Safe unwrap after assertion
40
35
  * );
41
36
  * ```
@@ -44,7 +39,4 @@ import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
44
39
  *
45
40
  * @category Assertions
46
41
  */
47
- export declare const assertFailure: {
48
- <R extends ResultAsync<never, any>>(result: R): Promise<Failure<InferFailure<R>>>;
49
- <R extends Result<never, any>>(result: R): Failure<InferFailure<R>>;
50
- };
42
+ export declare const assertFailure: <R extends ResultMaybeAsync<never, any>>(result: R) => true extends HasPromise<R> ? Promise<Failure<InferFailure<R>>> : Failure<InferFailure<R>>;
@@ -1,13 +1,17 @@
1
- import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
1
+ import type { HasPromise } from '../internals/types/has-promise.js';
2
+ import type { InferSuccess, ResultMaybeAsync, Success } from '../result.js';
2
3
  /**
3
4
  * Asserts that a {@link Result} or {@link ResultAsync} is a {@link Success} and returns it.
4
- * If the result is a {@link Failure}, throws an error.
5
+ * This function requires that the result's error type is `never`, meaning the result is
6
+ * guaranteed to be a {@link Success} at the type level.
7
+ * If the result is a {@link Failure} at runtime, throws an error.
5
8
  *
6
9
  * @function
7
- * @typeParam T - The type of the success value.
10
+ * @typeParam R - The result type that extends {@link ResultMaybeAsync} with `never` as the error type.
8
11
  * @param result - The {@link Result} or {@link ResultAsync} to assert as a {@link Success}.
12
+ * The error type must be `never`.
9
13
  * @returns The {@link Success} result or a Promise of {@link Success} result.
10
- * @throws {Error} If the result is a {@link Failure}.
14
+ * @throws {Error} If the result is a {@link Failure} at runtime.
11
15
  *
12
16
  * @example
13
17
  * ```ts
@@ -18,24 +22,15 @@ import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
18
22
  * // success: { type: 'Success', value: 42 }
19
23
  * ```
20
24
  *
21
- * @example Throws on Failure
22
- * ```ts
23
- * // @errors: 2769
24
- * import { Result } from '@praha/byethrow';
25
- *
26
- * const result = Result.fail('error');
27
- * Result.assertSuccess(result); // throws Error
28
- * ```
29
- *
30
- * @example Safe unwrap with assertSuccess
25
+ * @example Type-safe usage after narrowing error type
31
26
  * ```ts
32
27
  * import { Result } from '@praha/byethrow';
33
28
  *
34
29
  * const getResult = (): Result.Result<number, string> => Result.succeed(42);
35
30
  * const value = Result.pipe(
36
31
  * getResult(),
37
- * Result.orElse(() => Result.succeed('fallback')),
38
- * Result.assertSuccess,
32
+ * Result.orElse(() => Result.succeed(0)), // Error type becomes never
33
+ * Result.assertSuccess, // Type-safe: error type is now never
39
34
  * Result.unwrap(), // Safe unwrap after assertion
40
35
  * );
41
36
  * ```
@@ -44,7 +39,4 @@ import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
44
39
  *
45
40
  * @category Assertions
46
41
  */
47
- export declare const assertSuccess: {
48
- <R extends ResultAsync<any, never>>(result: R): Promise<Success<InferSuccess<R>>>;
49
- <R extends Result<any, never>>(result: R): Success<InferSuccess<R>>;
50
- };
42
+ export declare const assertSuccess: <R extends ResultMaybeAsync<any, never>>(result: R) => true extends HasPromise<R> ? Promise<Success<InferSuccess<R>>> : Success<InferSuccess<R>>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ fn: ()=>fn_fn
28
+ });
29
+ const external_fail_cjs_namespaceObject = require("./fail.cjs");
30
+ const external_succeed_cjs_namespaceObject = require("./succeed.cjs");
31
+ const is_promise_cjs_namespaceObject = require("../internals/helpers/is-promise.cjs");
32
+ const fn_fn = (options)=>{
33
+ const fn = (...args)=>{
34
+ try {
35
+ const output = options.try(...args);
36
+ if ((0, is_promise_cjs_namespaceObject.isPromise)(output)) {
37
+ const promise = (0, external_succeed_cjs_namespaceObject.succeed)(output);
38
+ if ('safe' in options && options.safe) return promise;
39
+ return promise.catch((error)=>(0, external_fail_cjs_namespaceObject.fail)(options.catch(error)));
40
+ }
41
+ return (0, external_succeed_cjs_namespaceObject.succeed)(output);
42
+ } catch (error) {
43
+ if ('safe' in options && options.safe) throw error;
44
+ return (0, external_fail_cjs_namespaceObject.fail)(options.catch(error));
45
+ }
46
+ };
47
+ return fn;
48
+ };
49
+ exports.fn = __webpack_exports__.fn;
50
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
51
+ "fn"
52
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
53
+ Object.defineProperty(exports, '__esModule', {
54
+ value: true
55
+ });
@@ -0,0 +1,84 @@
1
+ import type { Result, ResultAsync } from '../result.js';
2
+ /**
3
+ * Wraps a function that may throw and returns a new function that returns a {@link Result} or {@link ResultAsync}.
4
+ *
5
+ * You can use either a custom `catch` handler or rely on the `safe: true` option
6
+ * to assume the function cannot throw.
7
+ *
8
+ * @function
9
+ * @typeParam T - The function type to execute (sync or async) or a Promise type.
10
+ * @typeParam E - The error type to return if `catch` is used.
11
+ * @returns A new function that returns a {@link Result} or {@link ResultAsync} wrapping the original function's return value or the caught error.
12
+ *
13
+ * @example Sync try-catch
14
+ * ```ts
15
+ * import { Result } from '@praha/byethrow';
16
+ *
17
+ * const fn = Result.fn({
18
+ * try: (x: number) => {
19
+ * if (x < 0) throw new Error('Negative!');
20
+ * return x * 2;
21
+ * },
22
+ * catch: (error) => new Error('Oops!', { cause: error }),
23
+ * });
24
+ *
25
+ * const result = fn(5); // Result.Result<number, Error>
26
+ * ```
27
+ *
28
+ * @example Sync safe
29
+ * ```ts
30
+ * import { Result } from '@praha/byethrow';
31
+ *
32
+ * const fn = Result.fn({
33
+ * safe: true,
34
+ * try: (x: number) => x + 1,
35
+ * });
36
+ *
37
+ * const result = fn(1); // Result.Result<number, never>
38
+ * ```
39
+ *
40
+ * @example Async try-catch
41
+ * ```ts
42
+ * import { Result } from '@praha/byethrow';
43
+ *
44
+ * const fn = Result.fn({
45
+ * try: async (id: string) => await fetch(`/api/data/${id}`),
46
+ * catch: (error) => new Error('Oops!', { cause: error }),
47
+ * });
48
+ *
49
+ * const result = await fn('abc'); // Result.ResultAsync<Response, Error>
50
+ * ```
51
+ *
52
+ * @example Async safe
53
+ * ```ts
54
+ * import { Result } from '@praha/byethrow';
55
+ *
56
+ * const fn = Result.fn({
57
+ * safe: true,
58
+ * try: async () => await Promise.resolve('ok'),
59
+ * });
60
+ *
61
+ * const result = await fn(); // Result.ResultAsync<string, never>
62
+ * ```
63
+ *
64
+ * @category Creators
65
+ */
66
+ declare const fn: {
67
+ <T extends (...args: readonly any[]) => Promise<any>, E>(options: {
68
+ try: T;
69
+ catch: (error: unknown) => E;
70
+ }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, E>;
71
+ <T extends (...args: readonly any[]) => Promise<any>>(options: {
72
+ safe: true;
73
+ try: T;
74
+ }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, never>;
75
+ <T extends (...args: readonly any[]) => any, E>(options: {
76
+ try: T;
77
+ catch: (error: unknown) => E;
78
+ }): (...args: Parameters<T>) => Result<ReturnType<T>, E>;
79
+ <T extends (...args: readonly any[]) => any>(options: {
80
+ safe: true;
81
+ try: T;
82
+ }): (...args: Parameters<T>) => Result<ReturnType<T>, never>;
83
+ };
84
+ export { fn };
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ orThrough: ()=>orThrough
28
+ });
29
+ const external_is_success_cjs_namespaceObject = require("./is-success.cjs");
30
+ const is_promise_cjs_namespaceObject = require("../internals/helpers/is-promise.cjs");
31
+ const orThrough = (fn)=>(result)=>{
32
+ const apply = (r)=>{
33
+ if ((0, external_is_success_cjs_namespaceObject.isSuccess)(r)) return r;
34
+ const next = fn(r.error);
35
+ if ((0, is_promise_cjs_namespaceObject.isPromise)(next)) return next.then((n)=>{
36
+ if ((0, external_is_success_cjs_namespaceObject.isSuccess)(n)) return r;
37
+ return n;
38
+ });
39
+ if ((0, external_is_success_cjs_namespaceObject.isSuccess)(next)) return r;
40
+ return next;
41
+ };
42
+ return (0, is_promise_cjs_namespaceObject.isPromise)(result) ? result.then(apply) : apply(result);
43
+ };
44
+ exports.orThrough = __webpack_exports__.orThrough;
45
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
46
+ "orThrough"
47
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
48
+ Object.defineProperty(exports, '__esModule', {
49
+ value: true
50
+ });
@@ -0,0 +1,64 @@
1
+ import type { InferFailure, InferSuccess, ResultFor, ResultMaybeAsync } from '../result.js';
2
+ /**
3
+ * Runs an additional computation using the error value of a {@link Result} or {@link ResultAsync},
4
+ * but **returns the original failure** if the additional computation is successful.
5
+ *
6
+ * If the original result is a {@link Success}, it is returned immediately without running the function.
7
+ * If the original result is a {@link Failure}, the function is executed with the error value.
8
+ * If the function returns a {@link Success}, the original failure is returned.
9
+ * If the function returns a {@link Failure}, that new failure is returned.
10
+ *
11
+ * Useful for running error recovery or fallback logic while preserving the original error on success.
12
+ *
13
+ * @function
14
+ * @typeParam R1 - The input {@link Result} or {@link ResultAsync}.
15
+ * @typeParam R2 - The result type returned by `fn`.
16
+ *
17
+ * @example Success Case
18
+ * ```ts
19
+ * import { Result } from '@praha/byethrow';
20
+ *
21
+ * const result = Result.pipe(
22
+ * Result.succeed(5),
23
+ * Result.orThrough((error) => {
24
+ * return Result.succeed(null);
25
+ * }),
26
+ * );
27
+ * // { type: 'Success', value: 5 }
28
+ * ```
29
+ *
30
+ * @example Failure Case (function returns a Success)
31
+ * ```ts
32
+ * import { Result } from '@praha/byethrow';
33
+ *
34
+ * const result = Result.pipe(
35
+ * Result.fail('error'),
36
+ * Result.orThrough((error) => {
37
+ * console.log('Logging error:', error);
38
+ * return Result.succeed(null);
39
+ * }),
40
+ * );
41
+ * // { type: 'Failure', error: 'error' }
42
+ * ```
43
+ *
44
+ * @example Failure Case (function returns a Failure)
45
+ * ```ts
46
+ * import { Result } from '@praha/byethrow';
47
+ *
48
+ * const result = Result.pipe(
49
+ * Result.fail('original error'),
50
+ * Result.orThrough((error) => {
51
+ * return Result.fail('new error');
52
+ * }),
53
+ * );
54
+ * // { type: 'Failure', error: 'new error' }
55
+ * ```
56
+ *
57
+ * @see {@link pipe} - It is recommended to use this function with the {@link pipe} function for better readability and composability.
58
+ *
59
+ * @category Combinators
60
+ */
61
+ export declare const orThrough: {
62
+ <R1 extends ResultMaybeAsync<any, any>, R2 extends ResultMaybeAsync<any, any>>(fn: (a: InferFailure<R1>) => R2): (result: R1) => ResultFor<R1 | R2, InferSuccess<R1>, InferFailure<R1> | InferFailure<R2>>;
63
+ <F extends (a: any) => ResultMaybeAsync<any, any>>(fn: F): <R1 extends ResultMaybeAsync<any, Parameters<F>[0]>>(result: R1) => ResultFor<R1 | ReturnType<F>, InferSuccess<R1>, InferFailure<R1> | InferFailure<F>>;
64
+ };
@@ -30,9 +30,9 @@ const external_fail_cjs_namespaceObject = require("./fail.cjs");
30
30
  const external_succeed_cjs_namespaceObject = require("./succeed.cjs");
31
31
  const is_promise_cjs_namespaceObject = require("../internals/helpers/is-promise.cjs");
32
32
  const try_ = (options)=>{
33
- const fn = (...args)=>{
33
+ const fn = ()=>{
34
34
  try {
35
- const output = options.try(...args);
35
+ const output = options.try();
36
36
  if ((0, is_promise_cjs_namespaceObject.isPromise)(output)) {
37
37
  const promise = (0, external_succeed_cjs_namespaceObject.succeed)(output);
38
38
  if ('safe' in options && options.safe) return promise;
@@ -44,8 +44,7 @@ const try_ = (options)=>{
44
44
  return (0, external_fail_cjs_namespaceObject.fail)(options.catch(error));
45
45
  }
46
46
  };
47
- if ('immediate' in options && options.immediate) return fn();
48
- return fn;
47
+ return fn();
49
48
  };
50
49
  exports["try"] = __webpack_exports__["try"];
51
50
  for(var __rspack_i in __webpack_exports__)if (-1 === [
@@ -1,7 +1,6 @@
1
1
  import type { Result, ResultAsync } from '../result.js';
2
2
  /**
3
- * Wraps a function execution (sync or async) or a Promise in a {@link Result} or {@link ResultAsync} type,
4
- * capturing errors and returning them in a structured way.
3
+ * Executes a function that may throw and wraps the result in a {@link Result} or {@link ResultAsync}.
5
4
  *
6
5
  * You can use either a custom `catch` handler or rely on the `safe: true` option
7
6
  * to assume the function cannot throw.
@@ -9,28 +8,13 @@ import type { Result, ResultAsync } from '../result.js';
9
8
  * @function
10
9
  * @typeParam T - The function type to execute (sync or async) or a Promise type.
11
10
  * @typeParam E - The error type to return if `catch` is used.
11
+ * @returns A {@link Result} or {@link ResultAsync} wrapping the function's return value or the caught error.
12
12
  *
13
13
  * @example Sync try-catch
14
14
  * ```ts
15
15
  * import { Result } from '@praha/byethrow';
16
16
  *
17
- * const fn = Result.try({
18
- * try: (x: number) => {
19
- * if (x < 0) throw new Error('Negative!');
20
- * return x * 2;
21
- * },
22
- * catch: (error) => new Error('Oops!', { cause: error }),
23
- * });
24
- *
25
- * const result = fn(5); // Result.Result<number, Error>
26
- * ```
27
- *
28
- * @example Sync try-catch with immediate execution
29
- * ```ts
30
- * import { Result } from '@praha/byethrow';
31
- *
32
17
  * const result = Result.try({
33
- * immediate: true,
34
18
  * try: () => {
35
19
  * const x = Math.random() * 10 - 5;
36
20
  * if (x < 0) throw new Error('Negative!');
@@ -46,21 +30,8 @@ import type { Result, ResultAsync } from '../result.js';
46
30
  * ```ts
47
31
  * import { Result } from '@praha/byethrow';
48
32
  *
49
- * const fn = Result.try({
50
- * safe: true,
51
- * try: (x: number) => x + 1,
52
- * });
53
- *
54
- * const result = fn(1); // Result.Result<number, never>
55
- * ```
56
- *
57
- * @example Sync safe with immediate execution
58
- * ```ts
59
- * import { Result } from '@praha/byethrow';
60
- *
61
33
  * const result = Result.try({
62
34
  * safe: true,
63
- * immediate: true,
64
35
  * try: () => Math.random() + 1,
65
36
  * });
66
37
  *
@@ -71,20 +42,7 @@ import type { Result, ResultAsync } from '../result.js';
71
42
  * ```ts
72
43
  * import { Result } from '@praha/byethrow';
73
44
  *
74
- * const fn = Result.try({
75
- * try: async (id: string) => await fetch(`/api/data/${id}`),
76
- * catch: (error) => new Error('Oops!', { cause: error }),
77
- * });
78
- *
79
- * const result = await fn('abc'); // Result.ResultAsync<Response, Error>
80
- * ```
81
- *
82
- * @example Async try-catch with immediate execution
83
- * ```ts
84
- * import { Result } from '@praha/byethrow';
85
- *
86
45
  * const result = Result.try({
87
- * immediate: true,
88
46
  * try: () => fetch('/api/data'),
89
47
  * catch: (error) => new Error('Fetch failed', { cause: error }),
90
48
  * });
@@ -96,21 +54,8 @@ import type { Result, ResultAsync } from '../result.js';
96
54
  * ```ts
97
55
  * import { Result } from '@praha/byethrow';
98
56
  *
99
- * const fn = Result.try({
100
- * safe: true,
101
- * try: async () => await Promise.resolve('ok'),
102
- * });
103
- *
104
- * const result = await fn(); // Result.ResultAsync<string, never>
105
- * ```
106
- *
107
- * @example Async safe with immediate execution
108
- * ```ts
109
- * import { Result } from '@praha/byethrow';
110
- *
111
57
  * const result = Result.try({
112
58
  * safe: true,
113
- * immediate: true,
114
59
  * try: () => Promise.resolve('ok'),
115
60
  * });
116
61
  *
@@ -120,40 +65,20 @@ import type { Result, ResultAsync } from '../result.js';
120
65
  * @category Creators
121
66
  */
122
67
  declare const try_: {
123
- <T extends (...args: readonly any[]) => Promise<any>, E>(options: {
124
- try: T;
125
- catch: (error: unknown) => E;
126
- }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, E>;
127
68
  <T extends () => Promise<any>, E>(options: {
128
- immediate: true;
129
69
  try: T;
130
70
  catch: (error: unknown) => E;
131
71
  }): ResultAsync<Awaited<ReturnType<T>>, E>;
132
- <T extends (...args: readonly any[]) => Promise<any>>(options: {
133
- safe: true;
134
- try: T;
135
- }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, never>;
136
72
  <T extends () => Promise<any>>(options: {
137
73
  safe: true;
138
- immediate: true;
139
74
  try: T;
140
75
  }): ResultAsync<Awaited<ReturnType<T>>, never>;
141
- <T extends (...args: readonly any[]) => any, E>(options: {
142
- try: T;
143
- catch: (error: unknown) => E;
144
- }): (...args: Parameters<T>) => Result<ReturnType<T>, E>;
145
76
  <T extends () => any, E>(options: {
146
- immediate: true;
147
77
  try: T;
148
78
  catch: (error: unknown) => E;
149
79
  }): Result<ReturnType<T>, E>;
150
- <T extends (...args: readonly any[]) => any>(options: {
151
- safe: true;
152
- try: T;
153
- }): (...args: Parameters<T>) => Result<ReturnType<T>, never>;
154
80
  <T extends () => any>(options: {
155
81
  safe: true;
156
- immediate: true;
157
82
  try: T;
158
83
  }): Result<ReturnType<T>, never>;
159
84
  };
@@ -15,7 +15,7 @@
15
15
  * return Result.succeed();
16
16
  * };
17
17
  *
18
- * const findUser = Result.try({
18
+ * const findUser = Result.fn({
19
19
  * try: (id: string) => {
20
20
  * return { id, name: 'John Doe' };
21
21
  * },
@@ -44,7 +44,7 @@
44
44
  * return R.succeed();
45
45
  * };
46
46
  *
47
- * const findUser = R.try({
47
+ * const findUser = R.fn({
48
48
  * try: (id: string) => {
49
49
  * return { id, name: 'John Doe' };
50
50
  * },
@@ -7,6 +7,7 @@ export * from './functions/bind.js';
7
7
  export * from './functions/collect.js';
8
8
  export * from './functions/do.js';
9
9
  export * from './functions/fail.js';
10
+ export * from './functions/fn.js';
10
11
  export * from './functions/inspect.js';
11
12
  export * from './functions/inspect-error.js';
12
13
  export * from './functions/is-failure.js';
@@ -15,6 +16,7 @@ export * from './functions/is-success.js';
15
16
  export * from './functions/map.js';
16
17
  export * from './functions/map-error.js';
17
18
  export * from './functions/or-else.js';
19
+ export * from './functions/or-through.js';
18
20
  export * from './functions/parse.js';
19
21
  export * from './functions/pipe.js';
20
22
  export * from './functions/sequence.js';
@@ -7,6 +7,7 @@ export * from "./functions/bind.js";
7
7
  export * from "./functions/collect.js";
8
8
  export * from "./functions/do.js";
9
9
  export * from "./functions/fail.js";
10
+ export * from "./functions/fn.js";
10
11
  export * from "./functions/inspect.js";
11
12
  export * from "./functions/inspect-error.js";
12
13
  export * from "./functions/is-failure.js";
@@ -15,6 +16,7 @@ export * from "./functions/is-success.js";
15
16
  export * from "./functions/map.js";
16
17
  export * from "./functions/map-error.js";
17
18
  export * from "./functions/or-else.js";
19
+ export * from "./functions/or-through.js";
18
20
  export * from "./functions/parse.js";
19
21
  export * from "./functions/pipe.js";
20
22
  export * from "./functions/sequence.js";
@@ -1,13 +1,17 @@
1
- import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
1
+ import type { HasPromise } from '../internals/types/has-promise.js';
2
+ import type { Failure, InferFailure, ResultMaybeAsync } from '../result.js';
2
3
  /**
3
4
  * Asserts that a {@link Result} or {@link ResultAsync} is a {@link Failure} and returns it.
4
- * If the result is a {@link Success}, throws an error.
5
+ * This function requires that the result's success type is `never`, meaning the result is
6
+ * guaranteed to be a {@link Failure} at the type level.
7
+ * If the result is a {@link Success} at runtime, throws an error.
5
8
  *
6
9
  * @function
7
- * @typeParam E - The type of the error value.
10
+ * @typeParam R - The result type that extends {@link ResultMaybeAsync} with `never` as the success type.
8
11
  * @param result - The {@link Result} or {@link ResultAsync} to assert as a {@link Failure}.
9
- * @returns The {@link Failure} result or a Promise of {@link Success} result.
10
- * @throws {Error} If the result is a {@link Success}.
12
+ * The success type must be `never`.
13
+ * @returns The {@link Failure} result or a Promise of {@link Failure} result.
14
+ * @throws {Error} If the result is a {@link Success} at runtime.
11
15
  *
12
16
  * @example
13
17
  * ```ts
@@ -18,24 +22,15 @@ import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
18
22
  * // failure: { type: 'Failure', error: 'error' }
19
23
  * ```
20
24
  *
21
- * @example Throws on Success
22
- * ```ts
23
- * // @errors: 2769
24
- * import { Result } from '@praha/byethrow';
25
- *
26
- * const result = Result.succeed(42);
27
- * Result.assertFailure(result); // throws Error
28
- * ```
29
- *
30
- * @example Safe unwrap with assertFailure
25
+ * @example Type-safe usage after narrowing success type
31
26
  * ```ts
32
27
  * import { Result } from '@praha/byethrow';
33
28
  *
34
29
  * const getResult = (): Result.Result<number, string> => Result.fail('error');
35
30
  * const value = Result.pipe(
36
31
  * getResult(),
37
- * Result.andThen(() => Result.fail('die')),
38
- * Result.assertFailure,
32
+ * Result.andThen(() => Result.fail('die')), // Success type becomes never
33
+ * Result.assertFailure, // Type-safe: success type is now never
39
34
  * Result.unwrapError(), // Safe unwrap after assertion
40
35
  * );
41
36
  * ```
@@ -44,7 +39,4 @@ import type { Failure, InferFailure, Result, ResultAsync } from '../result.js';
44
39
  *
45
40
  * @category Assertions
46
41
  */
47
- export declare const assertFailure: {
48
- <R extends ResultAsync<never, any>>(result: R): Promise<Failure<InferFailure<R>>>;
49
- <R extends Result<never, any>>(result: R): Failure<InferFailure<R>>;
50
- };
42
+ export declare const assertFailure: <R extends ResultMaybeAsync<never, any>>(result: R) => true extends HasPromise<R> ? Promise<Failure<InferFailure<R>>> : Failure<InferFailure<R>>;
@@ -1,13 +1,17 @@
1
- import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
1
+ import type { HasPromise } from '../internals/types/has-promise.js';
2
+ import type { InferSuccess, ResultMaybeAsync, Success } from '../result.js';
2
3
  /**
3
4
  * Asserts that a {@link Result} or {@link ResultAsync} is a {@link Success} and returns it.
4
- * If the result is a {@link Failure}, throws an error.
5
+ * This function requires that the result's error type is `never`, meaning the result is
6
+ * guaranteed to be a {@link Success} at the type level.
7
+ * If the result is a {@link Failure} at runtime, throws an error.
5
8
  *
6
9
  * @function
7
- * @typeParam T - The type of the success value.
10
+ * @typeParam R - The result type that extends {@link ResultMaybeAsync} with `never` as the error type.
8
11
  * @param result - The {@link Result} or {@link ResultAsync} to assert as a {@link Success}.
12
+ * The error type must be `never`.
9
13
  * @returns The {@link Success} result or a Promise of {@link Success} result.
10
- * @throws {Error} If the result is a {@link Failure}.
14
+ * @throws {Error} If the result is a {@link Failure} at runtime.
11
15
  *
12
16
  * @example
13
17
  * ```ts
@@ -18,24 +22,15 @@ import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
18
22
  * // success: { type: 'Success', value: 42 }
19
23
  * ```
20
24
  *
21
- * @example Throws on Failure
22
- * ```ts
23
- * // @errors: 2769
24
- * import { Result } from '@praha/byethrow';
25
- *
26
- * const result = Result.fail('error');
27
- * Result.assertSuccess(result); // throws Error
28
- * ```
29
- *
30
- * @example Safe unwrap with assertSuccess
25
+ * @example Type-safe usage after narrowing error type
31
26
  * ```ts
32
27
  * import { Result } from '@praha/byethrow';
33
28
  *
34
29
  * const getResult = (): Result.Result<number, string> => Result.succeed(42);
35
30
  * const value = Result.pipe(
36
31
  * getResult(),
37
- * Result.orElse(() => Result.succeed('fallback')),
38
- * Result.assertSuccess,
32
+ * Result.orElse(() => Result.succeed(0)), // Error type becomes never
33
+ * Result.assertSuccess, // Type-safe: error type is now never
39
34
  * Result.unwrap(), // Safe unwrap after assertion
40
35
  * );
41
36
  * ```
@@ -44,7 +39,4 @@ import type { InferSuccess, Result, ResultAsync, Success } from '../result.js';
44
39
  *
45
40
  * @category Assertions
46
41
  */
47
- export declare const assertSuccess: {
48
- <R extends ResultAsync<any, never>>(result: R): Promise<Success<InferSuccess<R>>>;
49
- <R extends Result<any, never>>(result: R): Success<InferSuccess<R>>;
50
- };
42
+ export declare const assertSuccess: <R extends ResultMaybeAsync<any, never>>(result: R) => true extends HasPromise<R> ? Promise<Success<InferSuccess<R>>> : Success<InferSuccess<R>>;
@@ -0,0 +1,84 @@
1
+ import type { Result, ResultAsync } from '../result.js';
2
+ /**
3
+ * Wraps a function that may throw and returns a new function that returns a {@link Result} or {@link ResultAsync}.
4
+ *
5
+ * You can use either a custom `catch` handler or rely on the `safe: true` option
6
+ * to assume the function cannot throw.
7
+ *
8
+ * @function
9
+ * @typeParam T - The function type to execute (sync or async) or a Promise type.
10
+ * @typeParam E - The error type to return if `catch` is used.
11
+ * @returns A new function that returns a {@link Result} or {@link ResultAsync} wrapping the original function's return value or the caught error.
12
+ *
13
+ * @example Sync try-catch
14
+ * ```ts
15
+ * import { Result } from '@praha/byethrow';
16
+ *
17
+ * const fn = Result.fn({
18
+ * try: (x: number) => {
19
+ * if (x < 0) throw new Error('Negative!');
20
+ * return x * 2;
21
+ * },
22
+ * catch: (error) => new Error('Oops!', { cause: error }),
23
+ * });
24
+ *
25
+ * const result = fn(5); // Result.Result<number, Error>
26
+ * ```
27
+ *
28
+ * @example Sync safe
29
+ * ```ts
30
+ * import { Result } from '@praha/byethrow';
31
+ *
32
+ * const fn = Result.fn({
33
+ * safe: true,
34
+ * try: (x: number) => x + 1,
35
+ * });
36
+ *
37
+ * const result = fn(1); // Result.Result<number, never>
38
+ * ```
39
+ *
40
+ * @example Async try-catch
41
+ * ```ts
42
+ * import { Result } from '@praha/byethrow';
43
+ *
44
+ * const fn = Result.fn({
45
+ * try: async (id: string) => await fetch(`/api/data/${id}`),
46
+ * catch: (error) => new Error('Oops!', { cause: error }),
47
+ * });
48
+ *
49
+ * const result = await fn('abc'); // Result.ResultAsync<Response, Error>
50
+ * ```
51
+ *
52
+ * @example Async safe
53
+ * ```ts
54
+ * import { Result } from '@praha/byethrow';
55
+ *
56
+ * const fn = Result.fn({
57
+ * safe: true,
58
+ * try: async () => await Promise.resolve('ok'),
59
+ * });
60
+ *
61
+ * const result = await fn(); // Result.ResultAsync<string, never>
62
+ * ```
63
+ *
64
+ * @category Creators
65
+ */
66
+ declare const fn: {
67
+ <T extends (...args: readonly any[]) => Promise<any>, E>(options: {
68
+ try: T;
69
+ catch: (error: unknown) => E;
70
+ }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, E>;
71
+ <T extends (...args: readonly any[]) => Promise<any>>(options: {
72
+ safe: true;
73
+ try: T;
74
+ }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, never>;
75
+ <T extends (...args: readonly any[]) => any, E>(options: {
76
+ try: T;
77
+ catch: (error: unknown) => E;
78
+ }): (...args: Parameters<T>) => Result<ReturnType<T>, E>;
79
+ <T extends (...args: readonly any[]) => any>(options: {
80
+ safe: true;
81
+ try: T;
82
+ }): (...args: Parameters<T>) => Result<ReturnType<T>, never>;
83
+ };
84
+ export { fn };
@@ -0,0 +1,21 @@
1
+ import { fail } from "./fail.js";
2
+ import { succeed } from "./succeed.js";
3
+ import { isPromise } from "../internals/helpers/is-promise.js";
4
+ const fn_fn = (options)=>{
5
+ const fn = (...args)=>{
6
+ try {
7
+ const output = options.try(...args);
8
+ if (isPromise(output)) {
9
+ const promise = succeed(output);
10
+ if ('safe' in options && options.safe) return promise;
11
+ return promise.catch((error)=>fail(options.catch(error)));
12
+ }
13
+ return succeed(output);
14
+ } catch (error) {
15
+ if ('safe' in options && options.safe) throw error;
16
+ return fail(options.catch(error));
17
+ }
18
+ };
19
+ return fn;
20
+ };
21
+ export { fn_fn as fn };
@@ -0,0 +1,64 @@
1
+ import type { InferFailure, InferSuccess, ResultFor, ResultMaybeAsync } from '../result.js';
2
+ /**
3
+ * Runs an additional computation using the error value of a {@link Result} or {@link ResultAsync},
4
+ * but **returns the original failure** if the additional computation is successful.
5
+ *
6
+ * If the original result is a {@link Success}, it is returned immediately without running the function.
7
+ * If the original result is a {@link Failure}, the function is executed with the error value.
8
+ * If the function returns a {@link Success}, the original failure is returned.
9
+ * If the function returns a {@link Failure}, that new failure is returned.
10
+ *
11
+ * Useful for running error recovery or fallback logic while preserving the original error on success.
12
+ *
13
+ * @function
14
+ * @typeParam R1 - The input {@link Result} or {@link ResultAsync}.
15
+ * @typeParam R2 - The result type returned by `fn`.
16
+ *
17
+ * @example Success Case
18
+ * ```ts
19
+ * import { Result } from '@praha/byethrow';
20
+ *
21
+ * const result = Result.pipe(
22
+ * Result.succeed(5),
23
+ * Result.orThrough((error) => {
24
+ * return Result.succeed(null);
25
+ * }),
26
+ * );
27
+ * // { type: 'Success', value: 5 }
28
+ * ```
29
+ *
30
+ * @example Failure Case (function returns a Success)
31
+ * ```ts
32
+ * import { Result } from '@praha/byethrow';
33
+ *
34
+ * const result = Result.pipe(
35
+ * Result.fail('error'),
36
+ * Result.orThrough((error) => {
37
+ * console.log('Logging error:', error);
38
+ * return Result.succeed(null);
39
+ * }),
40
+ * );
41
+ * // { type: 'Failure', error: 'error' }
42
+ * ```
43
+ *
44
+ * @example Failure Case (function returns a Failure)
45
+ * ```ts
46
+ * import { Result } from '@praha/byethrow';
47
+ *
48
+ * const result = Result.pipe(
49
+ * Result.fail('original error'),
50
+ * Result.orThrough((error) => {
51
+ * return Result.fail('new error');
52
+ * }),
53
+ * );
54
+ * // { type: 'Failure', error: 'new error' }
55
+ * ```
56
+ *
57
+ * @see {@link pipe} - It is recommended to use this function with the {@link pipe} function for better readability and composability.
58
+ *
59
+ * @category Combinators
60
+ */
61
+ export declare const orThrough: {
62
+ <R1 extends ResultMaybeAsync<any, any>, R2 extends ResultMaybeAsync<any, any>>(fn: (a: InferFailure<R1>) => R2): (result: R1) => ResultFor<R1 | R2, InferSuccess<R1>, InferFailure<R1> | InferFailure<R2>>;
63
+ <F extends (a: any) => ResultMaybeAsync<any, any>>(fn: F): <R1 extends ResultMaybeAsync<any, Parameters<F>[0]>>(result: R1) => ResultFor<R1 | ReturnType<F>, InferSuccess<R1>, InferFailure<R1> | InferFailure<F>>;
64
+ };
@@ -0,0 +1,16 @@
1
+ import { isSuccess } from "./is-success.js";
2
+ import { isPromise } from "../internals/helpers/is-promise.js";
3
+ const orThrough = (fn)=>(result)=>{
4
+ const apply = (r)=>{
5
+ if (isSuccess(r)) return r;
6
+ const next = fn(r.error);
7
+ if (isPromise(next)) return next.then((n)=>{
8
+ if (isSuccess(n)) return r;
9
+ return n;
10
+ });
11
+ if (isSuccess(next)) return r;
12
+ return next;
13
+ };
14
+ return isPromise(result) ? result.then(apply) : apply(result);
15
+ };
16
+ export { orThrough };
@@ -1,7 +1,6 @@
1
1
  import type { Result, ResultAsync } from '../result.js';
2
2
  /**
3
- * Wraps a function execution (sync or async) or a Promise in a {@link Result} or {@link ResultAsync} type,
4
- * capturing errors and returning them in a structured way.
3
+ * Executes a function that may throw and wraps the result in a {@link Result} or {@link ResultAsync}.
5
4
  *
6
5
  * You can use either a custom `catch` handler or rely on the `safe: true` option
7
6
  * to assume the function cannot throw.
@@ -9,28 +8,13 @@ import type { Result, ResultAsync } from '../result.js';
9
8
  * @function
10
9
  * @typeParam T - The function type to execute (sync or async) or a Promise type.
11
10
  * @typeParam E - The error type to return if `catch` is used.
11
+ * @returns A {@link Result} or {@link ResultAsync} wrapping the function's return value or the caught error.
12
12
  *
13
13
  * @example Sync try-catch
14
14
  * ```ts
15
15
  * import { Result } from '@praha/byethrow';
16
16
  *
17
- * const fn = Result.try({
18
- * try: (x: number) => {
19
- * if (x < 0) throw new Error('Negative!');
20
- * return x * 2;
21
- * },
22
- * catch: (error) => new Error('Oops!', { cause: error }),
23
- * });
24
- *
25
- * const result = fn(5); // Result.Result<number, Error>
26
- * ```
27
- *
28
- * @example Sync try-catch with immediate execution
29
- * ```ts
30
- * import { Result } from '@praha/byethrow';
31
- *
32
17
  * const result = Result.try({
33
- * immediate: true,
34
18
  * try: () => {
35
19
  * const x = Math.random() * 10 - 5;
36
20
  * if (x < 0) throw new Error('Negative!');
@@ -46,21 +30,8 @@ import type { Result, ResultAsync } from '../result.js';
46
30
  * ```ts
47
31
  * import { Result } from '@praha/byethrow';
48
32
  *
49
- * const fn = Result.try({
50
- * safe: true,
51
- * try: (x: number) => x + 1,
52
- * });
53
- *
54
- * const result = fn(1); // Result.Result<number, never>
55
- * ```
56
- *
57
- * @example Sync safe with immediate execution
58
- * ```ts
59
- * import { Result } from '@praha/byethrow';
60
- *
61
33
  * const result = Result.try({
62
34
  * safe: true,
63
- * immediate: true,
64
35
  * try: () => Math.random() + 1,
65
36
  * });
66
37
  *
@@ -71,20 +42,7 @@ import type { Result, ResultAsync } from '../result.js';
71
42
  * ```ts
72
43
  * import { Result } from '@praha/byethrow';
73
44
  *
74
- * const fn = Result.try({
75
- * try: async (id: string) => await fetch(`/api/data/${id}`),
76
- * catch: (error) => new Error('Oops!', { cause: error }),
77
- * });
78
- *
79
- * const result = await fn('abc'); // Result.ResultAsync<Response, Error>
80
- * ```
81
- *
82
- * @example Async try-catch with immediate execution
83
- * ```ts
84
- * import { Result } from '@praha/byethrow';
85
- *
86
45
  * const result = Result.try({
87
- * immediate: true,
88
46
  * try: () => fetch('/api/data'),
89
47
  * catch: (error) => new Error('Fetch failed', { cause: error }),
90
48
  * });
@@ -96,21 +54,8 @@ import type { Result, ResultAsync } from '../result.js';
96
54
  * ```ts
97
55
  * import { Result } from '@praha/byethrow';
98
56
  *
99
- * const fn = Result.try({
100
- * safe: true,
101
- * try: async () => await Promise.resolve('ok'),
102
- * });
103
- *
104
- * const result = await fn(); // Result.ResultAsync<string, never>
105
- * ```
106
- *
107
- * @example Async safe with immediate execution
108
- * ```ts
109
- * import { Result } from '@praha/byethrow';
110
- *
111
57
  * const result = Result.try({
112
58
  * safe: true,
113
- * immediate: true,
114
59
  * try: () => Promise.resolve('ok'),
115
60
  * });
116
61
  *
@@ -120,40 +65,20 @@ import type { Result, ResultAsync } from '../result.js';
120
65
  * @category Creators
121
66
  */
122
67
  declare const try_: {
123
- <T extends (...args: readonly any[]) => Promise<any>, E>(options: {
124
- try: T;
125
- catch: (error: unknown) => E;
126
- }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, E>;
127
68
  <T extends () => Promise<any>, E>(options: {
128
- immediate: true;
129
69
  try: T;
130
70
  catch: (error: unknown) => E;
131
71
  }): ResultAsync<Awaited<ReturnType<T>>, E>;
132
- <T extends (...args: readonly any[]) => Promise<any>>(options: {
133
- safe: true;
134
- try: T;
135
- }): (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, never>;
136
72
  <T extends () => Promise<any>>(options: {
137
73
  safe: true;
138
- immediate: true;
139
74
  try: T;
140
75
  }): ResultAsync<Awaited<ReturnType<T>>, never>;
141
- <T extends (...args: readonly any[]) => any, E>(options: {
142
- try: T;
143
- catch: (error: unknown) => E;
144
- }): (...args: Parameters<T>) => Result<ReturnType<T>, E>;
145
76
  <T extends () => any, E>(options: {
146
- immediate: true;
147
77
  try: T;
148
78
  catch: (error: unknown) => E;
149
79
  }): Result<ReturnType<T>, E>;
150
- <T extends (...args: readonly any[]) => any>(options: {
151
- safe: true;
152
- try: T;
153
- }): (...args: Parameters<T>) => Result<ReturnType<T>, never>;
154
80
  <T extends () => any>(options: {
155
81
  safe: true;
156
- immediate: true;
157
82
  try: T;
158
83
  }): Result<ReturnType<T>, never>;
159
84
  };
@@ -2,9 +2,9 @@ import { fail } from "./fail.js";
2
2
  import { succeed } from "./succeed.js";
3
3
  import { isPromise } from "../internals/helpers/is-promise.js";
4
4
  const try_ = (options)=>{
5
- const fn = (...args)=>{
5
+ const fn = ()=>{
6
6
  try {
7
- const output = options.try(...args);
7
+ const output = options.try();
8
8
  if (isPromise(output)) {
9
9
  const promise = succeed(output);
10
10
  if ('safe' in options && options.safe) return promise;
@@ -16,7 +16,6 @@ const try_ = (options)=>{
16
16
  return fail(options.catch(error));
17
17
  }
18
18
  };
19
- if ('immediate' in options && options.immediate) return fn();
20
- return fn;
19
+ return fn();
21
20
  };
22
21
  export { try_ as try };
@@ -15,7 +15,7 @@
15
15
  * return Result.succeed();
16
16
  * };
17
17
  *
18
- * const findUser = Result.try({
18
+ * const findUser = Result.fn({
19
19
  * try: (id: string) => {
20
20
  * return { id, name: 'John Doe' };
21
21
  * },
@@ -44,7 +44,7 @@
44
44
  * return R.succeed();
45
45
  * };
46
46
  *
47
- * const findUser = R.try({
47
+ * const findUser = R.fn({
48
48
  * try: (id: string) => {
49
49
  * return { id, name: 'John Doe' };
50
50
  * },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@praha/byethrow",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "A lightweight, tree-shakable Result type package with a simple, consistent API designed",
5
5
  "keywords": [
6
6
  "javascript",
@@ -44,12 +44,12 @@
44
44
  "@standard-schema/spec": "^1.0.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@rslib/core": "0.18.5",
47
+ "@rslib/core": "0.19.5",
48
48
  "eslint": "9.39.2",
49
- "typedoc": "0.28.15",
50
- "typedoc-plugin-markdown": "4.9.0",
49
+ "typedoc": "0.28.17",
50
+ "typedoc-plugin-markdown": "4.10.0",
51
51
  "typescript": "5.9.3",
52
- "vitest": "4.0.16"
52
+ "vitest": "4.0.18"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "typescript": ">=5.0.0"