functype 0.18.0 → 0.20.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.
Files changed (67) hide show
  1. package/README.md +13 -11
  2. package/README.processed.md +2 -11
  3. package/dist/Brand-B-0nKo7I.d.ts +55 -0
  4. package/dist/Brand-Cfr5zy8F.js +2 -0
  5. package/dist/Brand-Cfr5zy8F.js.map +1 -0
  6. package/dist/Tuple-CKxIyX7l.d.ts +178 -0
  7. package/dist/Tuple-CgX4p79w.js +2 -0
  8. package/dist/Tuple-CgX4p79w.js.map +1 -0
  9. package/dist/branded/index.d.ts +2 -54
  10. package/dist/branded/index.js +1 -0
  11. package/dist/cli/index.d.ts +1 -0
  12. package/dist/cli/index.js +660 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/do/index.d.ts +4 -240
  15. package/dist/do/index.js +1 -0
  16. package/dist/either/index.d.ts +4 -2
  17. package/dist/either/index.js +1 -0
  18. package/dist/fpromise/index.d.ts +4 -373
  19. package/dist/fpromise/index.js +1 -0
  20. package/dist/index-Bnjlo4cT.d.ts +3575 -0
  21. package/dist/index.d.ts +4 -1934
  22. package/dist/index.js +1 -0
  23. package/dist/list/index.d.ts +4 -2
  24. package/dist/list/index.js +1 -0
  25. package/dist/map/index.d.ts +4 -58
  26. package/dist/map/index.js +1 -0
  27. package/dist/option/index.d.ts +4 -2
  28. package/dist/option/index.js +1 -0
  29. package/dist/set/index.d.ts +4 -2
  30. package/dist/set/index.js +1 -0
  31. package/dist/src-BOxI0-73.js +20 -0
  32. package/dist/src-BOxI0-73.js.map +1 -0
  33. package/dist/try/index.d.ts +4 -2
  34. package/dist/try/index.js +1 -0
  35. package/dist/tuple/index.d.ts +2 -75
  36. package/dist/tuple/index.js +1 -0
  37. package/package.json +31 -42
  38. package/dist/Either-Ccg0S1uS.d.ts +0 -1015
  39. package/dist/Typeable-DiGVtDnq.d.ts +0 -96
  40. package/dist/branded/index.mjs +0 -2
  41. package/dist/branded/index.mjs.map +0 -1
  42. package/dist/chunk-6ZIR6EKC.mjs +0 -38
  43. package/dist/chunk-6ZIR6EKC.mjs.map +0 -1
  44. package/dist/chunk-7JJIUQXK.mjs +0 -3
  45. package/dist/chunk-7JJIUQXK.mjs.map +0 -1
  46. package/dist/chunk-OR6V4TCO.mjs +0 -2
  47. package/dist/chunk-OR6V4TCO.mjs.map +0 -1
  48. package/dist/do/index.mjs +0 -2
  49. package/dist/do/index.mjs.map +0 -1
  50. package/dist/either/index.mjs +0 -2
  51. package/dist/either/index.mjs.map +0 -1
  52. package/dist/fpromise/index.mjs +0 -2
  53. package/dist/fpromise/index.mjs.map +0 -1
  54. package/dist/index.mjs +0 -2
  55. package/dist/index.mjs.map +0 -1
  56. package/dist/list/index.mjs +0 -2
  57. package/dist/list/index.mjs.map +0 -1
  58. package/dist/map/index.mjs +0 -2
  59. package/dist/map/index.mjs.map +0 -1
  60. package/dist/option/index.mjs +0 -2
  61. package/dist/option/index.mjs.map +0 -1
  62. package/dist/set/index.mjs +0 -2
  63. package/dist/set/index.mjs.map +0 -1
  64. package/dist/try/index.mjs +0 -2
  65. package/dist/try/index.mjs.map +0 -1
  66. package/dist/tuple/index.mjs +0 -2
  67. package/dist/tuple/index.mjs.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,1934 +1,4 @@
