wellcrafted 0.17.0 → 0.19.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.
@@ -1,455 +1,3 @@
1
- //#region src/result/result.d.ts
2
- /**
3
- * Represents the successful outcome of an operation, encapsulating the success value.
4
- *
5
- * This is the 'Ok' variant of the `Result` type. It holds a `data` property
6
- * of type `T` (the success value) and an `error` property explicitly set to `null`,
7
- * signifying no error occurred.
8
- *
9
- * Use this type in conjunction with `Err<E>` and `Result<T, E>`.
10
- *
11
- * @template T - The type of the success value contained within.
12
- */
13
- type Ok<T> = {
14
- data: T;
15
- error: null;
16
- };
17
- /**
18
- * Represents the failure outcome of an operation, encapsulating the error value.
19
- *
20
- * This is the 'Err' variant of the `Result` type. It holds an `error` property
21
- * of type `E` (the error value) and a `data` property explicitly set to `null`,
22
- * signifying that no success value is present due to the failure.
23
- *
24
- * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.
25
- *
26
- * @template E - The type of the error value contained within.
27
- */
28
- type Err<E> = {
29
- error: E;
30
- data: null;
31
- };
32
- /**
33
- * A type that represents the outcome of an operation that can either succeed or fail.
34
- *
35
- * `Result<T, E>` is a discriminated union type with two possible variants:
36
- * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.
37
- * In this case, the `error` field is `null`.
38
- * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.
39
- * In this case, the `data` field is `null`.
40
- *
41
- * This type promotes explicit error handling by requiring developers to check
42
- * the variant of the `Result` before accessing its potential value or error.
43
- * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).
44
- *
45
- * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).
46
- * @template E - The type of the error value if the operation fails (held in `Err<E>`).
47
- * @example
48
- * ```ts
49
- * function divide(numerator: number, denominator: number): Result<number, string> {
50
- * if (denominator === 0) {
51
- * return Err("Cannot divide by zero");
52
- * }
53
- * return Ok(numerator / denominator);
54
- * }
55
- *
56
- * const result1 = divide(10, 2);
57
- * if (isOk(result1)) {
58
- * console.log("Success:", result1.data); // Output: Success: 5
59
- * }
60
- *
61
- * const result2 = divide(10, 0);
62
- * if (isErr(result2)) {
63
- * console.error("Failure:", result2.error); // Output: Failure: Cannot divide by zero
64
- * }
65
- * ```
66
- */
67
- type Result<T, E> = Ok<T> | Err<E>;
68
- /**
69
- * Constructs an `Ok<T>` variant, representing a successful outcome.
70
- *
71
- * This factory function creates the success variant of a `Result`.
72
- * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.
73
- *
74
- * @template T - The type of the success value.
75
- * @param data - The success value to be wrapped in the `Ok` variant.
76
- * @returns An `Ok<T>` object with the provided data and `error` set to `null`.
77
- * @example
78
- * ```ts
79
- * const successfulResult = Ok("Operation completed successfully");
80
- * // successfulResult is { data: "Operation completed successfully", error: null }
81
- * ```
82
- */
83
- declare const Ok: <T>(data: T) => Ok<T>;
84
- /**
85
- * Constructs an `Err<E>` variant, representing a failure outcome.
86
- *
87
- * This factory function creates the error variant of a `Result`.
88
- * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
89
- *
90
- * @template E - The type of the error value.
91
- * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
92
- * @returns An `Err<E>` object with the provided error and `data` set to `null`.
93
- * @example
94
- * ```ts
95
- * const failedResult = Err(new TypeError("Invalid input"));
96
- * // failedResult is { error: TypeError("Invalid input"), data: null }
97
- * ```
98
- */
99
- declare const Err: <E>(error: E) => Err<E>;
100
- /**
101
- * Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.
102
- *
103
- * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
104
- * to `Ok<string>`. This can be useful in generic contexts or for type narrowing.
105
- *
106
- * @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.
107
- * Must extend `Result<unknown, unknown>`.
108
- */
109
- type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<R, {
110
- error: null;
111
- }>;
112
- /**
113
- * Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.
114
- *
115
- * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
116
- * to `Err<Error>`. This can be useful in generic contexts or for type narrowing.
117
- *
118
- * @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.
119
- * Must extend `Result<unknown, unknown>`.
120
- */
121
- type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<R, {
122
- data: null;
123
- }>;
124
- /**
125
- * Utility type to extract the success value's type `T` from a `Result<T, E>` type.
126
- *
127
- * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),
128
- * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.
129
- * This is useful for obtaining the type of the `data` field when you know you have a success.
130
- *
131
- * @template R - The `Result<T, E>` type from which to extract the success value's type.
132
- * Must extend `Result<unknown, unknown>`.
133
- * @example
134
- * ```ts
135
- * type MyResult = Result<number, string>;
136
- * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number
137
- *
138
- * type MyErrorResult = Err<string>;
139
- * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never
140
- * ```
141
- */
142
- type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U> ? U : never;
143
- /**
144
- * Utility type to extract the error value's type `E` from a `Result<T, E>` type.
145
- *
146
- * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),
147
- * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.
148
- * This is useful for obtaining the type of the `error` field when you know you have a failure.
149
- *
150
- * @template R - The `Result<T, E>` type from which to extract the error value's type.
151
- * Must extend `Result<unknown, unknown>`.
152
- * @example
153
- * ```ts
154
- * type MyResult = Result<number, string>;
155
- * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string
156
- *
157
- * type MySuccessResult = Ok<number>;
158
- * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never
159
- * ```
160
- */
161
- type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<infer E> ? E : never;
162
- /**
163
- * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.
164
- *
165
- * A value is considered a valid `Result` if:
166
- * 1. It is a non-null object.
167
- * 2. It has both `data` and `error` properties.
168
- * 3. Exactly one of `data` or `error` is `null`. The other must be non-`null`.
169
- *
170
- * This function does not validate the types of `data` or `error` beyond `null` checks.
171
- *
172
- * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).
173
- * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).
174
- * @param value - The value to check.
175
- * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.
176
- * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.
177
- * @example
178
- * ```ts
179
- * declare const someValue: unknown;
180
- *
181
- * if (isResult<string, Error>(someValue)) {
182
- * // someValue is now typed as Result<string, Error>
183
- * if (isOk(someValue)) {
184
- * console.log(someValue.data); // string
185
- * } else {
186
- * console.error(someValue.error); // Error
187
- * }
188
- * }
189
- * ```
190
- */
191
- declare function isResult<T = unknown, E = unknown>(value: unknown): value is Result<T, E>;
192
- /**
193
- * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.
194
- *
195
- * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.
196
- * An `Ok<T>` variant is identified by its `error` property being `null`.
197
- *
198
- * @template T - The success value type.
199
- * @template E - The error value type.
200
- * @param result - The `Result<T, E>` to check.
201
- * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.
202
- * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.
203
- * @example
204
- * ```ts
205
- * declare const myResult: Result<number, string>;
206
- *
207
- * if (isOk(myResult)) {
208
- * // myResult is now typed as Ok<number>
209
- * console.log("Success value:", myResult.data); // myResult.data is number
210
- * }
211
- * ```
212
- */
213
- declare function isOk<T, E>(result: Result<T, E>): result is Ok<T>;
214
- /**
215
- * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.
216
- *
217
- * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.
218
- * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).
219
- *
220
- * @template T - The success value type.
221
- * @template E - The error value type.
222
- * @param result - The `Result<T, E>` to check.
223
- * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.
224
- * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.
225
- * @example
226
- * ```ts
227
- * declare const myResult: Result<number, string>;
228
- *
229
- * if (isErr(myResult)) {
230
- * // myResult is now typed as Err<string>
231
- * console.error("Error value:", myResult.error); // myResult.error is string
232
- * }
233
- * ```
234
- */
235
- declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
236
- /**
237
- * Executes a synchronous operation and wraps its outcome (success or failure) in a `Result<T, E>`.
238
- *
239
- * This function attempts to execute the `operation`.
240
- * - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.
241
- * - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to
242
- * the `mapError` function. `mapError` is responsible for transforming this `unknown`
243
- * exception into a well-typed error value of type `E`. This error value is then wrapped
244
- * in an `Err<E>` variant.
245
- *
246
- * @template T - The type of the success value returned by the `operation` if it succeeds.
247
- * @template E - The type of the error value produced by `mapError` if the `operation` fails.
248
- * @param options - An object containing the operation and error mapping function.
249
- * @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.
250
- * @param options.mapError - A function that takes the `unknown` exception caught from `options.try`
251
- * and transforms it into a specific error value of type `E`. This function
252
- * is crucial for creating a well-typed error for the `Err<E>` variant.
253
- * @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapError` provides an error value.
254
- * @example
255
- * ```ts
256
- * function parseJson(jsonString: string): Result<object, SyntaxError> {
257
- * return trySync({
258
- * try: () => JSON.parse(jsonString),
259
- * mapError: (err: unknown) => {
260
- * if (err instanceof SyntaxError) return err;
261
- * return new SyntaxError("Unknown parsing error");
262
- * }
263
- * });
264
- * }
265
- *
266
- * const validResult = parseJson('{"name":"Result"}'); // Ok<{name: string}>
267
- * const invalidResult = parseJson('invalid json'); // Err<SyntaxError>
268
- *
269
- * if (isOk(validResult)) console.log(validResult.data);
270
- * if (isErr(invalidResult)) console.error(invalidResult.error.message);
271
- * ```
272
- */
273
- declare function trySync<T, E>({
274
- try: operation,
275
- mapError
276
- }: {
277
- try: () => T;
278
- mapError: (error: unknown) => E;
279
- }): Result<T, E>;
280
- /**
281
- * Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.
282
- *
283
- * This function attempts to execute the asynchronous `operation`.
284
- * - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
285
- * - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,
286
- * the caught exception/rejection reason (of type `unknown`) is passed to the `mapError` function.
287
- * `mapError` is responsible for transforming this `unknown` error into a well-typed error value of type `E`.
288
- * This error value is then wrapped in an `Err<E>` variant.
289
- *
290
- * The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.
291
- *
292
- * @template T - The type of the success value the `Promise` from `operation` resolves to.
293
- * @template E - The type of the error value produced by `mapError` if the `operation` fails or rejects.
294
- * @param options - An object containing the asynchronous operation and error mapping function.
295
- * @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.
296
- * @param options.mapError - A function that takes the `unknown` exception/rejection reason caught from `options.try`
297
- * and transforms it into a specific error value of type `E`. This function
298
- * is crucial for creating a well-typed error for the `Err<E>` variant.
299
- * @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,
300
- * or `Err<E>` if it rejects/throws and `options.mapError` provides an error value.
301
- * @example
302
- * ```ts
303
- * async function fetchData(url: string): Promise<Result<Response, Error>> {
304
- * return tryAsync({
305
- * try: async () => fetch(url),
306
- * mapError: (err: unknown) => {
307
- * if (err instanceof Error) return err;
308
- * return new Error("Network request failed");
309
- * }
310
- * });
311
- * }
312
- *
313
- * async function processData() {
314
- * const result = await fetchData("/api/data");
315
- * if (isOk(result)) {
316
- * const response = result.data;
317
- * console.log("Data fetched:", await response.json());
318
- * } else {
319
- * console.error("Fetch error:", result.error.message);
320
- * }
321
- * }
322
- * processData();
323
- * ```
324
- */
325
- declare function tryAsync<T, E>({
326
- try: operation,
327
- mapError
328
- }: {
329
- try: () => Promise<T>;
330
- mapError: (error: unknown) => E;
331
- }): Promise<Result<T, E>>;
332
- /**
333
- * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.
334
- *
335
- * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:
336
- * - If `value` is an `Ok<T>` variant, returns the contained success value.
337
- * - If `value` is an `Err<E>` variant, throws the contained error value.
338
- * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),
339
- * returns it as-is.
340
- *
341
- * This is useful when working with APIs that might return either direct values or Results,
342
- * allowing you to normalize them to the actual value or propagate errors via throwing.
343
- *
344
- * Use `resolve` when the input might or might not be a Result.
345
- * Use `unwrap` when you know the input is definitely a Result.
346
- *
347
- * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.
348
- * @template E - The type of the error value (if `value` is `Err<E>`).
349
- * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.
350
- * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.
351
- * @throws The error value `E` if `value` is an `Err<E>` variant.
352
- *
353
- * @example
354
- * ```ts
355
- * // Example with an Ok variant
356
- * const okResult = Ok("success data");
357
- * const resolved = resolve(okResult); // "success data"
358
- *
359
- * // Example with an Err variant
360
- * const errResult = Err(new Error("failure"));
361
- * try {
362
- * resolve(errResult);
363
- * } catch (e) {
364
- * console.error(e.message); // "failure"
365
- * }
366
- *
367
- * // Example with a plain value
368
- * const plainValue = "plain data";
369
- * const resolved = resolve(plainValue); // "plain data"
370
- *
371
- * // Example with a function that might return Result or plain value
372
- * declare function mightReturnResult(): string | Result<string, Error>;
373
- * const outcome = mightReturnResult();
374
- * try {
375
- * const finalValue = resolve(outcome); // handles both cases
376
- * console.log("Final value:", finalValue);
377
- * } catch (e) {
378
- * console.error("Operation failed:", e);
379
- * }
380
- * ```
381
- */
382
- /**
383
- * Unwraps a `Result<T, E>`, returning the success value or throwing the error.
384
- *
385
- * This function extracts the data from a `Result`:
386
- * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.
387
- * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.
388
- *
389
- * Unlike `resolve`, this function expects the input to always be a `Result` type,
390
- * making it more direct for cases where you know you're working with a `Result`.
391
- *
392
- * @template T - The type of the success value contained in the `Ok<T>` variant.
393
- * @template E - The type of the error value contained in the `Err<E>` variant.
394
- * @param result - The `Result<T, E>` to unwrap.
395
- * @returns The success value of type `T` if the `Result` is `Ok<T>`.
396
- * @throws The error value of type `E` if the `Result` is `Err<E>`.
397
- *
398
- * @example
399
- * ```ts
400
- * // Example with an Ok variant
401
- * const okResult = Ok("success data");
402
- * const value = unwrap(okResult); // "success data"
403
- *
404
- * // Example with an Err variant
405
- * const errResult = Err(new Error("something went wrong"));
406
- * try {
407
- * unwrap(errResult);
408
- * } catch (error) {
409
- * console.error(error.message); // "something went wrong"
410
- * }
411
- *
412
- * // Usage in a function that returns Result
413
- * function divide(a: number, b: number): Result<number, string> {
414
- * if (b === 0) return Err("Division by zero");
415
- * return Ok(a / b);
416
- * }
417
- *
418
- * try {
419
- * const result = unwrap(divide(10, 2)); // 5
420
- * console.log("Result:", result);
421
- * } catch (error) {
422
- * console.error("Division failed:", error);
423
- * }
424
- * ```
425
- */
426
- declare function unwrap<T, E>(result: Result<T, E>): T;
427
- declare function resolve<T, E>(value: T | Result<T, E>): T;
428
- //# sourceMappingURL=result.d.ts.map
429
- //#endregion
430
- //#region src/result/utils.d.ts
431
- /**
432
- * Partitions an array of Result objects into two separate arrays based on their status.
433
- *
434
- * @template T - The success type
435
- * @template E - The error type
436
- * @param results - An array of Result objects to partition
437
- * @returns An object containing two arrays:
438
- * - `oks`: Array of successful Result objects (Ok<T>[])
439
- * - `errs`: Array of error Result objects (Err<E>[])
440
- *
441
- * @example
442
- * const results = [Ok(1), Err("error"), Ok(2)];
443
- * const { oks, errs } = partitionResults(results);
444
- * // oks = [Ok(1), Ok(2)]
445
- * // errs = [Err("error")]
446
- */
447
- declare function partitionResults<T, E>(results: Result<T, E>[]): {
448
- oks: Ok<T>[];
449
- errs: Err<E>[];
450
- };
451
- //# sourceMappingURL=utils.d.ts.map
452
-
453
- //#endregion
454
- export { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
455
- //# sourceMappingURL=index.d.ts.map
1
+ import { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-t0dngyiE.js";
2
+ import { partitionResults } from "../index-DRbikk8-.js";
3
+ export { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };