@satoshibits/functional 1.0.2

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.
Files changed (46) hide show
  1. package/README.md +242 -0
  2. package/dist/array-utils.d.mts +317 -0
  3. package/dist/array-utils.d.mts.map +1 -0
  4. package/dist/array-utils.mjs +370 -0
  5. package/dist/array-utils.mjs.map +1 -0
  6. package/dist/composition.d.mts +603 -0
  7. package/dist/composition.d.mts.map +1 -0
  8. package/dist/composition.mjs +516 -0
  9. package/dist/composition.mjs.map +1 -0
  10. package/dist/object-utils.d.mts +267 -0
  11. package/dist/object-utils.d.mts.map +1 -0
  12. package/dist/object-utils.mjs +258 -0
  13. package/dist/object-utils.mjs.map +1 -0
  14. package/dist/option.d.mts +622 -0
  15. package/dist/option.d.mts.map +1 -0
  16. package/dist/option.mjs +637 -0
  17. package/dist/option.mjs.map +1 -0
  18. package/dist/performance.d.mts +265 -0
  19. package/dist/performance.d.mts.map +1 -0
  20. package/dist/performance.mjs +453 -0
  21. package/dist/performance.mjs.map +1 -0
  22. package/dist/pipeline.d.mts +431 -0
  23. package/dist/pipeline.d.mts.map +1 -0
  24. package/dist/pipeline.mjs +460 -0
  25. package/dist/pipeline.mjs.map +1 -0
  26. package/dist/predicates.d.mts +722 -0
  27. package/dist/predicates.d.mts.map +1 -0
  28. package/dist/predicates.mjs +802 -0
  29. package/dist/predicates.mjs.map +1 -0
  30. package/dist/reader-result.d.mts +422 -0
  31. package/dist/reader-result.d.mts.map +1 -0
  32. package/dist/reader-result.mjs +758 -0
  33. package/dist/reader-result.mjs.map +1 -0
  34. package/dist/result.d.mts +684 -0
  35. package/dist/result.d.mts.map +1 -0
  36. package/dist/result.mjs +814 -0
  37. package/dist/result.mjs.map +1 -0
  38. package/dist/types.d.mts +439 -0
  39. package/dist/types.d.mts.map +1 -0
  40. package/dist/types.mjs +191 -0
  41. package/dist/types.mjs.map +1 -0
  42. package/dist/validation.d.mts +622 -0
  43. package/dist/validation.d.mts.map +1 -0
  44. package/dist/validation.mjs +852 -0
  45. package/dist/validation.mjs.map +1 -0
  46. package/package.json +46 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reader-result.mjs","sourceRoot":"","sources":["../src/reader-result.mts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,IAAI,WAAW,EAAE,MAAM,cAAc,CAAC;AAiBrD;;GAEG;AACH,MAAM,CAAC,IAAM,YAAY,GAAG;IAC1B;;;;;;;;;;;;;;;;;;OAkBG;IACH,EAAE,EAAE,UAAU,KAAQ;QACpB,OAAA,cAAM,OAAA,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,EAAtC,CAAsC;IAA5C,CAA4C;IAE9C;;;;;;;;;;;;;;;;;;OAkBG;IACH,IAAI,EAAE,UAAU,KAAQ;QACtB,OAAA,cAAM,OAAA,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAvC,CAAuC;IAA7C,CAA6C;IAE/C;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,KAAK,EAAE,UACL,CAAkC,IAC/B,OAAA,UACH,EAAyB;QAEzB,OAAA,UAAO,IAAO;;;;4BACI,qBAAM,EAAE,CAAC,IAAI,CAAC,EAAA;;wBAAxB,OAAO,GAAG,SAAc;wBAC9B,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;4BACrB,sBAAO,OAAuB,EAAC,CAAC,sCAAsC;wBACxE,CAAC;wBACD,sBAAO,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAC;;;aAC9B;IAND,CAMC,EATE,CASF;IAEH;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,GAAG,EAAE,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K,EAAE,CAAC,CAAC;4BAC9F,CAAC;wBACH,CAAC;wBAED,sBAAO,MAAM,CAAC,MAAM,GAAG,CAAC;gCACtB,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC;gCACzB,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,IAAgF,CAAC,EAAC;;;aACtG;IApBD,CAoBC;CACJ,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,IAAM,UAAU,GAAG,UACxB,CAAkC,IAC/B,OAAA;IACH,cAAa;SAAb,UAAa,EAAb,qBAAa,EAAb,IAAa;QAAb,yBAAa;;IAEb,OAAA,YAAY,CAAC,UAAU,CAAC,CAAC,eAAI,IAAI,EAAE;AAAnC,CAAmC,EAHhC,CAGgC,CAAC;AAEtC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,CAAC,IAAM,SAAS,GAAG,UACvB,CAAyC,EACzC,OAA8B,IAC3B,OAAA;IACH,cAAa;SAAb,UAAa,EAAb,qBAAa,EAAb,IAAa;QAAb,yBAAa;;IAEb,OAAA,YAAY,CAAC,QAAQ,CACnB,UAAC,IAAO,IAAK,OAAA,CAAC,8BAAC,IAAI,GAAK,IAAI,WAAf,CAAgB,EAC7B,OAAO,CACR;AAHD,CAGC,EANE,CAMF,CAAC"}