1
- import { Brand } from './branded/index.js';
2
- export { BrandedBoolean, BrandedBoolean as BrandedBooleanType, BrandedNumber, BrandedNumber as BrandedNumberType, BrandedString, BrandedString as BrandedStringType, ExtractBrand, Unwrap, createBrander, hasBrand, unwrap as unwrapBrand } from './branded/index.js';
3
- import { L as List, O as Option, E as Either, D as DoResult, F as FunctypeBase, a as Extractable, A as AsyncMonad, P as Promisable, b as Doable, T as Try, c as Traversable, M as Matchable } from './Either-Ccg0S1uS.js';
4
- export { u as Applicative, C as Collection, r as CollectionOps, s as ContainerOps, v as Functor, l as Functype, m as FunctypeCollection, e as Left, n as MatchableUtils, w as Monad, N as None, o as OptionConstructor, R as Right, p as Set, S as Some, d as TestEither, h as TypeCheckLeft, g as TypeCheckRight, q as TypeNames, k as isExtractable, f as isLeft, i as isRight, t as tryCatch, j as tryCatchAsync } from './Either-Ccg0S1uS.js';
5
- import { T as Type, F as Foldable, P as Pipe, S as Serializable, a as Typeable } from './Typeable-DiGVtDnq.js';
6
- export { E as ExtractTag, b as SerializationMethods, c as TypeableParams, i as isTypeable } from './Typeable-DiGVtDnq.js';
7
- import { FPromise } from './fpromise/index.js';
8
- export { ErrorContext, FPromiseCompanion } from './fpromise/index.js';
9
- export { $, Do, DoAsync, DoGenerator, EmptyListError, FailureError, FailureErrorType, LeftError, LeftErrorType, NoneError, isDoCapable, unwrap } from './do/index.js';
10
- export { Map, SafeTraversable } from './map/index.js';
11
- export { Tuple } from './tuple/index.js';
12
-
13
- /**
14
- * LazyList provides lazy evaluation for list operations.
15
- * Operations are deferred until the list is materialized.
16
- *
17
- * @example
18
- * // Basic lazy evaluation
19
- * const result = LazyList([1, 2, 3, 4, 5])
20
- * .map(x => x * 2)
21
- * .filter(x => x > 5)
22
- * .toArray() // [6, 8, 10]
23
- *
24
- * @example
25
- * // Infinite sequences with take
26
- * const fibonacci = LazyList.iterate([0, 1], ([a, b]) => [b, a + b])
27
- * .map(([a]) => a)
28
- * .take(10)
29
- * .toArray() // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
30
- */
31
- interface LazyList<A extends Type> extends Foldable<A>, Pipe<LazyList<A>>, Serializable<LazyList<A>>, Typeable<"LazyList"> {
32
- [Symbol.iterator](): Iterator<A>;
33
- map<B extends Type>(f: (a: A) => B): LazyList<B>;
34
- flatMap<B extends Type>(f: (a: A) => LazyList<B>): LazyList<B>;
35
- filter(predicate: (a: A) => boolean): LazyList<A>;
36
- take(n: number): LazyList<A>;
37
- drop(n: number): LazyList<A>;
38
- takeWhile(predicate: (a: A) => boolean): LazyList<A>;
39
- dropWhile(predicate: (a: A) => boolean): LazyList<A>;
40
- concat(other: LazyList<A>): LazyList<A>;
41
- zip<B extends Type>(other: LazyList<B>): LazyList<[A, B]>;
42
- toList(): List<A>;
43
- toArray(): A[];
44
- forEach(f: (a: A) => void): void;
45
- reduce<B extends Type>(f: (acc: B, a: A) => B, initial: B): B;
46
- find(predicate: (a: A) => boolean): Option<A>;
47
- some(predicate: (a: A) => boolean): boolean;
48
- every(predicate: (a: A) => boolean): boolean;
49
- count(): number;
50
- first(): Option<A>;
51
- last(): Option<A>;
52
- toString(): string;
53
- }
54
- /**
55
- * Lazy list implementation for efficient deferred computation
56
- * @example
57
- * // Process large datasets efficiently
58
- * const result = LazyList.range(1, 1000000)
59
- * .filter(x => x % 2 === 0)
60
- * .map(x => x * x)
61
- * .take(5)
62
- * .toArray() // [4, 16, 36, 64, 100]
63
- *
64
- * @example
65
- * // Infinite sequences
66
- * const primes = LazyList.iterate(2, n => n + 1)
67
- * .filter(isPrime)
68
- * .take(10)
69
- * .toArray() // First 10 prime numbers
70
- *
71
- * @example
72
- * // Combining operations
73
- * const evens = LazyList.range(0, 100, 2)
74
- * const odds = LazyList.range(1, 100, 2)
75
- * const combined = evens.zip(odds)
76
- * .map(([e, o]) => e + o)
77
- * .take(5)
78
- * .toArray() // [1, 5, 9, 13, 17]
79
- */
80
- declare const LazyList: (<A extends Type>(iterable: Iterable<A>) => LazyList<A>) & {
81
- /**
82
- * Create an empty LazyList
83
- * @example
84
- * const empty = LazyList.empty<number>()
85
- * empty.toArray() // []
86
- */
87
- empty: <A extends Type>() => LazyList<A>;
88
- /**
89
- * Create a LazyList from a single value
90
- * @example
91
- * const single = LazyList.of(42)
92
- * .map(x => x * 2)
93
- * .toArray() // [84]
94
- */
95
- of: <A extends Type>(value: A) => LazyList<A>;
96
- /**
97
- * Create a LazyList from multiple values
98
- */
99
- from: <A extends Type>(...values: A[]) => LazyList<A>;
100
- /**
101
- * Create an infinite LazyList by repeatedly applying a function
102
- * @example
103
- * // Powers of 2
104
- * const powers = LazyList.iterate(1, x => x * 2)
105
- * .take(10)
106
- * .toArray() // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
107
- *
108
- * @example
109
- * // Fibonacci sequence
110
- * const fib = LazyList.iterate([0, 1], ([a, b]) => [b, a + b])
111
- * .map(([a]) => a)
112
- * .take(8)
113
- * .toArray() // [0, 1, 1, 2, 3, 5, 8, 13]
114
- */
115
- iterate: <A extends Type>(initial: A, f: (a: A) => A) => LazyList<A>;
116
- /**
117
- * Create an infinite LazyList by repeatedly calling a function
118
- */
119
- generate: <A extends Type>(f: () => A) => LazyList<A>;
120
- /**
121
- * Create a LazyList of numbers from start to end (exclusive)
122
- * @example
123
- * LazyList.range(1, 6).toArray() // [1, 2, 3, 4, 5]
124
- * LazyList.range(0, 10, 2).toArray() // [0, 2, 4, 6, 8]
125
- * LazyList.range(10, 0, -1).toArray() // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
126
- *
127
- * @example
128
- * // Sum of squares from 1 to 100
129
- * const sum = LazyList.range(1, 101)
130
- * .map(x => x * x)
131
- * .reduce((a, b) => a + b, 0) // 338350
132
- */
133
- range: (start: number, end: number, step?: number) => LazyList<number>;
134
- /**
135
- * Create a LazyList that repeats a value n times (or infinitely if n is not provided)
136
- */
137
- repeat: <A extends Type>(value: A, n?: number) => LazyList<A>;
138
- /**
139
- * Create a LazyList that cycles through an iterable infinitely
140
- */
141
- cycle: <A extends Type>(iterable: Iterable<A>) => LazyList<A>;
142
- };
143
-
144
- interface ValidatedBrandCompanion<K extends string, T> {
145
- readonly brand: K;
146
- readonly validate: (value: T) => boolean;
147
- readonly of: (value: T) => Option<ValidatedBrand<K, T>>;
148
- readonly from: (value: T) => Either<string, ValidatedBrand<K, T>>;
149
- readonly unsafeOf: (value: T) => ValidatedBrand<K, T>;
150
- readonly is: (value: unknown) => value is ValidatedBrand<K, T>;
151
- readonly unwrap: (branded: Brand<K, T>) => T;
152
- readonly refine: <K2 extends string>(brand: K2, validate: (value: Brand<K, T>) => boolean) => ValidatedBrandCompanion<K2, Brand<K, T>>;
153
- }
154
- type ValidatedBrand<K extends string, T> = Brand<K, T> & {
155
- readonly __validated: true;
156
- };
157
- /**
158
- * Create a validated brand with runtime validation
159
- * @example
160
- * const Email = ValidatedBrand("Email", (s: string) => /^[^@]+@[^@]+\.[^@]+$/.test(s))
161
- * const email = Email.of("user@example.com") // Some(Brand<"Email", string>)
162
- *
163
- * @example
164
- * // With Either for error messages
165
- * const Port = ValidatedBrand("Port", (n: number) => n >= 1 && n <= 65535)
166
- * const result = Port.from(8080) // Right(Brand<"Port", number>)
167
- * const error = Port.from(70000) // Left("Invalid Port: validation failed")
168
- *
169
- * @example
170
- * // Type guard usage
171
- * const value: unknown = "test@example.com"
172
- * if (Email.is(value)) {
173
- * // value is Brand<"Email", string>
174
- * }
175
- *
176
- * @example
177
- * // Best Practice: Use same brand name for seamless conversion
178
- * // ValidatedBrand extends Brand, so when using the same brand name,
179
- * // no casting is needed for conversion
180
- * const ValidatedUserId = ValidatedBrand("UserId", (s: string) => s.length > 0)
181
- * type ValidatedUserId = ReturnType<typeof ValidatedUserId.of> extends Option<infer T> ? T : never
182
- * type UserId = Brand<"UserId", string>
183
- *
184
- * const toSimpleUserId = (id: ValidatedUserId): UserId => id // No cast needed!
185
- *
186
- * // Avoid different brand names which require casting:
187
- * // ❌ ValidatedBrand("ValidatedUserId", ...) + Brand<"UserId", string>
188
- * // ✅ ValidatedBrand("UserId", ...) + Brand<"UserId", string>
189
- */
190
- declare function ValidatedBrand<K extends string, T>(brand: K, validate: (value: T) => boolean): ValidatedBrandCompanion<K, T>;
191
- /**
192
- * Positive number brand (> 0)
193
- * @example
194
- * const price = PositiveNumber.of(19.99) // Some(Brand<"PositiveNumber", number>)
195
- * const invalid = PositiveNumber.of(-5) // None
196
- * const checked = PositiveNumber.from(0) // Left("Invalid PositiveNumber: validation failed")
197
- */
198
- declare const PositiveNumber: ValidatedBrandCompanion<"PositiveNumber", number>;
199
- declare const NonNegativeNumber: ValidatedBrandCompanion<"NonNegativeNumber", number>;
200
- declare const IntegerNumber: ValidatedBrandCompanion<"IntegerNumber", number>;
201
- declare const PositiveInteger: ValidatedBrandCompanion<"PositiveInteger", Brand<"PositiveNumber", number>>;
202
- /**
203
- * Non-empty string brand
204
- * @example
205
- * const name = NonEmptyString.of("John") // Some(Brand<"NonEmptyString", string>)
206
- * const empty = NonEmptyString.of("") // None
207
- */
208
- declare const NonEmptyString: ValidatedBrandCompanion<"NonEmptyString", string>;
209
- /**
210
- * Email address brand with basic validation
211
- * @example
212
- * const email = EmailAddress.of("user@example.com") // Some(Brand<"EmailAddress", string>)
213
- * const invalid = EmailAddress.of("not-an-email") // None
214
- *
215
- * @example
216
- * // Using with forms
217
- * const processEmail = (input: string) => {
218
- * return EmailAddress.from(input)
219
- * .map(email => sendWelcomeEmail(email))
220
- * .orElse("Invalid email address")
221
- * }
222
- */
223
- declare const EmailAddress: ValidatedBrandCompanion<"EmailAddress", string>;
224
- declare const UrlString: ValidatedBrandCompanion<"UrlString", string>;
225
- declare const UUID: ValidatedBrandCompanion<"UUID", string>;
226
- declare const ISO8601Date: ValidatedBrandCompanion<"ISO8601Date", string>;
227
- /**
228
- * Create a number brand with min/max bounds
229
- * @example
230
- * const Percentage = BoundedNumber("Percentage", 0, 100)
231
- * const valid = Percentage.of(75) // Some(Brand<"Percentage", number>)
232
- * const invalid = Percentage.of(150) // None
233
- *
234
- * @example
235
- * const Port = BoundedNumber("Port", 1, 65535)
236
- * const httpPort = Port.unsafeOf(80) // Brand<"Port", number>
237
- * // Port.unsafeOf(70000) // throws Error
238
- */
239
- declare function BoundedNumber(brand: string, min: number, max: number): ValidatedBrandCompanion<string, number>;
240
- /**
241
- * Create a string brand with length constraints
242
- * @example
243
- * const Username = BoundedString("Username", 3, 20)
244
- * const valid = Username.of("johndoe") // Some(Brand<"Username", string>)
245
- * const tooShort = Username.of("jo") // None
246
- * const tooLong = Username.of("verylongusernamethatexceedslimit") // None
247
- */
248
- declare function BoundedString(brand: string, minLength: number, maxLength: number): ValidatedBrandCompanion<string, string>;
249
- /**
250
- * Create a string brand that matches a regex pattern
251
- * @example
252
- * const HexColor = PatternString("HexColor", /^#[0-9a-f]{6}$/i)
253
- * const red = HexColor.of("#ff0000") // Some(Brand<"HexColor", string>)
254
- * const invalid = HexColor.of("red") // None
255
- *
256
- * @example
257
- * const PhoneNumber = PatternString("PhoneNumber", /^\+?[1-9]\d{1,14}$/)
258
- * const phone = PhoneNumber.from("+1234567890")
259
- * .map(p => formatPhoneNumber(p))
260
- * .orElse("Invalid phone number")
261
- */
262
- declare function PatternString(brand: string, pattern: RegExp): ValidatedBrandCompanion<string, string>;
263
-
264
- /**
265
- * Creates a function-object hybrid similar to Scala's companion objects.
266
- * This utility allows creating TypeScript function objects with attached methods,
267
- * mimicking Scala's class + companion object pattern without using classes.
268
- *
269
- * @param object The main function that will be invoked when the object is called
270
- * @param companion Additional static methods to attach to the function
271
- * @returns A function with the attached methods
272
- *
273
- * @example
274
- * const greet = (name: string) => `Hello, ${name}!`;
275
- * const methods = {
276
- * formal: (name: string) => `Good day, ${name}.`,
277
- * casual: (name: string) => `Hey ${name}!`
278
- * };
279
- * const Greeter = createCompanionObject(greet, methods);
280
- *
281
- * // Usage:
282
- * Greeter("World"); // Hello, World!
283
- * Greeter.formal("Sir"); // Good day, Sir.
284
- * Greeter.casual("Friend"); // Hey Friend!
285
- */
286
- declare function Companion<ObjectF extends object, CompanionF extends object>(object: ObjectF, companion: CompanionF): ObjectF & CompanionF;
287
-
288
- /**
289
- * Helper types for working with the Companion pattern
290
- * @module CompanionTypes
291
- */
292
- /**
293
- * Extracts the companion methods type from a Companion object
294
- * @typeParam T - The Companion type
295
- * @example
296
- * ```typescript
297
- * type OptionCompanionMethods = CompanionMethods<typeof Option>
298
- * // { from: ..., none: ..., fromJSON: ..., etc. }
299
- * ```
300
- */
301
- type CompanionMethods<T> = T extends ((...args: never[]) => unknown) & infer C ? C : never;
302
- /**
303
- * Extracts the instance type from a constructor function
304
- * @typeParam T - The constructor function type
305
- * @example
306
- * ```typescript
307
- * type OptionInstance = InstanceType<typeof Option>
308
- * // Option<T>
309
- * ```
310
- */
311
- type InstanceType<T> = T extends (...args: infer Args) => infer R ? R extends (...args: unknown[]) => unknown ? ReturnType<R> : R : never;
312
- /**
313
- * Type guard to check if a value is a Companion object (has both constructor and companion methods)
314
- * @param value - The value to check
315
- * @returns True if value is a Companion object
316
- */
317
- declare const isCompanion: (value: unknown) => value is ((...args: never[]) => unknown) & Record<string, unknown>;
318
-
319
- /** @internal */
320
- type LazyCondChain<T> = {
321
- when: (condition: () => boolean, value: () => T) => LazyCondChain<T>;
322
- elseWhen: (condition: () => boolean, value: () => T) => LazyCondChain<T>;
323
- else: (value: () => T) => T;
324
- };
325
- /**
326
- * Conditional expression that enforces exhaustive returns without early returns.
327
- * Similar to Scala's if/else expressions that always return a value.
328
- *
329
- * @example
330
- * const discount = Cond.of<number>()
331
- * .when(isPremiumMember, 0.2)
332
- * .elseWhen(isRegularMember, 0.1)
333
- * .else(0)
334
- *
335
- * @example
336
- * // Chaining multiple conditions
337
- * const status = Cond.of<string>()
338
- * .when(response.status >= 500, "Server Error")
339
- * .elseWhen(response.status >= 400, "Client Error")
340
- * .elseWhen(response.status >= 200, "Success")
341
- * .else("Unknown")
342
- */
343
- type Cond<T extends Type> = {
344
- /**
345
- * Add an if condition
346
- */
347
- when: (condition: boolean, value: T | (() => T)) => Cond<T>;
348
- /**
349
- * Add an else-if condition
350
- */
351
- elseWhen: (condition: boolean, value: T | (() => T)) => Cond<T>;
352
- /**
353
- * Terminal else clause - required to get the result
354
- */
355
- else: (value: T | (() => T)) => T;
356
- /**
357
- * Get the result if a condition was met, throws if no condition met
358
- */
359
- orThrow: () => T;
360
- };
361
- /**
362
- * Conditional expression builder for functional if/else chains
363
- * @example
364
- * // Basic usage
365
- * const size = Cond.of<string>()
366
- * .when(value > 100, "large")
367
- * .elseWhen(value > 50, "medium")
368
- * .else("small")
369
- *
370
- * @example
371
- * // Pattern matching
372
- * const message = Cond.match(errorCode)({
373
- * 404: "Not Found",
374
- * 500: "Server Error",
375
- * 200: "OK"
376
- * })
377
- *
378
- * @example
379
- * // Lazy evaluation
380
- * const result = Cond.lazy<string>()
381
- * .when(() => checkCondition1(), () => "Result 1")
382
- * .when(() => checkCondition2(), () => "Result 2")
383
- * .else(() => "Default")
384
- */
385
- declare const Cond: (<T extends Type>() => Cond<T>) & {
386
- /**
387
- * Create a conditional expression that must end with else
388
- * @example
389
- * const x = 7
390
- * const result = Cond.of<string>()
391
- * .when(x > 10, "large")
392
- * .elseWhen(x > 5, "medium")
393
- * .else("small")
394
- * // result = "medium"
395
- *
396
- * @example
397
- * // With lazy evaluation
398
- * const discount = Cond.of<number>()
399
- * .when(isPremium, () => calculatePremiumDiscount())
400
- * .when(isLoyal, () => calculateLoyaltyDiscount())
401
- * .else(0)
402
- */
403
- of: <T extends Type>() => Cond<T>;
404
- /**
405
- * Pattern matching helper that ensures exhaustiveness
406
- * @example
407
- * type Status = "pending" | "success" | "error"
408
- * const status: Status = "success"
409
- * const result = Cond.match(status)({
410
- * "pending": "Waiting...",
411
- * "success": "Done!",
412
- * "error": "Failed!"
413
- * })
414
- * // result = "Done!"
415
- *
416
- * @example
417
- * // With function values
418
- * const action = "compute"
419
- * const result = Cond.match(action)({
420
- * "compute": () => expensiveComputation(),
421
- * "cache": () => getCachedValue(),
422
- * "skip": () => defaultValue
423
- * })
424
- */
425
- match: <T extends string | number | symbol>(value: T) => <R extends Type>(cases: Record<T, R | (() => R)>) => R;
426
- /**
427
- * Create a lazy conditional that defers evaluation
428
- * @example
429
- * // Only evaluates conditions and values when needed
430
- * const getMessage = Cond.lazy<string>()
431
- * .when(() => isError(), () => computeErrorMessage())
432
- * .when(() => isWarning(), () => computeWarningMessage())
433
- * .else(() => "Success")
434
- *
435
- * @example
436
- * // Complex conditional with expensive checks
437
- * const result = Cond.lazy<Action>()
438
- * .when(
439
- * () => user.role === "admin" && checkAdminPermissions(),
440
- * () => ({ type: "admin", permissions: loadAdminPermissions() })
441
- * )
442
- * .when(
443
- * () => user.role === "user" && user.isActive,
444
- * () => ({ type: "user", permissions: loadUserPermissions() })
445
- * )
446
- * .else(() => ({ type: "guest", permissions: [] }))
447
- */
448
- lazy: <T extends Type>() => LazyCondChain<T>;
449
- };
450
-
451
- /**
452
- * Type-level utilities for exhaustiveness checking
453
- * @internal
454
- */
455
- type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
456
- /** @internal */
457
- type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
458
- /** @internal */
459
- type RequireExhaustive<T, Cases> = IsUnion<T> extends true ? (keyof Cases extends T ? (T extends keyof Cases ? Cases : never) : never) : Cases;
460
- /**
461
- * Pattern types for nested matching
462
- * @internal
463
- */
464
- type Pattern<T> = T | {
465
- [K in keyof T]?: Pattern<T[K]>;
466
- } | ((value: T) => boolean) | {
467
- _: (value: T) => boolean;
468
- };
469
- /**
470
- * Extract result from pattern
471
- * @internal
472
- */
473
- type PatternResult<T, R> = R | ((matched: T) => R);
474
- /**
475
- * Pattern matching construct similar to Scala's match expressions.
476
- * Supports exhaustive matching, nested patterns, and guards.
477
- *
478
- * @example
479
- * // Basic pattern matching
480
- * const result = Match(value)
481
- * .case(x => x > 100, "large")
482
- * .case(x => x > 50, "medium")
483
- * .default("small")
484
- *
485
- * @example
486
- * // Matching exact values
487
- * const message = Match(status)
488
- * .caseValue("pending", "Please wait...")
489
- * .caseValue("success", "Completed!")
490
- * .caseValue("error", "Failed")
491
- * .default("Unknown")
492
- *
493
- * @example
494
- * // Nested pattern matching
495
- * const user = { name: "John", age: 30, role: "admin" }
496
- * const msg = Match(user)
497
- * .case({ role: "admin", age: n => n >= 18 }, "Adult admin")
498
- * .case({ role: "user" }, u => `User: ${u.name}`)
499
- * .default("Guest")
500
- */
501
- type Match<T extends Type, R extends Type> = {
502
- /**
503
- * Match against a pattern (value, nested object, or predicate)
504
- */
505
- case: (pattern: Pattern<T>, result: PatternResult<T, R>) => Match<T, R>;
506
- /**
507
- * Add a case that matches a specific value (backward compatibility)
508
- */
509
- caseValue: (match: T, result: R | (() => R)) => Match<T, R>;
510
- /**
511
- * Add a case that matches multiple values (backward compatibility)
512
- */
513
- caseValues: (matches: T[], result: R | (() => R)) => Match<T, R>;
514
- /**
515
- * Match with a guard function (alias for readability)
516
- */
517
- when: (guard: (value: T) => boolean, result: PatternResult<T, R>) => Match<T, R>;
518
- /**
519
- * Match multiple patterns (OR operation)
520
- */
521
- caseAny: (patterns: Pattern<T>[], result: PatternResult<T, R>) => Match<T, R>;
522
- /**
523
- * Default case - makes match non-exhaustive
524
- */
525
- default: (result: PatternResult<T, R>) => R;
526
- /**
527
- * Force exhaustive matching (compile-time check for union types)
528
- */
529
- exhaustive: () => R;
530
- /**
531
- * Get result if matched, throws if no match
532
- */
533
- orThrow: (errorMessage?: string) => R;
534
- /**
535
- * Get result wrapped in Option
536
- */
537
- toOption: () => Option<R>;
538
- };
539
- /**
540
- * Pattern matching utility for type-safe conditional logic with exhaustiveness checking,
541
- * nested patterns, and guard support
542
- *
543
- * @example
544
- * // Basic pattern matching
545
- * const result = Match(value)
546
- * .case(x => x > 0, "positive")
547
- * .case(x => x < 0, "negative")
548
- * .default("zero")
549
- *
550
- * @example
551
- * // Exhaustive matching for union types
552
- * type Color = "red" | "green" | "blue"
553
- * const hex = Match.exhaustive<Color, string>({
554
- * red: "#FF0000",
555
- * green: "#00FF00",
556
- * blue: "#0000FF"
557
- * })(color)
558
- *
559
- * @example
560
- * // Nested pattern matching
561
- * type User = { name: string; age: number; role: "admin" | "user" }
562
- * const user: User = { name: "John", age: 30, role: "admin" }
563
- *
564
- * const message = Match<User, string>(user)
565
- * .case({ role: "admin", age: (n) => n >= 18 }, "Adult admin")
566
- * .case({ role: "user" }, u => `User: ${u.name}`)
567
- * .default("Unknown")
568
- *
569
- * @example
570
- * // Using exhaustive() method
571
- * type Status = "idle" | "loading" | "success" | "error"
572
- * const result = Match<Status, string>("success")
573
- * .case("idle", "Waiting...")
574
- * .case("loading", "Loading...")
575
- * .case("success", "Done!")
576
- * .case("error", "Failed!")
577
- * .exhaustive()
578
- */
579
- declare const Match: (<T extends Type, R extends Type>(value: T) => Match<T, R>) & {
580
- /**
581
- * Create a type-safe exhaustive match for union types
582
- * @example
583
- * type Status = "pending" | "success" | "error"
584
- * const status: Status = "success"
585
- * const result = Match.exhaustive<Status, string>({
586
- * pending: "Waiting...",
587
- * success: "Done!",
588
- * error: "Failed!"
589
- * })(status)
590
- * // result = "Done!"
591
- *
592
- * @example
593
- * // For function values, wrap in object to prevent execution
594
- * type Operation = "add" | "subtract" | "multiply"
595
- * const ops = Match.exhaustive<Operation, { fn: (a: number, b: number) => number }>({
596
- * add: { fn: (a, b) => a + b },
597
- * subtract: { fn: (a, b) => a - b },
598
- * multiply: { fn: (a, b) => a * b }
599
- * })
600
- * const compute = ops("multiply").fn
601
- * const result = compute(4, 5) // 20
602
- */
603
- exhaustive: <T extends string | number | symbol, R extends Type>(cases: RequireExhaustive<T, Record<T, R>>) => (value: T) => R;
604
- /**
605
- * Create a partial match that requires a default
606
- * @example
607
- * const httpCode = 404
608
- * const message = Match.partial<number, string>({
609
- * 200: "OK",
610
- * 201: "Created",
611
- * 404: "Not Found",
612
- * 500: "Server Error"
613
- * }).withDefault("Unknown Status")(httpCode)
614
- * // message = "Not Found"
615
- *
616
- * @example
617
- * // With function default
618
- * const getMessage = Match.partial<number, string>({
619
- * 0: "Zero",
620
- * 1: "One",
621
- * 2: "Two"
622
- * }).withDefault((n) => `Number: ${n}`)
623
- * getMessage(5) // "Number: 5"
624
- */
625
- partial: <T extends string | number | symbol, R extends Type>(cases: Partial<Record<T, R | ((value: T) => R)>>) => {
626
- withDefault: (defaultValue: R | ((value: T) => R)) => (value: T) => R;
627
- };
628
- /**
629
- * Pattern match with guards
630
- * @example
631
- * const score = 85
632
- * const grade = Match.withGuards<number, string>([
633
- * [n => n >= 90, "A"],
634
- * [n => n >= 80, "B"],
635
- * [n => n >= 70, "C"],
636
- * [n => n >= 60, "D"]
637
- * ]).withDefault("F")(score)
638
- * // grade = "B"
639
- *
640
- * @example
641
- * // With function results for custom messages
642
- * const age = 25
643
- * const category = Match.withGuards<number, string>([
644
- * [n => n < 13, n => `Child (${n} years)`],
645
- * [n => n < 20, n => `Teenager (${n} years)`],
646
- * [n => n < 60, n => `Adult (${n} years)`],
647
- * [n => n >= 60, n => `Senior (${n} years)`]
648
- * ]).withDefault("Unknown")(age)
649
- * // category = "Adult (25 years)"
650
- */
651
- withGuards: <T extends Type, R extends Type>(guards: Array<[(value: T) => boolean, R | ((value: T) => R)]>) => {
652
- withDefault: (defaultValue: R | ((value: T) => R)) => (value: T) => R;
653
- };
654
- /**
655
- * Pattern matching for objects with specific structure
656
- * @example
657
- * type Event =
658
- * | { type: "click"; x: number; y: number }
659
- * | { type: "keypress"; key: string }
660
- * | { type: "hover"; element: string }
661
- *
662
- * const handler = Match.struct<Event, void>()
663
- * .case({ type: "click" }, (e) => console.log(`Click at ${e.x}, ${e.y}`))
664
- * .case({ type: "keypress", key: "Enter" }, () => console.log("Enter pressed"))
665
- * .case({ type: "hover" }, (e) => console.log(`Hovering over ${e.element}`))
666
- * .build()
667
- */
668
- struct: <T extends Type, R extends Type>() => {
669
- case: (pattern: Pattern<T>, handler: (value: T) => R) => /*elided*/ any;
670
- build: () => (value: T) => R;
671
- };
672
- /**
673
- * Create a pattern matcher with guards and nested patterns
674
- * @example
675
- * type User = {
676
- * name: string
677
- * age: number
678
- * permissions: string[]
679
- * }
680
- *
681
- * const canAccess = Match.builder<User, boolean>()
682
- * .when(u => u.permissions.includes("admin"), true)
683
- * .case({ age: n => n >= 18, permissions: p => p.length > 0 }, true)
684
- * .default(false)
685
- * .build()
686
- */
687
- builder: <T extends Type, R extends Type>() => {
688
- case: (pattern: Pattern<T>, result: PatternResult<T, R>) => /*elided*/ any;
689
- when: (guard: (value: T) => boolean, result: PatternResult<T, R>) => /*elided*/ any;
690
- default: (result: PatternResult<T, R>) => {
691
- build: () => (value: T) => R;
692
- };
693
- };
694
- };
695
-
696
- /**
697
- * Base Object from which most other objects inherit
698
- * Now includes automatic Do-notation support via doUnwrap method
699
- * @param type - The type name for the object
700
- * @param body - The implementation body
701
- */
702
- declare function Base<T extends Record<string, unknown>>(type: string, body: T): T & {
703
- toString(): string;
704
- doUnwrap(): DoResult<unknown>;
705
- _tag: string;
706
- };
707
-
708
- /**
709
- * The identifier name for Throwable type
710
- */
711
- declare const NAME: "Throwable";
712
- /**
713
- * @internal
714
- */
715
- type ThrowableType = Error & Typeable<typeof NAME> & {
716
- readonly data?: unknown;
717
- readonly cause?: Error;
718
- readonly taskInfo?: {
719
- name: string;
720
- description: string;
721
- };
722
- };
723
- declare class Throwable extends Error implements ThrowableType {
724
- readonly _tag: typeof NAME;
725
- readonly data?: unknown;
726
- readonly cause?: Error;
727
- readonly taskInfo?: {
728
- name: string;
729
- description: string;
730
- };
731
- protected constructor(message: string, options?: {
732
- data?: unknown | undefined;
733
- cause?: Error | undefined;
734
- stack?: string | undefined;
735
- taskInfo?: {
736
- name: string;
737
- description: string;
738
- } | undefined;
739
- });
740
- static apply(srcError: unknown, data?: unknown, taskInfo?: {
741
- name: string;
742
- description: string;
743
- }): ThrowableType;
744
- }
745
-
746
- /**
747
- * Type definition for errors with a _tag property that identifies them as Throwables
748
- */
749
- type TaggedThrowable = Error & {
750
- _tag: "Throwable";
751
- cause?: Error;
752
- taskInfo?: {
753
- name: string;
754
- description: string;
755
- };
756
- };
757
- /**
758
- * Type guard to check if an error is a TaggedThrowable
759
- */
760
- declare function isTaggedThrowable(error: unknown): error is TaggedThrowable;
761
- interface TaskParams {
762
- readonly name?: string;
763
- readonly description?: string;
764
- }
765
- interface TaskMetadata {
766
- readonly name: string;
767
- readonly description: string;
768
- }
769
- interface TaskOutcome<T> extends FunctypeBase<T, "Ok" | "Err">, Extractable<T>, AsyncMonad<T>, Promisable<T>, Doable<T> {
770
- readonly _tag: "Ok" | "Err";
771
- readonly _meta: TaskMetadata;
772
- readonly value?: T;
773
- readonly error?: Throwable;
774
- readonly map: <U>(f: (value: T) => U) => TaskOutcome<U>;
775
- readonly flatMap: <U>(f: (value: T) => TaskOutcome<U> | Either<Throwable, U>) => TaskOutcome<U>;
776
- readonly ap: <U>(ff: TaskOutcome<(value: T) => U>) => TaskOutcome<U>;
777
- readonly mapAsync: <U>(f: (value: T) => Promise<U>) => Promise<TaskOutcome<U>>;
778
- readonly flatMapAsync: <U>(f: (value: T) => Promise<TaskOutcome<U>>) => Promise<TaskOutcome<U>>;
779
- readonly mapError: (f: (error: Throwable) => Throwable) => TaskOutcome<T>;
780
- readonly recover: (value: T) => Ok<T>;
781
- readonly recoverWith: (f: (error: Throwable) => T) => Ok<T>;
782
- readonly isSuccess: () => this is Ok<T>;
783
- readonly isFailure: () => this is Err<T>;
784
- readonly isOk: () => this is Ok<T>;
785
- readonly isErr: () => this is Err<T>;
786
- readonly toEither: () => Either<Throwable, T>;
787
- readonly toTry: () => Try<T>;
788
- readonly toOption: () => Option<T>;
789
- readonly toList: () => List<T>;
790
- readonly fold: <U>(onErr: (error: Throwable) => U, onOk: (value: T) => U) => U;
791
- readonly match: <U>(patterns: {
792
- Ok: (value: T) => U;
793
- Err: (error: Throwable) => U;
794
- }) => U;
795
- }
796
- type TaskSuccess<T> = Ok<T>;
797
- type TaskFailure<T> = Err<T>;
798
- interface Err<T> extends TaskOutcome<T> {
799
- readonly _tag: "Err";
800
- readonly value: undefined;
801
- readonly error: Throwable;
802
- }
803
- /**
804
- * Err constructor - Creates a failed TaskOutcome
805
- * @param error - The error object
806
- * @param data - Additional data related to the error
807
- * @param params - Task parameters
808
- */
809
- declare const Err: <T>(error: unknown, data?: unknown, params?: TaskParams) => Err<T>;
810
- interface Ok<T> extends TaskOutcome<T> {
811
- readonly _tag: "Ok";
812
- readonly value: T;
813
- readonly error: undefined;
814
- }
815
- /**
816
- * Ok constructor - Creates a successful TaskOutcome
817
- * @param data - The successful value
818
- * @param params - Task parameters
819
- */
820
- declare const Ok: <T>(data: T, params?: TaskParams) => Ok<T>;
821
- type TaskResult<T> = Promise<TaskOutcome<T>>;
822
- /**
823
- * The CancellationToken is a control structure that allows long-running tasks to be cancelled
824
- * Cancellation is cooperative, meaning the task must check the token and respond to cancellation requests
825
- */
826
- type CancellationToken = {
827
- /** Whether the token has been cancelled */
828
- readonly isCancelled: boolean;
829
- /** Signal that can be used with fetch and other abortable APIs */
830
- readonly signal: AbortSignal;
831
- /** Register a callback to be called when cancellation occurs */
832
- onCancel(callback: () => void): void;
833
- };
834
- /**
835
- * Create a cancellation token and controller
836
- * The controller can be used to cancel operations that use the token
837
- */
838
- type CancellationTokenSource = {
839
- /** The token to be passed to cancellable operations */
840
- readonly token: CancellationToken;
841
- /** Cancel all operations using this token */
842
- cancel(): void;
843
- };
844
- /**
845
- * Create a cancellation token source
846
- * @returns A CancellationTokenSource that can be used to create and control cancellation tokens
847
- */
848
- declare const createCancellationTokenSource: () => CancellationTokenSource;
849
- type Sync<T> = TaskOutcome<T>;
850
- type Async<T> = TaskResult<T>;
851
- declare const Task: (<T = unknown>(params?: TaskParams) => {
852
- _type: string;
853
- /**
854
- * Run an async operation with explicit try/catch/finally semantics
855
- * Returns a raw Promise that can interact with traditional Promise-based code
856
- *
857
- * @param t - The main operation function that returns a value or Promise
858
- * @param e - Optional error handler function
859
- * @param f - Optional finally handler function
860
- * @param cancellationToken - Optional token for cancellation support
861
- */
862
- Async: <U = T>(t: () => U | Promise<U> | TaskOutcome<U> | Promise<TaskOutcome<U>>, e?: (error: unknown) => unknown | TaskOutcome<U>, f?: () => Promise<void> | void, cancellationToken?: CancellationToken) => FPromise<TaskOutcome<U>>;
863
- /**
864
- * Run a synchronous operation with explicit try/catch/finally semantics
865
- * Returns a TaskOutcome for functional error handling
866
- *
867
- * @param t - The main operation function that returns a value
868
- * @param e - Optional error handler function
869
- * @param f - Optional finally handler function
870
- */
871
- Sync: <U = T>(t: () => U, e?: (error: unknown) => unknown, f?: () => void) => TaskOutcome<U>;
872
- /**
873
- * Run an async operation with progress tracking capabilities
874
- * Returns a Promise and provides progress updates via callback
875
- *
876
- * @param t - The main operation that receives a progress updater function
877
- * @param onProgress - Callback that receives progress updates (0-100)
878
- * @param e - Optional error handler function
879
- * @param f - Optional finally handler function
880
- * @param cancellationToken - Optional token for cancellation support
881
- */
882
- AsyncWithProgress: <U = T>(t: (updateProgress: (percent: number) => void) => U | Promise<U> | TaskOutcome<U> | Promise<TaskOutcome<U>>, onProgress: (percent: number) => void, e?: (error: unknown) => unknown | TaskOutcome<U>, f?: () => Promise<void> | void, cancellationToken?: CancellationToken) => FPromise<TaskOutcome<U>>;
883
- toString(): string;
884
- doUnwrap(): DoResult<unknown>;
885
- _tag: string;
886
- }) & {
887
- /**
888
- * Create a successful Task result
889
- */
890
- success: <T>(data: T, params?: TaskParams) => Ok<T>;
891
- /**
892
- * Create a failed Task result
893
- */
894
- fail: <T>(error: unknown, data?: unknown, params?: TaskParams) => Err<T>;
895
- /**
896
- * Create a successful Task result (alias for success)
897
- * Preferred for new code
898
- */
899
- ok: <T>(data: T, params?: TaskParams) => Ok<T>;
900
- /**
901
- * Create a failed Task result (alias for fail)
902
- * Preferred for new code
903
- */
904
- err: <T>(error: unknown, data?: unknown, params?: TaskParams) => Err<T>;
905
- /**
906
- * Create TaskOutcome from Either
907
- * @param either - Either to convert
908
- * @param params - Task parameters
909
- */
910
- fromEither: <T>(either: Either<Throwable, T>, params?: TaskParams) => TaskOutcome<T>;
911
- /**
912
- * Create TaskOutcome from Try
913
- * @param tryValue - Try to convert
914
- * @param params - Task parameters
915
- */
916
- fromTry: <T>(tryValue: Try<T>, params?: TaskParams) => TaskOutcome<T>;
917
- /**
918
- * Extract the error chain from a Throwable error
919
- * Returns an array of errors from outermost to innermost
920
- *
921
- * @param error - The error to extract the chain from
922
- * @returns An array of errors in the chain, from outermost to innermost
923
- */
924
- getErrorChain: (error: Error | undefined) => Error[];
925
- /**
926
- * Format the error chain as a string with the option to include task details
927
- *
928
- * @param error - The error to format
929
- * @param options - Formatting options
930
- * @returns A formatted string representation of the error chain
931
- */
932
- formatErrorChain: (error: Error | undefined, options?: {
933
- includeTasks?: boolean;
934
- separator?: string;
935
- includeStackTrace?: boolean;
936
- }) => string;
937
- /**
938
- * Convert a Promise-returning function to a Task-compatible function
939
- */
940
- fromPromise: <U, Args extends unknown[]>(promiseFn: (...args: Args) => Promise<U>, params?: TaskParams) => ((...args: Args) => FPromise<TaskOutcome<U>>);
941
- /**
942
- * Convert a Task result to a Promise
943
- */
944
- toPromise: <U>(taskOutcome: TaskOutcome<U>) => Promise<U>;
945
- /**
946
- * Race multiple tasks and return the result of the first one to complete
947
- * Optionally specify a timeout after which the race will fail
948
- *
949
- * @param tasks - Array of tasks to race (as FPromises)
950
- * @param timeoutMs - Optional timeout in milliseconds
951
- * @param params - Task parameters for the race operation
952
- * @returns A promise that resolves with the first task to complete or rejects if all tasks fail
953
- */
954
- race: <T>(tasks: Array<FPromise<T> | FPromise<TaskOutcome<T>>>, timeoutMs?: number, params?: TaskParams) => FPromise<TaskOutcome<T>>;
955
- /**
956
- * Convert a Node.js style callback function to a Task-compatible function
957
- * Node.js callbacks typically have the signature (error, result) => void
958
- *
959
- * @param nodeFn - Function that accepts a Node.js style callback
960
- * @param params - Task parameters
961
- * @returns A function that returns an FPromise
962
- */
963
- fromNodeCallback: <T, Args extends unknown[]>(nodeFn: (...args: [...Args, (error: unknown, result: T) => void]) => void, params?: TaskParams) => ((...args: Args) => FPromise<TaskOutcome<T>>);
964
- /**
965
- * Create a cancellation token source
966
- * @returns A cancellation token source that can be used to control task cancellation
967
- */
968
- createCancellationTokenSource: () => CancellationTokenSource;
969
- /**
970
- * Create a task that can be cancelled
971
- *
972
- * @param task - The task function to make cancellable
973
- * @param params - Task parameters
974
- * @returns An object with the task and a function to cancel it
975
- */
976
- cancellable: <T>(task: (token: CancellationToken) => Promise<T> | Promise<TaskOutcome<T>>, params?: TaskParams) => {
977
- task: FPromise<TaskOutcome<T>>;
978
- cancel: () => void;
979
- };
980
- /**
981
- * Creates a task with progress tracking
982
- *
983
- * @param task - The task function that accepts a progress updater
984
- * @param onProgress - Callback function that receives progress updates
985
- * @param params - Task parameters
986
- * @returns An object with the task, cancel function, and current progress
987
- */
988
- withProgress: <T>(task: (updateProgress: (percent: number) => void, token: CancellationToken) => Promise<T> | Promise<TaskOutcome<T>>, onProgress?: (percent: number) => void, params?: TaskParams) => {
989
- task: FPromise<TaskOutcome<T>>;
990
- cancel: () => void;
991
- currentProgress: () => number;
992
- };
993
- };
994
- type Task = ReturnType<typeof Task>;
995
-
996
- /**
997
- * Type definition for task information that may be attached to errors
998
- */
999
- type TaskErrorInfo = {
1000
- name?: string;
1001
- description?: string;
1002
- [key: string]: unknown;
1003
- };
1004
- /**
1005
- * Type definition for an error with potential task information
1006
- */
1007
- type ErrorWithTaskInfo = Error & {
1008
- taskInfo?: TaskErrorInfo;
1009
- data?: unknown;
1010
- };
1011
- /**
1012
- * Type definition for a structured error chain element
1013
- */
1014
- type ErrorChainElement = {
1015
- message?: string;
1016
- name?: string;
1017
- taskInfo?: TaskErrorInfo;
1018
- stack?: string;
1019
- [key: string]: unknown;
1020
- };
1021
- /**
1022
- * Options for formatting error chains
1023
- */
1024
- type ErrorFormatterOptions = {
1025
- /** Include task names in the formatted output */
1026
- includeTasks?: boolean;
1027
- /** Include stack traces in the formatted output */
1028
- includeStackTrace?: boolean;
1029
- /** Separator between error lines (default: newline) */
1030
- separator?: string;
1031
- /** Include detailed error data in the output */
1032
- includeData?: boolean;
1033
- /** Maximum number of stack frames to include if stack trace is enabled */
1034
- maxStackFrames?: number;
1035
- /** Title to display at the start of the formatted error */
1036
- title?: string;
1037
- /** Format the output with colors for console display */
1038
- colors?: boolean;
1039
- };
1040
- /**
1041
- * Safely stringify data including BigInt values and circular references
1042
- */
1043
- declare function safeStringify(obj: unknown): string;
1044
- /**
1045
- * Format a stack trace string for better readability
1046
- */
1047
- declare function formatStackTrace(stack: string | undefined): string;
1048
- /**
1049
- * Create a formatted string representation of an error for better logging and display
1050
- *
1051
- * @example
1052
- * ```typescript
1053
- * const error = new Error("Something went wrong");
1054
- * console.error(formatError(error, { colors: true, includeData: true }));
1055
- * ```
1056
- */
1057
- declare function formatError(error: unknown, options?: ErrorFormatterOptions): string;
1058
- /**
1059
- * Create a serializer function for Pino or other JSON loggers
1060
- * to better represent errors with their full context
1061
- */
1062
- declare function createErrorSerializer(): (err: unknown) => unknown;
1063
-
1064
- declare const ParseError: (message?: string) => Error & {
1065
- name: "ParseError";
1066
- };
1067
- type ParseError = Error & {
1068
- name: "ParseError";
1069
- };
1070
-
1071
- /**
1072
- * Type-safe error codes using template literal types
1073
- */
1074
- type ErrorCode = "VALIDATION_FAILED" | "NETWORK_ERROR" | "AUTH_REQUIRED" | "NOT_FOUND" | "PERMISSION_DENIED" | "RATE_LIMITED" | "INTERNAL_ERROR" | "BAD_REQUEST" | "CONFLICT" | "TIMEOUT";
1075
- /**
1076
- * Template literal type for error messages based on error code
1077
- */
1078
- type ErrorMessage<T extends ErrorCode> = T extends "VALIDATION_FAILED" ? `Validation failed: ${string}` : T extends "NETWORK_ERROR" ? `Network error: ${string}` : T extends "AUTH_REQUIRED" ? `Authentication required: ${string}` : T extends "NOT_FOUND" ? `Not found: ${string}` : T extends "PERMISSION_DENIED" ? `Permission denied: ${string}` : T extends "RATE_LIMITED" ? `Rate limit exceeded: ${string}` : T extends "INTERNAL_ERROR" ? `Internal server error: ${string}` : T extends "BAD_REQUEST" ? `Bad request: ${string}` : T extends "CONFLICT" ? `Conflict: ${string}` : T extends "TIMEOUT" ? `Request timeout: ${string}` : never;
1079
- /**
1080
- * HTTP status codes mapped to error codes
1081
- */
1082
- type ErrorStatus<T extends ErrorCode> = T extends "VALIDATION_FAILED" | "BAD_REQUEST" ? 400 : T extends "AUTH_REQUIRED" ? 401 : T extends "PERMISSION_DENIED" ? 403 : T extends "NOT_FOUND" ? 404 : T extends "CONFLICT" ? 409 : T extends "RATE_LIMITED" ? 429 : T extends "TIMEOUT" ? 408 : T extends "INTERNAL_ERROR" ? 500 : T extends "NETWORK_ERROR" ? 503 : 500;
1083
- /**
1084
- * Context type for each error code
1085
- */
1086
- type TypedErrorContext<T extends ErrorCode> = T extends "VALIDATION_FAILED" ? {
1087
- field: string;
1088
- value: unknown;
1089
- rule: string;
1090
- } : T extends "NETWORK_ERROR" ? {
1091
- url: string;
1092
- method: string;
1093
- statusCode?: number;
1094
- } : T extends "AUTH_REQUIRED" ? {
1095
- resource: string;
1096
- requiredRole?: string;
1097
- } : T extends "NOT_FOUND" ? {
1098
- resource: string;
1099
- id: string | number;
1100
- } : T extends "PERMISSION_DENIED" ? {
1101
- action: string;
1102
- resource: string;
1103
- userId?: string;
1104
- } : T extends "RATE_LIMITED" ? {
1105
- limit: number;
1106
- window: string;
1107
- retryAfter?: number;
1108
- } : T extends "INTERNAL_ERROR" ? {
1109
- errorId: string;
1110
- timestamp: string;
1111
- } : T extends "BAD_REQUEST" ? {
1112
- reason: string;
1113
- expected?: string;
1114
- } : T extends "CONFLICT" ? {
1115
- resource: string;
1116
- conflictingValue: string;
1117
- } : T extends "TIMEOUT" ? {
1118
- duration: number;
1119
- operation: string;
1120
- } : Record<string, unknown>;
1121
- /**
1122
- * Type-safe error class with template literal types
1123
- */
1124
- interface TypedError<T extends ErrorCode> extends Throwable {
1125
- readonly code: T;
1126
- readonly message: ErrorMessage<T>;
1127
- readonly status: ErrorStatus<T>;
1128
- readonly context: TypedErrorContext<T>;
1129
- readonly timestamp: string;
1130
- readonly traceId?: string;
1131
- }
1132
- declare const TypedError: (<T extends ErrorCode>(code: T, message: ErrorMessage<T>, context: TypedErrorContext<T>, options?: {
1133
- cause?: unknown;
1134
- traceId?: string;
1135
- }) => TypedError<T>) & {
1136
- /**
1137
- * Create a validation error
1138
- * @example
1139
- * const error = TypedError.validation("email", "test@", "must be valid email")
1140
- * // Type: TypedError<"VALIDATION_FAILED">
1141
- * // Message must match: "Validation failed: ..."
1142
- */
1143
- validation: (field: string, value: unknown, rule: string) => TypedError<"VALIDATION_FAILED">;
1144
- /**
1145
- * Create a network error
1146
- * @example
1147
- * const error = TypedError.network("https://api.example.com", "POST", 500)
1148
- * // Type: TypedError<"NETWORK_ERROR">
1149
- */
1150
- network: (url: string, method: string, statusCode?: number) => TypedError<"NETWORK_ERROR">;
1151
- /**
1152
- * Create an authentication error
1153
- * @example
1154
- * const error = TypedError.auth("/api/admin", "admin")
1155
- * // Type: TypedError<"AUTH_REQUIRED">
1156
- */
1157
- auth: (resource: string, requiredRole?: string) => TypedError<"AUTH_REQUIRED">;
1158
- /**
1159
- * Create a not found error
1160
- * @example
1161
- * const error = TypedError.notFound("user", "123")
1162
- * // Type: TypedError<"NOT_FOUND">
1163
- */
1164
- notFound: (resource: string, id: string | number) => TypedError<"NOT_FOUND">;
1165
- /**
1166
- * Create a permission denied error
1167
- * @example
1168
- * const error = TypedError.permission("delete", "post", "user123")
1169
- * // Type: TypedError<"PERMISSION_DENIED">
1170
- */
1171
- permission: (action: string, resource: string, userId?: string) => TypedError<"PERMISSION_DENIED">;
1172
- /**
1173
- * Create a rate limit error
1174
- * @example
1175
- * const error = TypedError.rateLimit(100, "1h", 3600)
1176
- * // Type: TypedError<"RATE_LIMITED">
1177
- */
1178
- rateLimit: (limit: number, window: string, retryAfter?: number) => TypedError<"RATE_LIMITED">;
1179
- /**
1180
- * Create an internal error
1181
- * @example
1182
- * const error = TypedError.internal("ERR-500-ABC123")
1183
- * // Type: TypedError<"INTERNAL_ERROR">
1184
- */
1185
- internal: (errorId: string) => TypedError<"INTERNAL_ERROR">;
1186
- /**
1187
- * Create a bad request error
1188
- * @example
1189
- * const error = TypedError.badRequest("Invalid JSON", "valid JSON object")
1190
- * // Type: TypedError<"BAD_REQUEST">
1191
- */
1192
- badRequest: (reason: string, expected?: string) => TypedError<"BAD_REQUEST">;
1193
- /**
1194
- * Create a conflict error
1195
- * @example
1196
- * const error = TypedError.conflict("email", "user@example.com")
1197
- * // Type: TypedError<"CONFLICT">
1198
- */
1199
- conflict: (resource: string, conflictingValue: string) => TypedError<"CONFLICT">;
1200
- /**
1201
- * Create a timeout error
1202
- * @example
1203
- * const error = TypedError.timeout(30000, "database query")
1204
- * // Type: TypedError<"TIMEOUT">
1205
- */
1206
- timeout: (duration: number, operation: string) => TypedError<"TIMEOUT">;
1207
- /**
1208
- * Check if a value is a TypedError
1209
- */
1210
- isTypedError: (value: unknown) => value is TypedError<ErrorCode>;
1211
- /**
1212
- * Check if a TypedError has a specific code
1213
- */
1214
- hasCode: <T extends ErrorCode>(error: TypedError<ErrorCode>, code: T) => error is TypedError<T>;
1215
- };
1216
-
1217
- /**
1218
- * Validation rule types using template literal types
1219
- */
1220
- type ValidationRule = `min:${number}` | `max:${number}` | `minLength:${number}` | `maxLength:${number}` | `pattern:${string}` | `email` | `url` | `uuid` | `required` | `numeric` | `alpha` | `alphanumeric` | `date` | `future` | `past` | `in:${string}` | `notIn:${string}`;
1221
- /**
1222
- * Validator function type
1223
- */
1224
- type Validator<T> = (value: unknown) => Either<TypedError<"VALIDATION_FAILED">, T>;
1225
- /**
1226
- * Field validation result
1227
- */
1228
- type FieldValidation<T> = {
1229
- field: string;
1230
- value: unknown;
1231
- result: Either<TypedError<"VALIDATION_FAILED">, T>;
1232
- };
1233
- /**
1234
- * Form validation result
1235
- */
1236
- type FormValidation<T extends Record<string, Type>> = Either<List<TypedError<"VALIDATION_FAILED">>, T>;
1237
- declare const Validation: (<T extends Type>(rule: ValidationRule) => Validator<T>) & {
1238
- /**
1239
- * Common pre-built validators
1240
- */
1241
- validators: {
1242
- email: Validator<string>;
1243
- url: Validator<string>;
1244
- uuid: Validator<string>;
1245
- required: Validator<string>;
1246
- numeric: Validator<number>;
1247
- positiveNumber: Validator<number>;
1248
- nonEmptyString: Validator<string>;
1249
- };
1250
- /**
1251
- * Create a validator from a rule string
1252
- * @example
1253
- * const validator = Validation.rule<number>("min:18")
1254
- * const result = validator(25) // Right(25)
1255
- * const error = validator(15) // Left(TypedError)
1256
- */
1257
- rule: <T extends Type>(rule: ValidationRule) => Validator<T>;
1258
- /**
1259
- * Combine multiple validators
1260
- * @example
1261
- * const validator = Validation.combine(
1262
- * Validation.rule<string>("required"),
1263
- * Validation.rule<string>("email"),
1264
- * Validation.rule<string>("maxLength:100")
1265
- * )
1266
- */
1267
- combine: <T extends Type>(...validators: Validator<T>[]) => Validator<T>;
1268
- /**
1269
- * Create a custom validator
1270
- * @example
1271
- * const isEven = Validation.custom<number>(
1272
- * (value) => typeof value === "number" && value % 2 === 0,
1273
- * "must be an even number"
1274
- * )
1275
- */
1276
- custom: <T extends Type>(predicate: (value: unknown) => boolean, errorMessage: string) => Validator<T>;
1277
- /**
1278
- * Validate a form with multiple fields
1279
- * @example
1280
- * const schema = {
1281
- * name: Validation.rule<string>("required"),
1282
- * email: Validation.rule<string>("email"),
1283
- * age: Validation.rule<number>("min:18")
1284
- * }
1285
- * const result = Validation.form(schema, { name: "John", email: "john@example.com", age: 25 })
1286
- */
1287
- form: <T extends Record<string, Type>>(schema: { [K in keyof T]: Validator<T[K]>; }, data: Record<string, unknown>) => FormValidation<T>;
1288
- };
1289
-
1290
- /**
1291
- * Utility functions for working with Foldable data structures
1292
- */
1293
- declare const FoldableUtils: {
1294
- /**
1295
- * Converts a Foldable to an Option
1296
- *
1297
- * @param foldable - The foldable structure to convert
1298
- * @returns An Option containing the value, or None if empty
1299
- */
1300
- toOption: <A extends Type>(foldable: Foldable<A>) => Option<A>;
1301
- /**
1302
- * Converts a Foldable to a List
1303
- *
1304
- * @param foldable - The foldable structure to convert
1305
- * @returns A List containing the value(s), or empty List if empty
1306
- */
1307
- toList: <A extends Type>(foldable: Foldable<A>) => List<A>;
1308
- /**
1309
- * Converts a Foldable to an Either
1310
- *
1311
- * @param foldable - The foldable structure to convert
1312
- * @param left - The value to use for Left if empty
1313
- * @returns Either.Right with the value if non-empty, or Either.Left with left if empty
1314
- */
1315
- toEither: <A extends Type, E>(foldable: Foldable<A>, left: E) => Either<E, A>;
1316
- /**
1317
- * Checks if the Foldable is empty
1318
- *
1319
- * @param foldable - The foldable structure to check
1320
- * @returns true if empty, false otherwise
1321
- */
1322
- isEmpty: <A extends Type>(foldable: Foldable<A>) => boolean;
1323
- /**
1324
- * Calculates the size of the Foldable
1325
- *
1326
- * @param foldable - The foldable structure to measure
1327
- * @returns The size (number of elements)
1328
- */
1329
- size: <A extends Type>(foldable: Foldable<A>) => number;
1330
- };
1331
-
1332
- /**
1333
- * Type function for representing higher-kinded types
1334
- */
1335
- type Kind<F, A> = F extends (arg: infer T) => infer R ? R : never;
1336
- /**
1337
- * Type constructors for common Functype data types
1338
- */
1339
- type OptionKind = <A>(a: A) => Option<A>;
1340
- type ListKind = <A>(a: A) => List<A>;
1341
- type EitherKind<E> = <A>(a: A) => Either<E, A>;
1342
- type TryKind = <A>(a: A) => Try<A>;
1343
- /**
1344
- * Generic container types for type-safe operations
1345
- * @internal
1346
- */
1347
- type Mappable<T> = {
1348
- map<U>(f: (value: T) => U): unknown;
1349
- };
1350
- /**
1351
- * @internal
1352
- */
1353
- type Flattenable = {
1354
- flatten(): unknown;
1355
- };
1356
- /**
1357
- * @internal
1358
- */
1359
- type FlatMappable<T> = {
1360
- flatMap<U>(f: (value: T) => unknown): unknown;
1361
- };
1362
- /**
1363
- * Universal type that includes all potential return types from the HKT functions
1364
- * Used to avoid 'any' usage which the linter prohibits
1365
- */
1366
- type UniversalContainer = Option<unknown> | List<unknown> | Either<unknown, unknown> | Try<unknown>;
1367
- /**
1368
- * HKT provides utilities for working with higher-kinded types
1369
- * This allows writing generic code that works across different
1370
- * container types like Option, List, Either, etc.
1371
- */
1372
- declare const HKT: {
1373
- (): {
1374
- _tag: string;
1375
- map: <F, A, B>(fa: unknown, f: (a: A) => B) => unknown;
1376
- flatten: <F, A>(ffa: unknown) => unknown;
1377
- flatMap: <F, A, B>(fa: unknown, f: (a: A) => unknown) => unknown;
1378
- ap: <F, A, B>(ff: unknown, fa: unknown) => unknown;
1379
- sequence: <F, G, A>(fga: unknown) => unknown;
1380
- traverse: <F, G, A, B>(fa: unknown, f: (a: A) => unknown) => unknown;
1381
- _type: string;
1382
- };
1383
- map<F = unknown, A = unknown, B = unknown>(fa: unknown, f: (a: A) => B): unknown;
1384
- flatten<F = unknown, A = unknown>(ffa: unknown): unknown;
1385
- flatMap<F = unknown, A = unknown, B = unknown>(fa: unknown, f: (a: A) => unknown): unknown;
1386
- ap<F = unknown, A = unknown, B = unknown>(ff: unknown, fa: unknown): unknown;
1387
- sequence<F = unknown, G = unknown, A = unknown>(fga: unknown): unknown;
1388
- traverse<F = unknown, G = unknown, A = unknown, B = unknown>(fa: unknown, f: (a: A) => unknown): unknown;
1389
- isOption: <T extends Type>(value: unknown) => value is Option<T> & Mappable<T> & FlatMappable<T>;
1390
- isList: <T extends Type>(value: unknown) => value is List<T> & Mappable<T> & Flattenable & FlatMappable<T>;
1391
- isEither: <E extends Type, A extends Type>(value: unknown) => value is Either<E, A> & Mappable<A> & FlatMappable<A>;
1392
- isTry: <T extends Type>(value: unknown) => value is Try<T> & Mappable<T> & FlatMappable<T>;
1393
- };
1394
-
1395
- type Identity<T> = {
1396
- id: T;
1397
- isSame?: (other: Identity<T>) => boolean;
1398
- };
1399
- declare const Identity: (<T>(value: T) => Identity<T>) & {
1400
- /**
1401
- * Creates an Identity. Alias for Identity constructor.
1402
- * @param value - The value to wrap
1403
- * @returns Identity instance
1404
- */
1405
- of: <T>(value: T) => Identity<T>;
1406
- /**
1407
- * Creates an Identity. Same as of.
1408
- * @param value - The value to wrap
1409
- * @returns Identity instance
1410
- */
1411
- pure: <T>(value: T) => Identity<T>;
1412
- };
1413
-
1414
- /**
1415
- * Lazy type module
1416
- * @module Lazy
1417
- * @category Core
1418
- */
1419
- /**
1420
- * The Lazy type represents a computation that is deferred until needed.
1421
- * It provides memoization and safe evaluation with integration to Option, Either, and Try.
1422
- * @typeParam T - The type of the value to be computed
1423
- */
1424
- interface Lazy<T extends Type> extends FunctypeBase<T, "Lazy">, Extractable<T>, Pipe<T> {
1425
- /** Tag identifying this as a Lazy type */
1426
- readonly _tag: "Lazy";
1427
- /** Whether the computation has been evaluated */
1428
- readonly isEvaluated: boolean;
1429
- /**
1430
- * Returns the computed value or a default value if computation fails
1431
- * @param defaultValue - The value to return if computation fails
1432
- * @returns The computed value or defaultValue
1433
- */
1434
- orElse(defaultValue: T): T;
1435
- /**
1436
- * Returns the computed value or null if computation fails
1437
- * @returns The computed value or null
1438
- */
1439
- orNull(): T | null;
1440
- /**
1441
- * Returns the computed value or throws an error if computation fails
1442
- * @param error - Optional custom error to throw. If not provided, throws the computation error or a default error
1443
- * @returns The computed value
1444
- * @throws The specified error, computation error, or a default error
1445
- */
1446
- orThrow(error?: Error): T;
1447
- /**
1448
- * Returns this Lazy if computation succeeds, otherwise returns the alternative Lazy
1449
- * @param alternative - The alternative Lazy to use if computation fails
1450
- * @returns This Lazy or the alternative
1451
- */
1452
- or(alternative: Lazy<T>): Lazy<T>;
1453
- /**
1454
- * Maps the value inside the Lazy using the provided function
1455
- * @param f - The mapping function
1456
- * @returns A new Lazy containing the mapped value
1457
- */
1458
- map<U extends Type>(f: (value: T) => U): Lazy<U>;
1459
- /**
1460
- * Applies a wrapped function to a wrapped value (Applicative pattern)
1461
- * @param ff - A Lazy containing a function from T to U
1462
- * @returns A new Lazy containing the result
1463
- */
1464
- ap<U extends Type>(ff: Lazy<(value: T) => U>): Lazy<U>;
1465
- /**
1466
- * Maps the value inside the Lazy using an async function
1467
- * @param f - The async mapping function
1468
- * @returns A Promise of a new Lazy containing the mapped value
1469
- */
1470
- mapAsync<U extends Type>(f: (value: T) => Promise<U>): Promise<Lazy<U>>;
1471
- /**
1472
- * Maps the value using a function that returns a Lazy
1473
- * @param f - The mapping function returning a Lazy
1474
- * @returns A new Lazy containing the flattened result
1475
- */
1476
- flatMap<U extends Type>(f: (value: T) => Lazy<U>): Lazy<U>;
1477
- /**
1478
- * Maps the value using an async function that returns a Lazy
1479
- * @param f - The async mapping function returning a Lazy
1480
- * @returns A Promise of a new Lazy containing the flattened result
1481
- */
1482
- flatMapAsync<U extends Type>(f: (value: T) => Promise<Lazy<U>>): Promise<Lazy<U>>;
1483
- /**
1484
- * Returns a Lazy that filters the value based on a predicate
1485
- * @param predicate - The predicate function
1486
- * @returns A Lazy containing an Option of the value
1487
- */
1488
- filter(predicate: (value: T) => boolean): Lazy<Option<T>>;
1489
- /**
1490
- * Recovers from a failed computation by providing an alternative value
1491
- * @param f - Function that takes the error and returns a recovery value
1492
- * @returns A new Lazy that will use the recovery function if computation fails
1493
- */
1494
- recover(f: (error: unknown) => T): Lazy<T>;
1495
- /**
1496
- * Recovers from a failed computation by providing an alternative Lazy
1497
- * @param f - Function that takes the error and returns a recovery Lazy
1498
- * @returns A new Lazy that will use the recovery Lazy if computation fails
1499
- */
1500
- recoverWith(f: (error: unknown) => Lazy<T>): Lazy<T>;
1501
- /**
1502
- * Evaluates the computation and returns it as an Option
1503
- * @returns Some containing the value if successful, None if computation fails
1504
- */
1505
- toOption(): Option<T>;
1506
- /**
1507
- * Evaluates the computation and returns it as an Either
1508
- * @returns Right containing the value if successful, Left containing the error if computation fails
1509
- */
1510
- toEither(): Either<unknown, T>;
1511
- /**
1512
- * Evaluates the computation and returns it as an Either with a mapped error
1513
- * @param mapError - Function to map the error
1514
- * @returns Right containing the value if successful, Left containing the mapped error if computation fails
1515
- */
1516
- toEitherWith<E>(mapError: (error: unknown) => E): Either<E, T>;
1517
- /**
1518
- * Evaluates the computation and returns it as a Try
1519
- * @returns Try containing the result of the computation
1520
- */
1521
- toTry(): Try<T>;
1522
- /**
1523
- * Applies an effect function to the value if computation succeeds
1524
- * @param f - The effect function
1525
- * @returns This Lazy for chaining
1526
- */
1527
- tap(f: (value: T) => void): Lazy<T>;
1528
- /**
1529
- * Applies an effect function to the error if computation fails
1530
- * @param f - The effect function for errors
1531
- * @returns This Lazy for chaining
1532
- */
1533
- tapError(f: (error: unknown) => void): Lazy<T>;
1534
- /**
1535
- * Pattern matching on the Lazy value
1536
- * @param f - Function to apply to the computed value
1537
- * @returns The result of applying f to the computed value
1538
- */
1539
- fold<U>(f: (value: T) => U): U;
1540
- /**
1541
- * Pattern matching with success and failure handlers
1542
- * @param onFailure - Function to handle computation failure
1543
- * @param onSuccess - Function to handle successful computation
1544
- * @returns The result of the appropriate handler
1545
- */
1546
- foldWith<U>(onFailure: (error: unknown) => U, onSuccess: (value: T) => U): U;
1547
- /**
1548
- * Left fold operation
1549
- * @param z - Initial value
1550
- * @returns Function that takes an operator and applies it
1551
- */
1552
- foldLeft: <B>(z: B) => (op: (b: B, a: T) => B) => B;
1553
- /**
1554
- * Right fold operation
1555
- * @param z - Initial value
1556
- * @returns Function that takes an operator and applies it
1557
- */
1558
- foldRight: <B>(z: B) => (op: (a: T, b: B) => B) => B;
1559
- /**
1560
- * Pattern matching for the Lazy type
1561
- * @param patterns - Object with handler for Lazy pattern
1562
- * @returns The result of the matched handler
1563
- */
1564
- match<R>(patterns: {
1565
- Lazy: (value: T) => R;
1566
- }): R;
1567
- /**
1568
- * Creates a string representation of the Lazy
1569
- * @returns String representation showing evaluation status
1570
- */
1571
- toString(): string;
1572
- /**
1573
- * Converts the Lazy to a value object
1574
- * @returns Object representation of the Lazy with evaluation state
1575
- */
1576
- toValue(): {
1577
- _tag: "Lazy";
1578
- evaluated: boolean;
1579
- value?: T;
1580
- };
1581
- }
1582
- /**
1583
- * Creates a Lazy computation that defers evaluation until needed.
1584
- * Results are memoized after first evaluation.
1585
- *
1586
- * @example
1587
- * // Basic lazy evaluation
1588
- * const expensive = Lazy(() => {
1589
- * console.log("Computing...")
1590
- * return 42
1591
- * })
1592
- * // Nothing printed yet
1593
- * const result = expensive.orThrow() // Prints "Computing..." and returns 42
1594
- * const cached = expensive.orThrow() // Returns 42 without printing
1595
- *
1596
- * @example
1597
- * // Error handling
1598
- * const risky = Lazy(() => {
1599
- * if (Math.random() > 0.5) throw new Error("Failed")
1600
- * return "Success"
1601
- * })
1602
- * const safe = risky.orElse("Default") // Returns "Success" or "Default"
1603
- * const option = risky.toOption() // Some("Success") or None
1604
- * const either = risky.toEither() // Right("Success") or Left(Error)
1605
- *
1606
- * @example
1607
- * // Chaining computations
1608
- * const result = Lazy(() => 10)
1609
- * .map(x => x * 2)
1610
- * .flatMap(x => Lazy(() => x + 5))
1611
- * .recover(err => 0)
1612
- * .orThrow() // 25
1613
- *
1614
- * @example
1615
- * // Integration with functype
1616
- * const userOption = Option({ id: 1, name: "Alice" })
1617
- * const userName = Lazy.fromOption(userOption, () => ({ id: 0, name: "Anonymous" }))
1618
- * .map(user => user.name)
1619
- * .orThrow() // "Alice"
1620
- */
1621
- declare const Lazy: (<T extends Type>(thunk: () => T) => Lazy<T>) & {
1622
- /**
1623
- * Creates a Lazy from a thunk (deferred computation)
1624
- * @param thunk - Function that computes the value
1625
- * @returns A new Lazy instance
1626
- */
1627
- of: <T extends Type>(thunk: () => T) => Lazy<T>;
1628
- /**
1629
- * Creates a Lazy from an immediate value
1630
- * @param value - The value to wrap
1631
- * @returns A new Lazy instance that returns the value
1632
- */
1633
- fromValue: <T extends Type>(value: T) => Lazy<T>;
1634
- /**
1635
- * Creates a Lazy from an Option
1636
- * @param option - The Option to convert
1637
- * @param defaultThunk - Thunk to compute default value if Option is None
1638
- * @returns A new Lazy instance
1639
- */
1640
- fromOption: <T extends Type>(option: Option<T>, defaultThunk: () => T) => Lazy<T>;
1641
- /**
1642
- * Creates a Lazy from a Try
1643
- * @param tryValue - The Try to convert
1644
- * @returns A new Lazy instance
1645
- */
1646
- fromTry: <T extends Type>(tryValue: Try<T>) => Lazy<T>;
1647
- /**
1648
- * Creates a Lazy from an Either
1649
- * @param either - The Either to convert
1650
- * @returns A new Lazy instance
1651
- */
1652
- fromEither: <E, T extends Type>(either: Either<E, T>) => Lazy<T>;
1653
- /**
1654
- * Creates a Lazy that will throw an error since promises need to be awaited first
1655
- * @param promise - The Promise to convert
1656
- * @returns A new Lazy instance that throws an error
1657
- */
1658
- fromPromise: <T extends Type>(_promise: Promise<T>) => Lazy<T>;
1659
- /**
1660
- * Creates a failed Lazy that will throw when evaluated
1661
- * @param error - The error to throw
1662
- * @returns A new Lazy instance that throws the error
1663
- */
1664
- fail: <T extends Type>(error: unknown) => Lazy<T>;
1665
- };
1666
-
1667
- /**
1668
- * Type alias for the native JavaScript Map
1669
- * @interface
1670
- * @module Map
1671
- * @category Collections
1672
- */
1673
- type ESMapType<K, V> = Map<K, V>;
1674
- /**
1675
- * Reference to the native JavaScript Map
1676
- * @module Map
1677
- * @category Collections
1678
- */
1679
- declare const ESMap: MapConstructor;
1680
-
1681
- /**
1682
- * A mutable reference container that holds a value of type A.
1683
- * This provides controlled mutability in a functional context.
1684
- *
1685
- * @example
1686
- * const counter = Ref(0)
1687
- * counter.get() // 0
1688
- * counter.set(5)
1689
- * counter.get() // 5
1690
- * counter.update(n => n + 1)
1691
- * counter.get() // 6
1692
- */
1693
- interface Ref<A> {
1694
- /**
1695
- * Get the current value
1696
- */
1697
- get(): A;
1698
- /**
1699
- * Set a new value
1700
- */
1701
- set(value: A): void;
1702
- /**
1703
- * Update the value using a function
1704
- */
1705
- update(f: (current: A) => A): void;
1706
- /**
1707
- * Update and return the old value
1708
- */
1709
- getAndSet(value: A): A;
1710
- /**
1711
- * Update and return the new value
1712
- */
1713
- updateAndGet(f: (current: A) => A): A;
1714
- /**
1715
- * Update and return the old value
1716
- */
1717
- getAndUpdate(f: (current: A) => A): A;
1718
- /**
1719
- * Compare and swap - only updates if current value equals expected
1720
- */
1721
- compareAndSet(expected: A, newValue: A): boolean;
1722
- /**
1723
- * Modify the value and return a result
1724
- */
1725
- modify<B>(f: (current: A) => [A, B]): B;
1726
- }
1727
- declare const Ref: (<A extends Type>(initial: A) => Ref<A>) & {
1728
- /**
1729
- * Creates a Ref. Alias for Ref constructor.
1730
- * @param initial - The initial value
1731
- * @returns Ref instance
1732
- */
1733
- of: <A extends Type>(initial: A) => Ref<A>;
1734
- };
1735
-
1736
- /**
1737
- * Serialization result containing methods for different formats
1738
- */
1739
- interface SerializationResult {
1740
- /** Serializes to JSON string */
1741
- toJSON: () => string;
1742
- /** Serializes to YAML string */
1743
- toYAML: () => string;
1744
- /** Serializes to base64-encoded binary string */
1745
- toBinary: () => string;
1746
- }
1747
- /**
1748
- * Creates a serializer for a simple tagged value
1749
- * @param tag - The type tag (e.g., "Some", "List", "Success")
1750
- * @param value - The value to serialize
1751
- * @returns Serialization methods
1752
- */
1753
- declare const createSerializer: (tag: string, value: unknown) => SerializationResult;
1754
- /**
1755
- * Creates a serializer for complex objects with custom serialization logic
1756
- * @param data - The data object to serialize (should include _tag)
1757
- * @returns Serialization methods
1758
- */
1759
- declare const createCustomSerializer: (data: Record<string, unknown>) => SerializationResult;
1760
- /**
1761
- * Generic deserializer from JSON
1762
- * @param json - The JSON string to parse
1763
- * @param reconstructor - Function to reconstruct the type from parsed data
1764
- * @returns Reconstructed instance
1765
- */
1766
- declare const fromJSON: <T>(json: string, reconstructor: (parsed: {
1767
- _tag: string;
1768
- [key: string]: unknown;
1769
- }) => T) => T;
1770
- /**
1771
- * Generic deserializer from YAML (simple format)
1772
- * @param yaml - The YAML string to parse
1773
- * @param reconstructor - Function to reconstruct the type from parsed data
1774
- * @returns Reconstructed instance
1775
- */
1776
- declare const fromYAML: <T>(yaml: string, reconstructor: (parsed: {
1777
- _tag: string;
1778
- [key: string]: unknown;
1779
- }) => T) => T;
1780
- /**
1781
- * Generic deserializer from binary (base64-encoded JSON)
1782
- * @param binary - The base64-encoded binary string
1783
- * @param reconstructor - Function to reconstruct the type from parsed data
1784
- * @returns Reconstructed instance
1785
- */
1786
- declare const fromBinary: <T>(binary: string, reconstructor: (parsed: {
1787
- _tag: string;
1788
- [key: string]: unknown;
1789
- }) => T) => T;
1790
- /**
1791
- * Creates companion serialization methods for a type
1792
- * @param reconstructor - Function to reconstruct the type from parsed data
1793
- * @returns Companion methods object with fromJSON, fromYAML, and fromBinary
1794
- */
1795
- declare const createSerializationCompanion: <T>(reconstructor: (parsed: {
1796
- _tag: string;
1797
- [key: string]: unknown;
1798
- }) => T) => {
1799
- fromJSON: (json: string) => T;
1800
- fromYAML: (yaml: string) => T;
1801
- fromBinary: (binary: string) => T;
1802
- };
1803
-
1804
- /**
1805
- * Parameters for creating a Valuable instance
1806
- */
1807
- type ValuableParams<Tag extends string, T, V> = {
1808
- _tag: Tag;
1809
- impl: T;
1810
- value: V;
1811
- };
1812
- /**
1813
- * Represents a type that can extract its inner value. Creates a Valuable wrapper that adds value extraction capabilities.
1814
- * @param params - Configuration parameters
1815
- * @module Valuable
1816
- * @category Utilities
1817
- */
1818
- declare function Valuable<Tag extends string, V, T = object>(params: ValuableParams<Tag, T, V>): T & {
1819
- toValue: () => {
1820
- _tag: Tag;
1821
- value: V;
1822
- };
1823
- _tag: Tag;
1824
- };
1825
- type Valuable<Tag extends string, V, T = object> = Typeable<Tag, T> & {
1826
- toValue: () => {
1827
- _tag: Tag;
1828
- value: V;
1829
- };
1830
- };
1831
-
1832
- /**
1833
- * Stack data structure - Last In, First Out (LIFO)
1834
- * Implements the Traversable interface for working with ordered collections
1835
- */
1836
- type Stack<A extends Type> = {
1837
- /**
1838
- * Push a value onto the top of the stack
1839
- * @param value - The value to push
1840
- * @returns A new Stack with the value added
1841
- */
1842
- push(value: A): Stack<A>;
1843
- /**
1844
- * Remove and return the top value from the stack
1845
- * @returns A tuple containing the new Stack and the value
1846
- */
1847
- pop(): [Stack<A>, Option<A>];
1848
- /**
1849
- * Return the top value without removing it
1850
- * @returns The top value wrapped in an Option
1851
- */
1852
- peek(): Option<A>;
1853
- /**
1854
- * Transforms each element in the stack using the provided function
1855
- * @param f - The mapping function
1856
- * @returns A new Stack with transformed elements
1857
- */
1858
- map<B extends Type>(f: (a: A) => B): Stack<B>;
1859
- /**
1860
- * Maps each element to a Stack and flattens the result
1861
- * @param f - The mapping function returning a Stack
1862
- * @returns A new flattened Stack
1863
- */
1864
- flatMap<B extends Type>(f: (a: A) => Stack<B>): Stack<B>;
1865
- /**
1866
- * Applies a Stack of functions to this Stack
1867
- * @param ff - Stack of functions to apply
1868
- * @returns A new Stack with applied functions
1869
- */
1870
- ap<B extends Type>(ff: Stack<(value: A) => B>): Stack<B>;
1871
- /**
1872
- * Maps each element to an async Stack and flattens the result
1873
- * @param f - The async mapping function returning a Stack
1874
- * @returns A promise of the new flattened Stack
1875
- */
1876
- flatMapAsync<B extends Type>(f: (value: A) => PromiseLike<Stack<B>>): PromiseLike<Stack<B>>;
1877
- /**
1878
- * Convert the stack to a List
1879
- * @returns A List containing all elements
1880
- */
1881
- toList(): List<A>;
1882
- /**
1883
- * Convert the stack to an array
1884
- * @returns An array of all elements
1885
- */
1886
- toArray(): A[];
1887
- /**
1888
- * Returns a string representation of the stack
1889
- * @returns A string representation
1890
- */
1891
- toString(): string;
1892
- /**
1893
- * Pattern matches over the Stack, applying a handler function based on whether it's empty
1894
- * @param patterns - Object with handler functions for Empty and NonEmpty variants
1895
- * @returns The result of applying the matching handler function
1896
- */
1897
- match<R>(patterns: {
1898
- Empty: () => R;
1899
- NonEmpty: (values: A[]) => R;
1900
- }): R;
1901
- } & Traversable<A> & Valuable<"Stack", A[]> & Serializable<A> & Pipe<A[]> & Foldable<A> & Matchable<A[], "Empty" | "NonEmpty">;
1902
- declare const Stack: (<A extends Type>(values?: A[]) => Stack<A>) & {
1903
- /**
1904
- * Creates an empty stack
1905
- * @returns An empty Stack instance
1906
- */
1907
- empty: <A extends Type>() => Stack<A>;
1908
- /**
1909
- * Creates a Stack from a single value
1910
- * @param value - The value to create a stack with
1911
- * @returns A Stack with a single value
1912
- */
1913
- of: <A extends Type>(value: A) => Stack<A>;
1914
- /**
1915
- * Creates a Stack from JSON string
1916
- * @param json - The JSON string
1917
- * @returns Stack instance
1918
- */
1919
- fromJSON: <A>(json: string) => Stack<A>;
1920
- /**
1921
- * Creates a Stack from YAML string
1922
- * @param yaml - The YAML string
1923
- * @returns Stack instance
1924
- */
1925
- fromYAML: <A>(yaml: string) => Stack<A>;
1926
- /**
1927
- * Creates a Stack from binary string
1928
- * @param binary - The binary string
1929
- * @returns Stack instance
1930
- */
1931
- fromBinary: <A>(binary: string) => Stack<A>;
1932
- };
1933
-
1934
- export { type Async, AsyncMonad, Base, BoundedNumber, BoundedString, Brand, type CancellationToken, type CancellationTokenSource, Companion, type CompanionMethods, Cond, DoResult, Doable, ESMap, type ESMapType, Either, type EitherKind, EmailAddress, Err, type ErrorChainElement, type ErrorCode, type ErrorFormatterOptions, type ErrorMessage, type ErrorStatus, type ErrorWithTaskInfo, Extractable, FPromise, type FieldValidation, Foldable, FoldableUtils, type FormValidation, FunctypeBase, HKT, ISO8601Date, Identity, type InstanceType, IntegerNumber, type Kind, Lazy, LazyList, Lazy as LazyType, List, type ListKind, Match, Matchable, NAME, NonEmptyString, NonNegativeNumber, Ok, Option, type OptionKind, ParseError, PatternString, Pipe, PositiveInteger, PositiveNumber, Promisable, Ref, Ref as RefType, Serializable, type SerializationResult, Stack, type Sync, type TaggedThrowable, Task, type TaskErrorInfo, type TaskFailure, type TaskMetadata, type TaskOutcome, type TaskParams, type TaskResult, type TaskSuccess, Throwable, type ThrowableType, Traversable, Try, type TryKind, Type, Typeable, TypedError, type TypedErrorContext, UUID, type UniversalContainer, UrlString, ValidatedBrand, type ValidatedBrandCompanion, ValidatedBrand as ValidatedBrandType, Validation, type ValidationRule, type Validator, Valuable, type ValuableParams, createCancellationTokenSource, createCustomSerializer, createErrorSerializer, createSerializationCompanion, createSerializer, formatError, formatStackTrace, fromBinary, fromJSON, fromYAML, isCompanion, isTaggedThrowable, safeStringify };
1
+ import { a as ExtractBrand, c as hasBrand, i as BrandedString, l as unwrapBrand, n as BrandedBoolean, o as Unwrap, r as BrandedNumber, s as createBrander, t as Brand } from "./Brand-B-0nKo7I.js";
2
+ import { $ as EitherKind, $t as isCompanion, A as OptionConstructor, At as Ok, B as fromBinary, Bt as createCancellationTokenSource, C as Functype, Cn as ContainerOps, Ct as formatError, D as List, Dn as DoResult, Dt as CancellationToken, E as Collection, En as isExtractable, Et as Async, F as Set, Ft as TaskMetadata, G as MatchableUtils, Gt as NAME, H as fromYAML, Ht as ErrorContext, I as SerializationResult, It as TaskOutcome, J as Map, Jt as Base, K as ESMap, Kt as Throwable, L as createCustomSerializer, Lt as TaskParams, M as Stack, Mt as TaggedThrowable, N as Valuable, Nt as Task, O as None, On as Doable, Ot as CancellationTokenSource, P as ValuableParams, Pt as TaskFailure, Q as Identity, Qt as InstanceType, R as createSerializationCompanion, Rt as TaskResult, S as tryCatchAsync, Sn as CollectionOps, St as createErrorSerializer, T as FunctypeCollection, Tn as Extractable, Tt as safeStringify, U as Ref, Ut as FPromise, V as fromJSON, Vt as isTaggedThrowable, W as Matchable, Wt as FPromiseCompanion, X as Traversable, Xt as Cond, Y as SafeTraversable, Yt as Match, Z as Lazy, Zt as CompanionMethods, _ as TypeCheckLeft, _n as Promisable, _t as ParseError, a as EmptyListError, an as IntegerNumber, at as UniversalContainer, b as isRight, bn as Functor, bt as ErrorWithTaskInfo, c as LeftError, cn as PatternString, ct as FormValidation, d as isDoCapable, dn as UUID, dt as Validator, en as Companion, et as HKT, f as unwrap, fn as UrlString, ft as ErrorCode, g as TestEither, gn as TypeNames, gt as TypedErrorContext, h as Right, hn as Try, ht as TypedError, i as DoGenerator, in as ISO8601Date, it as TryKind, j as Some, jt as Sync, k as Option, kt as Err, l as LeftErrorType, ln as PositiveInteger, lt as Validation, m as Left, mn as ValidatedBrandCompanion, mt as ErrorStatus, n as Do, nn as BoundedString, nt as ListKind, o as FailureError, on as NonEmptyString, ot as FoldableUtils, p as Either, pn as ValidatedBrand, pt as ErrorMessage, q as ESMapType, qt as ThrowableType, r as DoAsync, rn as EmailAddress, rt as OptionKind, s as FailureErrorType, sn as NonNegativeNumber, st as FieldValidation, t as $, tn as BoundedNumber, tt as Kind, u as NoneError, un as PositiveNumber, ut as ValidationRule, v as TypeCheckRight, vn as Applicative, vt as ErrorChainElement, w as FunctypeBase, wn as LazyList, wt as formatStackTrace, x as tryCatch, xn as Monad, xt as TaskErrorInfo, y as isLeft, yn as AsyncMonad, yt as ErrorFormatterOptions, z as createSerializer, zt as TaskSuccess } from "./index-Bnjlo4cT.js";
3
+ import { a as isTypeable, c as Pipe, i as TypeableParams, l as Foldable, n as ExtractTag, o as Serializable, r as Typeable, s as SerializationMethods, t as Tuple, u as Type } from "./Tuple-CKxIyX7l.js";
4
+ export { $, Applicative, Async, AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, BrandedBoolean as BrandedBooleanType, BrandedNumber, BrandedNumber as BrandedNumberType, BrandedString, BrandedString as BrandedStringType, CancellationToken, CancellationTokenSource, Collection, CollectionOps, Companion, CompanionMethods, Cond, ContainerOps, Do, DoAsync, DoGenerator, DoResult, Doable, ESMap, ESMapType, Either, EitherKind, EmailAddress, EmptyListError, Err, ErrorChainElement, ErrorCode, ErrorContext, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, ExtractBrand, ExtractTag, Extractable, FPromise, FPromiseCompanion, FailureError, FailureErrorType, FieldValidation, Foldable, FoldableUtils, FormValidation, Functor, Functype, FunctypeBase, FunctypeCollection, HKT, ISO8601Date, Identity, InstanceType, IntegerNumber, Kind, Lazy, Lazy as LazyType, LazyList, Left, LeftError, LeftErrorType, List, ListKind, Map, Match, Matchable, MatchableUtils, Monad, NAME, NonEmptyString, NonNegativeNumber, None, NoneError, Ok, Option, OptionConstructor, OptionKind, ParseError, PatternString, Pipe, PositiveInteger, PositiveNumber, Promisable, Ref, Ref as RefType, Right, SafeTraversable, Serializable, SerializationMethods, SerializationResult, Set, Some, Stack, Sync, TaggedThrowable, Task, TaskErrorInfo, TaskFailure, TaskMetadata, TaskOutcome, TaskParams, TaskResult, TaskSuccess, TestEither, Throwable, ThrowableType, Traversable, Try, TryKind, Tuple, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, UUID, UniversalContainer, Unwrap, UrlString, ValidatedBrand, ValidatedBrand as ValidatedBrandType, ValidatedBrandCompanion, Validation, ValidationRule, Validator, Valuable, ValuableParams, createBrander, createCancellationTokenSource, createCustomSerializer, createErrorSerializer, createSerializationCompanion, createSerializer, formatError, formatStackTrace, fromBinary, fromJSON, fromYAML, hasBrand, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, safeStringify, tryCatch, tryCatchAsync, unwrap, unwrapBrand };