functype 1.27.2 → 2.0.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 (181) hide show
  1. package/README.md +63 -88
  2. package/dist/_virtual/_rolldown/runtime.js +1 -0
  3. package/dist/branded/ValidatedBrand.d.ts +122 -0
  4. package/dist/branded/ValidatedBrand.js +1 -0
  5. package/dist/branded/index.d.ts +52 -2
  6. package/dist/cli/data.d.ts +37 -0
  7. package/dist/cli/data.js +1 -0
  8. package/dist/cli/exports.d.ts +5 -46
  9. package/dist/cli/exports.js +1 -1
  10. package/dist/cli/formatters.js +4 -0
  11. package/dist/cli/full-interfaces.d.ts +6 -0
  12. package/dist/cli/full-interfaces.js +1139 -0
  13. package/dist/cli/index.js +3 -6
  14. package/dist/cli/interfaces.generated.js +1 -0
  15. package/dist/collections/index.d.ts +13 -0
  16. package/dist/companion/Companion.d.ts +23 -0
  17. package/dist/companion/Companion.js +1 -0
  18. package/dist/companion/CompanionTypes.d.ts +30 -0
  19. package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
  20. package/dist/companion/index.d.ts +2 -1
  21. package/dist/companion/index.js +1 -1
  22. package/dist/conditional/Cond.d.ts +147 -0
  23. package/dist/conditional/Cond.js +1 -0
  24. package/dist/conditional/Match.d.ts +295 -0
  25. package/dist/conditional/Match.js +1 -0
  26. package/dist/conditional/index.d.ts +3 -2
  27. package/dist/conditional/index.js +1 -1
  28. package/dist/core/base/Base.d.ts +12 -0
  29. package/dist/core/base/Base.js +1 -0
  30. package/dist/core/throwable/Throwable.d.ts +38 -0
  31. package/dist/core/throwable/Throwable.js +1 -0
  32. package/dist/decoder/Decoder.d.ts +15 -0
  33. package/dist/decoder/DecoderCompanion.js +1 -0
  34. package/dist/decoder/DecoderError.d.ts +56 -0
  35. package/dist/decoder/DecoderError.js +2 -0
  36. package/dist/decoder/Encoder.d.ts +15 -0
  37. package/dist/decoder/index.d.ts +71 -2
  38. package/dist/decoder/index.js +1 -1
  39. package/dist/decoder/tagged.js +1 -0
  40. package/dist/do/index.d.ts +246 -2
  41. package/dist/do/index.js +1 -1
  42. package/dist/do/protocol.d.ts +29 -0
  43. package/dist/either/index.d.ts +279 -2
  44. package/dist/either/index.js +1 -1
  45. package/dist/error/ErrorChain.d.ts +60 -0
  46. package/dist/error/ErrorChain.js +4 -0
  47. package/dist/error/ErrorFormatter.d.ts +67 -0
  48. package/dist/error/ErrorFormatter.js +6 -0
  49. package/dist/error/ParseError.d.ts +6 -0
  50. package/dist/error/ParseError.js +1 -0
  51. package/dist/error/typed/TypedError.d.ts +146 -0
  52. package/dist/error/typed/TypedError.js +1 -0
  53. package/dist/error/typed/Validation.d.ts +76 -0
  54. package/dist/error/typed/Validation.js +1 -0
  55. package/dist/extractable/Extractable.d.ts +62 -0
  56. package/dist/extractable/Extractable.js +1 -0
  57. package/dist/fetch/Http.d.ts +32 -0
  58. package/dist/fetch/Http.js +1 -0
  59. package/dist/fetch/HttpClient.d.ts +80 -0
  60. package/dist/fetch/HttpClient.js +1 -0
  61. package/dist/fetch/HttpError.d.ts +57 -0
  62. package/dist/fetch/HttpError.js +1 -0
  63. package/dist/fetch/HttpRequest.d.ts +103 -0
  64. package/dist/fetch/index.d.ts +5 -2
  65. package/dist/fetch/index.js +1 -1
  66. package/dist/foldable/Foldable.d.ts +27 -0
  67. package/dist/foldable/index.d.ts +55 -0
  68. package/dist/foldable/index.js +1 -0
  69. package/dist/functype/Functype.d.ts +76 -0
  70. package/dist/functype/FunctypeSum.d.ts +39 -0
  71. package/dist/functype/index.d.ts +4 -2
  72. package/dist/hkt/index.d.ts +68 -0
  73. package/dist/hkt/index.js +1 -0
  74. package/dist/identity/Identity.d.ts +34 -0
  75. package/dist/identity/Identity.js +1 -0
  76. package/dist/index.d.ts +74 -8
  77. package/dist/index.js +1 -1
  78. package/dist/internal/base64.js +1 -0
  79. package/dist/internal/call-alone.js +1 -0
  80. package/dist/internal/concurrency.d.ts +11 -0
  81. package/dist/internal/concurrency.js +1 -0
  82. package/dist/internal/define.js +1 -0
  83. package/dist/internal/mutation-utils.js +1 -0
  84. package/dist/internal/signal.js +1 -0
  85. package/dist/internal/stringify.js +1 -0
  86. package/dist/invariant/index.d.ts +32 -2
  87. package/dist/io/Context.d.ts +112 -0
  88. package/dist/io/Context.js +1 -0
  89. package/dist/io/Exit.d.ts +249 -0
  90. package/dist/io/Exit.js +1 -0
  91. package/dist/io/IO.d.ts +1243 -0
  92. package/dist/io/IO.js +1 -0
  93. package/dist/io/Layer.d.ts +139 -0
  94. package/dist/io/Layer.js +1 -0
  95. package/dist/io/SpanTracer.d.ts +78 -0
  96. package/dist/io/SpanTracer.js +1 -0
  97. package/dist/io/Tag.d.ts +75 -0
  98. package/dist/io/Tag.js +1 -0
  99. package/dist/io/TestClock.d.ts +133 -0
  100. package/dist/io/TestClock.js +1 -0
  101. package/dist/io/index.d.ts +41 -2
  102. package/dist/io/index.js +1 -1
  103. package/dist/lazy/Lazy.d.ts +312 -0
  104. package/dist/lazy/Lazy.js +1 -0
  105. package/dist/lazy/index.d.ts +2 -2
  106. package/dist/lazy/index.js +1 -1
  107. package/dist/list/LazyList.d.ts +182 -0
  108. package/dist/list/LazyList.js +1 -0
  109. package/dist/list/index.d.ts +137 -2
  110. package/dist/list/index.js +1 -1
  111. package/dist/logger/index.d.ts +24 -2
  112. package/dist/map/index.d.ts +95 -2
  113. package/dist/map/index.js +1 -1
  114. package/dist/map/shim.d.ts +13 -0
  115. package/dist/map/shim.js +1 -0
  116. package/dist/matchable/Matchable.d.ts +38 -0
  117. package/dist/matchable/Matchable.js +1 -0
  118. package/dist/obj/Obj.d.ts +212 -0
  119. package/dist/obj/Obj.js +1 -0
  120. package/dist/obj/index.d.ts +2 -2
  121. package/dist/obj/index.js +1 -1
  122. package/dist/option/index.d.ts +304 -2
  123. package/dist/option/index.js +1 -1
  124. package/dist/package.json.js +1 -0
  125. package/dist/pipe/index.d.ts +14 -0
  126. package/dist/ref/Ref.d.ts +77 -0
  127. package/dist/ref/Ref.js +1 -0
  128. package/dist/reshapeable/Reshapeable.d.ts +90 -0
  129. package/dist/serializable/Serializable.d.ts +39 -0
  130. package/dist/serialization/Serialization.d.ts +147 -0
  131. package/dist/serialization/Serialization.js +1 -0
  132. package/dist/serialization/SerializationCompanion.d.ts +125 -0
  133. package/dist/serialization/SerializationCompanion.js +1 -0
  134. package/dist/serialization/error-envelope.d.ts +44 -0
  135. package/dist/serialization/error-envelope.js +1 -0
  136. package/dist/serialization/index.d.ts +4 -2
  137. package/dist/serialization/index.js +1 -1
  138. package/dist/set/index.d.ts +106 -2
  139. package/dist/set/index.js +1 -1
  140. package/dist/stack/Stack.d.ts +120 -0
  141. package/dist/stack/Stack.js +1 -0
  142. package/dist/traced/TraceEvent.d.ts +27 -0
  143. package/dist/traced/TracedOption.d.ts +46 -0
  144. package/dist/traced/TracedOption.js +1 -0
  145. package/dist/traced/Tracer.d.ts +26 -0
  146. package/dist/traversable/KVTraversable.d.ts +14 -0
  147. package/dist/traversable/Traversable.d.ts +30 -0
  148. package/dist/try/index.d.ts +238 -2
  149. package/dist/try/index.js +1 -1
  150. package/dist/tuple/index.d.ts +92 -2
  151. package/dist/tuple/index.js +1 -1
  152. package/dist/typeable/Typeable.d.ts +40 -0
  153. package/dist/typeable/Typeable.js +1 -0
  154. package/dist/typeclass/ContainerOps.d.ts +131 -0
  155. package/dist/typeclass/Functor.d.ts +41 -0
  156. package/dist/typeclass/Promisable.d.ts +33 -0
  157. package/dist/typeclass/index.d.ts +4 -1
  158. package/dist/typeclass/index.js +1 -1
  159. package/dist/typeclass/variance.d.ts +54 -0
  160. package/dist/typeclass/variance.js +1 -0
  161. package/dist/types/index.d.ts +1 -0
  162. package/dist/util/index.d.ts +1 -3
  163. package/dist/valuable/Valuable.d.ts +28 -0
  164. package/dist/valuable/Valuable.js +1 -0
  165. package/dist/wire/index.d.ts +40 -2
  166. package/package.json +7 -12
  167. package/dist/Brand-bfnGXuum.d.ts +0 -54
  168. package/dist/Companion-DiOMBHDG.js +0 -1
  169. package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
  170. package/dist/Invariant-DEan-SxV.d.ts +0 -35
  171. package/dist/Logger-BmprRS8v.d.ts +0 -27
  172. package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
  173. package/dist/Wire-3hvw0Ogg.d.ts +0 -42
  174. package/dist/core/task/index.d.ts +0 -2
  175. package/dist/core/task/index.js +0 -1
  176. package/dist/full-interfaces-BadxJrCt.js +0 -1202
  177. package/dist/index-CLYh2qZu.d.ts +0 -6649
  178. package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
  179. package/dist/serialization-9_SyrfdG.js +0 -3
  180. package/dist/src-BQPeS6p2.js +0 -10
  181. package/dist/typeclass-C61yDVYd.js +0 -1