@@ -0,0 +1,684 @@
1
+ /**
2
+ * @module result
3
+ * @description Type-safe error handling without exceptions using the Result pattern.
4
+ * Result types represent operations that can either succeed with a value or fail
5
+ * with an error. This provides a functional alternative to try-catch blocks,
6
+ * making error handling explicit and composable. Similar to Rust's Result type
7
+ * or fp-ts's Either, but with a simpler API focused on practical use cases.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { Result, unwrap, safe } from './result.mts';
12
+ *
13
+ * // basic usage
14
+ * function divide(a: number, b: number): Result<number, string> {
15
+ * if (b === 0) {
16
+ * return Result.err('Division by zero');
17
+ * }
18
+ * return Result.ok(a / b);
19
+ * }
20
+ *
21
+ * // composing operations
22
+ * const result = Result.flatMap((x: number) => divide(x, 2))(
23
+ * Result.map((x: number) => x * 10)(
24
+ * divide(20, 4)
25
+ * )
26
+ * );
27
+ * // => { success: true, data: 25 }
28
+ *
29
+ * // error handling
30
+ * const safeOperation = Result.orElse(
31
+ * (error: string) => Result.ok(0) // default value on error
32
+ * )(divide(10, 0));
33
+ * // => { success: true, data: 0 }
34
+ * ```
35
+ *
36
+ * @category Core
37
+ * @since 2025-07-03
38
+ */
39
+ /**
40
+ * Result type for handling business errors without exceptions.
41
+ * @description Represents either a successful operation with data or a failure with an error.
42
+ * This discriminated union enables type-safe error handling where errors are
43
+ * values rather than exceptions.
44
+ *
45
+ * @template T - The type of the success value
46
+ * @template E - The type of the error value (defaults to string)
47
+ *
48
+ * @category Types
49
+ * @example
50
+ * ```typescript
51
+ * // Success case
52
+ * const success: Result<number> = { success: true, data: 42 };
53
+ *
54
+ * // Failure case
55
+ * const failure: Result<number> = { success: false, error: 'Not found' };
56
+ *
57
+ * // Custom error types
58
+ * type ApiError = { code: number; message: string };
59
+ * const apiFailure: Result<User, ApiError> = {
60
+ * success: false,
61
+ * error: { code: 404, message: 'User not found' }
62
+ * };
63
+ * ```
64
+ *
65
+ * @since 2025-07-03
66
+ */
67
+ export type Result<T, E = string> = {
68
+ success: true;
69
+ data: T;
70
+ } | {
71
+ success: false;
72
+ error: E;
73
+ };
74
+ /**
75
+ * Result utility functions for working with Result types.
76
+ * @description Provides a functional API for creating, transforming, and composing Results.
77
+ * All functions are curried to support functional composition and partial application.
78
+ *
79
+ * @category Utilities
80
+ * @since 2025-07-03
81
+ */
82
+ export declare const Result: {
83
+ /**
84
+ * Creates a successful Result containing the given data.
85
+ * @description Factory function for creating success cases. The error type
86
+ * can be inferred from context or explicitly specified.
87
+ *
88
+ * @template T - The type of the success value
89
+ * @template E - The type of the error (defaults to never for success cases)
90
+ * @param {T} data - The success value to wrap
91
+ * @returns {Result<T, E>} A successful Result containing the data
92
+ *
93
+ * @category Constructors
94
+ * @example
95
+ * // Basic usage
96
+ * const result = Result.ok(42);
97
+ * // => { success: true, data: 42 }
98
+ *
99
+ * @example
100
+ * // With explicit types
101
+ * const typed: Result<number, string> = Result.ok(42);
102
+ *
103
+ * @example
104
+ * // In a function
105
+ * function getUser(id: string): Result<User, string> {
106
+ * const user = database.find(id);
107
+ * return user ? Result.ok(user) : Result.err('User not found');
108
+ * }
109
+ *
110
+ * @since 2025-07-03
111
+ */
112
+ ok: <T, E = never>(data: T) => Result<T, E>;
113
+ /**
114
+ * Creates a failed Result containing the given error.
115
+ * @description Factory function for creating failure cases. The success type
116
+ * can be inferred from context or explicitly specified.
117
+ *
118
+ * @template T - The type of the success value (defaults to never for error cases)
119
+ * @template E - The type of the error (defaults to string)
120
+ * @param {E} error - The error value to wrap
121
+ * @returns {Result<T, E>} A failed Result containing the error
122
+ *
123
+ * @category Constructors
124
+ * @example
125
+ * // Basic usage
126
+ * const result = Result.err('Something went wrong');
127
+ * // => { success: false, error: 'Something went wrong' }
128
+ *
129
+ * @example
130
+ * // With custom error type
131
+ * interface ValidationError {
132
+ * field: string;
133
+ * message: string;
134
+ * }
135
+ *
136
+ * const error: Result<number, ValidationError> = Result.err({
137
+ * field: 'age',
138
+ * message: 'Must be positive'
139
+ * });
140
+ *
141
+ * @since 2025-07-03
142
+ */
143
+ err: <T = never, E = string>(error: E) => Result<T, E>;
144
+ /**
145
+ * Transforms the data inside a successful Result using the given function.
146
+ * @description If the Result is a failure, returns the failure unchanged.
147
+ * This is the functor map operation for Result types.
148
+ *
149
+ * @template T - The input success type
150
+ * @template U - The output success type
151
+ * @template E - The error type
152
+ * @param {function(T): U} f - Function to transform the success value
153
+ * @returns {function(Result<T, E>): Result<U, E>} A function that transforms Results
154
+ *
155
+ * @category Transformations
156
+ * @example
157
+ * // Basic transformation
158
+ * const double = Result.map((x: number) => x * 2);
159
+ * double(Result.ok(21)); // => { success: true, data: 42 }
160
+ * double(Result.err('error')); // => { success: false, error: 'error' }
161
+ *
162
+ * @example
163
+ * // Chaining transformations
164
+ * const result = Result.map((s: string) => s.toUpperCase())(
165
+ * Result.map((n: number) => n.toString())(
166
+ * Result.ok(42)
167
+ * )
168
+ * );
169
+ * // => { success: true, data: '42' }
170
+ *
171
+ * @since 2025-07-03
172
+ */
173
+ map: <T, U, E>(f: (data: T) => U) => (result: Result<T, E>) => Result<U, E>;
174
+ /**
175
+ * Chains Result-returning operations.
176
+ * @description If the first Result is successful, applies the function to its data.
177
+ * If it's a failure, returns the failure. This is the monadic bind operation
178
+ * for Result types, enabling sequential composition of fallible operations.
179
+ *
180
+ * @template T - The input success type
181
+ * @template U - The output success type
182
+ * @template E - The error type
183
+ * @param {function(T): Result<U, E>} f - Function that returns a new Result
184
+ * @returns {function(Result<T, E>): Result<U, E>} A function that chains Results
185
+ *
186
+ * @category Combinators
187
+ * @example
188
+ * // Chaining fallible operations
189
+ * function parseNumber(s: string): Result<number, string> {
190
+ * const n = Number(s);
191
+ * return isNaN(n) ? Result.err('Not a number') : Result.ok(n);
192
+ * }
193
+ *
194
+ * function safeDivide(n: number): Result<number, string> {
195
+ * return n === 0 ? Result.err('Division by zero') : Result.ok(100 / n);
196
+ * }
197
+ *
198
+ * const result = Result.flatMap(safeDivide)(
199
+ * parseNumber('5')
200
+ * );
201
+ * // => { success: true, data: 20 }
202
+ *
203
+ * @since 2025-07-03
204
+ */
205
+ flatMap: <T, U, E>(f: (data: T) => Result<U, E>) => (result: Result<T, E>) => Result<U, E>;
206
+ /**
207
+ * Transforms the error inside a failed Result using the given function.
208
+ * @description If the Result is successful, returns the success unchanged.
209
+ * Useful for normalizing errors or adding context to error messages.
210
+ *
211
+ * @template T - The success type
212
+ * @template E - The input error type
213
+ * @template F - The output error type
214
+ * @param {function(E): F} f - Function to transform the error
215
+ * @returns {function(Result<T, E>): Result<T, F>} A function that transforms error types
216
+ *
217
+ * @category Transformations
218
+ * @example
219
+ * // Adding context to errors
220
+ * const withContext = Result.mapError(
221
+ * (e: string) => `Database error: ${e}`
222
+ * );
223
+ *
224
+ * @example
225
+ * // Converting error types
226
+ * interface AppError {
227
+ * code: string;
228
+ * message: string;
229
+ * }
230
+ *
231
+ * const toAppError = Result.mapError(
232
+ * (e: Error): AppError => ({
233
+ * code: 'INTERNAL_ERROR',
234
+ * message: e.message
235
+ * })
236
+ * );
237
+ *
238
+ * @since 2025-07-03
239
+ */
240
+ mapError: <T, E, F>(f: (error: E) => F) => (result: Result<T, E>) => Result<T, F>;
241
+ /**
242
+ * Returns the data from a successful Result, or the provided default value if failed.
243
+ * @description Extracts the value from a Result, providing a fallback for the error case.
244
+ * Useful when you want to handle errors by substituting a default value.
245
+ *
246
+ * @template T - The success type
247
+ * @template E - The error type
248
+ * @param {T} defaultValue - The value to return if the Result is an error
249
+ * @returns {function(Result<T, E>): T} A function that extracts values with a default
250
+ *
251
+ * @category Extraction
252
+ * @example
253
+ * // Providing defaults
254
+ * const getWithDefault = Result.getOrElse(0);
255
+ * getWithDefault(Result.ok(42)); // => 42
256
+ * getWithDefault(Result.err('error')); // => 0
257
+ *
258
+ * @example
259
+ * // Configuration with fallback
260
+ * const port = Result.getOrElse(3000)(
261
+ * parsePort(process.env.PORT)
262
+ * );
263
+ *
264
+ * @since 2025-07-03
265
+ */
266
+ getOrElse: <T>(defaultValue: T) => <E>(result: Result<T, E>) => T;
267
+ /**
268
+ * Returns the data from a successful Result, or calls the provided function with the error.
269
+ * @description Pattern matches on the Result, applying one of two functions based on
270
+ * success or failure. Both functions must return the same type. This is similar
271
+ * to the fold operation in functional programming.
272
+ *
273
+ * @template T - The success type
274
+ * @template U - The return type
275
+ * @template E - The error type
276
+ * @param {function(T): U} onSuccess - Function to apply to success value
277
+ * @param {function(E): U} onFailure - Function to apply to error value
278
+ * @returns {function(Result<T, E>): U} A function that folds Results into a value
279
+ *
280
+ * @category Extraction
281
+ * @example
282
+ * // Converting to a message
283
+ * const toMessage = Result.fold(
284
+ * (user: User) => `Welcome, ${user.name}!`,
285
+ * (error: string) => `Error: ${error}`
286
+ * );
287
+ *
288
+ * @example
289
+ * // Converting to React component
290
+ * const renderResult = Result.fold(
291
+ * (data: Data) => <SuccessView data={data} />,
292
+ * (error: Error) => <ErrorView error={error} />
293
+ * );
294
+ *
295
+ * @since 2025-07-03
296
+ */
297
+ fold: <T, U, E>(onSuccess: (data: T) => U, onFailure: (error: E) => U) => (result: Result<T, E>) => U;
298
+ /**
299
+ * Combines two Results. If both are successful, applies the function to both data values.
300
+ * @description If either is a failure, returns the first failure encountered.
301
+ * This implements applicative-style composition for Result types.
302
+ *
303
+ * @template T - The first success type
304
+ * @template U - The second success type
305
+ * @template V - The combined success type
306
+ * @template E - The error type
307
+ * @param {function(T, U): V} f - Function to combine the success values
308
+ * @returns {function(Result<T, E>, Result<U, E>): Result<V, E>} A function that combines Results
309
+ *
310
+ * @category Combinations
311
+ * @example
312
+ * // Combining two results
313
+ * const add = Result.combine((a: number, b: number) => a + b);
314
+ * add(Result.ok(2), Result.ok(3)); // => { success: true, data: 5 }
315
+ * add(Result.ok(2), Result.err('error')); // => { success: false, error: 'error' }
316
+ *
317
+ * @example
318
+ * // Building objects from multiple Results
319
+ * const createUser = Result.combine(
320
+ * (name: string, age: number): User => ({ name, age })
321
+ * );
322
+ *
323
+ * const user = createUser(
324
+ * validateName(input.name),
325
+ * validateAge(input.age)
326
+ * );
327
+ *
328
+ * @since 2025-07-03
329
+ */
330
+ combine: <T, U, V, E>(f: (a: T, b: U) => V) => (resultA: Result<T, E>, resultB: Result<U, E>) => Result<V, E>;
331
+ /**
332
+ * Sequences an array of Results.
333
+ * @description If all are successful, returns an array of all data values.
334
+ * If any are failures, returns the first failure encountered. This is
335
+ * useful for validating multiple values where all must succeed.
336
+ *
337
+ * @template T - The success type of each Result
338
+ * @template E - The error type
339
+ * @param {Result<T, E>[]} results - Array of Results to sequence
340
+ * @returns {Result<T[], E>} A Result containing an array of values or the first error
341
+ *
342
+ * @category Combinations
343
+ * @example
344
+ * // Validating multiple inputs
345
+ * const results = [
346
+ * validateEmail('user@example.com'),
347
+ * validateEmail('admin@example.com'),
348
+ * validateEmail('test@example.com')
349
+ * ];
350
+ *
351
+ * const allEmails = Result.sequence(results);
352
+ * // If all valid: { success: true, data: ['user@...', 'admin@...', 'test@...'] }
353
+ * // If any invalid: { success: false, error: 'Invalid email format' }
354
+ *
355
+ * @see combineWithAllErrors - Collects all errors instead of short-circuiting
356
+ * @since 2025-07-03
357
+ */
358
+ sequence: <T, E>(results: Result<T, E>[]) => Result<T[], E>;
359
+ /**
360
+ * Filters a successful Result based on a predicate.
361
+ * @description If the predicate fails, returns a failure with the provided error.
362
+ * If the Result is already a failure, returns it unchanged. This allows
363
+ * adding validation to existing Results.
364
+ *
365
+ * @template T - The success type
366
+ * @template E - The error type
367
+ * @param {function(T): boolean} predicate - Function to test the success value
368
+ * @param {E} error - Error to return if the predicate fails
369
+ * @returns {function(Result<T, E>): Result<T, E>} A function that filters Results
370
+ *
371
+ * @category Validations
372
+ * @example
373
+ * // Adding validation
374
+ * const mustBePositive = Result.filter(
375
+ * (n: number) => n > 0,
376
+ * 'Number must be positive'
377
+ * );
378
+ *
379
+ * mustBePositive(Result.ok(42)); // => { success: true, data: 42 }
380
+ * mustBePositive(Result.ok(-1)); // => { success: false, error: 'Number must be positive' }
381
+ *
382
+ * @example
383
+ * // Chaining validations
384
+ * const validateAge = (age: number) => Result.ok(age)
385
+ * |> Result.filter(n => n >= 0, 'Age cannot be negative')
386
+ * |> Result.filter(n => n <= 150, 'Age seems unrealistic');
387
+ *
388
+ * @since 2025-07-03
389
+ */
390
+ filter: <T, E>(predicate: (data: T) => boolean, error: E) => (result: Result<T, E>) => Result<T, E>;
391
+ /**
392
+ * Provides a fallback Result if the original fails.
393
+ * @description The fallback function receives the error and returns a new Result.
394
+ * This allows error recovery and chaining of alternative operations.
395
+ *
396
+ * @template T - The success type
397
+ * @template E - The input error type
398
+ * @template F - The output error type
399
+ * @param {function(E): Result<T, F>} fallbackFn - Function to create a fallback Result
400
+ * @returns {function(Result<T, E>): Result<T, F>} A function that adds fallback logic
401
+ *
402
+ * @category Error Handling
403
+ * @example
404
+ * // Fallback to cache
405
+ * const getUser = Result.orElse(
406
+ * (error: string) => getCachedUser()
407
+ * )(fetchUserFromAPI());
408
+ *
409
+ * @example
410
+ * // Try multiple sources
411
+ * const config = Result.orElse(
412
+ * () => loadFromFile('./config.json')
413
+ * )(Result.orElse(
414
+ * () => loadFromEnv()
415
+ * )(loadFromDatabase()));
416
+ *
417
+ * @since 2025-07-03
418
+ */
419
+ orElse: <T, E, F>(fallbackFn: (error: E) => Result<T, F>) => (result: Result<T, E>) => Result<T, F>;
420
+ /**
421
+ * Combines an array of Results, collecting ALL errors instead of short-circuiting.
422
+ * @description If all succeed, returns an array of values. If any fail, returns
423
+ * an array of all errors. This is useful for validation scenarios where you
424
+ * want to report all errors at once rather than stopping at the first one.
425
+ *
426
+ * @template T - The success type of each Result
427
+ * @template E - The error type of each Result
428
+ * @param {Result<T, E>[]} results - Array of Results to combine
429
+ * @returns {Result<T[], E[]>} Success with all values or failure with all errors
430
+ *
431
+ * @category Combinations
432
+ * @example
433
+ * // Form validation with all errors
434
+ * const validations = [
435
+ * validateName(form.name),
436
+ * validateEmail(form.email),
437
+ * validateAge(form.age)
438
+ * ];
439
+ *
440
+ * const result = Result.combineWithAllErrors(validations);
441
+ * // If any fail: { success: false, error: ['Invalid name', 'Invalid email'] }
442
+ * // If all succeed: { success: true, data: ['John', 'john@example.com', 25] }
443
+ *
444
+ * @see sequence - Short-circuits on first error
445
+ * @since 2025-07-03
446
+ */
447
+ combineWithAllErrors: <T, E>(results: Result<T, E>[]) => Result<T[], E[]>;
448
+ /**
449
+ * Checks if a Result is successful.
450
+ * @description Type guard that narrows a Result to its success case.
451
+ * Useful in conditional statements and array filtering.
452
+ *
453
+ * @template T - The success type
454
+ * @template E - The error type
455
+ * @param {Result<T, E>} result - The Result to check
456
+ * @returns {result is { success: true; data: T }} True if the Result is successful
457
+ *
458
+ * @category Type Guards
459
+ * @example
460
+ * // Type narrowing
461
+ * const result = divide(10, 2);
462
+ * if (Result.isOk(result)) {
463
+ * console.log(result.data); // TypeScript knows data exists
464
+ * }
465
+ *
466
+ * @example
467
+ * // Filtering arrays
468
+ * const results = [Result.ok(1), Result.err('error'), Result.ok(2)];
469
+ * const successes = results.filter(Result.isOk);
470
+ * // => [{ success: true, data: 1 }, { success: true, data: 2 }]
471
+ *
472
+ * @see isErr - Check if Result is a failure
473
+ * @since 2025-07-03
474
+ */
475
+ isOk: <T, E>(result: Result<T, E>) => result is {
476
+ success: true;
477
+ data: T;
478
+ };
479
+ /**
480
+ * Checks if a Result is a failure.
481
+ * @description Type guard that narrows a Result to its failure case.
482
+ * Useful in conditional statements and error handling.
483
+ *
484
+ * @template T - The success type
485
+ * @template E - The error type
486
+ * @param {Result<T, E>} result - The Result to check
487
+ * @returns {result is { success: false; error: E }} True if the Result is a failure
488
+ *
489
+ * @category Type Guards
490
+ * @example
491
+ * // Error handling
492
+ * const result = parseJSON(input);
493
+ * if (Result.isErr(result)) {
494
+ * logger.error(result.error); // TypeScript knows error exists
495
+ * }
496
+ *
497
+ * @example
498
+ * // Collecting errors
499
+ * const results = processItems(items);
500
+ * const errors = results.filter(Result.isErr).map(r => r.error);
501
+ *
502
+ * @see isOk - Check if Result is successful
503
+ * @since 2025-07-03
504
+ */
505
+ isErr: <T, E>(result: Result<T, E>) => result is {
506
+ success: false;
507
+ error: E;
508
+ };
509
+ /**
510
+ * Converts a promise that might throw into a Result.
511
+ * @description Catches exceptions and converts them to error Results.
512
+ * This bridges the gap between exception-based and Result-based error handling.
513
+ *
514
+ * @template T - The type of the resolved value
515
+ * @param {Promise<T>} promise - The promise that might reject
516
+ * @returns {Promise<Result<T, Error>>} A promise of a Result
517
+ *
518
+ * @category Interop
519
+ * @example
520
+ * // Converting async operations
521
+ * const result = await Result.fromPromise(
522
+ * fetch('/api/user').then(r => r.json())
523
+ * );
524
+ *
525
+ * if (Result.isOk(result)) {
526
+ * console.log('User:', result.data);
527
+ * } else {
528
+ * console.error('Failed:', result.error.message);
529
+ * }
530
+ *
531
+ * @example
532
+ * // With async/await
533
+ * async function safeReadFile(path: string): Promise<Result<string, Error>> {
534
+ * return Result.fromPromise(
535
+ * fs.promises.readFile(path, 'utf-8')
536
+ * );
537
+ * }
538
+ *
539
+ * @since 2025-07-03
540
+ */
541
+ fromPromise: <T>(promise: Promise<T>) => Promise<Result<T, Error>>;
542
+ /**
543
+ * Converts a function that might throw into a Result-returning function.
544
+ * @description Wraps a function to catch any thrown exceptions and convert
545
+ * them to Result errors. This allows using exception-based APIs in a
546
+ * Result-based codebase.
547
+ *
548
+ * @template T - The tuple type of function arguments
549
+ * @template U - The return type of the function
550
+ * @param {function(...T): U} fn - Function that might throw
551
+ * @returns {function(...T): Result<U, Error>} A safe version that returns Results
552
+ *
553
+ * @category Interop
554
+ * @example
555
+ * // Wrapping JSON.parse
556
+ * const safeParseJSON = Result.fromThrowable(JSON.parse);
557
+ *
558
+ * const result = safeParseJSON('{"name": "John"}');
559
+ * // => { success: true, data: { name: 'John' } }
560
+ *
561
+ * const invalid = safeParseJSON('invalid json');
562
+ * // => { success: false, error: Error(...) }
563
+ *
564
+ * @example
565
+ * // Wrapping custom functions
566
+ * function riskyOperation(x: number): number {
567
+ * if (x < 0) throw new Error('Cannot process negative numbers');
568
+ * return Math.sqrt(x);
569
+ * }
570
+ *
571
+ * const safeSqrt = Result.fromThrowable(riskyOperation);
572
+ *
573
+ * @since 2025-07-03
574
+ */
575
+ fromThrowable: <T extends unknown[], U>(fn: (...args: T) => U) => (...args: T) => Result<U, Error>;
576
+ };
577
+ /**
578
+ * Utility type guard for checking if a value is a Result.
579
+ * @description Runtime type guard that checks if an unknown value conforms to
580
+ * the Result type structure. Useful for validation and type narrowing at
581
+ * runtime boundaries.
582
+ *
583
+ * @template T - The expected success type
584
+ * @template E - The expected error type
585
+ * @param {any} value - The value to check
586
+ * @returns {value is Result<T, E>} True if the value is a valid Result
587
+ *
588
+ * @category Type Guards
589
+ * @example
590
+ * // API response validation
591
+ * function handleResponse(data: unknown): void {
592
+ * if (isResult(data)) {
593
+ * if (data.success) {
594
+ * console.log('Success:', data.data);
595
+ * } else {
596
+ * console.error('Error:', data.error);
597
+ * }
598
+ * } else {
599
+ * console.error('Invalid response format');
600
+ * }
601
+ * }
602
+ *
603
+ * @example
604
+ * // Type narrowing in mixed arrays
605
+ * const mixed = [Result.ok(1), 'not a result', Result.err('error')];
606
+ * const results = mixed.filter(isResult);
607
+ * // TypeScript knows results contains only Result types
608
+ *
609
+ * @since 2025-07-03
610
+ */
611
+ export declare const isResult: <T, E>(value: any) => value is Result<T, E>;
612
+ /**
613
+ * Helper function to unwrap a Result, throwing if it's an error.
614
+ * @description Use sparingly, only when you're certain the Result should be successful.
615
+ * This function bridges Result-based code with exception-based code, but defeats
616
+ * the purpose of using Results for explicit error handling.
617
+ *
618
+ * @template T - The success type
619
+ * @template E - The error type
620
+ * @param {Result<T, E>} result - The Result to unwrap
621
+ * @returns {T} The success value
622
+ * @throws {Error} If the Result is a failure
623
+ *
624
+ * @category Extraction
625
+ * @example
626
+ * // In tests where you expect success
627
+ * test('calculation succeeds', () => {
628
+ * const result = calculate(10, 2);
629
+ * expect(unwrap(result)).toBe(5);
630
+ * });
631
+ *
632
+ * @example
633
+ * // At system boundaries where errors are exceptional
634
+ * const config = unwrap(loadConfig());
635
+ * // If this fails, the app cannot start anyway
636
+ *
637
+ * @warning Avoid using unwrap in normal application flow.
638
+ * Prefer Result.fold, Result.getOrElse, or pattern matching.
639
+ *
640
+ * @since 2025-07-03
641
+ */
642
+ export declare const unwrap: <T, E>(result: Result<T, E>) => T;
643
+ /**
644
+ * Helper function to safely access nested properties that might not exist.
645
+ * @description Returns a Result instead of throwing or returning undefined.
646
+ * This provides a safe way to access deeply nested properties without
647
+ * optional chaining or null checks.
648
+ *
649
+ * @template T - The type of the object
650
+ * @template U - The type of the extracted value
651
+ * @param {function(T): U} getter - Function that extracts a value from the object
652
+ * @param {string} errorMessage - Error message if extraction fails
653
+ * @returns {function(T): Result<U, string>} A function that safely extracts values
654
+ *
655
+ * @category Utilities
656
+ * @example
657
+ * // Safe property access
658
+ * interface User {
659
+ * profile?: {
660
+ * address?: {
661
+ * city?: string;
662
+ * };
663
+ * };
664
+ * }
665
+ *
666
+ * const getCity = safe((user: User) => user.profile!.address!.city!);
667
+ *
668
+ * const result = getCity({ profile: { address: { city: 'NYC' } } });
669
+ * // => { success: true, data: 'NYC' }
670
+ *
671
+ * const missing = getCity({});
672
+ * // => { success: false, error: 'Property access failed' }
673
+ *
674
+ * @example
675
+ * // Custom error messages
676
+ * const getName = safe(
677
+ * (data: any) => data.user.name as string,
678
+ * 'User name not found'
679
+ * );
680
+ *
681
+ * @since 2025-07-03
682
+ */
683
+ export declare const safe: <T, U>(getter: (obj: T) => U, errorMessage?: string) => (obj: T) => Result<U, string>;
684
+ //# sourceMappingURL=result.d.mts.map