either-lite 0.0.1 → 0.1.1-beta.implementation.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 ADDED
@@ -0,0 +1,513 @@
1
+ # either-lite
2
+
3
+ Opinionated `Either` implementation with a minimal API and async handlers.
4
+
5
+ ```bash
6
+ npm i -SE either-lite
7
+ ```
8
+
9
+ ## Why
10
+
11
+ Modern Either/Result libraries like `neverthrow`, `@sweet-monads/either`, `true-myth`, `fp-ts`, `effect` and etc ship rich APIs: `map`, `chain`, `fold`, `match`, applicative combinators, companion monads. It's handy, but most of time you need just unwrap Either instance from promise and continue your chain. That is what this library does!
12
+
13
+ ## The contract
14
+
15
+ Every step of a flow returns its outcome wrapped in `left()` / `right()`. Exceptions are never used for control flow: `try`/`catch` appears only at boundaries, to convert a foreign throwing API (like `fetch` or `JSON.parse`) into an Either. If a step can fail, it returns `left(...)` — that is a normal, non-exceptional outcome, and the chain carries it downstream.
16
+
17
+ The library enforces this rather than repairing deviations: `fromPromise` does not catch. A rejecting thunk rejects the chain and `await` throws, so a rejection is a bug that fails loudly — never a silently converted value.
18
+
19
+ ## Table of contents
20
+
21
+ - [Core concepts](#core-concepts)
22
+ - [General example](#general-example)
23
+ - [Top-level API](#top-level-api)
24
+ - [Creating Eithers](#creating-eithers)
25
+ - [`right(value)`](#rightvalue)
26
+ - [`left(value)`](#leftvalue)
27
+ - [Inspecting an Either](#inspecting-an-either)
28
+ - [`isRight()`](#isright)
29
+ - [`isLeft()`](#isleft)
30
+ - [The `value` field](#the-value-field)
31
+ - [Reacting to one side](#reacting-to-one-side)
32
+ - [`.right(callback)`](#rightcallback)
33
+ - [`.left(callback)`](#leftcallback)
34
+ - [Async chains](#async-chains)
35
+ - [`AsyncEither` overview](#asynceither-overview)
36
+ - [`fromPromise(fn)`](#frompromisefn)
37
+ - [`AsyncEither#asyncRight(callback)`](#asynceitherasyncrightcallback)
38
+ - [`AsyncEither#asyncLeft(callback)`](#asynceitherasyncleftcallback)
39
+ - [Sync taps: `AsyncEither#right(callback)` / `AsyncEither#left(callback)`](#sync-taps-asynceitherrightcallback--asynceitherleftcallback)
40
+ - [`await` and PromiseLike interop](#await-and-promiselike-interop)
41
+ - [Behavioral contracts and edge cases](#behavioral-contracts-and-edge-cases)
42
+ - [Type-level notes](#type-level-notes)
43
+ - [Design goals and non-goals](#design-goals-and-non-goals)
44
+
45
+ ## Core concepts
46
+
47
+ `Either<LeftValue, RightValue>` is a union of two concrete classes — `Left<LeftValue, RightValue>` and `Right<LeftValue, RightValue>` — both exported. Each holds its payload in a readonly `value` field, so a Right's `value` is `RightValue` and a Left's `value` is `LeftValue`. This is what makes `isRight()` / `isLeft()` real type guards — after a check, TypeScript knows exactly which type `value` holds.
48
+
49
+ An **async chain** is an `AsyncEither<LeftValue, RightValue>`: a `PromiseLike<Either<LeftValue, RightValue>>` that settles to exactly what its source settles to, created via `fromPromise(fn)` — the only way to build a chain:
50
+
51
+ - it **settles to exactly what the source settles to** — `fromPromise` captures nothing: a resolved Either becomes the chain's value (the very instance), a rejecting source rejects the chain, and a synchronously throwing thunk throws at the call site. Under the contract none of that happens — your own code returns failures as `Left` and converts foreign throwing APIs at the boundary — so when it does happen, it is a bug failing loudly, never a silently repaired value;
52
+ - it is `PromiseLike`, so `await`, `Promise.all`, and async-function returns all work on it;
53
+ - its `asyncRight` / `asyncLeft` handlers receive the *unwrapped* value and return the **next step** of the chain: an `Either`, an `AsyncEither`, or a `PromiseLike<Either>` — one level of flattening, exactly like `neverthrow`'s `andThen` / `orElse`. The opposite side is never called and passes through.
54
+ - its synchronous `right` / `left` taps observe the settled side without changing what the chain settles to — these are the "reaction" counterparts of the async steps.
55
+
56
+ ## General example
57
+
58
+ A request to a server can fail in three different places — the network itself, the server's error status, and parsing the response body. `Either` chains compose so that all three failures land in a single typed value:
59
+
60
+ ```ts
61
+ import { Either, fromPromise, left, right } from 'either-lite';
62
+
63
+ // Every failure in the flow is one of these — plain values, not Error instances.
64
+ type RequestError =
65
+ | 'network-failed' // connection dropped, DNS failed, offline, …
66
+ | 'invalid-json' // the body was not valid JSON
67
+ | number; // the server answered with an error HTTP status
68
+
69
+ interface User {
70
+ id: string;
71
+ name: string;
72
+ }
73
+
74
+ // Step 1 — send the request. A rejecting fetch() becomes a Left,
75
+ // and a non-OK status becomes a Left carrying the status code.
76
+ function fetchUser(id: string): Promise<Either<RequestError, Response>> {
77
+ return fetch(`/api/users/${id}`)
78
+ .then((res): Either<RequestError, Response> =>
79
+ res.ok ? right(res) : left(res.status),
80
+ )
81
+ .catch((): Either<RequestError, Response> => left('network-failed'));
82
+ }
83
+
84
+ // Step 2 — parse the body. res.json() rejects on malformed JSON,
85
+ // so the failure is converted to a Left as well.
86
+ async function parseUser(res: Response): Promise<Either<RequestError, User>> {
87
+ try {
88
+ return right((await res.json()) as User);
89
+ } catch {
90
+ return left('invalid-json');
91
+ }
92
+ }
93
+
94
+ // Step 3 — compose. fromPromise() starts a chain from the Either-returning
95
+ // fetchUser(), and asyncRight() flattens the Either that parseUser() returns,
96
+ // so the whole flow becomes a single chain of typed Left/Right values.
97
+ function loadUser(id: string) {
98
+ return fromPromise(() => fetchUser(id)).asyncRight(parseUser);
99
+ }
100
+
101
+ // Usage — one flow, two ways to consume it.
102
+
103
+ // 1. React to the in-flight chain: the taps fire when it settles,
104
+ // each receiving the unwrapped value.
105
+ loadUser('42')
106
+ .left((error) => showError(errorMessage(error)))
107
+ .right((profile) => renderProfile(profile));
108
+
109
+ // 2. Or await it: a plain Either comes out, handled with .left() / .right().
110
+ const user = await loadUser('42');
111
+ user.left((error) => showError(errorMessage(error)));
112
+ user.right((profile) => renderProfile(profile));
113
+
114
+ function errorMessage(error: RequestError): string {
115
+ // Plain values are compared with === — no instanceof anywhere.
116
+ return error === 'network-failed' ? 'You are offline'
117
+ : error === 'invalid-json' ? 'The server sent a malformed response'
118
+ : `The server answered with status ${error}`;
119
+ }
120
+ ```
121
+
122
+ After the two `===` checks TypeScript narrows `error` to `number` in the last branch, so the status code is used directly — no casting or `instanceof` needed.
123
+
124
+ ## Top-level API
125
+
126
+ ```ts
127
+ import {
128
+ Either, // type Either<LeftValue, RightValue> = Left | Right
129
+ Left, // class Left<LeftValue, RightValue>
130
+ Right, // class Right<LeftValue, RightValue>
131
+ type AsyncEither, // the async chain type — exported as type-only; build chains with fromPromise
132
+ AsyncEitherStep, // type of the values asyncRight/asyncLeft handlers return
133
+ fromPromise, // starts an async chain from a () => Promise<Either<LeftValue, RightValue>> thunk
134
+ right, // create a Right
135
+ left, // create a Left
136
+ } from 'either-lite';
137
+ ```
138
+
139
+ ## Creating Eithers
140
+
141
+ ### `right(value)`
142
+
143
+ Constructs the `Right` (success) variant.
144
+
145
+ **Signature:**
146
+
147
+ ```ts
148
+ right<LeftValue = never, RightValue = never>(value: RightValue): Either<LeftValue, RightValue>;
149
+ ```
150
+
151
+ **Example:**
152
+
153
+ ```ts
154
+ import { right, left, Either } from 'either-lite';
155
+
156
+ type ParseError = 'not-a-number' | 'out-of-range';
157
+
158
+ const v1 = right(2); // Either<never, number>
159
+ const v2 = right<ParseError, number>(8080); // Either<ParseError, number>
160
+
161
+ function parsePort(raw: string): Either<ParseError, number> {
162
+ const port = Number(raw);
163
+ if (!Number.isInteger(port)) {
164
+ return left<ParseError, number>('not-a-number');
165
+ }
166
+ if (port < 1 || port > 65535) {
167
+ return left<ParseError, number>('out-of-range');
168
+ }
169
+ return right<ParseError, number>(port);
170
+ }
171
+ ```
172
+
173
+ ### `left(value)`
174
+
175
+ Constructs the `Left` (failure) variant.
176
+
177
+ **Signature:**
178
+
179
+ ```ts
180
+ left<LeftValue = never, RightValue = never>(value: LeftValue): Either<LeftValue, RightValue>;
181
+ ```
182
+
183
+ **Example:**
184
+
185
+ ```ts
186
+ import { left, Either } from 'either-lite';
187
+
188
+ export const NOT_FOUND = Symbol('not-found');
189
+ type LoadError = typeof NOT_FOUND | 'offline';
190
+
191
+ const v1 = left(NOT_FOUND); // Either<typeof NOT_FOUND, never>
192
+ const v2 = left<LoadError, User>(NOT_FOUND); // Either<LoadError, User>
193
+ const v3 = left<LoadError, User>('offline'); // Either<LoadError, User>
194
+ ```
195
+
196
+ **A note on payloads.** `left()` accepts any data, and plain identifiers are usually the best fit: string literals and symbols compare with `===`, need no `instanceof`, survive serialization, and give you a closed list of failure reasons in the type. Reach for an `Error` object only when you genuinely need a stack trace.
197
+
198
+ Because the unfilled side defaults to `never`, a bare `left(x)` is assignable wherever a wider `Either` is expected; pass both generics explicitly when you want a fully typed value in one call (same as `@sweet-monads/either`'s `left<L, R>`).
199
+
200
+ The `Left` / `Right` classes are exported, but the factories are the idiomatic way to construct values — you rarely need `new Left(...)` / `new Right(...)` yourself.
201
+
202
+ ## Inspecting an Either
203
+
204
+ ### `isRight()`
205
+
206
+ Returns `true` if the Either is a Right. This is a type guard: inside the `if`, the value is narrowed and `value` is `RightValue`.
207
+
208
+ **Signature:**
209
+
210
+ ```ts
211
+ isRight(): boolean; // type guard: inside the if, value is RightValue
212
+ ```
213
+
214
+ **Example:**
215
+
216
+ ```ts
217
+ const result = parsePort('8080'); // Either<ParseError, number>
218
+
219
+ if (result.isRight()) {
220
+ result.value; // number — ParseError branch is excluded by the type system
221
+ } else {
222
+ result.value; // ParseError
223
+ }
224
+ ```
225
+
226
+ ### `isLeft()`
227
+
228
+ Returns `true` if the Either is a Left. Mirror of `isRight()`.
229
+
230
+ **Signature:**
231
+
232
+ ```ts
233
+ isLeft(): boolean; // type guard: inside the if, value is LeftValue
234
+ ```
235
+
236
+ **Example:**
237
+
238
+ ```ts
239
+ const result = parsePort('99999'); // Either<ParseError, number>
240
+
241
+ if (result.isLeft()) {
242
+ result.value; // 'not-a-number' | 'out-of-range'
243
+ if (result.value === 'out-of-range') {
244
+ // handle one specific reason — plain ===, no instanceof
245
+ }
246
+ }
247
+ ```
248
+
249
+ ### The `value` field
250
+
251
+ Readonly payload of the Either, typed by its side: `RightValue` on a Right, `LeftValue` on a Left.
252
+
253
+ On an `Either<LeftValue, RightValue>` union it is `L | R`; narrow with the guards above to get the precise type.
254
+
255
+ ```ts
256
+ const result = parsePort('8080'); // Either<ParseError, number>
257
+ result.value; // ParseError | number
258
+
259
+ if (result.isRight()) {
260
+ result.value; // number
261
+ }
262
+ ```
263
+
264
+ Eithers are immutable: `value` is `readonly` and no method mutates the instance.
265
+
266
+ ## Reacting to one side
267
+
268
+ ### `.right(callback)`
269
+
270
+ Runs `callback` with the unwrapped value **only if this is a Right**, then returns `this` for chaining. A Left is passed through untouched, callback not called.
271
+
272
+ **Signature:**
273
+
274
+ ```ts
275
+ right(onRight: (value: RightValue) => void): this;
276
+ ```
277
+
278
+ - `onRight: (value: RightValue) => void` — called with the payload when the Either is Right.
279
+ - Returns `this` (the same instance), so side handlers chain.
280
+
281
+ **Example:**
282
+
283
+ ```ts
284
+ parsePort(raw)
285
+ .right((port) => console.log(`listening on ${port}`)) // runs for Right only
286
+ .left((error) => console.error(`port error: ${error}`)); // runs for Left only
287
+ ```
288
+
289
+ The callback is invoked synchronously during the call. If the callback itself throws, the exception propagates to the caller as usual — this is the synchronous counterpart of the async fail-loud contract below.
290
+
291
+ ### `.left(callback)`
292
+
293
+ Runs `callback` with the unwrapped value **only if this is a Left**, then returns `this`. Mirror of `.right()`.
294
+
295
+ **Signature:**
296
+
297
+ ```ts
298
+ left(onLeft: (value: LeftValue) => void): this;
299
+ ```
300
+
301
+ **Example:**
302
+
303
+ ```ts
304
+ left<ParseError, number>('not-a-number')
305
+ .right((port) => console.log(port)) // not called
306
+ .left((error) => console.error(error)); // "not-a-number"
307
+ ```
308
+
309
+ ## Async chains
310
+
311
+ ### `AsyncEither` overview
312
+
313
+ `AsyncEither<LeftValue, RightValue>` is the async chain: a `PromiseLike<Either<LeftValue, RightValue>>` with two async step methods (`asyncRight` / `asyncLeft`), two sync taps (`right` / `left`), and `then`. It is exported as a **type only** — the class is module-private — so you can name it in annotations (`function loadUser(id: string): AsyncEither<RequestError, User>`), while `fromPromise` stays the only way to build a chain.
314
+
315
+ ### `fromPromise(fn)`
316
+
317
+ Starts an async chain from a *thunk* — a function producing a `Promise<Either<LeftValue, RightValue>>`. The thunk is called once, immediately, and the resolved Either is unwrapped into the chain. Both type parameters are inferred from the thunk's return type.
318
+
319
+ If you already hold the promise, pass a thunk that returns it — the thunk is still invoked once, immediately, so this is the direct way to adopt an existing `PromiseLike<Either<...>>`:
320
+
321
+ ```ts
322
+ // fetchUser(id): Promise<Either<RequestError, Response>> — already Either-based
323
+ const chain = fromPromise(() => fetchUser('42'));
324
+ chain.asyncRight((res) => parseUser(res));
325
+ ```
326
+
327
+ The chain settles to exactly what the thunk's promise settles to — `fromPromise` adds no capture or conversion. A resolved Either becomes the chain's value; a rejection rejects the chain; a synchronously throwing thunk throws at the call site. Under the contract neither happens (producers *return* `left(...)` for failures, and foreign throwing APIs are converted at the boundary with `try`/`catch`); if it does happen, it is a bug and it fails loudly — `await` throws, and an unhandled chain crashes the process.
328
+
329
+ **Signature:**
330
+
331
+ ```ts
332
+ fromPromise<LeftValue, RightValue>(
333
+ source: () => PromiseLike<Either<LeftValue, RightValue>>,
334
+ ): AsyncEither<LeftValue, RightValue>;
335
+ ```
336
+
337
+ **Example:**
338
+
339
+ ```ts
340
+ const loadData = () =>
341
+ fromPromise(fetchProduct) // () => Promise<Either<string, Product>>
342
+ .asyncRight((product) => fetchRelatedProducts(product.category)) // Either-returning step
343
+ .right((products) => products.forEach(renderProduct)); // sync tap on the result
344
+ ```
345
+
346
+ Handlers attached before settlement wait for it; handlers attached after fire on a subsequent microtask.
347
+
348
+ ### `AsyncEither#asyncRight(callback)`
349
+
350
+ Runs `callback` with the **unwrapped** value once the chain settles as a Right, and flattens the returned **step** into the chain. A step is one of:
351
+
352
+ - an `Either` — becomes the chain's next value (this is how transformations compose);
353
+ - an `AsyncEither` — awaited and adopted;
354
+ - a `PromiseLike<Either>` — awaited and flattened (this is how async functions that return `Promise<Either<...>>` plug in directly).
355
+
356
+ When the chain settles as a Left, the callback is skipped and the Left passes through to the returned chain.
357
+
358
+ **Signature:**
359
+
360
+ ```ts
361
+ asyncRight<NewRightValue, NewLeftValue>(
362
+ onRight: (value: RightValue) => AsyncEitherStep<NewLeftValue, NewRightValue>,
363
+ ): AsyncEither<LeftValue | NewLeftValue, NewRightValue>;
364
+ ```
365
+
366
+ - `onRight` receives the payload, not the Either.
367
+ - The method returns a **new** `AsyncEither`; the source chain is untouched.
368
+ - The left type widens: a step that can itself fail with `NewLeftValue` produces `AsyncEither<LeftValue | NewLeftValue, NewRightValue>`.
369
+
370
+ **Example:**
371
+
372
+ ```ts
373
+ // fetchUser(id): Promise<Either<RequestError, Response>>
374
+ // parseUser(res): Promise<Either<RequestError, User>>
375
+ fromPromise(() => fetchUser(1)) // AsyncEither<RequestError, Response>
376
+ .asyncRight(parseUser) // PromiseLike<Either> step → AsyncEither<RequestError, User>
377
+ .right((user) => renderProfile(user)); // reaction: sync tap, chain unchanged
378
+ ```
379
+
380
+ **Handlers must not throw.** An exception inside a step handler — or a step promise that rejects — surfaces as a rejection on the *derived* chain: an unhandled rejection (process crash under Node's default `--unhandled-rejections=throw`) if nobody handles it. This is deliberate: callback errors are never silently swallowed (see [Behavioral contracts](#behavioral-contracts-and-edge-cases)). If a handler can fail, handle the failure inside the handler and return it as a Left.
381
+
382
+ ### `AsyncEither#asyncLeft(callback)`
383
+
384
+ Runs `callback` with the **unwrapped** value once the chain settles as a Left, and flattens the returned step. Mirror of `asyncRight` — and the idiomatic recovery path: return a `Right` to fall back to a value, or a `Left` to keep failing (optionally with a new reason).
385
+
386
+ **Signature:**
387
+
388
+ ```ts
389
+ asyncLeft<NewLeftValue, NewRightValue>(
390
+ onLeft: (value: LeftValue) => AsyncEitherStep<NewLeftValue, NewRightValue>,
391
+ ): AsyncEither<NewLeftValue, RightValue | NewRightValue>;
392
+ ```
393
+
394
+ - The right type widens: a recovery that can produce `NewRightValue` yields `AsyncEither<NewLeftValue, RightValue | NewRightValue>`.
395
+ - When the chain settles as a Right, the callback is skipped and the Right passes through.
396
+
397
+ **Example:**
398
+
399
+ ```ts
400
+ fromPromise(() => loadUser(1)) // AsyncEither<LoadError, User>
401
+ .asyncLeft((error) => retry(error)) // recover: Either<LoadError, User>
402
+ .asyncRight((user) => renderProfile(user)) // skipped when loadUser fails
403
+ .left(() => showToast('giving up')); // reaction: sync tap on a settled Left
404
+ ```
405
+
406
+ ### Sync taps: `AsyncEither#right(callback)` / `AsyncEither#left(callback)`
407
+
408
+ Synchronous-style counterparts of the async steps, matching the settled-Either API: once the chain settles, the callback fires with the unwrapped value **only if the settled side matches**, and the method returns the same instance. Taps chain freely, and a `.left()` tap intercepts any upstream Left — no matter how many async steps produced it — while a `.right()` tap sees the Right value as it is at that point in the chain.
409
+
410
+ **Signature:**
411
+
412
+ ```ts
413
+ right(onRight: (value: RightValue) => void): this;
414
+ left(onLeft: (value: LeftValue) => void): this;
415
+ ```
416
+
417
+ - The callback's return value is ignored — a tap never transforms the chain (use `asyncRight` / `asyncLeft` for that). In particular, an Either or promise returned from a tap is *not* unwrapped.
418
+ - The callback runs on a microtask after settlement; like the async steps, a throwing tap fails loudly as an unhandled rejection.
419
+
420
+ **Example:**
421
+
422
+ ```ts
423
+ fromPromise(fetchProduct) // () => Promise<Either<string, Product>>
424
+ .asyncRight((product) => fetchRelatedProducts(product.category)) // async step
425
+ .right((products) => { products.forEach(renderProduct); }) // sync tap
426
+ .left(() => showError()); // intercepts any upstream Left
427
+ ```
428
+
429
+ ### `await` and PromiseLike interop
430
+
431
+ The chain implements `PromiseLike<Either<LeftValue, RightValue>>`: awaiting it (or calling `.then` on it) yields the settled `Either` itself.
432
+
433
+ **Signature:**
434
+
435
+ ```ts
436
+ then<FulfilledValue = Either<LeftValue, RightValue>, RejectedValue = never>(
437
+ onFulfilled?: ((value: Either<LeftValue, RightValue>) => FulfilledValue | PromiseLike<FulfilledValue>) | null,
438
+ onRejected?: ((reason: unknown) => RejectedValue | PromiseLike<RejectedValue>) | null,
439
+ ): PromiseLike<FulfilledValue | RejectedValue>;
440
+ ```
441
+
442
+ **Example:**
443
+
444
+ ```ts
445
+ // await yields the Either
446
+ const either: Either<LoadError, User> = await fromPromise(() => loadUser(1));
447
+
448
+ either.isRight(); // narrow and read as usual
449
+
450
+ // usable anywhere a PromiseLike is expected
451
+ const [either2] = await Promise.all([fromPromise(() => loadUser(2))]);
452
+
453
+ // returned from an async function, it is awaited like a normal thenable
454
+ async function load(id: number): Promise<Either<LoadError, User>> {
455
+ return fromPromise(() => loadUser(id));
456
+ }
457
+ ```
458
+
459
+ `onRejected` exists to satisfy the `PromiseLike` interface: it fires only if the source promise rejected — a contract violation — so in well-behaved code it is dead code.
460
+
461
+ ## Behavioral contracts and edge cases
462
+
463
+ These are guarantees (and sharp edges) of the implementation. Every one of them is covered by a unit test in `either.test.ts`.
464
+
465
+ **The chain settles to exactly what the source settles to.** `fromPromise` performs no capture or repair: a resolved Either becomes the chain's value, a rejection rejects the chain, and a synchronous throw in the thunk propagates to the caller. `await chain` hands you an Either whenever the contract holds; when it doesn't, the failure is loud — a thrown rejection where the chain is awaited, a process crash on an unhandled one. A step handler that throws or returns a rejecting step likewise rejects its derived chain (next paragraph).
466
+
467
+ **Right can carry any value.** A Right payload is never inspected or filtered: `0`, `''`, `null`, `undefined` and any other falsy value are perfectly valid Right values — only the constructor decides the side.
468
+
469
+ **fromPromise settles to the resolved Either — nothing more.** A promise that resolves to an Either settles the chain to that very instance; no copying, no re-wrapping, no inspection. Resolving with a non-Either is a contract violation — the types forbid it, and at runtime it will crash downstream when the chain touches it, not get silently repaired into `Right(value)`. To *carry* an Either as the Right value of another Either, wrap it once:
470
+
471
+ ```ts
472
+ const inner: Either<ParseError, number> = right<ParseError, number>(8080);
473
+ const nested = await fromPromise(() => Promise.resolve(right(inner)));
474
+ // Either<never, Either<ParseError, number>> — the Either is the Right payload
475
+ ```
476
+
477
+ **Async steps flatten exactly one level.** A step returning an Either, an AsyncEither, or a PromiseLike of Either is flattened into the chain; the opposite side passes through untouched.
478
+
479
+ **Async handlers fail loudly.** A throwing handler cannot propagate its exception back through the settled chain (the call site has long returned), so it surfaces as a rejection on the derived chain — an unhandled promise rejection, which Node's default policy turns into a process crash, when nobody handles it. The same applies to a step whose returned promise rejects, and to a sync `.right()` / `.left()` tap on a pending chain. Errors are never dropped silently; a handler that can throw must catch internally. The synchronous `.right()` / `.left()` on a settled Either are different: they run during the call, so a throwing callback propagates to the caller as usual.
480
+
481
+ **Handlers are additive and timing-agnostic.** Any number of `asyncRight` / `asyncLeft` steps and `right` / `left` taps can be attached, in any order, before or after settlement; all matching handlers run. Handlers attached after settlement run on a subsequent microtask, matching promise semantics.
482
+
483
+ **No mutation.** Eithers are immutable, and registering a handler never changes the settled value. Sync taps return the same chain; `asyncRight` / `asyncLeft` return a new chain that settles to the Either their handler returned — or to the settled Either, carried through, when the handler's side did not match.
484
+
485
+ ## Type-level notes
486
+
487
+ **Generic order is always `<LeftValue, RightValue>`** — matching the `Either<LeftValue, RightValue>` type, for the factories *and* `fromPromise`:
488
+
489
+ ```ts
490
+ right<ParseError, number>(8080); // Either<ParseError, number>
491
+ left<ParseError, number>('out-of-range'); // Either<ParseError, number>
492
+ fromPromise(fetchProduct); // AsyncEither<string, Product> — inferred
493
+ ```
494
+
495
+ **Literals are preserved.** `left('out-of-range')` infers `Either<'out-of-range', never>` and `right(7)` infers `Either<never, number>` — pin the generics when you want a wider type (`left<RequestError, User>('offline')`), or use them bare when the literal is all you need. The unfilled side defaults to `never`, which is assignable to anything, so a bare `left(x)` / `right(x)` fits any matching position.
496
+
497
+ **Step types widen by design.** A step that can fail adds its left type to the chain's (`AsyncEither<L | NewLeftValue, R>`); a recovery that can succeed adds its right type (`AsyncEither<L, R | NewRightValue>`). Fully recovering a chain back to a single right type requires the recovery step to produce that same right type.
498
+
499
+ **Narrowing is what makes `value` precise.** On the `Either<LeftValue, RightValue>` union, `value` is `L | R`; the `isRight()` / `isLeft()` type guards narrow the whole Either, and `value` narrows with it.
500
+
501
+ **`AsyncEither` is a named, exported type.** Name it directly in types (`function loadUser(id: string): AsyncEither<RequestError, User>`); there is no hidden chain type to work around. The class itself is module-private — `fromPromise` is the only constructor.
502
+
503
+ Requires TypeScript with `strict: true` (the type guards and narrowing assume it).
504
+
505
+ ## Design goals and non-goals
506
+
507
+ - **Failures are returned, not thrown.** The contract starts at the chain seed: `fromPromise` takes a thunk returning `Promise<Either<...>>`, and every step returns an Either — so a failing validation, a rejected request, a missing record are all ordinary `left(...)` values flowing down the chain. `fromPromise` captures nothing: a rejecting thunk rejects the chain and `await` throws — the catch-rejection-and-wrap-it behavior other libraries provide is exactly the kind of silent repair this library refuses, and throwing across the API is never required.
508
+ - **No separate `map` / `chain` / `fold` / `match` family.** The side callbacks do double duty: return an Either from `asyncRight` / `asyncLeft` to transform the chain, register a sync tap to react; branch with `isRight()` / `isLeft()` when you need the value in the current scope. Transformations that can fail belong in the `Either`-returning functions you call, not in dedicated combinators.
509
+ - **Steps return Eithers explicitly.** An `asyncRight` / `asyncLeft` handler never takes a plain value or `undefined` shortcut: the next step is always an `Either`, an `AsyncEither`, or a promise of one. That is the `neverthrow` discipline — what a step produces is visible at the call site, and only one level of flattening ever happens.
510
+ - **No error-accumulation combinators** (`mergeInMany`, `combineWithAllErrors`, `Validation`, …) and **no companion types** (Maybe, Option, Task, …). If you need those, look to other implementations.
511
+ - **Fail-loud over fail-silent.** Async handler errors crash rather than vanish (see contracts above). The library also never repairs contract violations: a producer that resolves with a non-Either fails loudly when the chain touches it, exactly like a handler that throws. If you prefer wrapped-and-ignored error channels, this is not your library.
512
+
513
+ What it keeps: a tiny API surface (`right`, `left`, `fromPromise` as the only constructors, classes `Left` / `Right`, exported types `Either` / `AsyncEither` / `AsyncEitherStep`, and the `asyncRight` / `asyncLeft` / side callbacks per layer), full type narrowing and zero runtime dependencies.
@@ -0,0 +1,33 @@
1
+ export type Either<LeftValue, RightValue> = Left<LeftValue, RightValue> | Right<LeftValue, RightValue>;
2
+ export declare class Left<LeftValue, RightValue> {
3
+ readonly value: LeftValue;
4
+ constructor(value: LeftValue);
5
+ isLeft(): this is Left<LeftValue, RightValue>;
6
+ isRight(): this is Right<LeftValue, RightValue>;
7
+ left(onLeft: (value: LeftValue) => void): this;
8
+ right(_onRight: (value: RightValue) => void): this;
9
+ }
10
+ export declare class Right<LeftValue, RightValue> {
11
+ readonly value: RightValue;
12
+ constructor(value: RightValue);
13
+ isLeft(): this is Left<LeftValue, RightValue>;
14
+ isRight(): this is Right<LeftValue, RightValue>;
15
+ left(_onLeft: (value: LeftValue) => void): this;
16
+ right(onRight: (value: RightValue) => void): this;
17
+ }
18
+ export declare function left<LeftValue extends string, RightValue = never>(value: LeftValue): Either<LeftValue, RightValue>;
19
+ export declare function left<LeftValue, RightValue = never>(value: LeftValue): Either<LeftValue, RightValue>;
20
+ export declare function right<LeftValue = never, RightValue extends string = string>(value: RightValue): Either<LeftValue, RightValue>;
21
+ export declare function right<LeftValue = never, RightValue = never>(value: RightValue): Either<LeftValue, RightValue>;
22
+ export type AsyncEitherStep<LeftValue, RightValue> = Either<LeftValue, RightValue> | AsyncEither<LeftValue, RightValue> | PromiseLike<Either<LeftValue, RightValue>>;
23
+ declare class AsyncEither<LeftValue, RightValue> implements PromiseLike<Either<LeftValue, RightValue>> {
24
+ private readonly _promise;
25
+ constructor(promise: PromiseLike<Either<LeftValue, RightValue>>);
26
+ asyncRight<NewRightValue, NewLeftValue>(onRight: (value: RightValue) => AsyncEitherStep<NewLeftValue, NewRightValue>): AsyncEither<LeftValue | NewLeftValue, NewRightValue>;
27
+ asyncLeft<NewLeftValue, NewRightValue>(onLeft: (value: LeftValue) => AsyncEitherStep<NewLeftValue, NewRightValue>): AsyncEither<NewLeftValue, RightValue | NewRightValue>;
28
+ left(onLeft: (value: LeftValue) => void): this;
29
+ right(onRight: (value: RightValue) => void): this;
30
+ then<FulfilledValue = Either<LeftValue, RightValue>, RejectedValue = never>(onFulfilled?: ((value: Either<LeftValue, RightValue>) => FulfilledValue | PromiseLike<FulfilledValue>) | null, onRejected?: ((reason: unknown) => RejectedValue | PromiseLike<RejectedValue>) | null): PromiseLike<FulfilledValue | RejectedValue>;
31
+ }
32
+ export type { AsyncEither };
33
+ export declare const fromPromise: <LeftValue, RightValue>(source: () => PromiseLike<Either<LeftValue, RightValue>>) => AsyncEither<LeftValue, RightValue>;
package/dist/either.js ADDED
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fromPromise = exports.Right = exports.Left = void 0;
4
+ exports.left = left;
5
+ exports.right = right;
6
+ class Left {
7
+ value;
8
+ constructor(value) {
9
+ this.value = value;
10
+ }
11
+ isLeft() {
12
+ return true;
13
+ }
14
+ isRight() {
15
+ return false;
16
+ }
17
+ left(onLeft) {
18
+ onLeft(this.value);
19
+ return this;
20
+ }
21
+ right(_onRight) {
22
+ return this;
23
+ }
24
+ }
25
+ exports.Left = Left;
26
+ class Right {
27
+ value;
28
+ constructor(value) {
29
+ this.value = value;
30
+ }
31
+ isLeft() {
32
+ return false;
33
+ }
34
+ isRight() {
35
+ return true;
36
+ }
37
+ left(_onLeft) {
38
+ return this;
39
+ }
40
+ right(onRight) {
41
+ onRight(this.value);
42
+ return this;
43
+ }
44
+ }
45
+ exports.Right = Right;
46
+ function left(value) {
47
+ return new Left(value);
48
+ }
49
+ function right(value) {
50
+ return new Right(value);
51
+ }
52
+ class AsyncEither {
53
+ _promise;
54
+ constructor(promise) {
55
+ this._promise = promise;
56
+ }
57
+ asyncRight(onRight) {
58
+ return new AsyncEither(this._promise.then(async (either) => {
59
+ if (either.isLeft()) {
60
+ return new Left(either.value);
61
+ }
62
+ return onRight(either.value);
63
+ }));
64
+ }
65
+ asyncLeft(onLeft) {
66
+ return new AsyncEither(this._promise.then(async (either) => {
67
+ if (either.isRight()) {
68
+ return new Right(either.value);
69
+ }
70
+ return onLeft(either.value);
71
+ }));
72
+ }
73
+ left(onLeft) {
74
+ void this._promise.then((either) => {
75
+ if (either.isLeft()) {
76
+ onLeft(either.value);
77
+ }
78
+ });
79
+ return this;
80
+ }
81
+ right(onRight) {
82
+ void this._promise.then((either) => {
83
+ if (either.isRight()) {
84
+ onRight(either.value);
85
+ }
86
+ });
87
+ return this;
88
+ }
89
+ then(onFulfilled, onRejected) {
90
+ return this._promise.then(onFulfilled, onRejected);
91
+ }
92
+ }
93
+ const fromPromise = (source) => new AsyncEither(source());
94
+ exports.fromPromise = fromPromise;
package/package.json CHANGED
@@ -1,4 +1,45 @@
1
1
  {
2
2
  "name": "either-lite",
3
- "version": "0.0.1"
3
+ "version": "0.1.1-beta.implementation.0",
4
+ "description": "Minimal Either with typed async chains — left/right factories, type-guard narrowing, fail-loud handlers, zero dependencies",
5
+ "main": "dist/either.js",
6
+ "types": "dist/either.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/either.d.ts",
10
+ "default": "./dist/either.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "sideEffects": false,
17
+ "license": "MIT",
18
+ "author": "LakeVostok",
19
+ "repository": "LakeVostok/either-lite",
20
+ "bugs": "https://github.com/LakeVostok/either-lite/issues",
21
+ "homepage": "https://github.com/LakeVostok/either-lite#readme",
22
+ "keywords": [
23
+ "either",
24
+ "result",
25
+ "monad",
26
+ "error-handling",
27
+ "async",
28
+ "functional"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.build.json",
32
+ "tsc": "tsc --noEmit -p tsconfig.json",
33
+ "test": "vitest run",
34
+ "lint": "eslint .",
35
+ "check": "npm run lint && npm t && npm run tsc",
36
+ "prepublishOnly": "npm run check && npm run build"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "26.6.6",
40
+ "eslint": "10.14.0",
41
+ "typescript": "5.9.3",
42
+ "typescript-eslint": "8.72.1",
43
+ "vitest": "5.1.0"
44
+ }
4
45
  }