@@ -1,2 +1,279 @@
1
- import { _r as isRight, cr as EitherBase, dr as Right, fr as RightOf, gr as isLeft, hr as TypeCheckRight, lr as Left, mr as TypeCheckLeft, pr as TestEither, sr as Either, ur as LeftOf, vr as tryCatch, yr as tryCatchAsync } from "../index-CLYh2qZu.js";
2
- export { Either, EitherBase, Left, LeftOf, Right, RightOf, TestEither, TypeCheckLeft, TypeCheckRight, isLeft, isRight, tryCatch, tryCatchAsync };
1
+ import { Doable } from "../do/protocol.js";
2
+ import { Extractable } from "../extractable/Extractable.js";
3
+ import { FunctypeSum } from "../functype/FunctypeSum.js";
4
+ import { ConcurrencyOptions } from "../internal/concurrency.js";
5
+ import { Option } from "../option/index.js";
6
+ import { Reshapeable } from "../reshapeable/Reshapeable.js";
7
+ import { AsyncMonad } from "../typeclass/Functor.js";
8
+ import { Promisable } from "../typeclass/Promisable.js";
9
+ import { Type } from "../types/index.js";
10
+ /**
11
+ * Either type module
12
+ * @module Either
13
+ * @category Core
14
+ */
15
+ /**
16
+ * Shared interface for Either variants. Contains all methods and type guards but
17
+ * does NOT include the discriminant `_tag` or `value` — those are declared on the
18
+ * variant interfaces (LeftOf / RightOf) so that Either acts as a true discriminated
19
+ * union. After `if (e.isLeft())`, the else branch narrows `e` to RightOf<L,R> and
20
+ * `e.value` narrows to R without a cast.
21
+ */
22
+ export interface EitherBase<out L extends Type, out R extends Type> extends FunctypeSum<R, "Left" | "Right">, Promisable<R>, Doable<R>, Reshapeable<R>, Extractable<R> {
23
+ isLeft(): this is LeftOf<L, R>;
24
+ isRight(): this is RightOf<L, R>;
25
+ /**
26
+ * Returns the Right value, or calls `defaultValue` on a Left. The default is lazy: it runs only
27
+ * on a Left. A default that fits `R` keeps `R`, so a literal union is not widened; a default of
28
+ * another type widens the result to `R | R2`.
29
+ */
30
+ getOrElse<R2 extends Type = never>(defaultValue: () => R | R2): R | R2;
31
+ /**
32
+ * Returns the Right value, or throws on a Left. Pass an `Error` to throw it, or a builder to make one
33
+ * from the Left value — for code that must throw for a host (a retrying step runner, an MCP tool, a
34
+ * React Query `queryFn`). With no argument, throws the Left value itself.
35
+ */
36
+ orThrow(error?: Error | ((left: L) => Error)): R;
37
+ /**
38
+ * Returns the right value, or calls the never-returning handler with the Left's value.
39
+ * Use this when you have a helper like `(msg) => fail(msg, 2)` that terminates the
40
+ * program — the result type is unconditionally `R`, so you avoid the TypeScript
41
+ * narrowing trap where `if (e.isLeft()) fail(...)` fails to narrow `e.value` when
42
+ * `fail` is an arrow function typed as `(...): never`.
43
+ */
44
+ expect(handler: (value: L) => never): R;
45
+ /**
46
+ * Returns this Either if it is a Right, otherwise calls `alternative` for another Either.
47
+ * The alternative is lazy: it runs only on a Left.
48
+ */
49
+ orElse<L2 extends Type, R2 extends Type>(alternative: () => Either<L2, R2>): Either<L | L2, R | R2>;
50
+ orNull(): R | null;
51
+ orUndefined(): R | undefined;
52
+ map<U extends Type>(f: (value: R) => U): Either<L, U>;
53
+ ap<L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>): Either<L | L2, U>;
54
+ merge<L1 extends Type, R1 extends Type>(other: Either<L1, R1>): Either<L | L1, [R, R1]>;
55
+ /**
56
+ * Maps the Right value with an async function. A Left resolves unchanged.
57
+ * If `f` rejects or throws, the returned Promise rejects with the same reason: it does not
58
+ * become a Left, and it never throws synchronously. To turn a rejection into a Left, use `Either.fromPromise(p, onRejected)`
59
+ * or `tryCatchAsync`, which take a function from the reason to `L`.
60
+ */
61
+ mapAsync<U extends Type>(f: (value: R) => Promise<U>): Promise<Either<L, U>>;
62
+ flatMap<L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U>;
63
+ /**
64
+ * Chains an async function that returns an Either. A Left resolves unchanged.
65
+ * If `f` rejects or throws, the returned Promise rejects with the same reason, as with `mapAsync`.
66
+ */
67
+ flatMapAsync<L2 extends Type, U extends Type>(f: (value: R) => Promise<Either<L2, U>>): Promise<Either<L | L2, U>>;
68
+ toOption(): Option<R>;
69
+ toString(): string;
70
+ [Symbol.iterator]: () => Iterator<R>;
71
+ yield(): Generator<R, void, unknown>;
72
+ traverse<L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U[]>;
73
+ tap(f: (value: R) => void): Either<L, R>;
74
+ tapLeft(f: (value: L) => void): Either<L, R>;
75
+ mapLeft<L2 extends Type>(f: (value: L) => L2): Either<L2, R>;
76
+ /**
77
+ * Applies a predicate to the Right value. If the predicate fails, short-circuits
78
+ * to a Left carrying the value produced by `onUnsatisfied`. Left passes through
79
+ * unchanged (predicate not evaluated). Lets you turn a value-level guard into the
80
+ * Left channel without breaking the chain with an `if/return Left(...)` ladder.
81
+ * @param predicate - The predicate to test the Right value
82
+ * @param onUnsatisfied - Builds the new Left value when the predicate fails
83
+ * @returns Right if the predicate holds, Left(onUnsatisfied(value)) otherwise
84
+ */
85
+ filterOrElse<L2 extends Type>(predicate: (value: R) => boolean, onUnsatisfied: (value: R) => L2): Either<L | L2, R>;
86
+ bimap<L2 extends Type, R2 extends Type>(fl: (value: L) => L2, fr: (value: R) => R2): Either<L2, R2>;
87
+ fold<T extends Type>(onLeft: (value: L) => T, onRight: (value: R) => T): T;
88
+ /**
89
+ * Async variant of fold. Accepts sync or async handlers on either branch and
90
+ * always returns a Promise, keeping chains fluent when at least one branch is async.
91
+ */
92
+ foldAsync<T extends Type>(onLeft: (value: L) => T | Promise<T>, onRight: (value: R) => T | Promise<T>): Promise<T>;
93
+ swap(): Either<R, L>;
94
+ /**
95
+ * Pipes the value through the provided function based on whether this is a Left or Right
96
+ */
97
+ pipeEither<U extends Type>(onLeft: (value: L) => U, onRight: (value: R) => U): U;
98
+ /**
99
+ * Pipes the Either value through the provided function
100
+ */
101
+ pipe<U extends Type>(f: (value: L | R) => U): U;
102
+ /**
103
+ * Pattern matches over the Either, applying a handler function based on the variant
104
+ */
105
+ match<T>(patterns: {
106
+ Left: (value: L) => T;
107
+ Right: (value: R) => T;
108
+ }): T;
109
+ /**
110
+ * Returns the value and tag for inspection
111
+ */
112
+ toValue(): {
113
+ _tag: "Left" | "Right";
114
+ value: L | R;
115
+ };
116
+ /**
117
+ * Custom JSON serialization that excludes getter properties.
118
+ * Emits the canonical functype envelope with `@functype: "Either"` so
119
+ * native `JSON.stringify` recursion (e.g. inside a plain object body)
120
+ * produces a marker-bearing envelope that survives a round-trip through
121
+ * `Serialization.deserialize`.
122
+ */
123
+ toJSON(): {
124
+ "@functype": "Either";
125
+ _tag: "Left" | "Right";
126
+ value: L | R;
127
+ };
128
+ }
129
+ /**
130
+ * Left variant of Either. Discriminated by `_tag: "Left"` with `value: L`.
131
+ */
132
+ export interface LeftOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
133
+ readonly _tag: "Left";
134
+ readonly value: L;
135
+ }
136
+ /**
137
+ * Right variant of Either. Discriminated by `_tag: "Right"` with `value: R`.
138
+ */
139
+ export interface RightOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
140
+ readonly _tag: "Right";
141
+ readonly value: R;
142
+ }
143
+ /**
144
+ * Either is a discriminated union of LeftOf and RightOf. TypeScript narrows
145
+ * across both branches of `isLeft()` / `isRight()` and `_tag` checks. Variance
146
+ * is inherited from LeftOf/RightOf (both covariant in L and R) — union type
147
+ * aliases cannot carry their own variance annotations in TS.
148
+ */
149
+ export type Either<L extends Type, R extends Type> = LeftOf<L, R> | RightOf<L, R>;
150
+ export type TestEither<L extends Type, R extends Type> = Either<L, R> & AsyncMonad<R>;
151
+ export declare const Right: <L extends Type, R extends Type>(value: R) => Either<L, R>;
152
+ export declare const Left: <L extends Type, R extends Type>(value: L) => Either<L, R>;
153
+ export declare const isRight: <L extends Type, R extends Type>(either: Either<L, R>) => either is RightOf<L, R>;
154
+ export declare const isLeft: <L extends Type, R extends Type>(either: Either<L, R>) => either is LeftOf<L, R>;
155
+ export declare const tryCatch: <L extends Type, R extends Type>(f: () => R, onError: (error: unknown) => L) => Either<L, R>;
156
+ export declare const TypeCheckRight: <L extends Type, R extends Type>(value: R) => TestEither<L, R>;
157
+ export declare const TypeCheckLeft: <L extends Type, R extends Type>(value: L) => TestEither<L, R>;
158
+ export declare const tryCatchAsync: <L extends Type, R extends Type>(f: () => Promise<R>, onError: (error: unknown) => L) => Promise<Either<L, R>>;
159
+ /**
160
+ * Either constructor that creates Left or Right based on the isRight parameter
161
+ * @param value - The value to wrap
162
+ * @param isRight - If true, creates Right, otherwise creates Left
163
+ * @returns Either instance
164
+ */
165
+ declare const EitherConstructor: <L extends Type, R extends Type>(value: R | L, isRight: boolean) => Either<L, R>;
166
+ declare const EitherStatics: {
167
+ /**
168
+ * Creates a Left instance
169
+ * @param value - The left value
170
+ * @returns Left Either
171
+ */
172
+ left: <L extends Type, R extends Type>(value: L) => Either<L, R>;
173
+ /**
174
+ * Creates a Right instance
175
+ * @param value - The right value
176
+ * @returns Right Either
177
+ */
178
+ right: <L extends Type, R extends Type>(value: R) => Either<L, R>;
179
+ /**
180
+ * Creates a Right<L, void> — convenience for "operation succeeded with no meaningful value".
181
+ * Avoids variance quirks around Either<L, void> vs Either<L, undefined>.
182
+ * @returns Right Either with void value
183
+ */
184
+ void: <L extends Type>() => Either<L, void>;
185
+ /**
186
+ * Type guard to check if an Either is Right
187
+ * @param either - The Either to check
188
+ * @returns True if Either is Right
189
+ */
190
+ isRight: <L extends Type, R extends Type>(either: Either<L, R>) => either is RightOf<L, R>;
191
+ /**
192
+ * Type guard to check if an Either is Left
193
+ * @param either - The Either to check
194
+ * @returns True if Either is Left
195
+ */
196
+ isLeft: <L extends Type, R extends Type>(either: Either<L, R>) => either is LeftOf<L, R>;
197
+ /**
198
+ * Combines an array of Eithers into a single Either containing an array
199
+ * @param eithers - Array of Either values
200
+ * @returns Either with array of values or first Left encountered
201
+ */
202
+ sequence: <L extends Type, R extends Type>(eithers: ReadonlyArray<Either<L, R>>) => Either<L, R[]>;
203
+ /**
204
+ * Maps an array through a function that returns Either, then sequences the results.
205
+ * Short-circuits on the first Left: `f` is not called for the elements after it.
206
+ * @param arr - Array of values
207
+ * @param f - Function that returns Either, given each value and its index
208
+ * @returns Either with array of results or first Left encountered
209
+ */
210
+ traverse: <L extends Type, R extends Type, U extends Type>(arr: ReadonlyArray<R>, f: (value: R, index: number) => Either<L, U>) => Either<L, U[]>;
211
+ /**
212
+ * Async traverse: runs `f` over `items` and collects the Right values, stopping at the first Left.
213
+ *
214
+ * Runs one call at a time, in order, by default. Pass `{ concurrency: n }` to allow up to `n` calls at once,
215
+ * or `"unbounded"` to start them all together. After a Left no new calls start; calls already running
216
+ * finish, and the result is the Left of the earliest item that failed. A rejected promise rejects the result.
217
+ *
218
+ * @param items - Values to traverse (an array, List, or any iterable)
219
+ * @param f - Async function returning Either
220
+ * @param options - `{ concurrency }`; defaults to 1 (sequential)
221
+ * @returns Right of all results in input order, or the first Left
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const saved = await Either.traverseAsync(rows, (row) => saveRow(row))
226
+ * // Either<SaveError, SavedRow[]>, one save at a time, stopping at the first failure
227
+ *
228
+ * const fetched = await Either.traverseAsync(ids, fetchUser, { concurrency: 4 })
229
+ * ```
230
+ */
231
+ traverseAsync: <L extends Type, A extends Type, U extends Type>(items: Iterable<A>, f: (value: A) => PromiseLike<Either<L, U>>, options?: ConcurrencyOptions) => Promise<Either<L, U[]>>;
232
+ /**
233
+ * Creates an Either from a nullable value
234
+ * @param value - The value that might be null or undefined
235
+ * @param leftValue - The value to use for Left if value is null/undefined
236
+ * @returns Right if value is not null/undefined, Left otherwise
237
+ */
238
+ fromNullable: <L extends Type, R extends Type>(value: R | null | undefined, leftValue: L) => Either<L, R>;
239
+ /**
240
+ * Creates an Either based on a predicate
241
+ * @param value - The value to test
242
+ * @param predicate - The predicate function
243
+ * @param leftValue - The value to use for Left if predicate fails
244
+ * @returns Right if predicate passes, Left otherwise
245
+ */
246
+ fromPredicate: <L extends Type, R extends Type>(value: R, predicate: (value: R) => boolean, leftValue: L) => Either<L, R>;
247
+ /**
248
+ * Applicative apply - applies a wrapped function to a wrapped value
249
+ * @param eitherF - Either containing a function
250
+ * @param eitherV - Either containing a value
251
+ * @returns Either with function applied to value
252
+ */
253
+ ap: <L extends Type, R extends Type, U extends Type>(eitherF: Either<L, (value: R) => U>, eitherV: Either<L, R>) => Either<L, U>;
254
+ /**
255
+ * Creates an Either from a Promise
256
+ * @param promise - The Promise to convert
257
+ * @param onRejected - Function to convert rejection reason to Left value
258
+ * @returns Promise that resolves to Either
259
+ */
260
+ fromPromise: <L, R>(promise: Promise<R>, onRejected: (reason: unknown) => L) => Promise<Either<L, R>>;
261
+ /**
262
+ * Creates an Either from JSON string
263
+ * @param json - The JSON string
264
+ * @returns Either instance
265
+ */
266
+ fromJSON: <L extends Type, R extends Type>(json: string) => Either<L, R>;
267
+ /**
268
+ * Creates an Either from binary string
269
+ * @param binary - The binary string
270
+ * @returns Either instance
271
+ */
272
+ fromBinary: <L extends Type, R extends Type>(binary: string) => Either<L, R>;
273
+ };
274
+ export declare const Either: EitherCompanion;
275
+ /** The type of `Either`: its constructor and its statics, named so that errors and hovers print `EitherCompanion`. */
276
+ export interface EitherCompanion extends EitherConstructorType, EitherStaticsType {}
277
+ type EitherConstructorType = typeof EitherConstructor;
278
+ type EitherStaticsType = typeof EitherStatics;
279
+ export {};
@@ -1 +1 @@
1
- import{Ct as e,St as t,_t as n,bt as r,gt as i,ht as a,vt as o,xt as s,yt as c}from"../src-BQPeS6p2.js";export{a as Either,i as Left,n as Right,o as TypeCheckLeft,c as TypeCheckRight,r as isLeft,s as isRight,t as tryCatch,e as tryCatchAsync};
1
+ import{Companion as e}from"../companion/Companion.js";import{base64ToUtf8 as t}from"../internal/base64.js";import{traverseWithConcurrency as n}from"../internal/concurrency.js";import{define as r}from"../internal/define.js";import{showValue as i}from"../internal/stringify.js";import{List as a}from"../list/index.js";import{None as o,Some as s}from"../option/index.js";import{createSerializer as c,expectMarker as l}from"../serialization/SerializationCompanion.js";import{Try as u}from"../try/index.js";const d=(e,t)=>[e,t],f=r()(`Right`,{[Symbol.toStringTag]:`Either`,isLeft(){return!1},isRight(){return!0},getOrElse(){return this.value},orThrow(){return this.value},expect(){return this.value},orElse(){return this},orNull(){return this.value},orUndefined(){return this.value},map(e){return m(e(this.value))},ap(e){return e._tag===`Right`?m(e.value(this.value)):_(e.value)},async mapAsync(e){return m(await e(this.value))},merge(e){return e.isLeft()?_(e.value):m(d(this.value,e.value))},flatMap(e){return e(this.value)},async flatMapAsync(e){return e(this.value)},toOption(){return s(this.value)},toList(){return a([this.value])},toEither(){return m(this.value)},toTry(){return u(()=>this.value)},toJSON(){return{"@functype":`Either`,_tag:`Right`,value:this.value}},toString(){return`Right(${i(this.value)})`},*[Symbol.iterator](){yield this.value},*yield(){yield this.value},traverse(e){let t=e(this.value);return t.isLeft()?_(t.value):m([t.value])},tap(e){return e(this.value),this},tapLeft(){return this},mapLeft(){return m(this.value)},filterOrElse(e,t){return e(this.value)?this:_(t(this.value))},bimap(e,t){return m(t(this.value))},fold(e,t){return t(this.value)},async foldAsync(e,t){return t(this.value)},foldLeft(e){return t=>t(e,this.value)},foldRight(e){return t=>t(this.value,e)},match(e){return e.Right(this.value)},swap(){return _(this.value)},toPromise(){return Promise.resolve(this.value)},toValue(){return{_tag:`Right`,value:this.value}},pipeEither(e,t){return t(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Right`,this.value)},contains(e){return this.value===e},exists(e){return e(this.value)},every(e){return e(this.value)},forEach(e){e(this.value)},doUnwrap(){return{ok:!0,value:this.value}}}),p=r()(`Left`,{[Symbol.toStringTag]:`Either`,isLeft(){return!0},isRight(){return!1},getOrElse(e){return e()},orThrow(e){throw e===void 0?this.value:typeof e==`function`?e(this.value):e},expect(e){return e(this.value)},orElse(e){return e()},orNull(){return null},orUndefined(){},map(){return h(this.value)},ap(){return h(this.value)},mapAsync(){return Promise.resolve(h(this.value))},merge(){return h(this.value)},flatMap(){return h(this.value)},flatMapAsync(){return Promise.resolve(h(this.value))},toOption(){return o()},toList(){return a()},toEither(e){return h(e)},toTry(){return u(()=>{throw Error(String(this.value))})},toJSON(){return{"@functype":`Either`,_tag:`Left`,value:this.value}},toString(){return`Left(${i(this.value)})`},*[Symbol.iterator](){},*yield(){},traverse(){return h(this.value)},tap(){return this},tapLeft(e){return e(this.value),this},mapLeft(e){return h(e(this.value))},filterOrElse(){return this},bimap(e){return h(e(this.value))},fold(e){return e(this.value)},async foldAsync(e){return e(this.value)},foldLeft(e){return()=>e},foldRight(e){return()=>e},match(e){return e.Left(this.value)},swap(){return m(this.value)},toPromise(){return Promise.reject(this.value)},toValue(){return{_tag:`Left`,value:this.value}},pipeEither(e){return e(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Left`,this.value)},contains(){return!1},exists(){return!1},every(){return!0},forEach(){},doUnwrap(){return{ok:!1,empty:!1,error:this.value}}}),m=e=>{let t=Object.create(f);return t._tag=`Right`,t.value=e,t},h=e=>{let t=Object.create(p);return t._tag=`Left`,t.value=e,t},g=e=>m(e),_=e=>h(e),v=e=>e.isRight(),y=e=>e.isLeft(),b=(e,t)=>{try{return g(e())}catch(e){return _(t(e))}},x=e=>m(e);console.assert(x);const S=e=>h(e);console.assert(S);const C=async(e,t)=>{try{let t=await e();return g(t)}catch(e){return _(t(e))}},w=(e,t)=>t?g(e):_(e),T=(e,t)=>(l(e,`Either`,t),e._tag===`Right`?g(e.value):_(e.value)),E={left:e=>_(e),right:e=>g(e),void:()=>g(void 0),isRight:e=>e.isRight(),isLeft:e=>e.isLeft(),sequence:e=>e.reduce((e,t)=>e.isLeft()?e:t.isLeft()?_(t.value):e.map(e=>[...e,t.value]),g([])),traverse:(e,t)=>e.reduce((e,n,r)=>e.flatMap(e=>t(n,r).map(t=>[...e,t])),g([])),traverseAsync:async(e,t,r)=>{let i=await n(e,t,r?.concurrency??1,e=>e.isLeft());return E.sequence(i)},fromNullable:(e,t)=>e==null?_(t):g(e),fromPredicate:(e,t,n)=>t(e)?g(e):_(n),ap:(e,t)=>e.flatMap(e=>t.map(e)),fromPromise:async(e,t)=>{try{let t=await e;return g(t)}catch(e){return _(t(e))}},fromJSON:e=>T(JSON.parse(e),`fromJSON`),fromBinary:e=>{let n=t(e);return E.fromJSON(n)}},D=e(w,E);export{D as Either,_ as Left,g as Right,S as TypeCheckLeft,x as TypeCheckRight,y as isLeft,v as isRight,b as tryCatch,C as tryCatchAsync};
@@ -0,0 +1,60 @@
1
+ /**
2
+ * An `Error` marked as a functype `Throwable`, with an optional cause and the name of the step that raised it.
3
+ */
4
+ export type TaggedThrowable = Error & {
5
+ _tag: "Throwable";
6
+ cause?: Error;
7
+ taskInfo?: {
8
+ name: string;
9
+ description: string;
10
+ };
11
+ };
12
+ /**
13
+ * Type guard to check if an error is a TaggedThrowable
14
+ */
15
+ export declare function isTaggedThrowable(error: unknown): error is TaggedThrowable;
16
+ /**
17
+ * Options for {@link formatErrorChain}
18
+ */
19
+ export type ErrorChainFormatOptions = {
20
+ /** Prefix each line with the step name from `taskInfo`, as `[name] ` */
21
+ includeTasks?: boolean;
22
+ /** Separator between lines (default: newline) */
23
+ separator?: string;
24
+ /** Append each error's stack frames */
25
+ includeStackTrace?: boolean;
26
+ };
27
+ /**
28
+ * Extract the chain of errors linked by `cause`, from outermost to innermost.
29
+ *
30
+ * Stops after 100 links, so a circular `cause` can't loop forever.
31
+ *
32
+ * @param error - The error to extract the chain from
33
+ * @returns An array of errors in the chain, from outermost to innermost
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const inner = new Error("connection refused")
38
+ * const outer = new Error("load user failed", { cause: inner })
39
+ * getErrorChain(outer) // [outer, inner]
40
+ * ```
41
+ */
42
+ export declare const getErrorChain: (error: Error | undefined) => Error[];
43
+ /**
44
+ * Format an error's cause chain as a string, one error per line.
45
+ *
46
+ * Lines after the first start with `↳ `. With `includeTasks`, a line whose error carries
47
+ * `taskInfo.name` (as `Throwable` does) is prefixed with `[name] `.
48
+ *
49
+ * @param error - The error to format
50
+ * @param options - Formatting options
51
+ * @returns A formatted string representation of the error chain
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * const inner = new Error("connection refused")
56
+ * const outer = new Error("load user failed", { cause: inner })
57
+ * formatErrorChain(outer) // "load user failed\n↳ connection refused"
58
+ * ```
59
+ */
60
+ export declare const formatErrorChain: (error: Error | undefined, options?: ErrorChainFormatOptions) => string;
@@ -0,0 +1,4 @@
1
+ import{ArrayBuilder as e}from"../internal/mutation-utils.js";import{Ref as t}from"../ref/Ref.js";function n(e){return e instanceof Error&&e._tag===`Throwable`}const r=n=>{if(!n)return[];let r=e();r.add(n);let i=t(n);for(;i.get()&&i.get().cause;){let{cause:e}=i.get();if(e)r.add(e),i.set(e);else break;if(r.size()>100)break}return r.build()},i=(e,n)=>{let i=r(e),a=n?.separator??`
2
+ `;return i.map((e,r)=>{if(!e)return`${r>0?`↳ `:``}Unknown error`;let{taskInfo:i}=e,a=n?.includeTasks&&i?.name?`[${i.name}] `:``,o=e.message??`No message`,s=t(`${r>0?`↳ `:``}${a}${o}`);return n?.includeStackTrace&&e.stack&&s.set(`${s.get()}\n${e.stack.split(`
3
+ `).slice(1).join(`
4
+ `)}`),s.get()}).join(a)};export{i as formatErrorChain,r as getErrorChain,n as isTaggedThrowable};
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Type definition for task information that may be attached to errors
3
+ */
4
+ export type TaskErrorInfo = {
5
+ name?: string;
6
+ description?: string;
7
+ [key: string]: unknown;
8
+ };
9
+ /**
10
+ * Type definition for an error with potential task information
11
+ */
12
+ export type ErrorWithTaskInfo = Error & {
13
+ taskInfo?: TaskErrorInfo;
14
+ data?: unknown;
15
+ };
16
+ /**
17
+ * Type definition for a structured error chain element
18
+ */
19
+ export type ErrorChainElement = {
20
+ message?: string;
21
+ name?: string;
22
+ taskInfo?: TaskErrorInfo;
23
+ stack?: string;
24
+ [key: string]: unknown;
25
+ };
26
+ /**
27
+ * Options for formatting error chains
28
+ */
29
+ export type ErrorFormatterOptions = {
30
+ /** Include task names in the formatted output */
31
+ includeTasks?: boolean;
32
+ /** Include stack traces in the formatted output */
33
+ includeStackTrace?: boolean;
34
+ /** Separator between error lines (default: newline) */
35
+ separator?: string;
36
+ /** Include detailed error data in the output */
37
+ includeData?: boolean;
38
+ /** Maximum number of stack frames to include if stack trace is enabled */
39
+ maxStackFrames?: number;
40
+ /** Title to display at the start of the formatted error */
41
+ title?: string;
42
+ /** Format the output with colors for console display */
43
+ colors?: boolean;
44
+ };
45
+ /**
46
+ * Safely stringify data including BigInt values and circular references
47
+ */
48
+ export declare function safeStringify(obj: unknown): string;
49
+ /**
50
+ * Format a stack trace string for better readability
51
+ */
52
+ export declare function formatStackTrace(stack: string | undefined): string;
53
+ /**
54
+ * Create a formatted string representation of an error for better logging and display
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const error = new Error("Something went wrong");
59
+ * console.error(formatError(error, { colors: true, includeData: true }));
60
+ * ```
61
+ */
62
+ export declare function formatError(error: unknown, options?: ErrorFormatterOptions): string;
63
+ /**
64
+ * Create a serializer function for Pino or other JSON loggers
65
+ * to better represent errors with their full context
66
+ */
67
+ export declare function createErrorSerializer(): (err: unknown) => unknown;
@@ -0,0 +1,6 @@
1
+ import{Throwable as e}from"../core/throwable/Throwable.js";import{formatErrorChain as t,getErrorChain as n}from"./ErrorChain.js";const r={includeTasks:!0,includeStackTrace:!1,separator:`
2
+ `,includeData:!1,maxStackFrames:3,title:`Error`,colors:!1};function i(e){let t=/* @__PURE__ */ new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return`${n.toString()}n`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular Reference]`;t.add(n)}return e===`stack`&&typeof n==`string`?a(n):n},2)}function a(e){if(e===void 0||e===``)return``;let t=e.split(`
3
+ `);return[t[0],...t.slice(1).map(e=>e.trim())].join(`
4
+ `)}function o(t,o){let s={...r,...o},c=t instanceof Error?t:e.apply(t),l=n(c),u=`${s.colors?`\x1b[31m${s.title}:\x1b[0m ${c.message}`:`${s.title}: ${c.message}`}\n\n${l.map((e,t)=>{let n=` `.repeat(t),i=t>0?`↳ `:``,{taskInfo:o}=e,c=`${n}${i}${s.includeTasks&&o?.name?s.colors?`\x1b[36m[${o.name}]\x1b[0m `:`[${o.name}] `:``}${e.message}`;if(s.includeStackTrace&&e.stack){let t=a(e.stack).split(`
5
+ `).slice(1),i=s.maxStackFrames??r.maxStackFrames??3,o=t.slice(0,i).map(e=>`${n} ${s.colors?`\x1B[90m`:``}${e}${s.colors?`\x1B[0m`:``}`).join(`
6
+ `);c+=`\n${o}`,t.length>i&&(c+=`\n${n} ${s.colors?`\x1B[90m`:``}...${t.length-i} more stack frames${s.colors?`\x1B[0m`:``}`)}return c}).join(s.separator)}`;if(s.includeData){let{data:e}=c;if(e){let t=s.colors?`\n\n\x1b[33mContext:\x1b[0m\n${i(e)}`:`\n\nContext:\n${i(e)}`;u+=t}}return u}function s(){return function(e){if(!e)return e;let r=e instanceof Error?e:Error(String(e)),i={message:r.message,name:r.name||`Error`,stack:r.stack?a(r.stack):void 0};r.taskInfo&&(i.taskInfo=r.taskInfo),r.data&&(i.data=r.data);try{let e=n(r);e.length>1&&(i.errorChain=t(r,{includeTasks:!0}),i.structuredErrorChain=e.map(e=>({message:e.message,name:e.name,taskInfo:e.taskInfo,stack:e.stack?a(e.stack):void 0})))}catch{}return Object.getOwnPropertyNames(r).forEach(e=>{if(!i[e]){let t=r[e];i[e]=t}}),i}}export{s as createErrorSerializer,o as formatError,a as formatStackTrace,i as safeStringify};
@@ -0,0 +1,6 @@
1
+ export declare const ParseError: (message?: string) => Error & {
2
+ name: "ParseError";
3
+ };
4
+ export type ParseError = Error & {
5
+ name: "ParseError";
6
+ };
@@ -0,0 +1 @@
1
+ const e=e=>{let t=Error(e);return t.name=`ParseError`,t};export{e as ParseError};
@@ -0,0 +1,146 @@
1
+ import { Throwable } from "../../core/throwable/Throwable.js";
2
+ /**
3
+ * Type-safe error codes using template literal types
4
+ */
5
+ export type ErrorCode = "VALIDATION_FAILED" | "NETWORK_ERROR" | "AUTH_REQUIRED" | "NOT_FOUND" | "PERMISSION_DENIED" | "RATE_LIMITED" | "INTERNAL_ERROR" | "BAD_REQUEST" | "CONFLICT" | "TIMEOUT";
6
+ /**
7
+ * Template literal type for error messages based on error code
8
+ */
9
+ export 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;
10
+ /**
11
+ * HTTP status codes mapped to error codes
12
+ */
13
+ export 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;
14
+ /**
15
+ * Context type for each error code
16
+ */
17
+ export type TypedErrorContext<T extends ErrorCode> = T extends "VALIDATION_FAILED" ? {
18
+ field: string;
19
+ value: unknown;
20
+ rule: string;
21
+ } : T extends "NETWORK_ERROR" ? {
22
+ url: string;
23
+ method: string;
24
+ statusCode?: number;
25
+ } : T extends "AUTH_REQUIRED" ? {
26
+ resource: string;
27
+ requiredRole?: string;
28
+ } : T extends "NOT_FOUND" ? {
29
+ resource: string;
30
+ id: string | number;
31
+ } : T extends "PERMISSION_DENIED" ? {
32
+ action: string;
33
+ resource: string;
34
+ userId?: string;
35
+ } : T extends "RATE_LIMITED" ? {
36
+ limit: number;
37
+ window: string;
38
+ retryAfter?: number;
39
+ } : T extends "INTERNAL_ERROR" ? {
40
+ errorId: string;
41
+ timestamp: string;
42
+ } : T extends "BAD_REQUEST" ? {
43
+ reason: string;
44
+ expected?: string;
45
+ } : T extends "CONFLICT" ? {
46
+ resource: string;
47
+ conflictingValue: string;
48
+ } : T extends "TIMEOUT" ? {
49
+ duration: number;
50
+ operation: string;
51
+ } : Record<string, unknown>;
52
+ /**
53
+ * Type-safe error class with template literal types
54
+ */
55
+ export interface TypedError<T extends ErrorCode> extends Throwable {
56
+ readonly code: T;
57
+ readonly message: ErrorMessage<T>;
58
+ readonly status: ErrorStatus<T>;
59
+ readonly context: TypedErrorContext<T>;
60
+ readonly timestamp: string;
61
+ readonly traceId?: string;
62
+ }
63
+ export declare const TypedError: (<T extends ErrorCode>(code: T, message: ErrorMessage<T>, context: TypedErrorContext<T>, options?: {
64
+ cause?: unknown;
65
+ traceId?: string;
66
+ }) => TypedError<T>) & {
67
+ /**
68
+ * Create a validation error
69
+ * @example
70
+ * const error = TypedError.validation("email", "test@", "must be valid email")
71
+ * // Type: TypedError<"VALIDATION_FAILED">
72
+ * // Message must match: "Validation failed: ..."
73
+ */
74
+ validation: (field: string, value: unknown, rule: string) => TypedError<"VALIDATION_FAILED">;
75
+ /**
76
+ * Create a network error
77
+ * @example
78
+ * const error = TypedError.network("https://api.example.com", "POST", 500)
79
+ * // Type: TypedError<"NETWORK_ERROR">
80
+ */
81
+ network: (url: string, method: string, statusCode?: number) => TypedError<"NETWORK_ERROR">;
82
+ /**
83
+ * Create an authentication error
84
+ * @example
85
+ * const error = TypedError.auth("/api/admin", "admin")
86
+ * // Type: TypedError<"AUTH_REQUIRED">
87
+ */
88
+ auth: (resource: string, requiredRole?: string) => TypedError<"AUTH_REQUIRED">;
89
+ /**
90
+ * Create a not found error
91
+ * @example
92
+ * const error = TypedError.notFound("user", "123")
93
+ * // Type: TypedError<"NOT_FOUND">
94
+ */
95
+ notFound: (resource: string, id: string | number) => TypedError<"NOT_FOUND">;
96
+ /**
97
+ * Create a permission denied error
98
+ * @example
99
+ * const error = TypedError.permission("delete", "post", "user123")
100
+ * // Type: TypedError<"PERMISSION_DENIED">
101
+ */
102
+ permission: (action: string, resource: string, userId?: string) => TypedError<"PERMISSION_DENIED">;
103
+ /**
104
+ * Create a rate limit error
105
+ * @example
106
+ * const error = TypedError.rateLimit(100, "1h", 3600)
107
+ * // Type: TypedError<"RATE_LIMITED">
108
+ */
109
+ rateLimit: (limit: number, window: string, retryAfter?: number) => TypedError<"RATE_LIMITED">;
110
+ /**
111
+ * Create an internal error
112
+ * @example
113
+ * const error = TypedError.internal("ERR-500-ABC123")
114
+ * // Type: TypedError<"INTERNAL_ERROR">
115
+ */
116
+ internal: (errorId: string) => TypedError<"INTERNAL_ERROR">;
117
+ /**
118
+ * Create a bad request error
119
+ * @example
120
+ * const error = TypedError.badRequest("Invalid JSON", "valid JSON object")
121
+ * // Type: TypedError<"BAD_REQUEST">
122
+ */
123
+ badRequest: (reason: string, expected?: string) => TypedError<"BAD_REQUEST">;
124
+ /**
125
+ * Create a conflict error
126
+ * @example
127
+ * const error = TypedError.conflict("email", "user@example.com")
128
+ * // Type: TypedError<"CONFLICT">
129
+ */
130
+ conflict: (resource: string, conflictingValue: string) => TypedError<"CONFLICT">;
131
+ /**
132
+ * Create a timeout error
133
+ * @example
134
+ * const error = TypedError.timeout(30000, "database query")
135
+ * // Type: TypedError<"TIMEOUT">
136
+ */
137
+ timeout: (duration: number, operation: string) => TypedError<"TIMEOUT">;
138
+ /**
139
+ * Check if a value is a TypedError
140
+ */
141
+ isTypedError: (value: unknown) => value is TypedError<ErrorCode>;
142
+ /**
143
+ * Check if a TypedError has a specific code
144
+ */
145
+ hasCode: <T extends ErrorCode>(error: TypedError<ErrorCode>, code: T) => error is TypedError<T>;
146
+ };
@@ -0,0 +1 @@
1
+ import{Throwable as e}from"../../core/throwable/Throwable.js";import{mergeObjects as t}from"../../util/index.js";const n=(n,i,a,o)=>{let s=e.apply(i,a,{name:n,description:i});return t(s,{code:n,message:i,status:r(n),context:a,timestamp:(/* @__PURE__ */ new Date()).toISOString(),traceId:o?.traceId})},r=e=>({VALIDATION_FAILED:400,BAD_REQUEST:400,AUTH_REQUIRED:401,PERMISSION_DENIED:403,NOT_FOUND:404,TIMEOUT:408,CONFLICT:409,RATE_LIMITED:429,INTERNAL_ERROR:500,NETWORK_ERROR:503})[e],i=Object.assign(n,{validation:(e,t,r)=>n(`VALIDATION_FAILED`,`Validation failed: ${e} ${r}`,{field:e,value:t,rule:r}),network:(e,t,r)=>n(`NETWORK_ERROR`,`Network error: ${t} ${e}${r?` (${r})`:``}`,{url:e,method:t,statusCode:r}),auth:(e,t)=>n(`AUTH_REQUIRED`,`Authentication required: ${e}${t?` (role: ${t})`:``}`,{resource:e,requiredRole:t}),notFound:(e,t)=>n(`NOT_FOUND`,`Not found: ${e} with id ${t}`,{resource:e,id:t}),permission:(e,t,r)=>n(`PERMISSION_DENIED`,`Permission denied: cannot ${e} ${t}`,{action:e,resource:t,userId:r}),rateLimit:(e,t,r)=>n(`RATE_LIMITED`,`Rate limit exceeded: ${e} requests per ${t}`,{limit:e,window:t,retryAfter:r}),internal:e=>n(`INTERNAL_ERROR`,`Internal server error: ${e}`,{errorId:e,timestamp:(/* @__PURE__ */ new Date()).toISOString()}),badRequest:(e,t)=>n(`BAD_REQUEST`,`Bad request: ${e}`,{reason:e,expected:t}),conflict:(e,t)=>n(`CONFLICT`,`Conflict: ${e} already exists with value ${t}`,{resource:e,conflictingValue:t}),timeout:(e,t)=>n(`TIMEOUT`,`Request timeout: ${t} exceeded ${e}ms`,{duration:e,operation:t}),isTypedError:e=>typeof e==`object`&&!!e&&`code`in e&&`message`in e&&`status`in e&&`context`in e&&`_tag`in e&&e._tag===`Throwable`,hasCode:(e,t)=>e.code===t});export{i as TypedError};