functype 1.27.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1150 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +290 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1263 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +8 -13
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-BadxJrCt.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BQPeS6p2.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
package/dist/either/index.d.ts
CHANGED
|
@@ -1,2 +1,290 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
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
|
+
/**
|
|
54
|
+
* Maps the Right value with a function that may throw, catching the throw into a Left built by
|
|
55
|
+
* `onError`. `map` lets a throw escape. Use `mapTry` for a callback you don't own.
|
|
56
|
+
*
|
|
57
|
+
* - A Left passes through unchanged, and `f` doesn't run.
|
|
58
|
+
* - A throw from `onError` itself escapes.
|
|
59
|
+
* - Only a synchronous throw is caught. For an async callback, use `tryCatchAsync`.
|
|
60
|
+
*
|
|
61
|
+
* Same as `either.flatMap((value) => tryCatch(() => f(value), onError))`, with functype's `tryCatch`.
|
|
62
|
+
*/
|
|
63
|
+
mapTry<U extends Type, L2 extends Type>(f: (value: R) => U, onError: (error: unknown) => L2): Either<L | L2, U>;
|
|
64
|
+
ap<L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>): Either<L | L2, U>;
|
|
65
|
+
merge<L1 extends Type, R1 extends Type>(other: Either<L1, R1>): Either<L | L1, [R, R1]>;
|
|
66
|
+
/**
|
|
67
|
+
* Maps the Right value with an async function. A Left resolves unchanged.
|
|
68
|
+
* If `f` rejects or throws, the returned Promise rejects with the same reason: it does not
|
|
69
|
+
* become a Left, and it never throws synchronously. To turn a rejection into a Left, use `Either.fromPromise(p, onRejected)`
|
|
70
|
+
* or `tryCatchAsync`, which take a function from the reason to `L`.
|
|
71
|
+
*/
|
|
72
|
+
mapAsync<U extends Type>(f: (value: R) => Promise<U>): Promise<Either<L, U>>;
|
|
73
|
+
flatMap<L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U>;
|
|
74
|
+
/**
|
|
75
|
+
* Chains an async function that returns an Either. A Left resolves unchanged.
|
|
76
|
+
* If `f` rejects or throws, the returned Promise rejects with the same reason, as with `mapAsync`.
|
|
77
|
+
*/
|
|
78
|
+
flatMapAsync<L2 extends Type, U extends Type>(f: (value: R) => Promise<Either<L2, U>>): Promise<Either<L | L2, U>>;
|
|
79
|
+
toOption(): Option<R>;
|
|
80
|
+
toString(): string;
|
|
81
|
+
[Symbol.iterator]: () => Iterator<R>;
|
|
82
|
+
yield(): Generator<R, void, unknown>;
|
|
83
|
+
traverse<L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U[]>;
|
|
84
|
+
tap(f: (value: R) => void): Either<L, R>;
|
|
85
|
+
tapLeft(f: (value: L) => void): Either<L, R>;
|
|
86
|
+
mapLeft<L2 extends Type>(f: (value: L) => L2): Either<L2, R>;
|
|
87
|
+
/**
|
|
88
|
+
* Applies a predicate to the Right value. If the predicate fails, short-circuits
|
|
89
|
+
* to a Left carrying the value produced by `onUnsatisfied`. Left passes through
|
|
90
|
+
* unchanged (predicate not evaluated). Lets you turn a value-level guard into the
|
|
91
|
+
* Left channel without breaking the chain with an `if/return Left(...)` ladder.
|
|
92
|
+
* @param predicate - The predicate to test the Right value
|
|
93
|
+
* @param onUnsatisfied - Builds the new Left value when the predicate fails
|
|
94
|
+
* @returns Right if the predicate holds, Left(onUnsatisfied(value)) otherwise
|
|
95
|
+
*/
|
|
96
|
+
filterOrElse<L2 extends Type>(predicate: (value: R) => boolean, onUnsatisfied: (value: R) => L2): Either<L | L2, R>;
|
|
97
|
+
bimap<L2 extends Type, R2 extends Type>(fl: (value: L) => L2, fr: (value: R) => R2): Either<L2, R2>;
|
|
98
|
+
fold<T extends Type>(onLeft: (value: L) => T, onRight: (value: R) => T): T;
|
|
99
|
+
/**
|
|
100
|
+
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
101
|
+
* always returns a Promise, keeping chains fluent when at least one branch is async.
|
|
102
|
+
*/
|
|
103
|
+
foldAsync<T extends Type>(onLeft: (value: L) => T | Promise<T>, onRight: (value: R) => T | Promise<T>): Promise<T>;
|
|
104
|
+
swap(): Either<R, L>;
|
|
105
|
+
/**
|
|
106
|
+
* Pipes the value through the provided function based on whether this is a Left or Right
|
|
107
|
+
*/
|
|
108
|
+
pipeEither<U extends Type>(onLeft: (value: L) => U, onRight: (value: R) => U): U;
|
|
109
|
+
/**
|
|
110
|
+
* Pipes the Either value through the provided function
|
|
111
|
+
*/
|
|
112
|
+
pipe<U extends Type>(f: (value: L | R) => U): U;
|
|
113
|
+
/**
|
|
114
|
+
* Pattern matches over the Either, applying a handler function based on the variant
|
|
115
|
+
*/
|
|
116
|
+
match<T>(patterns: {
|
|
117
|
+
Left: (value: L) => T;
|
|
118
|
+
Right: (value: R) => T;
|
|
119
|
+
}): T;
|
|
120
|
+
/**
|
|
121
|
+
* Returns the value and tag for inspection
|
|
122
|
+
*/
|
|
123
|
+
toValue(): {
|
|
124
|
+
_tag: "Left" | "Right";
|
|
125
|
+
value: L | R;
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Custom JSON serialization that excludes getter properties.
|
|
129
|
+
* Emits the canonical functype envelope with `@functype: "Either"` so
|
|
130
|
+
* native `JSON.stringify` recursion (e.g. inside a plain object body)
|
|
131
|
+
* produces a marker-bearing envelope that survives a round-trip through
|
|
132
|
+
* `Serialization.deserialize`.
|
|
133
|
+
*/
|
|
134
|
+
toJSON(): {
|
|
135
|
+
"@functype": "Either";
|
|
136
|
+
_tag: "Left" | "Right";
|
|
137
|
+
value: L | R;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Left variant of Either. Discriminated by `_tag: "Left"` with `value: L`.
|
|
142
|
+
*/
|
|
143
|
+
export interface LeftOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
|
|
144
|
+
readonly _tag: "Left";
|
|
145
|
+
readonly value: L;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Right variant of Either. Discriminated by `_tag: "Right"` with `value: R`.
|
|
149
|
+
*/
|
|
150
|
+
export interface RightOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
|
|
151
|
+
readonly _tag: "Right";
|
|
152
|
+
readonly value: R;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Either is a discriminated union of LeftOf and RightOf. TypeScript narrows
|
|
156
|
+
* across both branches of `isLeft()` / `isRight()` and `_tag` checks. Variance
|
|
157
|
+
* is inherited from LeftOf/RightOf (both covariant in L and R) — union type
|
|
158
|
+
* aliases cannot carry their own variance annotations in TS.
|
|
159
|
+
*/
|
|
160
|
+
export type Either<L extends Type, R extends Type> = LeftOf<L, R> | RightOf<L, R>;
|
|
161
|
+
export type TestEither<L extends Type, R extends Type> = Either<L, R> & AsyncMonad<R>;
|
|
162
|
+
export declare const Right: <L extends Type, R extends Type>(value: R) => Either<L, R>;
|
|
163
|
+
export declare const Left: <L extends Type, R extends Type>(value: L) => Either<L, R>;
|
|
164
|
+
export declare const isRight: <L extends Type, R extends Type>(either: Either<L, R>) => either is RightOf<L, R>;
|
|
165
|
+
export declare const isLeft: <L extends Type, R extends Type>(either: Either<L, R>) => either is LeftOf<L, R>;
|
|
166
|
+
export declare const tryCatch: <L extends Type, R extends Type>(f: () => R, onError: (error: unknown) => L) => Either<L, R>;
|
|
167
|
+
export declare const TypeCheckRight: <L extends Type, R extends Type>(value: R) => TestEither<L, R>;
|
|
168
|
+
export declare const TypeCheckLeft: <L extends Type, R extends Type>(value: L) => TestEither<L, R>;
|
|
169
|
+
export declare const tryCatchAsync: <L extends Type, R extends Type>(f: () => Promise<R>, onError: (error: unknown) => L) => Promise<Either<L, R>>;
|
|
170
|
+
/**
|
|
171
|
+
* Either constructor that creates Left or Right based on the isRight parameter
|
|
172
|
+
* @param value - The value to wrap
|
|
173
|
+
* @param isRight - If true, creates Right, otherwise creates Left
|
|
174
|
+
* @returns Either instance
|
|
175
|
+
*/
|
|
176
|
+
declare const EitherConstructor: <L extends Type, R extends Type>(value: R | L, isRight: boolean) => Either<L, R>;
|
|
177
|
+
declare const EitherStatics: {
|
|
178
|
+
/**
|
|
179
|
+
* Creates a Left instance
|
|
180
|
+
* @param value - The left value
|
|
181
|
+
* @returns Left Either
|
|
182
|
+
*/
|
|
183
|
+
left: <L extends Type, R extends Type>(value: L) => Either<L, R>;
|
|
184
|
+
/**
|
|
185
|
+
* Creates a Right instance
|
|
186
|
+
* @param value - The right value
|
|
187
|
+
* @returns Right Either
|
|
188
|
+
*/
|
|
189
|
+
right: <L extends Type, R extends Type>(value: R) => Either<L, R>;
|
|
190
|
+
/**
|
|
191
|
+
* Creates a Right<L, void> — convenience for "operation succeeded with no meaningful value".
|
|
192
|
+
* Avoids variance quirks around Either<L, void> vs Either<L, undefined>.
|
|
193
|
+
* @returns Right Either with void value
|
|
194
|
+
*/
|
|
195
|
+
void: <L extends Type>() => Either<L, void>;
|
|
196
|
+
/**
|
|
197
|
+
* Type guard to check if an Either is Right
|
|
198
|
+
* @param either - The Either to check
|
|
199
|
+
* @returns True if Either is Right
|
|
200
|
+
*/
|
|
201
|
+
isRight: <L extends Type, R extends Type>(either: Either<L, R>) => either is RightOf<L, R>;
|
|
202
|
+
/**
|
|
203
|
+
* Type guard to check if an Either is Left
|
|
204
|
+
* @param either - The Either to check
|
|
205
|
+
* @returns True if Either is Left
|
|
206
|
+
*/
|
|
207
|
+
isLeft: <L extends Type, R extends Type>(either: Either<L, R>) => either is LeftOf<L, R>;
|
|
208
|
+
/**
|
|
209
|
+
* Combines an array of Eithers into a single Either containing an array
|
|
210
|
+
* @param eithers - Array of Either values
|
|
211
|
+
* @returns Either with array of values or first Left encountered
|
|
212
|
+
*/
|
|
213
|
+
sequence: <L extends Type, R extends Type>(eithers: ReadonlyArray<Either<L, R>>) => Either<L, R[]>;
|
|
214
|
+
/**
|
|
215
|
+
* Maps an array through a function that returns Either, then sequences the results.
|
|
216
|
+
* Short-circuits on the first Left: `f` is not called for the elements after it.
|
|
217
|
+
* @param arr - Array of values
|
|
218
|
+
* @param f - Function that returns Either, given each value and its index
|
|
219
|
+
* @returns Either with array of results or first Left encountered
|
|
220
|
+
*/
|
|
221
|
+
traverse: <L extends Type, R extends Type, U extends Type>(arr: ReadonlyArray<R>, f: (value: R, index: number) => Either<L, U>) => Either<L, U[]>;
|
|
222
|
+
/**
|
|
223
|
+
* Async traverse: runs `f` over `items` and collects the Right values, stopping at the first Left.
|
|
224
|
+
*
|
|
225
|
+
* Runs one call at a time, in order, by default. Pass `{ concurrency: n }` to allow up to `n` calls at once,
|
|
226
|
+
* or `"unbounded"` to start them all together. After a Left no new calls start; calls already running
|
|
227
|
+
* finish, and the result is the Left of the earliest item that failed. A rejected promise rejects the result.
|
|
228
|
+
*
|
|
229
|
+
* @param items - Values to traverse (an array, List, or any iterable)
|
|
230
|
+
* @param f - Async function returning Either
|
|
231
|
+
* @param options - `{ concurrency }`; defaults to 1 (sequential)
|
|
232
|
+
* @returns Right of all results in input order, or the first Left
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```typescript
|
|
236
|
+
* const saved = await Either.traverseAsync(rows, (row) => saveRow(row))
|
|
237
|
+
* // Either<SaveError, SavedRow[]>, one save at a time, stopping at the first failure
|
|
238
|
+
*
|
|
239
|
+
* const fetched = await Either.traverseAsync(ids, fetchUser, { concurrency: 4 })
|
|
240
|
+
* ```
|
|
241
|
+
*/
|
|
242
|
+
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[]>>;
|
|
243
|
+
/**
|
|
244
|
+
* Creates an Either from a nullable value
|
|
245
|
+
* @param value - The value that might be null or undefined
|
|
246
|
+
* @param leftValue - The value to use for Left if value is null/undefined
|
|
247
|
+
* @returns Right if value is not null/undefined, Left otherwise
|
|
248
|
+
*/
|
|
249
|
+
fromNullable: <L extends Type, R extends Type>(value: R | null | undefined, leftValue: L) => Either<L, R>;
|
|
250
|
+
/**
|
|
251
|
+
* Creates an Either based on a predicate
|
|
252
|
+
* @param value - The value to test
|
|
253
|
+
* @param predicate - The predicate function
|
|
254
|
+
* @param leftValue - The value to use for Left if predicate fails
|
|
255
|
+
* @returns Right if predicate passes, Left otherwise
|
|
256
|
+
*/
|
|
257
|
+
fromPredicate: <L extends Type, R extends Type>(value: R, predicate: (value: R) => boolean, leftValue: L) => Either<L, R>;
|
|
258
|
+
/**
|
|
259
|
+
* Applicative apply - applies a wrapped function to a wrapped value
|
|
260
|
+
* @param eitherF - Either containing a function
|
|
261
|
+
* @param eitherV - Either containing a value
|
|
262
|
+
* @returns Either with function applied to value
|
|
263
|
+
*/
|
|
264
|
+
ap: <L extends Type, R extends Type, U extends Type>(eitherF: Either<L, (value: R) => U>, eitherV: Either<L, R>) => Either<L, U>;
|
|
265
|
+
/**
|
|
266
|
+
* Creates an Either from a Promise
|
|
267
|
+
* @param promise - The Promise to convert
|
|
268
|
+
* @param onRejected - Function to convert rejection reason to Left value
|
|
269
|
+
* @returns Promise that resolves to Either
|
|
270
|
+
*/
|
|
271
|
+
fromPromise: <L, R>(promise: Promise<R>, onRejected: (reason: unknown) => L) => Promise<Either<L, R>>;
|
|
272
|
+
/**
|
|
273
|
+
* Creates an Either from JSON string
|
|
274
|
+
* @param json - The JSON string
|
|
275
|
+
* @returns Either instance
|
|
276
|
+
*/
|
|
277
|
+
fromJSON: <L extends Type, R extends Type>(json: string) => Either<L, R>;
|
|
278
|
+
/**
|
|
279
|
+
* Creates an Either from binary string
|
|
280
|
+
* @param binary - The binary string
|
|
281
|
+
* @returns Either instance
|
|
282
|
+
*/
|
|
283
|
+
fromBinary: <L extends Type, R extends Type>(binary: string) => Either<L, R>;
|
|
284
|
+
};
|
|
285
|
+
export declare const Either: EitherCompanion;
|
|
286
|
+
/** The type of `Either`: its constructor and its statics, named so that errors and hovers print `EitherCompanion`. */
|
|
287
|
+
export interface EitherCompanion extends EitherConstructorType, EitherStaticsType {}
|
|
288
|
+
type EitherConstructorType = typeof EitherConstructor;
|
|
289
|
+
type EitherStaticsType = typeof EitherStatics;
|
|
290
|
+
export {};
|
package/dist/either/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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))},mapTry(e,t){return b(()=>e(this.value),t)},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)},mapTry(){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 @@
|
|
|
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};
|