@nlozgachev/pipelined 0.64.0 → 0.65.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/dist/Core-BDXRLmMa.cjs +6147 -0
- package/dist/Core-BHN87zoB.mjs +6010 -0
- package/dist/InternalTypes-B1Lh9uw_.d.cts +143 -0
- package/dist/InternalTypes-DzDey5Do.d.ts +143 -0
- package/dist/composition.cjs +724 -632
- package/dist/composition.d.cts +453 -446
- package/dist/composition.d.ts +453 -446
- package/dist/composition.mjs +695 -577
- package/dist/core.cjs +24 -6580
- package/dist/core.d.cts +3 -2627
- package/dist/core.d.ts +3 -2627
- package/dist/core.mjs +2 -6532
- package/dist/data.cjs +2889 -3682
- package/dist/data.d.cts +1234 -1228
- package/dist/data.d.ts +1234 -1228
- package/dist/data.mjs +2880 -3647
- package/dist/index-B07Wr815.d.ts +4383 -0
- package/dist/index-Bs8En5LJ.d.cts +238 -0
- package/dist/index-Bs8En5LJ.d.ts +238 -0
- package/dist/index-DCK_VPog.d.cts +4383 -0
- package/dist/index.cjs +69 -9607
- package/dist/index.d.cts +6 -7
- package/dist/index.d.ts +6 -7
- package/dist/index.mjs +5 -9517
- package/dist/types.cjs +195 -225
- package/dist/types.d.cts +2 -58
- package/dist/types.d.ts +2 -58
- package/dist/types.mjs +192 -196
- package/package.json +24 -15
- package/dist/Duration-DeyxG6VQ.d.cts +0 -181
- package/dist/Duration-DeyxG6VQ.d.ts +0 -181
- package/dist/InternalTypes-CCXa8Kvr.d.ts +0 -142
- package/dist/InternalTypes-GFn4RTwD.d.cts +0 -142
- package/dist/Task-9SJCMtG4.d.ts +0 -1748
- package/dist/Task-C_goFYQ1.d.cts +0 -1748
|
@@ -0,0 +1,4383 @@
|
|
|
1
|
+
import { n as Duration, t as RetryPolicy } from "./index-Bs8En5LJ.js";
|
|
2
|
+
import { _ as WithSecond, a as Thenable, b as WithValue, c as WithCooldown, d as WithErrors, f as WithFirst, g as WithN, h as WithMinInterval, i as RetryOptions, l as WithDuration, m as WithLog, o as TimeoutOptions, p as WithKind, r as NonEmptyArr, s as WithConcurrency, u as WithError, v as WithSize, x as Deferred, y as WithTimeout } from "./InternalTypes-DzDey5Do.js";
|
|
3
|
+
//#region src/Core/Combinable.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A type that can combine two values of type `A` into one, with a neutral starting value.
|
|
6
|
+
* `empty` is the identity: `combine(empty)(a) === a` and `combine(a)(empty) === a`.
|
|
7
|
+
* `combine(b)(a)` appends `b` onto `a` — `a` is the accumulated value, `b` is the new element.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* pipe(["hello", ", ", "world"], Combinable.fold(Combinable.string)); // "hello, world"
|
|
12
|
+
* pipe([1, 2, 3, 4, 5], Combinable.fold(Combinable.sum)); // 15
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
type Combinable<A> = {
|
|
16
|
+
readonly empty: A;
|
|
17
|
+
readonly combine: (b: A) => (a: A) => A;
|
|
18
|
+
};
|
|
19
|
+
declare const Combinable: {
|
|
20
|
+
/**
|
|
21
|
+
* Combines strings by concatenation. Empty string is the neutral element.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* pipe(["a", "b", "c"], Combinable.fold(Combinable.string)); // "abc"
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
string: Combinable<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Combines numbers by addition. `0` is the neutral element.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* pipe([1, 2, 3], Combinable.fold(Combinable.sum)); // 6
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
sum: Combinable<number>;
|
|
38
|
+
/**
|
|
39
|
+
* Combines numbers by multiplication. `1` is the neutral element.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* pipe([2, 3, 4], Combinable.fold(Combinable.product)); // 24
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
product: Combinable<number>;
|
|
47
|
+
/**
|
|
48
|
+
* Combines booleans with logical AND. `true` is the neutral element.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* pipe([true, true, false], Combinable.fold(Combinable.all)); // false
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
all: Combinable<boolean>;
|
|
56
|
+
/**
|
|
57
|
+
* Combines booleans with logical OR. `false` is the neutral element.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* pipe([false, false, true], Combinable.fold(Combinable.any)); // true
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
any: Combinable<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* Combines arrays by concatenation. Empty array is the neutral element.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* pipe([[1, 2], [3], [4, 5]], Combinable.fold(Combinable.array<number>())); // [1, 2, 3, 4, 5]
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
array: <A>() => Combinable<readonly A[]>;
|
|
74
|
+
/**
|
|
75
|
+
* Lifts a `Combinable<A>` to `Combinable<Maybe<A>>`. `None` is the neutral element —
|
|
76
|
+
* combining with `None` on either side returns the other value unchanged.
|
|
77
|
+
* Two `Some` values combine their inner values using the inner `Combinable`.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const c = Combinable.maybe(Combinable.sum);
|
|
82
|
+
* c.combine(Maybe.make.some(3))(Maybe.make.some(2)); // Some(5)
|
|
83
|
+
* c.combine(Maybe.make.none())(Maybe.make.some(5)); // Some(5)
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
maybe: <A>(inner: Combinable<A>) => Combinable<Maybe<A>>;
|
|
87
|
+
/**
|
|
88
|
+
* Folds an array into a single value using the `Combinable`'s `empty` as the starting point.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* pipe([1, 2, 3, 4, 5], Combinable.fold(Combinable.sum)); // 15
|
|
93
|
+
* pipe([], Combinable.fold(Combinable.sum)); // 0
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
fold: <A>(c: Combinable<A>) => (data: readonly A[]) => A;
|
|
97
|
+
/**
|
|
98
|
+
* Derives a `Combinable` for a record of fields from field-level `Combinable` instances.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* const StatsCombinable = Combinable.struct({
|
|
103
|
+
* count: Combinable.sum,
|
|
104
|
+
* tags: Combinable.array<string>(),
|
|
105
|
+
* });
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
struct: <R extends Record<string, unknown>>(fields: { [K in keyof R]: Combinable<R[K]>; }) => Combinable<R>;
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/Core/Equality.d.ts
|
|
112
|
+
/**
|
|
113
|
+
* A function that checks whether two values of type `A` are equal.
|
|
114
|
+
* Use built-in instances (`Equality.string`, `Equality.number`, etc.) as starting points,
|
|
115
|
+
* then adapt them with `Equality.by` and combine them with `Equality.and`.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* type User = { id: string; name: string };
|
|
120
|
+
* const byId = pipe(Equality.string, Equality.by((u: User) => u.id));
|
|
121
|
+
*
|
|
122
|
+
* pipe(users, Arr.uniqWith(byId));
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
type Equality<A> = (a: A, b: A) => boolean;
|
|
126
|
+
declare const Equality: {
|
|
127
|
+
/**
|
|
128
|
+
* Equality for strings. Case-sensitive.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* Equality.string("hello", "hello"); // true
|
|
133
|
+
* Equality.string("hello", "Hello"); // false
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
string: Equality<string>;
|
|
137
|
+
/**
|
|
138
|
+
* Equality for numbers. Uses strict equality.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* Equality.number(42, 42); // true
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
number: Equality<number>;
|
|
146
|
+
/**
|
|
147
|
+
* Equality for booleans.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```ts
|
|
151
|
+
* Equality.boolean(true, true); // true
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
boolean: Equality<boolean>;
|
|
155
|
+
/**
|
|
156
|
+
* Equality for `Date` values. Compares by numeric time value.
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```ts
|
|
160
|
+
* Equality.date(new Date("2024-01-01"), new Date("2024-01-01")); // true
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
date: Equality<Date>;
|
|
164
|
+
/**
|
|
165
|
+
* Lifts an element equality into an array equality. Two arrays are equal if they have the
|
|
166
|
+
* same length and every element pair is equal under `eq`.
|
|
167
|
+
*
|
|
168
|
+
* @example
|
|
169
|
+
* ```ts
|
|
170
|
+
* Equality.array(Equality.number)([1, 2, 3], [1, 2, 3]); // true
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
array: <A>(eq: Equality<A>) => Equality<readonly A[]>;
|
|
174
|
+
/**
|
|
175
|
+
* Adapts an equality for type `A` into an equality for type `B` by extracting a field.
|
|
176
|
+
* Read as "equality by this field": `pipe(Equality.string, Equality.by(u => u.name))`.
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* ```ts
|
|
180
|
+
* type Product = { id: string; price: number };
|
|
181
|
+
* const byId = pipe(Equality.string, Equality.by((p: Product) => p.id));
|
|
182
|
+
* byId({ id: "p1", price: 9 }, { id: "p1", price: 12 }); // true
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
by: <A, B>(f: (b: B) => A) => (eq: Equality<A>) => Equality<B>;
|
|
186
|
+
/**
|
|
187
|
+
* Combines two equalities with logical AND. Both must pass for two values to be considered equal.
|
|
188
|
+
* Data-last: the first equality is the data being piped.
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* const exact = pipe(byName, Equality.and(byRole));
|
|
193
|
+
* exact(userA, userB); // true only if name AND role match
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
and: <A>(eq2: Equality<A>) => (eq1: Equality<A>) => Equality<A>;
|
|
197
|
+
/**
|
|
198
|
+
* Derives deep equality for a record from field-level `Equality` checkers.
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* ```ts
|
|
202
|
+
* const userEq = Equality.struct({
|
|
203
|
+
* id: Equality.string,
|
|
204
|
+
* age: Equality.number,
|
|
205
|
+
* });
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
struct: <R extends Record<string, unknown>>(fields: { [K in keyof R]: Equality<R[K]>; }) => Equality<R>;
|
|
209
|
+
/**
|
|
210
|
+
* Derives element-wise equality for a tuple from positional `Equality` checkers.
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* ```ts
|
|
214
|
+
* const pairEq = Equality.tuple(Equality.string, Equality.number);
|
|
215
|
+
* pairEq(["a", 1], ["a", 1]); // true
|
|
216
|
+
* ```
|
|
217
|
+
*/
|
|
218
|
+
tuple: <T extends readonly unknown[]>(...equalities: { [K in keyof T]: Equality<T[K]>; }) => Equality<T>;
|
|
219
|
+
};
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/Core/Lazy.d.ts
|
|
222
|
+
/**
|
|
223
|
+
* A synchronous memoized computation. The factory function runs exactly once —
|
|
224
|
+
* on the first call to `Lazy.evaluate` — and the result is cached for all subsequent calls.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```ts
|
|
228
|
+
* const config = Lazy.from(() => parseConfig(rawInput));
|
|
229
|
+
*
|
|
230
|
+
* pipe(
|
|
231
|
+
* config,
|
|
232
|
+
* Lazy.map(cfg => cfg.port),
|
|
233
|
+
* Lazy.evaluate,
|
|
234
|
+
* ); // parseConfig ran once; cfg.port returned
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
type Lazy<A> = {
|
|
238
|
+
readonly get: () => A;
|
|
239
|
+
};
|
|
240
|
+
declare const Lazy: {
|
|
241
|
+
/**
|
|
242
|
+
* Wraps a thunk in a `Lazy`. The thunk runs exactly once, on first `evaluate`.
|
|
243
|
+
*
|
|
244
|
+
* @example
|
|
245
|
+
* ```ts
|
|
246
|
+
* const expensive = Lazy.from(() => computeExpensiveValue(input));
|
|
247
|
+
* ```
|
|
248
|
+
*/
|
|
249
|
+
from: <A>(f: () => A) => Lazy<A>;
|
|
250
|
+
/**
|
|
251
|
+
* Forces evaluation and returns the cached result. Safe to call multiple times.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* ```ts
|
|
255
|
+
* const value = Lazy.evaluate(Lazy.from(() => 42)); // 42
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
evaluate: <A>(lazy: Lazy<A>) => A;
|
|
259
|
+
/**
|
|
260
|
+
* Transforms the result of a `Lazy` without triggering evaluation.
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* ```ts
|
|
264
|
+
* pipe(Lazy.from(() => loadConfig()), Lazy.map(cfg => cfg.port));
|
|
265
|
+
* ```
|
|
266
|
+
*/
|
|
267
|
+
map: <A, B>(f: (a: A) => B) => (lazy: Lazy<A>) => Lazy<B>;
|
|
268
|
+
/**
|
|
269
|
+
* Chains a `Lazy`-returning transformation without triggering evaluation.
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* ```ts
|
|
273
|
+
* pipe(
|
|
274
|
+
* Lazy.from(() => loadConfig()),
|
|
275
|
+
* Lazy.chain(cfg => Lazy.from(() => openConnection(cfg.dbUrl))),
|
|
276
|
+
* );
|
|
277
|
+
* ```
|
|
278
|
+
*/
|
|
279
|
+
chain: <A, B>(f: (a: A) => Lazy<B>) => (lazy: Lazy<A>) => Lazy<B>;
|
|
280
|
+
/**
|
|
281
|
+
* Runs a side effect on the value without changing it. Fires once, on first `evaluate`.
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```ts
|
|
285
|
+
* pipe(Lazy.from(() => compute()), Lazy.tap(v => console.log("computed:", v)));
|
|
286
|
+
* ```
|
|
287
|
+
*/
|
|
288
|
+
tap: <A>(f: (a: A) => void) => (lazy: Lazy<A>) => Lazy<A>;
|
|
289
|
+
};
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/Core/Lens.d.ts
|
|
292
|
+
/**
|
|
293
|
+
* Lens<S, A> focuses on a single value A inside a structure S, providing
|
|
294
|
+
* a composable way to read and immutably update nested data.
|
|
295
|
+
*
|
|
296
|
+
* A Lens always succeeds: the focused value is guaranteed to exist.
|
|
297
|
+
* For optional or indexed focuses, use Optional<S, A>.
|
|
298
|
+
*
|
|
299
|
+
* @example
|
|
300
|
+
* ```ts
|
|
301
|
+
* type Address = { city: string; zip: string };
|
|
302
|
+
* type User = { name: string; address: Address };
|
|
303
|
+
*
|
|
304
|
+
* const addressLens = Lens.from.property<User>()("address");
|
|
305
|
+
* const cityLens = Lens.from.property<Address>()("city");
|
|
306
|
+
* const userCityLens = pipe(addressLens, Lens.andThen(cityLens));
|
|
307
|
+
*
|
|
308
|
+
* pipe(user, Lens.get(userCityLens)); // "Berlin"
|
|
309
|
+
* pipe(user, Lens.set(userCityLens)("Hamburg")); // new User with city updated
|
|
310
|
+
* pipe(user, Lens.modify(userCityLens)(c => c.toUpperCase())); // "BERLIN"
|
|
311
|
+
* ```
|
|
312
|
+
*/
|
|
313
|
+
type Lens<S, A> = {
|
|
314
|
+
readonly get: (s: S) => A;
|
|
315
|
+
readonly set: (a: A) => (s: S) => S;
|
|
316
|
+
};
|
|
317
|
+
declare const Lens: {
|
|
318
|
+
from: {
|
|
319
|
+
/**
|
|
320
|
+
* Constructs a Lens from a getter and a setter.
|
|
321
|
+
*
|
|
322
|
+
* @example
|
|
323
|
+
* ```ts
|
|
324
|
+
* const nameLens = Lens.from.accessors(
|
|
325
|
+
* (user: User) => user.name,
|
|
326
|
+
* (name) => (user) => ({ ...user, name }),
|
|
327
|
+
* );
|
|
328
|
+
* ```
|
|
329
|
+
*/
|
|
330
|
+
accessors: <S, A>(get: (s: S) => A, set: (a: A) => (s: S) => S) => Lens<S, A>;
|
|
331
|
+
/**
|
|
332
|
+
* Creates a Lens that focuses on a property of an object.
|
|
333
|
+
* Call with the structure type first, then the key.
|
|
334
|
+
*
|
|
335
|
+
* @example
|
|
336
|
+
* ```ts
|
|
337
|
+
* const nameLens = Lens.from.property<User>()("name");
|
|
338
|
+
* ```
|
|
339
|
+
*/
|
|
340
|
+
property: <S>() => <K extends keyof S>(key: K) => Lens<S, S[K]>;
|
|
341
|
+
};
|
|
342
|
+
/**
|
|
343
|
+
* Reads the focused value from a structure.
|
|
344
|
+
*
|
|
345
|
+
* @example
|
|
346
|
+
* ```ts
|
|
347
|
+
* pipe(user, Lens.get(nameLens)); // "Alice"
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
get: <S, A>(lens: Lens<S, A>) => (s: S) => A;
|
|
351
|
+
/**
|
|
352
|
+
* Replaces the focused value within a structure, returning a new structure.
|
|
353
|
+
*
|
|
354
|
+
* @example
|
|
355
|
+
* ```ts
|
|
356
|
+
* pipe(user, Lens.set(nameLens)("Bob")); // new User with name "Bob"
|
|
357
|
+
* ```
|
|
358
|
+
*/
|
|
359
|
+
set: <S, A>(lens: Lens<S, A>) => (a: A) => (s: S) => S;
|
|
360
|
+
/**
|
|
361
|
+
* Applies a function to the focused value, returning a new structure.
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* ```ts
|
|
365
|
+
* pipe(user, Lens.modify(nameLens)(n => n.toUpperCase())); // "ALICE"
|
|
366
|
+
* ```
|
|
367
|
+
*/
|
|
368
|
+
modify: <S, A>(lens: Lens<S, A>) => (f: (a: A) => A) => (s: S) => S;
|
|
369
|
+
/**
|
|
370
|
+
* Composes two Lenses: focuses through the outer, then through the inner.
|
|
371
|
+
* Use in a pipe chain to build up a deep focus step by step.
|
|
372
|
+
*
|
|
373
|
+
* @example
|
|
374
|
+
* ```ts
|
|
375
|
+
* const userCityLens = pipe(
|
|
376
|
+
* Lens.from.property<User>()("address"),
|
|
377
|
+
* Lens.andThen(Lens.from.property<Address>()("city")),
|
|
378
|
+
* );
|
|
379
|
+
* ```
|
|
380
|
+
*/
|
|
381
|
+
andThen: <A, B>(inner: Lens<A, B>) => <S>(outer: Lens<S, A>) => Lens<S, B>;
|
|
382
|
+
/**
|
|
383
|
+
* Composes a Lens with an Optional, producing an Optional.
|
|
384
|
+
* Use when the next step in the focus is optional (may be absent).
|
|
385
|
+
*
|
|
386
|
+
* @example
|
|
387
|
+
* ```ts
|
|
388
|
+
* const userBioOpt = pipe(
|
|
389
|
+
* Lens.from.property<User>()("profile"),
|
|
390
|
+
* Lens.andThenOptional(Optional.from.property<Profile>()("bio")),
|
|
391
|
+
* );
|
|
392
|
+
* ```
|
|
393
|
+
*/
|
|
394
|
+
andThenOptional: <A, B>(inner: Optional<A, B>) => <S>(outer: Lens<S, A>) => Optional<S, B>;
|
|
395
|
+
/**
|
|
396
|
+
* Converts a Lens to an Optional. Every Lens is a valid Optional
|
|
397
|
+
* whose get always returns Some.
|
|
398
|
+
*
|
|
399
|
+
* @example
|
|
400
|
+
* ```ts
|
|
401
|
+
* pipe(
|
|
402
|
+
* Lens.from.property<User>()("address"),
|
|
403
|
+
* Lens.toOptional,
|
|
404
|
+
* Optional.andThen(Optional.from.property<Address>()("landmark")),
|
|
405
|
+
* );
|
|
406
|
+
* ```
|
|
407
|
+
*/
|
|
408
|
+
toOptional: <S, A>(lens: Lens<S, A>) => Optional<S, A>;
|
|
409
|
+
};
|
|
410
|
+
//#endregion
|
|
411
|
+
//#region src/Core/Logged.d.ts
|
|
412
|
+
/**
|
|
413
|
+
* A value paired with an accumulated log.
|
|
414
|
+
*
|
|
415
|
+
* `Logged<W, A>` pairs a result `A` with a sequence of log entries `W`. When
|
|
416
|
+
* you sequence two `Logged` computations with `chain`, the logs are
|
|
417
|
+
* automatically concatenated — you never have to thread the log array through
|
|
418
|
+
* your code manually.
|
|
419
|
+
*
|
|
420
|
+
* @example
|
|
421
|
+
* ```ts
|
|
422
|
+
* const program = pipe(
|
|
423
|
+
* Logged.from.value<string, number>(0),
|
|
424
|
+
* Logged.chain(n => pipe(
|
|
425
|
+
* Logged.from.entry("start"),
|
|
426
|
+
* Logged.map(() => n + 1),
|
|
427
|
+
* )),
|
|
428
|
+
* Logged.chain(n => pipe(
|
|
429
|
+
* Logged.from.entry("done"),
|
|
430
|
+
* Logged.map(() => n * 10),
|
|
431
|
+
* )),
|
|
432
|
+
* );
|
|
433
|
+
*
|
|
434
|
+
* Logged.run(program); // [10, ["start", "done"]]
|
|
435
|
+
* ```
|
|
436
|
+
*/
|
|
437
|
+
type Logged<L, A> = WithValue<A> & WithLog<L>;
|
|
438
|
+
declare const Logged: {
|
|
439
|
+
from: {
|
|
440
|
+
/**
|
|
441
|
+
* Wraps a pure value into a `Logged` with an empty log.
|
|
442
|
+
*
|
|
443
|
+
* @example
|
|
444
|
+
* ```ts
|
|
445
|
+
* Logged.from.value<string, number>(42); // { value: 42, log: [] }
|
|
446
|
+
* ```
|
|
447
|
+
*/
|
|
448
|
+
value: <W, A>(val: A) => Logged<W, A>;
|
|
449
|
+
/**
|
|
450
|
+
* Creates a `Logged` that records a single log entry and produces no
|
|
451
|
+
* meaningful value. Use this to append to the log inside a `chain`.
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* ```ts
|
|
455
|
+
* Logged.from.entry("operation completed"); // { value: undefined, log: ["operation completed"] }
|
|
456
|
+
* ```
|
|
457
|
+
*/
|
|
458
|
+
entry: <W>(logEntry: W) => Logged<W, undefined>;
|
|
459
|
+
};
|
|
460
|
+
/**
|
|
461
|
+
* Transforms the value inside a `Logged` without affecting the log.
|
|
462
|
+
*
|
|
463
|
+
* @example
|
|
464
|
+
* ```ts
|
|
465
|
+
* pipe(
|
|
466
|
+
* Logged.from.value<string, number>(5),
|
|
467
|
+
* Logged.map(n => n * 2),
|
|
468
|
+
* ); // { value: 10, log: [] }
|
|
469
|
+
* ```
|
|
470
|
+
*/
|
|
471
|
+
map: <W, A, B>(f: (a: A) => B) => (data: Logged<W, A>) => Logged<W, B>;
|
|
472
|
+
/**
|
|
473
|
+
* Sequences two `Logged` computations, concatenating their logs.
|
|
474
|
+
* The value from the first is passed to `f`; the resulting log entries are
|
|
475
|
+
* appended after the entries from the first.
|
|
476
|
+
*
|
|
477
|
+
* Data-last — the first computation is the data being piped.
|
|
478
|
+
*
|
|
479
|
+
* @example
|
|
480
|
+
* ```ts
|
|
481
|
+
* const result = pipe(
|
|
482
|
+
* Logged.from.value<string, number>(1),
|
|
483
|
+
* Logged.chain(n => pipe(Logged.from.entry("step"), Logged.map(() => n + 1))),
|
|
484
|
+
* Logged.chain(n => pipe(Logged.from.entry("done"), Logged.map(() => n * 10))),
|
|
485
|
+
* );
|
|
486
|
+
*
|
|
487
|
+
* Logged.run(result); // [20, ["step", "done"]]
|
|
488
|
+
* ```
|
|
489
|
+
*/
|
|
490
|
+
chain: <W, A, B>(f: (a: A) => Logged<W, B>) => (data: Logged<W, A>) => Logged<W, B>;
|
|
491
|
+
/**
|
|
492
|
+
* Applies a function wrapped in a `Logged` to a value wrapped in a `Logged`,
|
|
493
|
+
* concatenating both logs.
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```ts
|
|
497
|
+
* const fn: Logged<string, (n: number) => number> = {
|
|
498
|
+
* value: n => n * 2,
|
|
499
|
+
* log: ["fn-loaded"],
|
|
500
|
+
* };
|
|
501
|
+
* const arg: Logged<string, number> = { value: 5, log: ["arg-loaded"] };
|
|
502
|
+
*
|
|
503
|
+
* const result = pipe(fn, Logged.ap(arg));
|
|
504
|
+
* Logged.run(result); // [10, ["fn-loaded", "arg-loaded"]]
|
|
505
|
+
* ```
|
|
506
|
+
*/
|
|
507
|
+
ap: <W, A>(arg: Logged<W, A>) => <B>(data: Logged<W, (a: A) => B>) => Logged<W, B>;
|
|
508
|
+
/**
|
|
509
|
+
* Runs a side effect on the value without changing the `Logged`.
|
|
510
|
+
* Useful for debugging or inspecting intermediate values.
|
|
511
|
+
*
|
|
512
|
+
* @example
|
|
513
|
+
* ```ts
|
|
514
|
+
* pipe(
|
|
515
|
+
* Logged.from.value<string, number>(42),
|
|
516
|
+
* Logged.tap(n => console.log("value:", n)),
|
|
517
|
+
* );
|
|
518
|
+
* ```
|
|
519
|
+
*/
|
|
520
|
+
tap: <W, A>(f: (a: A) => void) => (data: Logged<W, A>) => Logged<W, A>;
|
|
521
|
+
/**
|
|
522
|
+
* Extracts the value and log as a `readonly [A, ReadonlyArray<W>]` tuple.
|
|
523
|
+
* Use this at the boundary where you need to consume both.
|
|
524
|
+
*
|
|
525
|
+
* @example
|
|
526
|
+
* ```ts
|
|
527
|
+
* const result = pipe(
|
|
528
|
+
* Logged.from.value<string, number>(1),
|
|
529
|
+
* Logged.chain(n => pipe(Logged.from.entry("incremented"), Logged.map(() => n + 1))),
|
|
530
|
+
* );
|
|
531
|
+
*
|
|
532
|
+
* const [value, log] = Logged.run(result);
|
|
533
|
+
* // value = 2, log = ["incremented"]
|
|
534
|
+
* ```
|
|
535
|
+
*/
|
|
536
|
+
run: <W, A>(data: Logged<W, A>) => readonly [A, ReadonlyArray<W>];
|
|
537
|
+
/**
|
|
538
|
+
* Lifts a Logged value into an accumulator object.
|
|
539
|
+
*
|
|
540
|
+
* @example
|
|
541
|
+
* ```ts
|
|
542
|
+
* pipe(Logged.from.value<string, number>(42), Logged.bindTo("value")); // Logged({ value: 42 })
|
|
543
|
+
* ```
|
|
544
|
+
*/
|
|
545
|
+
bindTo: <K extends string>(key: K) => <W, A>(data: Logged<W, A>) => Logged<W, { [P in K]: A; }>;
|
|
546
|
+
/**
|
|
547
|
+
* Evaluates a new Logged using the current accumulator and attaches the output to a new key.
|
|
548
|
+
*
|
|
549
|
+
* @example
|
|
550
|
+
* ```ts
|
|
551
|
+
* pipe(
|
|
552
|
+
* Logged.from.value<string, { a: number }>({ a: 1 }),
|
|
553
|
+
* Logged.bind("b", ({ a }) => Logged.from.value<string, number>(a + 1))
|
|
554
|
+
* ); // Logged({ value: { a: 1, b: 2 } })
|
|
555
|
+
* ```
|
|
556
|
+
*/
|
|
557
|
+
bind: <K extends string, W, A, B>(key: K, f: (a: A) => Logged<W, B>) => (data: Logged<W, A>) => Logged<W, A & { [P in K]: B; }>;
|
|
558
|
+
/**
|
|
559
|
+
* Focuses a Logged computation's value transformation using a Lens.
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```ts
|
|
563
|
+
* const nameLens = Lens.from.property<{ name: string }>()("name");
|
|
564
|
+
* const logged = Logged.from.value<string, { name: string }>({ name: "alice" });
|
|
565
|
+
* pipe(logged, Logged.focus(nameLens)(s => s.toUpperCase()));
|
|
566
|
+
* ```
|
|
567
|
+
*/
|
|
568
|
+
focus: <S, A>(lens: Lens<S, A>) => <W>(f: (a: A) => A) => (data: Logged<W, S>) => Logged<W, S>;
|
|
569
|
+
};
|
|
570
|
+
//#endregion
|
|
571
|
+
//#region src/Core/Maybe.d.ts
|
|
572
|
+
/**
|
|
573
|
+
* Maybe represents an optional value: every Maybe is either Some (contains a value) or None (empty).
|
|
574
|
+
* Use Maybe instead of null/undefined to make optionality explicit and composable.
|
|
575
|
+
*
|
|
576
|
+
* @example
|
|
577
|
+
* ```ts
|
|
578
|
+
* const user = { name: "Alice", email: Maybe.make.some("alice@example.com") };
|
|
579
|
+
*
|
|
580
|
+
* pipe(
|
|
581
|
+
* user.email,
|
|
582
|
+
* Maybe.map(email => email.toUpperCase()),
|
|
583
|
+
* Maybe.getOrElse(() => "NO EMAIL")
|
|
584
|
+
* ); // "ALICE@EXAMPLE.COM"
|
|
585
|
+
* ```
|
|
586
|
+
*/
|
|
587
|
+
type Maybe<T> = Some<T> | None;
|
|
588
|
+
type Some<A> = WithKind<"Some"> & WithValue<A>;
|
|
589
|
+
type None = WithKind<"None">;
|
|
590
|
+
declare const Maybe: {
|
|
591
|
+
make: {
|
|
592
|
+
/**
|
|
593
|
+
* Creates a Some containing the given value.
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ```ts
|
|
597
|
+
* Maybe.make.some(42); // Some(42)
|
|
598
|
+
* ```
|
|
599
|
+
*/
|
|
600
|
+
some: <A>(value: A) => Some<A>;
|
|
601
|
+
/**
|
|
602
|
+
* Creates a None (empty Maybe).
|
|
603
|
+
*
|
|
604
|
+
* @example
|
|
605
|
+
* ```ts
|
|
606
|
+
* Maybe.make.none(); // None
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
none: () => None;
|
|
610
|
+
};
|
|
611
|
+
is: {
|
|
612
|
+
/**
|
|
613
|
+
* Type guard that checks if a Maybe is Some.
|
|
614
|
+
*
|
|
615
|
+
* @example
|
|
616
|
+
* ```ts
|
|
617
|
+
* const value = Maybe.make.some(42);
|
|
618
|
+
* if (Maybe.is.some(value)) {
|
|
619
|
+
* console.log(value.value); // 42
|
|
620
|
+
* }
|
|
621
|
+
* ```
|
|
622
|
+
*/
|
|
623
|
+
some: <A>(data: Maybe<A>) => data is Some<A>;
|
|
624
|
+
/**
|
|
625
|
+
* Type guard that checks if a Maybe is None.
|
|
626
|
+
*
|
|
627
|
+
* @example
|
|
628
|
+
* ```ts
|
|
629
|
+
* const value = Maybe.make.none();
|
|
630
|
+
* if (Maybe.is.none(value)) {
|
|
631
|
+
* console.log("No value present");
|
|
632
|
+
* }
|
|
633
|
+
* ```
|
|
634
|
+
*/
|
|
635
|
+
none: <A>(data: Maybe<A>) => data is None;
|
|
636
|
+
};
|
|
637
|
+
to: {
|
|
638
|
+
/**
|
|
639
|
+
* Extracts the value from a Maybe, returning null if None.
|
|
640
|
+
*
|
|
641
|
+
* @example
|
|
642
|
+
* ```ts
|
|
643
|
+
* Maybe.to.nullable(Maybe.make.some(42)); // 42
|
|
644
|
+
* Maybe.to.nullable(Maybe.make.none()); // null
|
|
645
|
+
* ```
|
|
646
|
+
*/
|
|
647
|
+
nullable: <A>(data: Maybe<A>) => A | null;
|
|
648
|
+
/**
|
|
649
|
+
* Extracts the value from a Maybe, returning undefined if None.
|
|
650
|
+
*
|
|
651
|
+
* @example
|
|
652
|
+
* ```ts
|
|
653
|
+
* Maybe.to.undefined(Maybe.make.some(42)); // 42
|
|
654
|
+
* Maybe.to.undefined(Maybe.make.none()); // undefined
|
|
655
|
+
* ```
|
|
656
|
+
*/
|
|
657
|
+
undefined: <A>(data: Maybe<A>) => A | undefined;
|
|
658
|
+
/**
|
|
659
|
+
* Converts a Maybe to a Result.
|
|
660
|
+
* Some becomes Ok, None becomes Err with the provided error.
|
|
661
|
+
*
|
|
662
|
+
* @example
|
|
663
|
+
* ```ts
|
|
664
|
+
* pipe(
|
|
665
|
+
* Maybe.make.some(42),
|
|
666
|
+
* Maybe.to.Result(() => "Value was missing")
|
|
667
|
+
* ); // Ok(42)
|
|
668
|
+
*
|
|
669
|
+
* pipe(
|
|
670
|
+
* Maybe.make.none(),
|
|
671
|
+
* Maybe.to.Result(() => "Value was missing")
|
|
672
|
+
* ); // Err("Value was missing")
|
|
673
|
+
* ```
|
|
674
|
+
*/
|
|
675
|
+
Result: <E>(onNone: () => E) => <A>(data: Maybe<A>) => Result<E, A>;
|
|
676
|
+
};
|
|
677
|
+
from: {
|
|
678
|
+
/**
|
|
679
|
+
* Creates a Maybe from a nullable value.
|
|
680
|
+
* Returns None if the value is null or undefined, Some otherwise.
|
|
681
|
+
*
|
|
682
|
+
* @example
|
|
683
|
+
* ```ts
|
|
684
|
+
* Maybe.from.nullable(null); // None
|
|
685
|
+
* Maybe.from.nullable(42); // Some(42)
|
|
686
|
+
* ```
|
|
687
|
+
*/
|
|
688
|
+
nullable: <A>(value: A | null | undefined) => Maybe<A>;
|
|
689
|
+
/**
|
|
690
|
+
* Creates a Maybe from a predicate applied to a value.
|
|
691
|
+
* Returns Some if the predicate passes, None otherwise.
|
|
692
|
+
*
|
|
693
|
+
* @example
|
|
694
|
+
* ```ts
|
|
695
|
+
* Maybe.from.Predicate((n: number) => n >= 18)(21); // Some(21)
|
|
696
|
+
* Maybe.from.Predicate((n: number) => n >= 18)(15); // None
|
|
697
|
+
*
|
|
698
|
+
* pipe("hello", Maybe.from.Predicate((s: string) => s.length > 0)); // Some("hello")
|
|
699
|
+
* pipe("", Maybe.from.Predicate((s: string) => s.length > 0)); // None
|
|
700
|
+
* ```
|
|
701
|
+
*/
|
|
702
|
+
Predicate: <A>(pred: (a: A) => boolean) => (a: A) => Maybe<A>;
|
|
703
|
+
/**
|
|
704
|
+
* Creates a Maybe from a Result.
|
|
705
|
+
* Ok becomes Some, Err becomes None (the error is discarded).
|
|
706
|
+
*
|
|
707
|
+
* @example
|
|
708
|
+
* ```ts
|
|
709
|
+
* Maybe.from.Result(Result.make.ok(42)); // Some(42)
|
|
710
|
+
* Maybe.from.Result(Result.make.err("oops")); // None
|
|
711
|
+
* ```
|
|
712
|
+
*/
|
|
713
|
+
Result: <E, A>(data: Result<E, A>) => Maybe<A>;
|
|
714
|
+
};
|
|
715
|
+
/**
|
|
716
|
+
* Transforms the value inside a Maybe if it exists.
|
|
717
|
+
*
|
|
718
|
+
* @example
|
|
719
|
+
* ```ts
|
|
720
|
+
* pipe(Maybe.make.some(5), Maybe.map(n => n * 2)); // Some(10)
|
|
721
|
+
* pipe(Maybe.make.none(), Maybe.map(n => n * 2)); // None
|
|
722
|
+
* ```
|
|
723
|
+
*/
|
|
724
|
+
map: <A, B>(f: (a: A) => B) => (data: Maybe<A>) => Maybe<B>;
|
|
725
|
+
/**
|
|
726
|
+
* Chains Maybe computations. If the first is Some, passes the value to f.
|
|
727
|
+
* If the first is None, propagates None.
|
|
728
|
+
*
|
|
729
|
+
* @example
|
|
730
|
+
* ```ts
|
|
731
|
+
* const parseNumber = (s: string): Maybe<number> => {
|
|
732
|
+
* const n = parseInt(s, 10);
|
|
733
|
+
* return isNaN(n) ? Maybe.make.none() : Maybe.make.some(n);
|
|
734
|
+
* };
|
|
735
|
+
*
|
|
736
|
+
* pipe(Maybe.make.some("42"), Maybe.chain(parseNumber)); // Some(42)
|
|
737
|
+
* pipe(Maybe.make.some("abc"), Maybe.chain(parseNumber)); // None
|
|
738
|
+
* ```
|
|
739
|
+
*/
|
|
740
|
+
chain: <A, B>(f: (a: A) => Maybe<B>) => (data: Maybe<A>) => Maybe<B>;
|
|
741
|
+
/**
|
|
742
|
+
* Extracts the value from a Maybe by providing handlers for both cases.
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* ```ts
|
|
746
|
+
* pipe(
|
|
747
|
+
* Maybe.make.some(5),
|
|
748
|
+
* Maybe.fold(
|
|
749
|
+
* () => "No value",
|
|
750
|
+
* n => `Value: ${n}`
|
|
751
|
+
* )
|
|
752
|
+
* ); // "Value: 5"
|
|
753
|
+
* ```
|
|
754
|
+
*/
|
|
755
|
+
fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: Maybe<A>) => B;
|
|
756
|
+
/**
|
|
757
|
+
* Pattern matches on a Maybe, returning the result of the matching case.
|
|
758
|
+
*
|
|
759
|
+
* @example
|
|
760
|
+
* ```ts
|
|
761
|
+
* pipe(
|
|
762
|
+
* optionUser,
|
|
763
|
+
* Maybe.match({
|
|
764
|
+
* some: user => `Hello, ${user.name}`,
|
|
765
|
+
* none: () => "Hello, stranger"
|
|
766
|
+
* })
|
|
767
|
+
* );
|
|
768
|
+
* ```
|
|
769
|
+
*/
|
|
770
|
+
match: <A, B>(cases: {
|
|
771
|
+
none: () => B;
|
|
772
|
+
some: (a: A) => B;
|
|
773
|
+
}) => (data: Maybe<A>) => B;
|
|
774
|
+
/**
|
|
775
|
+
* Returns the value inside a Maybe, or a default value if None.
|
|
776
|
+
* The default is a thunk `() => B` — evaluated only when the Maybe is None.
|
|
777
|
+
* The default can be a different type, widening the result to `A | B`.
|
|
778
|
+
*
|
|
779
|
+
* @example
|
|
780
|
+
* ```ts
|
|
781
|
+
* pipe(Maybe.make.some(5), Maybe.getOrElse(() => 0)); // 5
|
|
782
|
+
* pipe(Maybe.make.none(), Maybe.getOrElse(() => 0)); // 0
|
|
783
|
+
* pipe(Maybe.make.none<string>(), Maybe.getOrElse(() => null)); // null — typed as string | null
|
|
784
|
+
* ```
|
|
785
|
+
*/
|
|
786
|
+
getOrElse: <B>(defaultValue: () => B) => <A>(data: Maybe<A>) => A | B;
|
|
787
|
+
/**
|
|
788
|
+
* Executes a side effect on the value without changing the Maybe.
|
|
789
|
+
* Useful for logging or debugging.
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* ```ts
|
|
793
|
+
* pipe(
|
|
794
|
+
* Maybe.make.some(5),
|
|
795
|
+
* Maybe.tap(n => console.log("Value:", n)),
|
|
796
|
+
* Maybe.map(n => n * 2)
|
|
797
|
+
* );
|
|
798
|
+
* ```
|
|
799
|
+
*/
|
|
800
|
+
tap: <A>(f: (a: A) => void) => (data: Maybe<A>) => Maybe<A>;
|
|
801
|
+
/**
|
|
802
|
+
* Filters a Maybe based on a predicate.
|
|
803
|
+
* Returns None if the predicate returns false or if the Maybe is already None.
|
|
804
|
+
*
|
|
805
|
+
* @example
|
|
806
|
+
* ```ts
|
|
807
|
+
* pipe(Maybe.make.some(5), Maybe.filter(n => n > 3)); // Some(5)
|
|
808
|
+
* pipe(Maybe.make.some(2), Maybe.filter(n => n > 3)); // None
|
|
809
|
+
* ```
|
|
810
|
+
*/
|
|
811
|
+
filter: <A>(predicate: (a: A) => boolean) => (data: Maybe<A>) => Maybe<A>;
|
|
812
|
+
/**
|
|
813
|
+
* Recovers from a None by providing a fallback Maybe.
|
|
814
|
+
* The fallback can produce a different type, widening the result to `Maybe<A | B>`.
|
|
815
|
+
*
|
|
816
|
+
* @example
|
|
817
|
+
* ```ts
|
|
818
|
+
* pipe(Maybe.make.none(), Maybe.recover(() => Maybe.make.some(42))); // Some(42)
|
|
819
|
+
* pipe(Maybe.make.some(10), Maybe.recover(() => Maybe.make.some(42))); // Some(10)
|
|
820
|
+
* ```
|
|
821
|
+
*/
|
|
822
|
+
recover: <B>(fallback: () => Maybe<B>) => <A>(data: Maybe<A>) => Maybe<A | B>;
|
|
823
|
+
/**
|
|
824
|
+
* Applies a function wrapped in a Maybe to a value wrapped in a Maybe.
|
|
825
|
+
*
|
|
826
|
+
* @example
|
|
827
|
+
* ```ts
|
|
828
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
829
|
+
* pipe(
|
|
830
|
+
* Maybe.make.some(add),
|
|
831
|
+
* Maybe.ap(Maybe.make.some(5)),
|
|
832
|
+
* Maybe.ap(Maybe.make.some(3))
|
|
833
|
+
* ); // Some(8)
|
|
834
|
+
* ```
|
|
835
|
+
*/
|
|
836
|
+
ap: <A>(arg: Maybe<A>) => <B>(data: Maybe<(a: A) => B>) => Maybe<B>;
|
|
837
|
+
/**
|
|
838
|
+
* Converts a Maybe value into an object containing a single property.
|
|
839
|
+
* Initiates the pipeline accumulator record.
|
|
840
|
+
*
|
|
841
|
+
* @example
|
|
842
|
+
* ```ts
|
|
843
|
+
* pipe(Maybe.make.some(42), Maybe.bindTo("value")); // Some({ value: 42 })
|
|
844
|
+
* ```
|
|
845
|
+
*/
|
|
846
|
+
bindTo: <K extends string>(key: K) => <A>(data: Maybe<A>) => Maybe<{ [P in K]: A; }>;
|
|
847
|
+
/**
|
|
848
|
+
* Evaluates a new Maybe using the current accumulator and attaches the output to a new key.
|
|
849
|
+
*
|
|
850
|
+
* @example
|
|
851
|
+
* ```ts
|
|
852
|
+
* pipe(
|
|
853
|
+
* Maybe.make.some({ a: 1 }),
|
|
854
|
+
* Maybe.bind("b", ({ a }) => Maybe.make.some(a + 1))
|
|
855
|
+
* ); // Some({ a: 1, b: 2 })
|
|
856
|
+
* ```
|
|
857
|
+
*/
|
|
858
|
+
bind: <K extends string, A, B>(key: K, f: (a: A) => Maybe<B>) => (data: Maybe<A>) => Maybe<A & { [P in K]: B; }>;
|
|
859
|
+
/**
|
|
860
|
+
* Combines a record of Maybes into a single Maybe of a record.
|
|
861
|
+
* Evaluates fields in key order and short-circuits on the first None.
|
|
862
|
+
*
|
|
863
|
+
* @example
|
|
864
|
+
* ```ts
|
|
865
|
+
* Maybe.struct({
|
|
866
|
+
* name: Maybe.make.some("Alice"),
|
|
867
|
+
* age: Maybe.make.some(30)
|
|
868
|
+
* }); // Some({ name: "Alice", age: 30 })
|
|
869
|
+
* ```
|
|
870
|
+
*/
|
|
871
|
+
struct: <R extends Record<string, any>>(fields: { [K in keyof R]: Maybe<R[K]>; }) => Maybe<R>;
|
|
872
|
+
/**
|
|
873
|
+
* Swaps the outer `Maybe` and inner `Result` context.
|
|
874
|
+
* `Some(Ok(a))` becomes `Ok(Some(a))`, `Some(Err(e))` becomes `Err(e)`, and `None` becomes `Ok(None)`.
|
|
875
|
+
*
|
|
876
|
+
* @example
|
|
877
|
+
* ```ts
|
|
878
|
+
* Maybe.transposeResult(Maybe.make.some(Result.make.ok(42))); // Ok(Some(42))
|
|
879
|
+
* Maybe.transposeResult(Maybe.make.some(Result.make.err("e"))); // Err("e")
|
|
880
|
+
* Maybe.transposeResult(Maybe.make.none()); // Ok(None)
|
|
881
|
+
* ```
|
|
882
|
+
*/
|
|
883
|
+
transposeResult: <E, A>(data: Maybe<Result<E, A>>) => Result<E, Maybe<A>>;
|
|
884
|
+
};
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/Core/Op.d.ts
|
|
887
|
+
/**
|
|
888
|
+
* A reusable description of async work — decoupled from execution strategy and lifetime.
|
|
889
|
+
*
|
|
890
|
+
* Separate concerns:
|
|
891
|
+
* - **What** to do: encoded in the `Op` via `Op.create`
|
|
892
|
+
* - **How** to execute: chosen at `Op.interpret` time (restartable, exclusive, queue, etc.)
|
|
893
|
+
*
|
|
894
|
+
* An `Op` never runs on its own. It only executes when passed to `Op.interpret`, which
|
|
895
|
+
* attaches a concurrency strategy and returns a `Manager` that owns the execution.
|
|
896
|
+
*
|
|
897
|
+
* @example
|
|
898
|
+
* ```ts
|
|
899
|
+
* const fetchUser = Op.create(
|
|
900
|
+
* (signal) => (id: string) =>
|
|
901
|
+
* fetch(`/users/${id}`, { signal }).then(r => {
|
|
902
|
+
* if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
|
|
903
|
+
* return r.json() as Promise<User>;
|
|
904
|
+
* }),
|
|
905
|
+
* (e) => new ApiError(e),
|
|
906
|
+
* );
|
|
907
|
+
*
|
|
908
|
+
* const manager = Op.interpret(fetchUser, { strategy: "restartable" });
|
|
909
|
+
* manager.subscribe(state => {
|
|
910
|
+
* if (Op.is.pending(state)) showSpinner();
|
|
911
|
+
* if (Op.is.ok(state)) render(state.value);
|
|
912
|
+
* if (Op.is.err(state)) showError(state.error);
|
|
913
|
+
* if (Op.is.nil(state)) resetUI();
|
|
914
|
+
* });
|
|
915
|
+
* manager.run(userId);
|
|
916
|
+
* ```
|
|
917
|
+
*/
|
|
918
|
+
type Op<I, E, A> = {
|
|
919
|
+
/**
|
|
920
|
+
* @internal — Used by `Op.interpret`. Do not call directly.
|
|
921
|
+
* Returns `null` when the operation was aborted (signal fired before factory resolved).
|
|
922
|
+
*/
|
|
923
|
+
readonly _factory: (input: I, signal: AbortSignal) => Deferred<Result<E, A> | null>;
|
|
924
|
+
};
|
|
925
|
+
type MaybeRetry<E, O> = O extends {
|
|
926
|
+
retry: RetryOptions<E>;
|
|
927
|
+
} ? Op.Retrying<E> : never;
|
|
928
|
+
type AllInterpretOptions<I, E> = ({
|
|
929
|
+
strategy: "once";
|
|
930
|
+
retry?: RetryOptions<E>;
|
|
931
|
+
} & WithTimeout<E>) | ({
|
|
932
|
+
strategy: "restartable";
|
|
933
|
+
retry?: RetryOptions<E>;
|
|
934
|
+
} & WithMinInterval & WithTimeout<E>) | ({
|
|
935
|
+
strategy: "exclusive";
|
|
936
|
+
retry?: RetryOptions<E>;
|
|
937
|
+
} & WithCooldown & WithTimeout<E>) | ({
|
|
938
|
+
strategy: "queue";
|
|
939
|
+
retry?: RetryOptions<E>;
|
|
940
|
+
maxSize?: number;
|
|
941
|
+
overflow?: "drop" | "replace-last";
|
|
942
|
+
dedupe?: (a: I, b: I) => boolean;
|
|
943
|
+
} & WithConcurrency & WithTimeout<E>) | ({
|
|
944
|
+
strategy: "buffered";
|
|
945
|
+
retry?: RetryOptions<E>;
|
|
946
|
+
} & WithSize & WithTimeout<E>) | ({
|
|
947
|
+
strategy: "debounced";
|
|
948
|
+
retry?: RetryOptions<E>;
|
|
949
|
+
leading?: true;
|
|
950
|
+
maxWait?: Duration;
|
|
951
|
+
} & WithDuration & WithTimeout<E>) | ({
|
|
952
|
+
strategy: "throttled";
|
|
953
|
+
retry?: RetryOptions<E>;
|
|
954
|
+
trailing?: true;
|
|
955
|
+
} & WithDuration & WithTimeout<E>) | ({
|
|
956
|
+
strategy: "concurrent";
|
|
957
|
+
retry?: RetryOptions<E>;
|
|
958
|
+
overflow?: "queue" | "drop";
|
|
959
|
+
} & WithN & WithTimeout<E>) | ({
|
|
960
|
+
strategy: "keyed";
|
|
961
|
+
perKey?: "exclusive" | "restartable";
|
|
962
|
+
key: (input: I) => unknown;
|
|
963
|
+
} & WithTimeout<E>);
|
|
964
|
+
type KeyType<I, O> = O extends {
|
|
965
|
+
key: (input: I) => infer K;
|
|
966
|
+
} ? K : unknown;
|
|
967
|
+
type InterpretResult<I, E, A, O> = [O] extends [{
|
|
968
|
+
strategy: "throttled";
|
|
969
|
+
trailing: true;
|
|
970
|
+
}] ? Op.Manager<I, E, A, Op.ThrottledTrailingState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
971
|
+
strategy: "throttled";
|
|
972
|
+
}] ? Op.Manager<I, E, A, Op.ThrottledState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
973
|
+
strategy: "debounced";
|
|
974
|
+
}] ? Op.Manager<I, E, A, Op.DebouncedState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
975
|
+
strategy: "concurrent";
|
|
976
|
+
overflow: "queue";
|
|
977
|
+
}] ? Op.Manager<I, E, A, Op.ConcurrentQueueState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
978
|
+
strategy: "concurrent";
|
|
979
|
+
}] ? Op.Manager<I, E, A, Op.ConcurrentDropState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
980
|
+
strategy: "keyed";
|
|
981
|
+
perKey: "restartable";
|
|
982
|
+
}] ? Op.KeyedManager<I, KeyType<I, O>, E, Op.KeyedRestartablePerKey<E, A>> : [O] extends [{
|
|
983
|
+
strategy: "keyed";
|
|
984
|
+
}] ? Op.KeyedManager<I, KeyType<I, O>, E, Op.KeyedExclusivePerKey<E, A>> : [O] extends [{
|
|
985
|
+
strategy: "once";
|
|
986
|
+
}] ? Op.Manager<I, E, A, Op.OnceState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
987
|
+
strategy: "restartable";
|
|
988
|
+
}] ? Op.Manager<I, E, A, Op.RestartableState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
989
|
+
strategy: "exclusive";
|
|
990
|
+
}] ? Op.Manager<I, E, A, Op.ExclusiveState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
991
|
+
strategy: "queue";
|
|
992
|
+
overflow: "replace-last";
|
|
993
|
+
dedupe: (a: I, b: I) => boolean;
|
|
994
|
+
}] ? Op.Manager<I, E, A, Op.QueueDropAndReplaceState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
995
|
+
strategy: "queue";
|
|
996
|
+
overflow: "replace-last";
|
|
997
|
+
}] ? Op.Manager<I, E, A, Op.QueueReplaceState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
998
|
+
strategy: "queue";
|
|
999
|
+
maxSize: number;
|
|
1000
|
+
}] ? Op.Manager<I, E, A, Op.QueueDropState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
1001
|
+
strategy: "queue";
|
|
1002
|
+
dedupe: (a: I, b: I) => boolean;
|
|
1003
|
+
}] ? Op.Manager<I, E, A, Op.QueueDropState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
1004
|
+
strategy: "queue";
|
|
1005
|
+
}] ? Op.Manager<I, E, A, Op.QueueState<E, A> | MaybeRetry<E, O>> : [O] extends [{
|
|
1006
|
+
strategy: "buffered";
|
|
1007
|
+
}] ? Op.Manager<I, E, A, Op.BufferedState<E, A> | MaybeRetry<E, O>> : never;
|
|
1008
|
+
declare function interpretFn<I, E, A, O extends AllInterpretOptions<I, E>>(op: Op<I, E, A>, options: O): InterpretResult<I, E, A, O>;
|
|
1009
|
+
declare const Op: {
|
|
1010
|
+
make: {
|
|
1011
|
+
/**
|
|
1012
|
+
* Creates an Ok outcome with the given value.
|
|
1013
|
+
*
|
|
1014
|
+
* @example
|
|
1015
|
+
* ```ts
|
|
1016
|
+
* Op.make.ok(42); // { kind: "OpOk", value: 42 }
|
|
1017
|
+
* ```
|
|
1018
|
+
*/
|
|
1019
|
+
ok: <A>(value: A) => Op.Ok<A>;
|
|
1020
|
+
/**
|
|
1021
|
+
* Creates an Err outcome with the given error.
|
|
1022
|
+
*
|
|
1023
|
+
* @example
|
|
1024
|
+
* ```ts
|
|
1025
|
+
* Op.make.err("Something went wrong"); // { kind: "OpErr", error: "Something went wrong" }
|
|
1026
|
+
* ```
|
|
1027
|
+
*/
|
|
1028
|
+
err: <E>(error: E) => Op.Err<E>;
|
|
1029
|
+
/**
|
|
1030
|
+
* Creates a Nil outcome with the given cancellation/drop reason.
|
|
1031
|
+
*
|
|
1032
|
+
* @example
|
|
1033
|
+
* ```ts
|
|
1034
|
+
* Op.make.nil("aborted"); // { kind: "OpNil", reason: "aborted" }
|
|
1035
|
+
* ```
|
|
1036
|
+
*/
|
|
1037
|
+
nil: (reason: Op.NilReason) => Op.Nil;
|
|
1038
|
+
};
|
|
1039
|
+
is: {
|
|
1040
|
+
/**
|
|
1041
|
+
* Type guard that checks if an Op state is Idle.
|
|
1042
|
+
*
|
|
1043
|
+
* @example
|
|
1044
|
+
* ```ts
|
|
1045
|
+
* if (Op.is.idle(manager.state)) {
|
|
1046
|
+
* console.log("Ready to execute");
|
|
1047
|
+
* }
|
|
1048
|
+
* ```
|
|
1049
|
+
*/
|
|
1050
|
+
idle: <E, A>(state: Op.State<E, A>) => state is Op.Idle;
|
|
1051
|
+
/**
|
|
1052
|
+
* Type guard that checks if an Op state is Pending (actively executing).
|
|
1053
|
+
*
|
|
1054
|
+
* @example
|
|
1055
|
+
* ```ts
|
|
1056
|
+
* if (Op.is.pending(manager.state)) {
|
|
1057
|
+
* showSpinner();
|
|
1058
|
+
* }
|
|
1059
|
+
* ```
|
|
1060
|
+
*/
|
|
1061
|
+
pending: <E, A>(state: Op.State<E, A>) => state is Op.Pending;
|
|
1062
|
+
/**
|
|
1063
|
+
* Type guard that checks if an Op state is Queued (waiting in a concurrency queue).
|
|
1064
|
+
*
|
|
1065
|
+
* @example
|
|
1066
|
+
* ```ts
|
|
1067
|
+
* if (Op.is.queued(manager.state)) {
|
|
1068
|
+
* console.log("Position in queue:", manager.state.position);
|
|
1069
|
+
* }
|
|
1070
|
+
* ```
|
|
1071
|
+
*/
|
|
1072
|
+
queued: <E, A>(state: Op.State<E, A>) => state is Op.Queued;
|
|
1073
|
+
/**
|
|
1074
|
+
* Type guard that checks if an Op state is Retrying after a failure.
|
|
1075
|
+
*
|
|
1076
|
+
* @example
|
|
1077
|
+
* ```ts
|
|
1078
|
+
* if (Op.is.retrying(manager.state)) {
|
|
1079
|
+
* console.log("Retry attempt:", manager.state.attempt);
|
|
1080
|
+
* }
|
|
1081
|
+
* ```
|
|
1082
|
+
*/
|
|
1083
|
+
retrying: <E, A>(state: Op.State<E, A>) => state is Op.Retrying<E>;
|
|
1084
|
+
/**
|
|
1085
|
+
* Type guard that checks if an Op state or outcome is Ok.
|
|
1086
|
+
*
|
|
1087
|
+
* @example
|
|
1088
|
+
* ```ts
|
|
1089
|
+
* if (Op.is.ok(outcome)) {
|
|
1090
|
+
* render(outcome.value);
|
|
1091
|
+
* }
|
|
1092
|
+
* ```
|
|
1093
|
+
*/
|
|
1094
|
+
ok: <E, A>(state: Op.State<E, A>) => state is Op.Ok<A>;
|
|
1095
|
+
/**
|
|
1096
|
+
* Type guard that checks if an Op state or outcome is Err.
|
|
1097
|
+
*
|
|
1098
|
+
* @example
|
|
1099
|
+
* ```ts
|
|
1100
|
+
* if (Op.is.err(outcome)) {
|
|
1101
|
+
* showError(outcome.error);
|
|
1102
|
+
* }
|
|
1103
|
+
* ```
|
|
1104
|
+
*/
|
|
1105
|
+
err: <E, A>(state: Op.State<E, A>) => state is Op.Err<E>;
|
|
1106
|
+
/**
|
|
1107
|
+
* Type guard that checks if an Op state or outcome is Nil.
|
|
1108
|
+
*
|
|
1109
|
+
* @example
|
|
1110
|
+
* ```ts
|
|
1111
|
+
* if (Op.is.nil(outcome)) {
|
|
1112
|
+
* console.log("Skipped due to:", outcome.reason);
|
|
1113
|
+
* }
|
|
1114
|
+
* ```
|
|
1115
|
+
*/
|
|
1116
|
+
nil: <E, A>(state: Op.State<E, A>) => state is Op.Nil;
|
|
1117
|
+
};
|
|
1118
|
+
create: <E, A, I = void>(factory: (signal: AbortSignal) => (input: I) => Promise<A>, onError: (e: unknown) => E) => Op<I, E, A>;
|
|
1119
|
+
lift: <I, A>(f: (input: I, signal: AbortSignal) => Promise<A>) => Op<I, unknown, A>;
|
|
1120
|
+
match: <E, A, B>(cases: {
|
|
1121
|
+
ok: (a: A) => B;
|
|
1122
|
+
err: (e: E) => B;
|
|
1123
|
+
nil: () => B;
|
|
1124
|
+
}) => (outcome: Op.Outcome<E, A>) => B;
|
|
1125
|
+
fold: <E, A, B>(onErr: (e: E) => B, onNil: () => B, onOk: (a: A) => B) => (outcome: Op.Outcome<E, A>) => B;
|
|
1126
|
+
getOrElse: <E, A, B>(defaultValue: () => B) => (outcome: Op.Outcome<E, A>) => A | B;
|
|
1127
|
+
map: <E, A, B>(f: (a: A) => B) => (outcome: Op.Outcome<E, A>) => Op.Outcome<E, B>;
|
|
1128
|
+
mapError: <E, F, A>(f: (e: E) => F) => (outcome: Op.Outcome<E, A>) => Op.Outcome<F, A>;
|
|
1129
|
+
chain: <E, A, B>(f: (a: A) => Op.Outcome<E, B>) => (outcome: Op.Outcome<E, A>) => Op.Outcome<E, B>;
|
|
1130
|
+
tap: <E, A>(f: (a: A) => void) => (outcome: Op.Outcome<E, A>) => Op.Outcome<E, A>;
|
|
1131
|
+
recover: <E, A, B>(f: (e: E) => Op.Outcome<E, B>) => (outcome: Op.Outcome<E, A>) => Op.Outcome<E, A | B>;
|
|
1132
|
+
to: {
|
|
1133
|
+
Result: <E, A>(onNil: () => E) => (outcome: Op.Outcome<E, A>) => Result<E, A>;
|
|
1134
|
+
Maybe: <E, A>(outcome: Op.Outcome<E, A>) => Maybe<A>;
|
|
1135
|
+
};
|
|
1136
|
+
all: <E, A>(invocations: ReadonlyArray<Deferred<Op.Outcome<E, A>>>) => Deferred<ReadonlyArray<Op.Outcome<E, A>>>;
|
|
1137
|
+
race: <E, A>(invocations: ReadonlyArray<Deferred<Op.Outcome<E, A>>>) => Deferred<Op.Outcome<E, A>>;
|
|
1138
|
+
wire: <I, E, A, S extends Op.State<E, A>>(source: Op.Manager<I, E, A, S>, f: (a: A) => void) => () => void;
|
|
1139
|
+
interpret: typeof interpretFn;
|
|
1140
|
+
};
|
|
1141
|
+
declare namespace Op {
|
|
1142
|
+
type Outcome<E, A> = Ok<A> | Err<E> | Nil;
|
|
1143
|
+
type Ok<A> = WithKind<"OpOk"> & WithValue<A>;
|
|
1144
|
+
type Err<E> = WithKind<"OpErr"> & WithError<E>;
|
|
1145
|
+
type Nil = WithKind<"OpNil"> & {
|
|
1146
|
+
readonly reason: NilReason;
|
|
1147
|
+
};
|
|
1148
|
+
type NilReason = "aborted" | "dropped" | "replaced" | "evicted";
|
|
1149
|
+
type AbortedNil = Nil & {
|
|
1150
|
+
readonly reason: "aborted";
|
|
1151
|
+
};
|
|
1152
|
+
type DroppedNil = Nil & {
|
|
1153
|
+
readonly reason: "dropped";
|
|
1154
|
+
};
|
|
1155
|
+
type ReplacedNil = Nil & {
|
|
1156
|
+
readonly reason: "replaced";
|
|
1157
|
+
};
|
|
1158
|
+
type EvictedNil = Nil & {
|
|
1159
|
+
readonly reason: "evicted";
|
|
1160
|
+
};
|
|
1161
|
+
type State<E, A> = Idle | Pending | Queued | Retrying<E> | Outcome<E, A>;
|
|
1162
|
+
type Idle = WithKind<"Idle">;
|
|
1163
|
+
type Pending = WithKind<"Pending">;
|
|
1164
|
+
type Queued = WithKind<"Queued"> & {
|
|
1165
|
+
readonly position: number;
|
|
1166
|
+
};
|
|
1167
|
+
type Retrying<E> = WithKind<"Retrying"> & {
|
|
1168
|
+
readonly attempt: number;
|
|
1169
|
+
readonly lastError: E;
|
|
1170
|
+
readonly nextRetryIn?: number;
|
|
1171
|
+
};
|
|
1172
|
+
type Manager<I, E, A, S extends State<E, A>> = {
|
|
1173
|
+
readonly state: S;
|
|
1174
|
+
run: (input: I) => Deferred<Exclude<S, Idle | Pending | Queued | Retrying<E>>>;
|
|
1175
|
+
abort: () => void;
|
|
1176
|
+
subscribe: (cb: (state: S) => void) => () => void;
|
|
1177
|
+
reset: () => void;
|
|
1178
|
+
poll: (input: I, options: {
|
|
1179
|
+
interval: Duration;
|
|
1180
|
+
}) => () => void;
|
|
1181
|
+
};
|
|
1182
|
+
type KeyedManager<I, K, E, PerKeyS> = {
|
|
1183
|
+
readonly state: ReadonlyMap<K, PerKeyS>;
|
|
1184
|
+
run: (input: I) => Deferred<Exclude<PerKeyS, Pending | Retrying<E>>>;
|
|
1185
|
+
abort: (key?: K) => void;
|
|
1186
|
+
subscribe: (cb: (state: ReadonlyMap<K, PerKeyS>) => void) => () => void;
|
|
1187
|
+
reset: () => void;
|
|
1188
|
+
poll: (input: I, options: {
|
|
1189
|
+
interval: Duration;
|
|
1190
|
+
}) => () => void;
|
|
1191
|
+
};
|
|
1192
|
+
type OnceState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1193
|
+
type RetryableOnceState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1194
|
+
type RestartableState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | ReplacedNil;
|
|
1195
|
+
type RetryableRestartableState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | ReplacedNil;
|
|
1196
|
+
type ExclusiveState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1197
|
+
type RetryableExclusiveState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1198
|
+
type QueueState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil;
|
|
1199
|
+
type RetryableQueueState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil;
|
|
1200
|
+
type QueueDropState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1201
|
+
type RetryableQueueDropState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1202
|
+
type QueueReplaceState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1203
|
+
type RetryableQueueReplaceState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1204
|
+
type QueueDropAndReplaceState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil | DroppedNil | EvictedNil;
|
|
1205
|
+
type RetryableQueueDropAndReplaceState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil | EvictedNil;
|
|
1206
|
+
type BufferedState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1207
|
+
type RetryableBufferedState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1208
|
+
type DebouncedState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1209
|
+
type RetryableDebouncedState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1210
|
+
type ThrottledState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1211
|
+
type RetryableThrottledState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1212
|
+
type ThrottledTrailingState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1213
|
+
type RetryableThrottledTrailingState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | EvictedNil;
|
|
1214
|
+
type ConcurrentQueueState<E, A> = Idle | Pending | Queued | Ok<A> | Err<E> | AbortedNil;
|
|
1215
|
+
type RetryableConcurrentQueueState<E, A> = Idle | Pending | Queued | Retrying<E> | Ok<A> | Err<E> | AbortedNil;
|
|
1216
|
+
type ConcurrentDropState<E, A> = Idle | Pending | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1217
|
+
type RetryableConcurrentDropState<E, A> = Idle | Pending | Retrying<E> | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1218
|
+
type KeyedExclusivePerKey<E, A> = Pending | Ok<A> | Err<E> | AbortedNil | DroppedNil;
|
|
1219
|
+
type KeyedRestartablePerKey<E, A> = Pending | Ok<A> | Err<E> | AbortedNil | ReplacedNil;
|
|
1220
|
+
type RetryOptions<E> = RetryOptions<E>;
|
|
1221
|
+
type TimeoutOptions<E> = TimeoutOptions<E>;
|
|
1222
|
+
}
|
|
1223
|
+
//#endregion
|
|
1224
|
+
//#region src/Core/Optional.d.ts
|
|
1225
|
+
/** Keys of T for which undefined is assignable (i.e. optional fields). */
|
|
1226
|
+
type OptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? K : never; }[keyof T];
|
|
1227
|
+
/**
|
|
1228
|
+
* Optional<S, A> focuses on a value A inside a structure S that may or may
|
|
1229
|
+
* not be present. Like a Lens, but get returns Maybe<A>.
|
|
1230
|
+
*
|
|
1231
|
+
* Compose with other Optionals via `andThen`, or with a Lens via `andThenLens`.
|
|
1232
|
+
* Convert a Lens to an Optional with `Lens.toOptional`.
|
|
1233
|
+
*
|
|
1234
|
+
* @example
|
|
1235
|
+
* ```ts
|
|
1236
|
+
* type Profile = { username: string; bio?: string };
|
|
1237
|
+
*
|
|
1238
|
+
* const bioOpt = Optional.from.property<Profile>()("bio");
|
|
1239
|
+
*
|
|
1240
|
+
* pipe(profile, Optional.get(bioOpt)); // Some("hello") or None
|
|
1241
|
+
* pipe(profile, Optional.set(bioOpt)("hello")); // new Profile with bio set
|
|
1242
|
+
* pipe(profile, Optional.modify(bioOpt)(s => s + "!")); // appends if present
|
|
1243
|
+
* ```
|
|
1244
|
+
*/
|
|
1245
|
+
type Optional<S, A> = {
|
|
1246
|
+
readonly get: (s: S) => Maybe<A>;
|
|
1247
|
+
readonly set: (a: A) => (s: S) => S;
|
|
1248
|
+
};
|
|
1249
|
+
declare const Optional: {
|
|
1250
|
+
from: {
|
|
1251
|
+
/**
|
|
1252
|
+
* Constructs an Optional from a getter (returning Maybe<A>) and a setter.
|
|
1253
|
+
*
|
|
1254
|
+
* @example
|
|
1255
|
+
* ```ts
|
|
1256
|
+
* const firstChar = Optional.from.accessors(
|
|
1257
|
+
* (s: string) => s.length > 0 ? Maybe.make.some(s[0]) : Maybe.make.none(),
|
|
1258
|
+
* (c) => (s) => s.length > 0 ? c + s.slice(1) : s,
|
|
1259
|
+
* );
|
|
1260
|
+
* ```
|
|
1261
|
+
*/
|
|
1262
|
+
accessors: <S, A>(get: (s: S) => Maybe<A>, set: (a: A) => (s: S) => S) => Optional<S, A>;
|
|
1263
|
+
/**
|
|
1264
|
+
* Creates an Optional that focuses on an optional property of an object.
|
|
1265
|
+
* Only keys whose type includes undefined (i.e. `field?: T`) are accepted.
|
|
1266
|
+
* Call with the structure type first, then the key.
|
|
1267
|
+
*
|
|
1268
|
+
* @example
|
|
1269
|
+
* ```ts
|
|
1270
|
+
* type Profile = { username: string; bio?: string };
|
|
1271
|
+
* const bioOpt = Optional.from.property<Profile>()("bio");
|
|
1272
|
+
* ```
|
|
1273
|
+
*/
|
|
1274
|
+
property: <S>() => <K extends OptionalKeys<S>>(key: K) => Optional<S, NonNullable<S[K]>>;
|
|
1275
|
+
};
|
|
1276
|
+
/**
|
|
1277
|
+
* Creates an Optional that focuses on an element at a given index in an array.
|
|
1278
|
+
* Returns None when the index is out of bounds; set is a no-op when out of bounds.
|
|
1279
|
+
*
|
|
1280
|
+
* @example
|
|
1281
|
+
* ```ts
|
|
1282
|
+
* const firstItem = Optional.index<string>(0);
|
|
1283
|
+
*
|
|
1284
|
+
* pipe(["a", "b"], Optional.get(firstItem)); // Some("a")
|
|
1285
|
+
* pipe([], Optional.get(firstItem)); // None
|
|
1286
|
+
* ```
|
|
1287
|
+
*/
|
|
1288
|
+
index: <A>(i: number) => Optional<A[], A>;
|
|
1289
|
+
/**
|
|
1290
|
+
* Reads the focused value from a structure, returning Maybe<A>.
|
|
1291
|
+
*
|
|
1292
|
+
* @example
|
|
1293
|
+
* ```ts
|
|
1294
|
+
* pipe(profile, Optional.get(bioOpt)); // Some("...") or None
|
|
1295
|
+
* ```
|
|
1296
|
+
*/
|
|
1297
|
+
get: <S, A>(opt: Optional<S, A>) => (s: S) => Maybe<A>;
|
|
1298
|
+
/**
|
|
1299
|
+
* Replaces the focused value within a structure.
|
|
1300
|
+
* For indexed focuses, this is a no-op when the index is out of bounds.
|
|
1301
|
+
*
|
|
1302
|
+
* @example
|
|
1303
|
+
* ```ts
|
|
1304
|
+
* pipe(profile, Optional.set(bioOpt)("hello"));
|
|
1305
|
+
* ```
|
|
1306
|
+
*/
|
|
1307
|
+
set: <S, A>(opt: Optional<S, A>) => (a: A) => (s: S) => S;
|
|
1308
|
+
/**
|
|
1309
|
+
* Applies a function to the focused value if it is present; returns the
|
|
1310
|
+
* structure unchanged if the focus is absent.
|
|
1311
|
+
*
|
|
1312
|
+
* @example
|
|
1313
|
+
* ```ts
|
|
1314
|
+
* pipe(profile, Optional.modify(bioOpt)(s => s.toUpperCase()));
|
|
1315
|
+
* ```
|
|
1316
|
+
*/
|
|
1317
|
+
modify: <S, A>(opt: Optional<S, A>) => (f: (a: A) => A) => (s: S) => S;
|
|
1318
|
+
/**
|
|
1319
|
+
* Returns the focused value or a default when the focus is absent.
|
|
1320
|
+
*
|
|
1321
|
+
* @example
|
|
1322
|
+
* ```ts
|
|
1323
|
+
* pipe(profile, Optional.getOrElse(bioOpt)(() => "no bio"));
|
|
1324
|
+
* ```
|
|
1325
|
+
*/
|
|
1326
|
+
getOrElse: <S, A>(opt: Optional<S, A>) => (defaultValue: () => A) => (s: S) => A;
|
|
1327
|
+
/**
|
|
1328
|
+
* Extracts a value from an Optional focus using handlers for the present
|
|
1329
|
+
* and absent cases.
|
|
1330
|
+
*
|
|
1331
|
+
* @example
|
|
1332
|
+
* ```ts
|
|
1333
|
+
* pipe(profile, Optional.fold(bioOpt)(() => "no bio", (bio) => bio.toUpperCase()));
|
|
1334
|
+
* ```
|
|
1335
|
+
*/
|
|
1336
|
+
fold: <S, A>(opt: Optional<S, A>) => <B>(onNone: () => B, onSome: (a: A) => B) => (s: S) => B;
|
|
1337
|
+
/**
|
|
1338
|
+
* Pattern matches on an Optional focus using a named-case object.
|
|
1339
|
+
*
|
|
1340
|
+
* @example
|
|
1341
|
+
* ```ts
|
|
1342
|
+
* pipe(
|
|
1343
|
+
* profile,
|
|
1344
|
+
* Optional.match(bioOpt)({ none: () => "no bio", some: (bio) => bio }),
|
|
1345
|
+
* );
|
|
1346
|
+
* ```
|
|
1347
|
+
*/
|
|
1348
|
+
match: <S, A>(opt: Optional<S, A>) => <B>(cases: {
|
|
1349
|
+
none: () => B;
|
|
1350
|
+
some: (a: A) => B;
|
|
1351
|
+
}) => (s: S) => B;
|
|
1352
|
+
/**
|
|
1353
|
+
* Composes two Optionals: focuses through the outer, then through the inner.
|
|
1354
|
+
* Returns None if either focus is absent.
|
|
1355
|
+
*
|
|
1356
|
+
* @example
|
|
1357
|
+
* ```ts
|
|
1358
|
+
* const deepOpt = pipe(
|
|
1359
|
+
* Optional.from.property<User>()("address"),
|
|
1360
|
+
* Optional.andThen(Optional.from.property<Address>()("landmark")),
|
|
1361
|
+
* );
|
|
1362
|
+
* ```
|
|
1363
|
+
*/
|
|
1364
|
+
andThen: <A, B>(inner: Optional<A, B>) => <S>(outer: Optional<S, A>) => Optional<S, B>;
|
|
1365
|
+
/**
|
|
1366
|
+
* Composes an Optional with a Lens, producing an Optional.
|
|
1367
|
+
* The Lens focuses within the value found by the Optional.
|
|
1368
|
+
*
|
|
1369
|
+
* @example
|
|
1370
|
+
* ```ts
|
|
1371
|
+
* const cityOpt = pipe(
|
|
1372
|
+
* Optional.from.property<User>()("address"),
|
|
1373
|
+
* Optional.andThenLens(Lens.from.property<Address>()("city")),
|
|
1374
|
+
* );
|
|
1375
|
+
* ```
|
|
1376
|
+
*/
|
|
1377
|
+
andThenLens: <A, B>(inner: Lens<A, B>) => <S>(outer: Optional<S, A>) => Optional<S, B>;
|
|
1378
|
+
};
|
|
1379
|
+
//#endregion
|
|
1380
|
+
//#region src/Core/Ordering.d.ts
|
|
1381
|
+
/**
|
|
1382
|
+
* A function that orders two values of type `A`. Returns a negative number when `a` comes before
|
|
1383
|
+
* `b`, a positive number when `a` comes after `b`, and `0` when they are equal.
|
|
1384
|
+
*
|
|
1385
|
+
* Compatible with `Array.prototype.sort` and `Arr.sortWith`.
|
|
1386
|
+
*
|
|
1387
|
+
* @example
|
|
1388
|
+
* ```ts
|
|
1389
|
+
* type Employee = { name: string; salary: number };
|
|
1390
|
+
*
|
|
1391
|
+
* const byName = pipe(Ordering.string, Ordering.by((e: Employee) => e.name));
|
|
1392
|
+
* const bySalary = pipe(Ordering.number, Ordering.by((e: Employee) => e.salary));
|
|
1393
|
+
*
|
|
1394
|
+
* pipe(employees, Arr.sortWith(pipe(byName, Ordering.thenBy(bySalary))));
|
|
1395
|
+
* ```
|
|
1396
|
+
*/
|
|
1397
|
+
type Ordering<A> = (a: A, b: A) => number;
|
|
1398
|
+
declare const Ordering: {
|
|
1399
|
+
/**
|
|
1400
|
+
* Alphabetical ordering for strings.
|
|
1401
|
+
*
|
|
1402
|
+
* @example
|
|
1403
|
+
* ```ts
|
|
1404
|
+
* Ordering.string("apple", "banana"); // negative
|
|
1405
|
+
* ```
|
|
1406
|
+
*/
|
|
1407
|
+
string: Ordering<string>;
|
|
1408
|
+
/**
|
|
1409
|
+
* Numeric ordering. Equivalent to `(a, b) => a - b`.
|
|
1410
|
+
*
|
|
1411
|
+
* @example
|
|
1412
|
+
* ```ts
|
|
1413
|
+
* pipe([3, 1, 2], Arr.sortWith(Ordering.number)); // [1, 2, 3]
|
|
1414
|
+
* ```
|
|
1415
|
+
*/
|
|
1416
|
+
number: Ordering<number>;
|
|
1417
|
+
/**
|
|
1418
|
+
* Ordering for `Date` values by numeric time value.
|
|
1419
|
+
*
|
|
1420
|
+
* @example
|
|
1421
|
+
* ```ts
|
|
1422
|
+
* pipe(dates, Arr.sortWith(Ordering.date)); // earliest first
|
|
1423
|
+
* ```
|
|
1424
|
+
*/
|
|
1425
|
+
date: Ordering<Date>;
|
|
1426
|
+
/**
|
|
1427
|
+
* Flips the direction of an ordering.
|
|
1428
|
+
*
|
|
1429
|
+
* @example
|
|
1430
|
+
* ```ts
|
|
1431
|
+
* pipe([3, 1, 2], Arr.sortWith(Ordering.reverse(Ordering.number))); // [3, 2, 1]
|
|
1432
|
+
* ```
|
|
1433
|
+
*/
|
|
1434
|
+
reverse: <A>(ord: Ordering<A>) => Ordering<A>;
|
|
1435
|
+
/**
|
|
1436
|
+
* Chains two orderings: the second is used only when the first returns `0`.
|
|
1437
|
+
* Data-last: the first ordering is the data being piped.
|
|
1438
|
+
*
|
|
1439
|
+
* @example
|
|
1440
|
+
* ```ts
|
|
1441
|
+
* const byDeptThenSalary = pipe(byDept, Ordering.thenBy(bySalary));
|
|
1442
|
+
* ```
|
|
1443
|
+
*/
|
|
1444
|
+
thenBy: <A>(ord2: Ordering<A>) => (ord1: Ordering<A>) => Ordering<A>;
|
|
1445
|
+
/**
|
|
1446
|
+
* Adapts an ordering for type `A` into an ordering for type `B` by extracting a field.
|
|
1447
|
+
* Read as "ordering by this field": `pipe(Ordering.number, Ordering.by(p => p.price))`.
|
|
1448
|
+
*
|
|
1449
|
+
* @example
|
|
1450
|
+
* ```ts
|
|
1451
|
+
* type Product = { name: string; price: number };
|
|
1452
|
+
* const byPrice = pipe(Ordering.number, Ordering.by((p: Product) => p.price));
|
|
1453
|
+
* pipe(products, Arr.sortWith(byPrice));
|
|
1454
|
+
* ```
|
|
1455
|
+
*/
|
|
1456
|
+
by: <A, B>(f: (b: B) => A) => (ord: Ordering<A>) => Ordering<B>;
|
|
1457
|
+
/**
|
|
1458
|
+
* Combines a list of orderings into a single composite comparator.
|
|
1459
|
+
* Evaluates each ordering in sequence until a non-zero comparison result is found.
|
|
1460
|
+
*
|
|
1461
|
+
* @example
|
|
1462
|
+
* ```ts
|
|
1463
|
+
* const byName = pipe(Ordering.string, Ordering.by((u: User) => u.name));
|
|
1464
|
+
* const byAge = pipe(Ordering.number, Ordering.by((u: User) => u.age));
|
|
1465
|
+
* const sortUsers = Ordering.byFields([byName, byAge]);
|
|
1466
|
+
* ```
|
|
1467
|
+
*/
|
|
1468
|
+
byFields: <A>(orderings: ReadonlyArray<Ordering<A>>) => Ordering<A>;
|
|
1469
|
+
/**
|
|
1470
|
+
* Derives a lexicographical tuple ordering from positional `Ordering` comparators.
|
|
1471
|
+
*
|
|
1472
|
+
* @example
|
|
1473
|
+
* ```ts
|
|
1474
|
+
* const pairOrd = Ordering.tuple(Ordering.string, Ordering.number);
|
|
1475
|
+
* pairOrd(["a", 1], ["a", 2]); // negative
|
|
1476
|
+
* ```
|
|
1477
|
+
*/
|
|
1478
|
+
tuple: <T extends readonly unknown[]>(...orderings: { [K in keyof T]: Ordering<T[K]>; }) => Ordering<T>;
|
|
1479
|
+
};
|
|
1480
|
+
//#endregion
|
|
1481
|
+
//#region src/Core/Pair.d.ts
|
|
1482
|
+
/**
|
|
1483
|
+
* Pair<A, B> represents a pair of two values that are always both present.
|
|
1484
|
+
* It is a typed alias for `readonly [A, B]`.
|
|
1485
|
+
*
|
|
1486
|
+
* Use Pair when two values always travel together through a pipeline and you
|
|
1487
|
+
* want to transform either or both sides without destructuring.
|
|
1488
|
+
*
|
|
1489
|
+
* @example
|
|
1490
|
+
* ```ts
|
|
1491
|
+
* import { Pair } from "@nlozgachev/pipelined/core";
|
|
1492
|
+
* import { pipe } from "@nlozgachev/pipelined/composition";
|
|
1493
|
+
*
|
|
1494
|
+
* const entry = Pair.from.pair("alice", 42);
|
|
1495
|
+
*
|
|
1496
|
+
* pipe(
|
|
1497
|
+
* entry,
|
|
1498
|
+
* Pair.mapFirst((name) => name.toUpperCase()),
|
|
1499
|
+
* Pair.mapSecond((score) => score * 2),
|
|
1500
|
+
* Pair.fold((name, score) => `${name}: ${score}`),
|
|
1501
|
+
* ); // "ALICE: 84"
|
|
1502
|
+
* ```
|
|
1503
|
+
*/
|
|
1504
|
+
type Pair<A, B> = readonly [A, B];
|
|
1505
|
+
declare const Pair: {
|
|
1506
|
+
from: {
|
|
1507
|
+
/**
|
|
1508
|
+
* Creates a Pair from two values.
|
|
1509
|
+
*
|
|
1510
|
+
* @example
|
|
1511
|
+
* ```ts
|
|
1512
|
+
* Pair.from.pair("Paris", 2_161_000); // ["Paris", 2161000]
|
|
1513
|
+
* ```
|
|
1514
|
+
*/
|
|
1515
|
+
pair: <A, B>(first: A, second: B) => Pair<A, B>;
|
|
1516
|
+
/**
|
|
1517
|
+
* Creates a Pair from a two-element array.
|
|
1518
|
+
*
|
|
1519
|
+
* @example
|
|
1520
|
+
* ```ts
|
|
1521
|
+
* Pair.from.array(["Paris", 2_161_000] as const); // ["Paris", 2161000]
|
|
1522
|
+
* ```
|
|
1523
|
+
*/
|
|
1524
|
+
array: <A, B>(arr: readonly [A, B]) => Pair<A, B>;
|
|
1525
|
+
};
|
|
1526
|
+
/**
|
|
1527
|
+
* Returns the first value from the pair.
|
|
1528
|
+
*
|
|
1529
|
+
* @example
|
|
1530
|
+
* ```ts
|
|
1531
|
+
* Pair.first(Pair.from.pair("Paris", 2_161_000)); // "Paris"
|
|
1532
|
+
* ```
|
|
1533
|
+
*/
|
|
1534
|
+
first: <A, B>(p: Pair<A, B>) => A;
|
|
1535
|
+
/**
|
|
1536
|
+
* Returns the second value from the pair.
|
|
1537
|
+
*
|
|
1538
|
+
* @example
|
|
1539
|
+
* ```ts
|
|
1540
|
+
* Pair.second(Pair.from.pair("Paris", 2_161_000)); // 2161000
|
|
1541
|
+
* ```
|
|
1542
|
+
*/
|
|
1543
|
+
second: <A, B>(p: Pair<A, B>) => B;
|
|
1544
|
+
/**
|
|
1545
|
+
* Transforms the first value, leaving the second unchanged.
|
|
1546
|
+
*
|
|
1547
|
+
* @example
|
|
1548
|
+
* ```ts
|
|
1549
|
+
* pipe(Pair.from.pair("alice", 42), Pair.mapFirst((s) => s.toUpperCase())); // ["ALICE", 42]
|
|
1550
|
+
* ```
|
|
1551
|
+
*/
|
|
1552
|
+
mapFirst: <A, C>(f: (a: A) => C) => <B>(p: Pair<A, B>) => Pair<C, B>;
|
|
1553
|
+
/**
|
|
1554
|
+
* Transforms the second value, leaving the first unchanged.
|
|
1555
|
+
*
|
|
1556
|
+
* @example
|
|
1557
|
+
* ```ts
|
|
1558
|
+
* pipe(Pair.from.pair("alice", 42), Pair.mapSecond((n) => n * 2)); // ["alice", 84]
|
|
1559
|
+
* ```
|
|
1560
|
+
*/
|
|
1561
|
+
mapSecond: <B, D>(f: (b: B) => D) => <A>(p: Pair<A, B>) => Pair<A, D>;
|
|
1562
|
+
/**
|
|
1563
|
+
* Transforms both values independently in a single step.
|
|
1564
|
+
*
|
|
1565
|
+
* @example
|
|
1566
|
+
* ```ts
|
|
1567
|
+
* pipe(
|
|
1568
|
+
* Pair.from.pair("alice", 42),
|
|
1569
|
+
* Pair.mapBoth(
|
|
1570
|
+
* (name) => name.toUpperCase(),
|
|
1571
|
+
* (score) => score * 2,
|
|
1572
|
+
* ),
|
|
1573
|
+
* ); // ["ALICE", 84]
|
|
1574
|
+
* ```
|
|
1575
|
+
*/
|
|
1576
|
+
mapBoth: <A, C, B, D>(onFirst: (a: A) => C, onSecond: (b: B) => D) => (p: Pair<A, B>) => Pair<C, D>;
|
|
1577
|
+
/**
|
|
1578
|
+
* Applies a binary function to both values, collapsing the pair into a single value.
|
|
1579
|
+
* Useful as the final step when consuming a pair in a pipeline.
|
|
1580
|
+
*
|
|
1581
|
+
* @example
|
|
1582
|
+
* ```ts
|
|
1583
|
+
* pipe(Pair.from.pair("Alice", 100), Pair.fold((name, score) => `${name}: ${score}`));
|
|
1584
|
+
* // "Alice: 100"
|
|
1585
|
+
* ```
|
|
1586
|
+
*/
|
|
1587
|
+
fold: <A, B, C>(f: (a: A, b: B) => C) => (p: Pair<A, B>) => C;
|
|
1588
|
+
/**
|
|
1589
|
+
* Swaps the two values: `[A, B]` becomes `[B, A]`.
|
|
1590
|
+
*
|
|
1591
|
+
* @example
|
|
1592
|
+
* ```ts
|
|
1593
|
+
* Pair.swap(Pair.from.pair("key", 1)); // [1, "key"]
|
|
1594
|
+
* ```
|
|
1595
|
+
*/
|
|
1596
|
+
swap: <A, B>(p: Pair<A, B>) => Pair<B, A>;
|
|
1597
|
+
to: {
|
|
1598
|
+
/**
|
|
1599
|
+
* Converts the pair to a heterogeneous readonly array `readonly (A | B)[]`.
|
|
1600
|
+
*
|
|
1601
|
+
* @example
|
|
1602
|
+
* ```ts
|
|
1603
|
+
* Pair.to.Array(Pair.from.pair("hello", 42)); // ["hello", 42]
|
|
1604
|
+
* ```
|
|
1605
|
+
*/
|
|
1606
|
+
Array: <A, B>(p: Pair<A, B>) => readonly (A | B)[];
|
|
1607
|
+
};
|
|
1608
|
+
/**
|
|
1609
|
+
* Runs a side effect with both values without changing the pair.
|
|
1610
|
+
* Useful for logging or debugging in the middle of a pipeline.
|
|
1611
|
+
*
|
|
1612
|
+
* @example
|
|
1613
|
+
* ```ts
|
|
1614
|
+
* pipe(
|
|
1615
|
+
* Pair.from.pair("Paris", 2_161_000),
|
|
1616
|
+
* Pair.tap((city, pop) => console.log(`${city}: ${pop}`)),
|
|
1617
|
+
* Pair.mapSecond((n) => n / 1_000_000),
|
|
1618
|
+
* ); // logs "Paris: 2161000", returns ["Paris", 2.161]
|
|
1619
|
+
* ```
|
|
1620
|
+
*/
|
|
1621
|
+
tap: <A, B>(f: (a: A, b: B) => void) => (p: Pair<A, B>) => Pair<A, B>;
|
|
1622
|
+
};
|
|
1623
|
+
//#endregion
|
|
1624
|
+
//#region src/Core/Predicate.d.ts
|
|
1625
|
+
/**
|
|
1626
|
+
* A boolean-valued function over a type `A`.
|
|
1627
|
+
*
|
|
1628
|
+
* A `Predicate<A>` is the simpler sibling of `Refinement<A, B>`: it tests whether a
|
|
1629
|
+
* value satisfies a condition at runtime but carries no compile-time narrowing guarantee.
|
|
1630
|
+
* Use it when you need to combine, negate, or adapt boolean checks as first-class values
|
|
1631
|
+
* and do not require the extra type information that a `Refinement` provides.
|
|
1632
|
+
*
|
|
1633
|
+
* Every `Refinement<A, B>` is a `Predicate<A>` — convert with `Predicate.from.Refinement`
|
|
1634
|
+
* when you want to compose a narrowing check alongside plain predicates.
|
|
1635
|
+
*
|
|
1636
|
+
* @example
|
|
1637
|
+
* ```ts
|
|
1638
|
+
* const isAdult: Predicate<number> = n => n >= 18;
|
|
1639
|
+
* const isRetired: Predicate<number> = n => n >= 65;
|
|
1640
|
+
*
|
|
1641
|
+
* const isWorkingAge: Predicate<number> = pipe(
|
|
1642
|
+
* isAdult,
|
|
1643
|
+
* Predicate.and(Predicate.not(isRetired))
|
|
1644
|
+
* );
|
|
1645
|
+
*
|
|
1646
|
+
* isWorkingAge(30); // true
|
|
1647
|
+
* isWorkingAge(15); // false
|
|
1648
|
+
* isWorkingAge(70); // false
|
|
1649
|
+
* ```
|
|
1650
|
+
*/
|
|
1651
|
+
type Predicate<A> = (a: A) => boolean;
|
|
1652
|
+
declare const Predicate: {
|
|
1653
|
+
/**
|
|
1654
|
+
* Negates a predicate: the result passes exactly when the original fails.
|
|
1655
|
+
*
|
|
1656
|
+
* @example
|
|
1657
|
+
* ```ts
|
|
1658
|
+
* const isBlank: Predicate<string> = s => s.trim().length === 0;
|
|
1659
|
+
* const isNotBlank = Predicate.not(isBlank);
|
|
1660
|
+
*
|
|
1661
|
+
* isNotBlank("hello"); // true
|
|
1662
|
+
* isNotBlank(" "); // false
|
|
1663
|
+
* ```
|
|
1664
|
+
*/
|
|
1665
|
+
not: <A>(p: Predicate<A>) => Predicate<A>;
|
|
1666
|
+
/**
|
|
1667
|
+
* Combines two predicates with logical AND: passes only when both hold.
|
|
1668
|
+
*
|
|
1669
|
+
* Data-last — the first predicate is the data being piped.
|
|
1670
|
+
*
|
|
1671
|
+
* @example
|
|
1672
|
+
* ```ts
|
|
1673
|
+
* const isPositive: Predicate<number> = n => n > 0;
|
|
1674
|
+
* const isEven: Predicate<number> = n => n % 2 === 0;
|
|
1675
|
+
*
|
|
1676
|
+
* const isPositiveEven: Predicate<number> = pipe(isPositive, Predicate.and(isEven));
|
|
1677
|
+
*
|
|
1678
|
+
* isPositiveEven(4); // true
|
|
1679
|
+
* isPositiveEven(3); // false — positive but odd
|
|
1680
|
+
* isPositiveEven(-2); // false — even but not positive
|
|
1681
|
+
* ```
|
|
1682
|
+
*/
|
|
1683
|
+
and: <A>(second: Predicate<A>) => (first: Predicate<A>) => Predicate<A>;
|
|
1684
|
+
/**
|
|
1685
|
+
* Combines two predicates with logical OR: passes when either holds.
|
|
1686
|
+
*
|
|
1687
|
+
* Data-last — the first predicate is the data being piped.
|
|
1688
|
+
*
|
|
1689
|
+
* @example
|
|
1690
|
+
* ```ts
|
|
1691
|
+
* const isChild: Predicate<number> = n => n < 13;
|
|
1692
|
+
* const isSenior: Predicate<number> = n => n >= 65;
|
|
1693
|
+
*
|
|
1694
|
+
* const getsDiscount: Predicate<number> = pipe(isChild, Predicate.or(isSenior));
|
|
1695
|
+
*
|
|
1696
|
+
* getsDiscount(8); // true
|
|
1697
|
+
* getsDiscount(70); // true
|
|
1698
|
+
* getsDiscount(30); // false
|
|
1699
|
+
* ```
|
|
1700
|
+
*/
|
|
1701
|
+
or: <A>(second: Predicate<A>) => (first: Predicate<A>) => Predicate<A>;
|
|
1702
|
+
/**
|
|
1703
|
+
* Adapts a `Predicate<A>` to work on a different input type `B` by applying `f`
|
|
1704
|
+
* to extract the relevant `A` from a `B` before running the check.
|
|
1705
|
+
*
|
|
1706
|
+
* Data-last — the predicate is the data being piped; `f` is the extractor.
|
|
1707
|
+
*
|
|
1708
|
+
* @example
|
|
1709
|
+
* ```ts
|
|
1710
|
+
* type User = { name: string; age: number };
|
|
1711
|
+
*
|
|
1712
|
+
* const isAdult: Predicate<number> = n => n >= 18;
|
|
1713
|
+
*
|
|
1714
|
+
* // Lift isAdult to work on Users by extracting the age field
|
|
1715
|
+
* const isAdultUser: Predicate<User> = pipe(
|
|
1716
|
+
* isAdult,
|
|
1717
|
+
* Predicate.using((u: User) => u.age)
|
|
1718
|
+
* );
|
|
1719
|
+
*
|
|
1720
|
+
* isAdultUser({ name: "Alice", age: 30 }); // true
|
|
1721
|
+
* isAdultUser({ name: "Bob", age: 15 }); // false
|
|
1722
|
+
* ```
|
|
1723
|
+
*/
|
|
1724
|
+
using: <A, B>(f: (b: B) => A) => (p: Predicate<A>) => Predicate<B>;
|
|
1725
|
+
/**
|
|
1726
|
+
* Combines an array of predicates with AND: passes only when every predicate holds.
|
|
1727
|
+
* Returns `true` for an empty array (vacuous truth).
|
|
1728
|
+
*
|
|
1729
|
+
* @example
|
|
1730
|
+
* ```ts
|
|
1731
|
+
* const checks: Predicate<string>[] = [
|
|
1732
|
+
* s => s.length > 0,
|
|
1733
|
+
* s => s.length <= 100,
|
|
1734
|
+
* s => !s.includes("<"),
|
|
1735
|
+
* ];
|
|
1736
|
+
*
|
|
1737
|
+
* Predicate.all(checks)("hello"); // true
|
|
1738
|
+
* Predicate.all(checks)(""); // false — too short
|
|
1739
|
+
* Predicate.all(checks)("<b>"); // false — contains "<"
|
|
1740
|
+
* Predicate.all([])("anything"); // true
|
|
1741
|
+
* ```
|
|
1742
|
+
*/
|
|
1743
|
+
all: <A>(predicates: ReadonlyArray<Predicate<A>>) => Predicate<A>;
|
|
1744
|
+
/**
|
|
1745
|
+
* Combines an array of predicates with OR: passes when at least one holds.
|
|
1746
|
+
* Returns `false` for an empty array.
|
|
1747
|
+
*
|
|
1748
|
+
* @example
|
|
1749
|
+
* ```ts
|
|
1750
|
+
* const acceptedFormats: Predicate<string>[] = [
|
|
1751
|
+
* s => s.endsWith(".jpg"),
|
|
1752
|
+
* s => s.endsWith(".png"),
|
|
1753
|
+
* s => s.endsWith(".webp"),
|
|
1754
|
+
* ];
|
|
1755
|
+
*
|
|
1756
|
+
* Predicate.any(acceptedFormats)("photo.jpg"); // true
|
|
1757
|
+
* Predicate.any(acceptedFormats)("photo.gif"); // false
|
|
1758
|
+
* Predicate.any([])("anything"); // false
|
|
1759
|
+
* ```
|
|
1760
|
+
*/
|
|
1761
|
+
any: <A>(predicates: ReadonlyArray<Predicate<A>>) => Predicate<A>;
|
|
1762
|
+
from: {
|
|
1763
|
+
/**
|
|
1764
|
+
* Converts a `Refinement<A, B>` into a `Predicate<A>`, discarding the compile-time
|
|
1765
|
+
* narrowing. Use this when you want to combine a type guard with plain predicates
|
|
1766
|
+
* using `and`, `or`, or `all`.
|
|
1767
|
+
*
|
|
1768
|
+
* This is a zero-cost runtime type cast.
|
|
1769
|
+
*
|
|
1770
|
+
* @example
|
|
1771
|
+
* ```ts
|
|
1772
|
+
* const isString: Refinement<unknown, string> =
|
|
1773
|
+
* Refinement.from.predicate(x => typeof x === "string");
|
|
1774
|
+
*
|
|
1775
|
+
* const isShortString: Predicate<unknown> = pipe(
|
|
1776
|
+
* Predicate.from.Refinement(isString),
|
|
1777
|
+
* Predicate.and(x => (x as string).length < 10)
|
|
1778
|
+
* );
|
|
1779
|
+
*
|
|
1780
|
+
* isShortString("hi"); // true
|
|
1781
|
+
* isShortString("a very long string that exceeds ten characters"); // false
|
|
1782
|
+
* isShortString(42); // false
|
|
1783
|
+
* ```
|
|
1784
|
+
*/
|
|
1785
|
+
Refinement: <A, B extends A>(r: Refinement<A, B>) => Predicate<A>;
|
|
1786
|
+
};
|
|
1787
|
+
/**
|
|
1788
|
+
* Performs declarative conditional branching over `[predicate, handler]` pairs,
|
|
1789
|
+
* returning the handler result of the first matching predicate or evaluating the fallback.
|
|
1790
|
+
*
|
|
1791
|
+
* @example
|
|
1792
|
+
* ```ts
|
|
1793
|
+
* const classifyNumber = Predicate.match(
|
|
1794
|
+
* [
|
|
1795
|
+
* [(n: number) => n < 0, () => "negative"],
|
|
1796
|
+
* [(n: number) => n === 0, () => "zero"],
|
|
1797
|
+
* ],
|
|
1798
|
+
* () => "positive",
|
|
1799
|
+
* );
|
|
1800
|
+
* classifyNumber(-5); // "negative"
|
|
1801
|
+
* ```
|
|
1802
|
+
*/
|
|
1803
|
+
match: <A, B>(branches: ReadonlyArray<readonly [Predicate<A>, (a: A) => B]>, fallback: (a: A) => B) => (a: A) => B;
|
|
1804
|
+
};
|
|
1805
|
+
//#endregion
|
|
1806
|
+
//#region src/Core/Reader.d.ts
|
|
1807
|
+
/**
|
|
1808
|
+
* A computation that reads from a shared environment `R` and produces a value `A`.
|
|
1809
|
+
* Use Reader to thread a dependency (config, logger, DB pool) through a pipeline
|
|
1810
|
+
* without passing it explicitly to every function.
|
|
1811
|
+
*
|
|
1812
|
+
* @example
|
|
1813
|
+
* ```ts
|
|
1814
|
+
* type Config = { baseUrl: string; apiKey: string };
|
|
1815
|
+
*
|
|
1816
|
+
* const buildUrl = (path: string): Reader<Config, string> =>
|
|
1817
|
+
* (config) => `${config.baseUrl}${path}`;
|
|
1818
|
+
*
|
|
1819
|
+
* const withAuth = (url: string): Reader<Config, string> =>
|
|
1820
|
+
* (config) => `${url}?key=${config.apiKey}`;
|
|
1821
|
+
*
|
|
1822
|
+
* const fetchEndpoint = (path: string): Reader<Config, string> =>
|
|
1823
|
+
* pipe(
|
|
1824
|
+
* buildUrl(path),
|
|
1825
|
+
* Reader.chain(withAuth)
|
|
1826
|
+
* );
|
|
1827
|
+
*
|
|
1828
|
+
* // Inject the config once at the edge
|
|
1829
|
+
* fetchEndpoint("/users")(appConfig); // "https://api.example.com/users?key=secret"
|
|
1830
|
+
* ```
|
|
1831
|
+
*/
|
|
1832
|
+
type Reader<R, A> = (env: R) => A;
|
|
1833
|
+
declare const Reader: {
|
|
1834
|
+
/**
|
|
1835
|
+
* Lifts a pure value into a Reader. The environment is ignored.
|
|
1836
|
+
*
|
|
1837
|
+
* @example
|
|
1838
|
+
* ```ts
|
|
1839
|
+
* const always42: Reader<Config, number> = Reader.resolve(42);
|
|
1840
|
+
* always42(anyConfig); // 42
|
|
1841
|
+
* ```
|
|
1842
|
+
*/
|
|
1843
|
+
resolve: <R, A>(value: A) => Reader<R, A>;
|
|
1844
|
+
/**
|
|
1845
|
+
* Returns the full environment as the result.
|
|
1846
|
+
* The fundamental way to access the environment in a pipeline.
|
|
1847
|
+
*
|
|
1848
|
+
* @example
|
|
1849
|
+
* ```ts
|
|
1850
|
+
* pipe(
|
|
1851
|
+
* Reader.ask<Config>(),
|
|
1852
|
+
* Reader.map(config => config.baseUrl)
|
|
1853
|
+
* )(appConfig); // "https://api.example.com"
|
|
1854
|
+
* ```
|
|
1855
|
+
*/
|
|
1856
|
+
ask: <R>() => Reader<R, R>;
|
|
1857
|
+
/**
|
|
1858
|
+
* Projects a value from the environment using a selector function.
|
|
1859
|
+
* Equivalent to `pipe(Reader.ask(), Reader.map(f))` but more direct.
|
|
1860
|
+
*
|
|
1861
|
+
* @example
|
|
1862
|
+
* ```ts
|
|
1863
|
+
* const getBaseUrl: Reader<Config, string> = Reader.asks(c => c.baseUrl);
|
|
1864
|
+
* getBaseUrl(appConfig); // "https://api.example.com"
|
|
1865
|
+
* ```
|
|
1866
|
+
*/
|
|
1867
|
+
asks: <R, A>(f: (env: R) => A) => Reader<R, A>;
|
|
1868
|
+
/**
|
|
1869
|
+
* Transforms the value produced by a Reader.
|
|
1870
|
+
*
|
|
1871
|
+
* @example
|
|
1872
|
+
* ```ts
|
|
1873
|
+
* pipe(
|
|
1874
|
+
* Reader.asks((c: Config) => c.baseUrl),
|
|
1875
|
+
* Reader.map(url => url.toUpperCase())
|
|
1876
|
+
* )(appConfig); // "HTTPS://API.EXAMPLE.COM"
|
|
1877
|
+
* ```
|
|
1878
|
+
*/
|
|
1879
|
+
map: <R, A, B>(f: (a: A) => B) => (data: Reader<R, A>) => Reader<R, B>;
|
|
1880
|
+
/**
|
|
1881
|
+
* Sequences two Readers. Both see the same environment.
|
|
1882
|
+
* The output of the first is passed to `f`, which returns the next Reader.
|
|
1883
|
+
*
|
|
1884
|
+
* @example
|
|
1885
|
+
* ```ts
|
|
1886
|
+
* const buildUrl = (path: string): Reader<Config, string> =>
|
|
1887
|
+
* Reader.asks(c => `${c.baseUrl}${path}`);
|
|
1888
|
+
*
|
|
1889
|
+
* const addAuth = (url: string): Reader<Config, string> =>
|
|
1890
|
+
* Reader.asks(c => `${url}?key=${c.apiKey}`);
|
|
1891
|
+
*
|
|
1892
|
+
* pipe(
|
|
1893
|
+
* buildUrl("/items"),
|
|
1894
|
+
* Reader.chain(addAuth)
|
|
1895
|
+
* )(appConfig); // "https://api.example.com/items?key=secret"
|
|
1896
|
+
* ```
|
|
1897
|
+
*/
|
|
1898
|
+
chain: <R, A, B>(f: (a: A) => Reader<R, B>) => (data: Reader<R, A>) => Reader<R, B>;
|
|
1899
|
+
/**
|
|
1900
|
+
* Applies a function wrapped in a Reader to a value wrapped in a Reader.
|
|
1901
|
+
* Both Readers see the same environment.
|
|
1902
|
+
*
|
|
1903
|
+
* @example
|
|
1904
|
+
* ```ts
|
|
1905
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
1906
|
+
* pipe(
|
|
1907
|
+
* Reader.resolve<Config, typeof add>(add),
|
|
1908
|
+
* Reader.ap(Reader.asks(c => c.timeout)),
|
|
1909
|
+
* Reader.ap(Reader.resolve(5))
|
|
1910
|
+
* )(appConfig);
|
|
1911
|
+
* ```
|
|
1912
|
+
*/
|
|
1913
|
+
ap: <R, A>(arg: Reader<R, A>) => <B>(data: Reader<R, (a: A) => B>) => Reader<R, B>;
|
|
1914
|
+
/**
|
|
1915
|
+
* Executes a side effect on the produced value without changing the Reader.
|
|
1916
|
+
* Useful for logging or debugging inside a pipeline.
|
|
1917
|
+
*
|
|
1918
|
+
* @example
|
|
1919
|
+
* ```ts
|
|
1920
|
+
* pipe(
|
|
1921
|
+
* buildUrl("/users"),
|
|
1922
|
+
* Reader.tap(url => console.log("Requesting:", url)),
|
|
1923
|
+
* Reader.chain(addAuth)
|
|
1924
|
+
* )(appConfig);
|
|
1925
|
+
* ```
|
|
1926
|
+
*/
|
|
1927
|
+
tap: <R, A>(f: (a: A) => void) => (data: Reader<R, A>) => Reader<R, A>;
|
|
1928
|
+
/**
|
|
1929
|
+
* Adapts a Reader to work with a different (typically wider) environment
|
|
1930
|
+
* by transforming the environment before passing it to the Reader.
|
|
1931
|
+
* This lets you compose Readers that expect different environments.
|
|
1932
|
+
*
|
|
1933
|
+
* @example
|
|
1934
|
+
* ```ts
|
|
1935
|
+
* type AppEnv = { db: DbPool; config: Config; logger: Logger };
|
|
1936
|
+
*
|
|
1937
|
+
* // buildUrl only needs Config
|
|
1938
|
+
* const buildUrl: Reader<Config, string> = Reader.asks(c => c.baseUrl);
|
|
1939
|
+
*
|
|
1940
|
+
* // Zoom in from AppEnv to Config
|
|
1941
|
+
* const buildUrlFromApp: Reader<AppEnv, string> =
|
|
1942
|
+
* pipe(buildUrl, Reader.local((env: AppEnv) => env.config));
|
|
1943
|
+
*
|
|
1944
|
+
* buildUrlFromApp(appEnv); // works with the full AppEnv
|
|
1945
|
+
* ```
|
|
1946
|
+
*/
|
|
1947
|
+
local: <R2, R>(f: (env: R2) => R) => <A>(data: Reader<R, A>) => Reader<R2, A>;
|
|
1948
|
+
/**
|
|
1949
|
+
* Runs a Reader by supplying the environment. Use this at the edge of your
|
|
1950
|
+
* program where the environment is available.
|
|
1951
|
+
*
|
|
1952
|
+
* @example
|
|
1953
|
+
* ```ts
|
|
1954
|
+
* pipe(
|
|
1955
|
+
* buildEndpoint("/users"),
|
|
1956
|
+
* Reader.run(appConfig)
|
|
1957
|
+
* ); // "https://api.example.com/users?key=secret"
|
|
1958
|
+
* ```
|
|
1959
|
+
*/
|
|
1960
|
+
run: <R>(env: R) => <A>(data: Reader<R, A>) => A;
|
|
1961
|
+
/**
|
|
1962
|
+
* Lifts a Reader value into an accumulator object.
|
|
1963
|
+
*
|
|
1964
|
+
* @example
|
|
1965
|
+
* ```ts
|
|
1966
|
+
* pipe(Reader.resolve(42), Reader.bindTo("value")); // Reader({ value: 42 })
|
|
1967
|
+
* ```
|
|
1968
|
+
*/
|
|
1969
|
+
bindTo: <K extends string>(key: K) => <R, A>(data: Reader<R, A>) => Reader<R, { [P in K]: A; }>;
|
|
1970
|
+
/**
|
|
1971
|
+
* Evaluates a new Reader using the current accumulator and attaches the output to a new key.
|
|
1972
|
+
*
|
|
1973
|
+
* @example
|
|
1974
|
+
* ```ts
|
|
1975
|
+
* pipe(
|
|
1976
|
+
* Reader.resolve({ a: 1 }),
|
|
1977
|
+
* Reader.bind("b", ({ a }) => Reader.resolve(a + 1))
|
|
1978
|
+
* ); // Reader({ a: 1, b: 2 })
|
|
1979
|
+
* ```
|
|
1980
|
+
*/
|
|
1981
|
+
bind: <K extends string, R, A, B>(key: K, f: (a: A) => Reader<R, B>) => (data: Reader<R, A>) => Reader<R, A & { [P in K]: B; }>;
|
|
1982
|
+
};
|
|
1983
|
+
//#endregion
|
|
1984
|
+
//#region src/Core/Refinement.d.ts
|
|
1985
|
+
/**
|
|
1986
|
+
* A function from `A` to `A is B` — a type predicate paired with a runtime check.
|
|
1987
|
+
*
|
|
1988
|
+
* A `Refinement<A, B>` proves at compile time that a value of type `A` is actually
|
|
1989
|
+
* the narrower type `B extends A`, backed by a runtime boolean test. Use it to
|
|
1990
|
+
* express domain invariants (non-empty strings, positive numbers, valid emails) as
|
|
1991
|
+
* first-class, composable values rather than one-off type guards scattered across
|
|
1992
|
+
* the codebase.
|
|
1993
|
+
*
|
|
1994
|
+
* @example
|
|
1995
|
+
* ```ts
|
|
1996
|
+
* type NonEmptyString = string & { readonly _tag: "NonEmptyString" };
|
|
1997
|
+
*
|
|
1998
|
+
* const isNonEmpty: Refinement<string, NonEmptyString> =
|
|
1999
|
+
* Refinement.from.predicate(s => s.length > 0);
|
|
2000
|
+
*
|
|
2001
|
+
* pipe(
|
|
2002
|
+
* "hello",
|
|
2003
|
+
* Refinement.to.Maybe(isNonEmpty)
|
|
2004
|
+
* ); // Some("hello")
|
|
2005
|
+
* ```
|
|
2006
|
+
*/
|
|
2007
|
+
type Refinement<A, B extends A> = (a: A) => a is B;
|
|
2008
|
+
declare const Refinement: {
|
|
2009
|
+
from: {
|
|
2010
|
+
/**
|
|
2011
|
+
* Creates a `Refinement<A, B>` from a plain boolean predicate.
|
|
2012
|
+
*
|
|
2013
|
+
* This is an unsafe cast — the caller is responsible for ensuring that the
|
|
2014
|
+
* predicate truly characterises values of type `B`. Use this only when
|
|
2015
|
+
* bootstrapping a new refinement; prefer `compose`, `and`, or `or` to build
|
|
2016
|
+
* derived refinements from existing ones.
|
|
2017
|
+
*
|
|
2018
|
+
* @example
|
|
2019
|
+
* ```ts
|
|
2020
|
+
* type PositiveNumber = number & { readonly _tag: "PositiveNumber" };
|
|
2021
|
+
*
|
|
2022
|
+
* const isPositive: Refinement<number, PositiveNumber> =
|
|
2023
|
+
* Refinement.from.predicate(n => n > 0);
|
|
2024
|
+
* ```
|
|
2025
|
+
*/
|
|
2026
|
+
predicate: <A, B extends A>(f: (a: A) => boolean) => Refinement<A, B>;
|
|
2027
|
+
};
|
|
2028
|
+
/**
|
|
2029
|
+
* Chains two refinements: if `ab` narrows `A` to `B` and `bc` narrows `B` to `C`,
|
|
2030
|
+
* the result narrows `A` directly to `C`.
|
|
2031
|
+
*
|
|
2032
|
+
* Data-last — the first refinement `ab` is the data being piped.
|
|
2033
|
+
*
|
|
2034
|
+
* @example
|
|
2035
|
+
* ```ts
|
|
2036
|
+
* type NonEmptyString = string & { readonly _tag: "NonEmpty" };
|
|
2037
|
+
* type TrimmedString = NonEmptyString & { readonly _tag: "Trimmed" };
|
|
2038
|
+
*
|
|
2039
|
+
* const isNonEmpty: Refinement<string, NonEmptyString> =
|
|
2040
|
+
* Refinement.from.predicate(s => s.length > 0);
|
|
2041
|
+
* const isTrimmed: Refinement<NonEmptyString, TrimmedString> =
|
|
2042
|
+
* Refinement.from.predicate(s => s === s.trim());
|
|
2043
|
+
*
|
|
2044
|
+
* const isNonEmptyTrimmed: Refinement<string, TrimmedString> = pipe(
|
|
2045
|
+
* isNonEmpty,
|
|
2046
|
+
* Refinement.compose(isTrimmed)
|
|
2047
|
+
* );
|
|
2048
|
+
* ```
|
|
2049
|
+
*/
|
|
2050
|
+
compose: <A, B extends A, C extends B>(bc: Refinement<B, C>) => (ab: Refinement<A, B>) => Refinement<A, C>;
|
|
2051
|
+
/**
|
|
2052
|
+
* Intersects two refinements: the result narrows `A` to `B & C`, passing only
|
|
2053
|
+
* when both refinements hold simultaneously.
|
|
2054
|
+
*
|
|
2055
|
+
* Data-last — the first refinement is the data being piped.
|
|
2056
|
+
*
|
|
2057
|
+
* @example
|
|
2058
|
+
* ```ts
|
|
2059
|
+
* const isString: Refinement<unknown, string> = Refinement.from.predicate(x => typeof x === "string");
|
|
2060
|
+
* const isNonEmpty: Refinement<unknown, { length: number }> =
|
|
2061
|
+
* Refinement.from.predicate(x => (x as any).length > 0);
|
|
2062
|
+
*
|
|
2063
|
+
* const isNonEmptyString = pipe(isString, Refinement.and(isNonEmpty));
|
|
2064
|
+
* isNonEmptyString("hi"); // true
|
|
2065
|
+
* isNonEmptyString(""); // false
|
|
2066
|
+
* ```
|
|
2067
|
+
*/
|
|
2068
|
+
and: <A, C extends A>(second: Refinement<A, C>) => <B extends A>(first: Refinement<A, B>) => Refinement<A, B & C>;
|
|
2069
|
+
/**
|
|
2070
|
+
* Unions two refinements: the result narrows `A` to `B | C`, passing when either
|
|
2071
|
+
* refinement holds.
|
|
2072
|
+
*
|
|
2073
|
+
* Data-last — the first refinement is the data being piped.
|
|
2074
|
+
*
|
|
2075
|
+
* @example
|
|
2076
|
+
* ```ts
|
|
2077
|
+
* const isString: Refinement<unknown, string> = Refinement.from.predicate(x => typeof x === "string");
|
|
2078
|
+
* const isNumber: Refinement<unknown, number> = Refinement.from.predicate(x => typeof x === "number");
|
|
2079
|
+
*
|
|
2080
|
+
* const isStringOrNumber = pipe(isString, Refinement.or(isNumber));
|
|
2081
|
+
* isStringOrNumber("hi"); // true
|
|
2082
|
+
* isStringOrNumber(42); // true
|
|
2083
|
+
* isStringOrNumber(true); // false
|
|
2084
|
+
* ```
|
|
2085
|
+
*/
|
|
2086
|
+
or: <A, C extends A>(second: Refinement<A, C>) => <B extends A>(first: Refinement<A, B>) => Refinement<A, B | C>;
|
|
2087
|
+
to: {
|
|
2088
|
+
/**
|
|
2089
|
+
* Converts a `Refinement<A, B>` into a function `(a: A) => Maybe<B>`.
|
|
2090
|
+
*
|
|
2091
|
+
* Returns `Some(a)` when the refinement holds, `None` otherwise. Useful for
|
|
2092
|
+
* integrating runtime validation into a `Maybe`-based pipeline.
|
|
2093
|
+
*
|
|
2094
|
+
* @example
|
|
2095
|
+
* ```ts
|
|
2096
|
+
* type PositiveNumber = number & { readonly _tag: "Positive" };
|
|
2097
|
+
* const isPositive: Refinement<number, PositiveNumber> =
|
|
2098
|
+
* Refinement.from.predicate(n => n > 0);
|
|
2099
|
+
*
|
|
2100
|
+
* pipe(-1, Refinement.to.Maybe(isPositive)); // None
|
|
2101
|
+
* pipe(42, Refinement.to.Maybe(isPositive)); // Some(42)
|
|
2102
|
+
* ```
|
|
2103
|
+
*/
|
|
2104
|
+
Maybe: <A, B extends A>(r: Refinement<A, B>) => (a: A) => Maybe<B>;
|
|
2105
|
+
/**
|
|
2106
|
+
* Converts a `Refinement<A, B>` into a function `(a: A) => Result<E, B>`.
|
|
2107
|
+
*
|
|
2108
|
+
* Returns `Ok(a)` when the refinement holds, `Err(onFail(a))` otherwise. Use
|
|
2109
|
+
* this to surface validation failures as typed errors inside a `Result` pipeline.
|
|
2110
|
+
*
|
|
2111
|
+
* @example
|
|
2112
|
+
* ```ts
|
|
2113
|
+
* type NonEmptyString = string & { readonly _tag: "NonEmpty" };
|
|
2114
|
+
* const isNonEmpty: Refinement<string, NonEmptyString> =
|
|
2115
|
+
* Refinement.from.predicate(s => s.length > 0);
|
|
2116
|
+
*
|
|
2117
|
+
* pipe("", Refinement.to.Result(isNonEmpty, () => "must not be empty")); // Err(...)
|
|
2118
|
+
* pipe("hi", Refinement.to.Result(isNonEmpty, () => "must not be empty")); // Ok("hi")
|
|
2119
|
+
* ```
|
|
2120
|
+
*/
|
|
2121
|
+
Result: <A, B extends A, E>(r: Refinement<A, B>, onFail: (a: A) => E) => (a: A) => Result<E, B>;
|
|
2122
|
+
};
|
|
2123
|
+
};
|
|
2124
|
+
//#endregion
|
|
2125
|
+
//#region src/Core/RemoteData.d.ts
|
|
2126
|
+
/**
|
|
2127
|
+
* RemoteData represents the state of an async data fetch.
|
|
2128
|
+
* It has four states: NotAsked, Loading, Failure, and Success.
|
|
2129
|
+
*
|
|
2130
|
+
* Use RemoteData to model data fetching states explicitly,
|
|
2131
|
+
* replacing the common `{ data: T | null; loading: boolean; error: Error | null }` pattern.
|
|
2132
|
+
*
|
|
2133
|
+
* @example
|
|
2134
|
+
* ```ts
|
|
2135
|
+
* const renderUser = pipe(
|
|
2136
|
+
* userData,
|
|
2137
|
+
* RemoteData.match({
|
|
2138
|
+
* notAsked: () => "Click to load",
|
|
2139
|
+
* loading: () => "Loading...",
|
|
2140
|
+
* failure: e => `Error: ${e.message}`,
|
|
2141
|
+
* success: user => `Hello, ${user.name}!`
|
|
2142
|
+
* })
|
|
2143
|
+
* );
|
|
2144
|
+
* ```
|
|
2145
|
+
*/
|
|
2146
|
+
type RemoteData<E, A> = NotAsked | Loading | Failure<E> | Success<A>;
|
|
2147
|
+
type NotAsked = WithKind<"NotAsked">;
|
|
2148
|
+
type Loading = WithKind<"Loading">;
|
|
2149
|
+
type Failure<E> = WithKind<"Failure"> & WithError<E>;
|
|
2150
|
+
type Success<A> = WithKind<"Success"> & WithValue<A>;
|
|
2151
|
+
declare const RemoteData: {
|
|
2152
|
+
make: {
|
|
2153
|
+
/**
|
|
2154
|
+
* Creates a NotAsked RemoteData.
|
|
2155
|
+
*
|
|
2156
|
+
* @example
|
|
2157
|
+
* ```ts
|
|
2158
|
+
* RemoteData.make.notAsked(); // NotAsked
|
|
2159
|
+
* ```
|
|
2160
|
+
*/
|
|
2161
|
+
notAsked: () => NotAsked;
|
|
2162
|
+
/**
|
|
2163
|
+
* Creates a Loading RemoteData.
|
|
2164
|
+
*
|
|
2165
|
+
* @example
|
|
2166
|
+
* ```ts
|
|
2167
|
+
* RemoteData.make.loading(); // Loading
|
|
2168
|
+
* ```
|
|
2169
|
+
*/
|
|
2170
|
+
loading: () => Loading;
|
|
2171
|
+
/**
|
|
2172
|
+
* Creates a Failure RemoteData with the given error.
|
|
2173
|
+
*
|
|
2174
|
+
* @example
|
|
2175
|
+
* ```ts
|
|
2176
|
+
* RemoteData.make.failure("Network error"); // Failure("Network error")
|
|
2177
|
+
* ```
|
|
2178
|
+
*/
|
|
2179
|
+
failure: <E>(error: E) => Failure<E>;
|
|
2180
|
+
/**
|
|
2181
|
+
* Creates a Success RemoteData with the given value.
|
|
2182
|
+
*
|
|
2183
|
+
* @example
|
|
2184
|
+
* ```ts
|
|
2185
|
+
* RemoteData.make.success(42); // Success(42)
|
|
2186
|
+
* ```
|
|
2187
|
+
*/
|
|
2188
|
+
success: <A>(value: A) => Success<A>;
|
|
2189
|
+
};
|
|
2190
|
+
is: {
|
|
2191
|
+
/**
|
|
2192
|
+
* Type guard that checks if a RemoteData is NotAsked.
|
|
2193
|
+
*
|
|
2194
|
+
* @example
|
|
2195
|
+
* ```ts
|
|
2196
|
+
* const data = RemoteData.make.notAsked();
|
|
2197
|
+
* if (RemoteData.is.notAsked(data)) {
|
|
2198
|
+
* console.log("Data fetch not initiated");
|
|
2199
|
+
* }
|
|
2200
|
+
* ```
|
|
2201
|
+
*/
|
|
2202
|
+
notAsked: <E, A>(data: RemoteData<E, A>) => data is NotAsked;
|
|
2203
|
+
/**
|
|
2204
|
+
* Type guard that checks if a RemoteData is Loading.
|
|
2205
|
+
*
|
|
2206
|
+
* @example
|
|
2207
|
+
* ```ts
|
|
2208
|
+
* const data = RemoteData.make.loading();
|
|
2209
|
+
* if (RemoteData.is.loading(data)) {
|
|
2210
|
+
* console.log("Data is loading");
|
|
2211
|
+
* }
|
|
2212
|
+
* ```
|
|
2213
|
+
*/
|
|
2214
|
+
loading: <E, A>(data: RemoteData<E, A>) => data is Loading;
|
|
2215
|
+
/**
|
|
2216
|
+
* Type guard that checks if a RemoteData is Failure.
|
|
2217
|
+
*
|
|
2218
|
+
* @example
|
|
2219
|
+
* ```ts
|
|
2220
|
+
* const data = RemoteData.make.failure("Failed");
|
|
2221
|
+
* if (RemoteData.is.failure(data)) {
|
|
2222
|
+
* console.log(data.error); // "Failed"
|
|
2223
|
+
* }
|
|
2224
|
+
* ```
|
|
2225
|
+
*/
|
|
2226
|
+
failure: <E, A>(data: RemoteData<E, A>) => data is Failure<E>;
|
|
2227
|
+
/**
|
|
2228
|
+
* Type guard that checks if a RemoteData is Success.
|
|
2229
|
+
*
|
|
2230
|
+
* @example
|
|
2231
|
+
* ```ts
|
|
2232
|
+
* const data = RemoteData.make.success(42);
|
|
2233
|
+
* if (RemoteData.is.success(data)) {
|
|
2234
|
+
* console.log(data.value); // 42
|
|
2235
|
+
* }
|
|
2236
|
+
* ```
|
|
2237
|
+
*/
|
|
2238
|
+
success: <E, A>(data: RemoteData<E, A>) => data is Success<A>;
|
|
2239
|
+
};
|
|
2240
|
+
/**
|
|
2241
|
+
* Transforms the success value inside a RemoteData.
|
|
2242
|
+
*
|
|
2243
|
+
* @example
|
|
2244
|
+
* ```ts
|
|
2245
|
+
* pipe(RemoteData.make.success(5), RemoteData.map(n => n * 2)); // Success(10)
|
|
2246
|
+
* pipe(RemoteData.make.loading(), RemoteData.map(n => n * 2)); // Loading
|
|
2247
|
+
* ```
|
|
2248
|
+
*/
|
|
2249
|
+
map: <A, B>(f: (a: A) => B) => <E>(data: RemoteData<E, A>) => RemoteData<E, B>;
|
|
2250
|
+
/**
|
|
2251
|
+
* Transforms the error value inside a RemoteData.
|
|
2252
|
+
*
|
|
2253
|
+
* @example
|
|
2254
|
+
* ```ts
|
|
2255
|
+
* pipe(RemoteData.make.failure("oops"), RemoteData.mapError(e => e.toUpperCase())); // Failure("OOPS")
|
|
2256
|
+
* ```
|
|
2257
|
+
*/
|
|
2258
|
+
mapError: <E, F>(f: (e: E) => F) => <A>(data: RemoteData<E, A>) => RemoteData<F, A>;
|
|
2259
|
+
/**
|
|
2260
|
+
* Chains RemoteData computations. If the input is Success, passes the value to f.
|
|
2261
|
+
* Otherwise, propagates the current state.
|
|
2262
|
+
*
|
|
2263
|
+
* @example
|
|
2264
|
+
* ```ts
|
|
2265
|
+
* pipe(
|
|
2266
|
+
* RemoteData.make.success(5),
|
|
2267
|
+
* RemoteData.chain(n => n > 0 ? RemoteData.make.success(n) : RemoteData.make.failure("negative"))
|
|
2268
|
+
* );
|
|
2269
|
+
* ```
|
|
2270
|
+
*/
|
|
2271
|
+
chain: <E2, A, B>(f: (a: A) => RemoteData<E2, B>) => <E1 = never>(data: RemoteData<E1, A>) => RemoteData<E1 | E2, B>;
|
|
2272
|
+
/**
|
|
2273
|
+
* Applies a function wrapped in a RemoteData to a value wrapped in a RemoteData.
|
|
2274
|
+
*
|
|
2275
|
+
* @example
|
|
2276
|
+
* ```ts
|
|
2277
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
2278
|
+
* pipe(
|
|
2279
|
+
* RemoteData.make.success(add),
|
|
2280
|
+
* RemoteData.ap(RemoteData.make.success(5)),
|
|
2281
|
+
* RemoteData.ap(RemoteData.make.success(3))
|
|
2282
|
+
* ); // Success(8)
|
|
2283
|
+
* ```
|
|
2284
|
+
*/
|
|
2285
|
+
ap: <E, A>(arg: RemoteData<E, A>) => <B>(data: RemoteData<E, (a: A) => B>) => RemoteData<E, B>;
|
|
2286
|
+
/**
|
|
2287
|
+
* Extracts the value from a RemoteData by providing handlers for all four cases.
|
|
2288
|
+
*
|
|
2289
|
+
* @example
|
|
2290
|
+
* ```ts
|
|
2291
|
+
* pipe(
|
|
2292
|
+
* userData,
|
|
2293
|
+
* RemoteData.fold(
|
|
2294
|
+
* e => `Error: ${e}`,
|
|
2295
|
+
* () => "Not asked",
|
|
2296
|
+
* () => "Loading...",
|
|
2297
|
+
* value => `Got: ${value}`
|
|
2298
|
+
* )
|
|
2299
|
+
* );
|
|
2300
|
+
* ```
|
|
2301
|
+
*/
|
|
2302
|
+
fold: <E, A, B>(onFailure: (e: E) => B, onNotAsked: () => B, onLoading: () => B, onSuccess: (a: A) => B) => (data: RemoteData<E, A>) => B;
|
|
2303
|
+
/**
|
|
2304
|
+
* Pattern matches on a RemoteData, returning the result of the matching case.
|
|
2305
|
+
*
|
|
2306
|
+
* @example
|
|
2307
|
+
* ```ts
|
|
2308
|
+
* pipe(
|
|
2309
|
+
* userData,
|
|
2310
|
+
* RemoteData.match({
|
|
2311
|
+
* notAsked: () => "Click to load",
|
|
2312
|
+
* loading: () => "Loading...",
|
|
2313
|
+
* failure: e => `Error: ${e}`,
|
|
2314
|
+
* success: user => `Hello, ${user.name}!`
|
|
2315
|
+
* })
|
|
2316
|
+
* );
|
|
2317
|
+
* ```
|
|
2318
|
+
*/
|
|
2319
|
+
match: <E, A, B>(cases: {
|
|
2320
|
+
notAsked: () => B;
|
|
2321
|
+
loading: () => B;
|
|
2322
|
+
failure: (e: E) => B;
|
|
2323
|
+
success: (a: A) => B;
|
|
2324
|
+
}) => (data: RemoteData<E, A>) => B;
|
|
2325
|
+
/**
|
|
2326
|
+
* Returns the success value or a default value if the RemoteData is not Success.
|
|
2327
|
+
* The default can be a different type, widening the result to `A | B`.
|
|
2328
|
+
*
|
|
2329
|
+
* @example
|
|
2330
|
+
* ```ts
|
|
2331
|
+
* pipe(RemoteData.make.success(5), RemoteData.getOrElse(() => 0)); // 5
|
|
2332
|
+
* pipe(RemoteData.make.loading(), RemoteData.getOrElse(() => 0)); // 0
|
|
2333
|
+
* pipe(RemoteData.make.loading<string, number>(), RemoteData.getOrElse(() => null)); // null — typed as number | null
|
|
2334
|
+
* ```
|
|
2335
|
+
*/
|
|
2336
|
+
getOrElse: <B>(defaultValue: () => B) => <E, A>(data: RemoteData<E, A>) => A | B;
|
|
2337
|
+
/**
|
|
2338
|
+
* Executes a side effect on the success value without changing the RemoteData.
|
|
2339
|
+
*
|
|
2340
|
+
* @example
|
|
2341
|
+
* ```ts
|
|
2342
|
+
* pipe(
|
|
2343
|
+
* RemoteData.make.success(5),
|
|
2344
|
+
* RemoteData.tap(n => console.log("Value:", n)),
|
|
2345
|
+
* RemoteData.map(n => n * 2)
|
|
2346
|
+
* );
|
|
2347
|
+
* ```
|
|
2348
|
+
*/
|
|
2349
|
+
tap: <E, A>(f: (a: A) => void) => (data: RemoteData<E, A>) => RemoteData<E, A>;
|
|
2350
|
+
/**
|
|
2351
|
+
* Executes a side effect on the failure error without changing the RemoteData.
|
|
2352
|
+
* Useful for logging errors.
|
|
2353
|
+
*
|
|
2354
|
+
* @example
|
|
2355
|
+
* ```ts
|
|
2356
|
+
* pipe(
|
|
2357
|
+
* RemoteData.make.failure("not found"),
|
|
2358
|
+
* RemoteData.tapError(e => console.error("fetch failed:", e)),
|
|
2359
|
+
* RemoteData.map(render)
|
|
2360
|
+
* );
|
|
2361
|
+
* ```
|
|
2362
|
+
*/
|
|
2363
|
+
tapError: <E, A>(f: (e: E) => void) => (data: RemoteData<E, A>) => RemoteData<E, A>;
|
|
2364
|
+
/**
|
|
2365
|
+
* Recovers from a Failure state by providing a fallback RemoteData.
|
|
2366
|
+
* The fallback can produce a different success type, widening the result to `RemoteData<E, A | B>`.
|
|
2367
|
+
*/
|
|
2368
|
+
recover: <E, B>(fallback: (e: E) => RemoteData<E, B>) => <A>(data: RemoteData<E, A>) => RemoteData<E, A | B>;
|
|
2369
|
+
to: {
|
|
2370
|
+
/**
|
|
2371
|
+
* Converts a RemoteData to a Maybe.
|
|
2372
|
+
* Success becomes Some, all other states become None.
|
|
2373
|
+
*/
|
|
2374
|
+
Maybe: <E, A>(data: RemoteData<E, A>) => Maybe<A>;
|
|
2375
|
+
/**
|
|
2376
|
+
* Converts a RemoteData to a Result.
|
|
2377
|
+
* Success becomes Ok, Failure becomes Err.
|
|
2378
|
+
* NotAsked and Loading become Err with the provided fallback error.
|
|
2379
|
+
*
|
|
2380
|
+
* @example
|
|
2381
|
+
* ```ts
|
|
2382
|
+
* pipe(
|
|
2383
|
+
* RemoteData.make.success(42),
|
|
2384
|
+
* RemoteData.to.Result(() => "not loaded")
|
|
2385
|
+
* ); // Ok(42)
|
|
2386
|
+
* ```
|
|
2387
|
+
*/
|
|
2388
|
+
Result: <E>(onNotReady: () => E) => <A>(data: RemoteData<E, A>) => Result<E, A>;
|
|
2389
|
+
};
|
|
2390
|
+
from: {
|
|
2391
|
+
/**
|
|
2392
|
+
* Converts a Result to a RemoteData.
|
|
2393
|
+
* Ok becomes Success, Err becomes Failure.
|
|
2394
|
+
*
|
|
2395
|
+
* @example
|
|
2396
|
+
* ```ts
|
|
2397
|
+
* const result = await Task.Result.tryCatch(() => loadUser(), { onError: String })();
|
|
2398
|
+
* setState(RemoteData.from.Result(result)); // Success(user) or Failure(msg)
|
|
2399
|
+
* ```
|
|
2400
|
+
*/
|
|
2401
|
+
Result: <E, A>(data: Result<E, A>) => RemoteData<E, A>;
|
|
2402
|
+
/**
|
|
2403
|
+
* Converts a Maybe to a RemoteData.
|
|
2404
|
+
* Some becomes Success, None becomes Failure using the onNone error producer.
|
|
2405
|
+
*
|
|
2406
|
+
* @example
|
|
2407
|
+
* ```ts
|
|
2408
|
+
* pipe(Maybe.make.some(user), RemoteData.from.Maybe(() => "not found")); // Success(user)
|
|
2409
|
+
* pipe(Maybe.make.none(), RemoteData.from.Maybe(() => "not found")); // Failure("not found")
|
|
2410
|
+
* ```
|
|
2411
|
+
*/
|
|
2412
|
+
Maybe: <E>(onNone: () => E) => <A>(data: Maybe<A>) => RemoteData<E, A>;
|
|
2413
|
+
};
|
|
2414
|
+
/**
|
|
2415
|
+
* Filters a `Success` value. When the predicate passes, the value is kept. When it fails,
|
|
2416
|
+
* `Success` becomes `Failure` using the error produced by `onFalse`. All other states pass through unchanged.
|
|
2417
|
+
*
|
|
2418
|
+
* @example
|
|
2419
|
+
* ```ts
|
|
2420
|
+
* RemoteData.filter(n => n > 0, n => `${n} is not a valid price`)(RemoteData.make.success(9.99));
|
|
2421
|
+
* // Success(9.99)
|
|
2422
|
+
* RemoteData.filter(n => n > 0, n => `${n} is not a valid price`)(RemoteData.make.success(-1));
|
|
2423
|
+
* // Failure("-1 is not a valid price")
|
|
2424
|
+
* RemoteData.filter(n => n > 0, () => "error")(RemoteData.make.loading()); // Loading
|
|
2425
|
+
* ```
|
|
2426
|
+
*/
|
|
2427
|
+
filter: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (data: RemoteData<E, A>) => RemoteData<E, A>;
|
|
2428
|
+
};
|
|
2429
|
+
//#endregion
|
|
2430
|
+
//#region src/Core/Resource.d.ts
|
|
2431
|
+
/**
|
|
2432
|
+
* A Resource pairs an async acquisition step with a guaranteed cleanup step.
|
|
2433
|
+
*
|
|
2434
|
+
* Use it whenever something must be explicitly closed, released, or torn down
|
|
2435
|
+
* after you are done with it — database connections, file handles, locks,
|
|
2436
|
+
* temporary directories, or any object with a lifecycle.
|
|
2437
|
+
*
|
|
2438
|
+
* The key guarantee: `release` always runs after `Resource.use`, even when
|
|
2439
|
+
* the work function returns an error. If `acquire` itself fails, `release` is
|
|
2440
|
+
* skipped — there is nothing to clean up.
|
|
2441
|
+
*
|
|
2442
|
+
* Build a Resource with `Resource.from.handlers` or `Resource.from.Task`, then run it
|
|
2443
|
+
* with `Resource.use`.
|
|
2444
|
+
*
|
|
2445
|
+
* @example
|
|
2446
|
+
* ```ts
|
|
2447
|
+
* const dbResource = Resource.from.handlers(
|
|
2448
|
+
* Task.Result.tryCatch(() => openConnection(config), { onError: (e) => new DbError(e) }),
|
|
2449
|
+
* (conn) => Task.tryCatch(() => conn.close(), { onError: () => {} })
|
|
2450
|
+
* );
|
|
2451
|
+
*
|
|
2452
|
+
* const result = await pipe(
|
|
2453
|
+
* dbResource,
|
|
2454
|
+
* Resource.use((conn) => queryUser(conn, userId))
|
|
2455
|
+
* )();
|
|
2456
|
+
* // conn.close() is called whether queryUser succeeds or fails
|
|
2457
|
+
* ```
|
|
2458
|
+
*/
|
|
2459
|
+
type Resource<E, A> = {
|
|
2460
|
+
readonly acquire: Task.Result<E, A>;
|
|
2461
|
+
readonly release: (a: A) => Task<void>;
|
|
2462
|
+
};
|
|
2463
|
+
declare const Resource: {
|
|
2464
|
+
from: {
|
|
2465
|
+
/**
|
|
2466
|
+
* Creates a Resource from an acquire operation that may fail and a release function.
|
|
2467
|
+
*
|
|
2468
|
+
* @example
|
|
2469
|
+
* ```ts
|
|
2470
|
+
* const fileResource = Resource.from.handlers(
|
|
2471
|
+
* Task.Result.tryCatch(() => fs.promises.open("data.csv", "r"), { onError: toFileError }),
|
|
2472
|
+
* (handle) => Task.tryCatch(() => handle.close(), { onError: () => {} })
|
|
2473
|
+
* );
|
|
2474
|
+
* ```
|
|
2475
|
+
*/
|
|
2476
|
+
handlers: <E, A>(acquire: Task.Result<E, A>, release: (a: A) => Task<void>) => Resource<E, A>;
|
|
2477
|
+
/**
|
|
2478
|
+
* Creates a Resource from an acquire operation that cannot fail.
|
|
2479
|
+
* Use this when opening the resource is guaranteed to succeed, such as
|
|
2480
|
+
* in-memory locks, counters, or timers.
|
|
2481
|
+
*
|
|
2482
|
+
* @example
|
|
2483
|
+
* ```ts
|
|
2484
|
+
* const timerResource = Resource.from.Task<never, Timer>(
|
|
2485
|
+
* Task.tryCatch(() => Promise.resolve(startTimer()), { onError: () => defaultTimer }),
|
|
2486
|
+
* (timer) => Task.tryCatch(() => Promise.resolve(timer.stop()), { onError: () => {} })
|
|
2487
|
+
* );
|
|
2488
|
+
* ```
|
|
2489
|
+
*/
|
|
2490
|
+
Task: <E, A>(acquire: Task<A>, release: (a: A) => Task<void>) => Resource<E, A>;
|
|
2491
|
+
};
|
|
2492
|
+
/**
|
|
2493
|
+
* Acquires the resource, runs `f` with it, then releases it.
|
|
2494
|
+
*
|
|
2495
|
+
* Release always runs, even when `f` returns an error.
|
|
2496
|
+
* If acquire fails, `f` and release are both skipped and the error is returned.
|
|
2497
|
+
*
|
|
2498
|
+
* @example
|
|
2499
|
+
* ```ts
|
|
2500
|
+
* const rows = await pipe(
|
|
2501
|
+
* dbResource,
|
|
2502
|
+
* Resource.use((conn) => runQuery(conn, "SELECT * FROM users"))
|
|
2503
|
+
* )();
|
|
2504
|
+
* // conn is closed whether the query succeeds or fails
|
|
2505
|
+
* ```
|
|
2506
|
+
*/
|
|
2507
|
+
use: <E, A, B>(f: (a: A) => Task.Result<E, B>) => (resource: Resource<E, A>) => Task.Result<E, B>;
|
|
2508
|
+
/**
|
|
2509
|
+
* Acquires two resources in sequence and presents them as a tuple.
|
|
2510
|
+
* Resources are released in reverse order: the second is released before the first.
|
|
2511
|
+
*
|
|
2512
|
+
* If the second resource fails to acquire, the first is released immediately
|
|
2513
|
+
* before returning the error.
|
|
2514
|
+
*
|
|
2515
|
+
* @example
|
|
2516
|
+
* ```ts
|
|
2517
|
+
* const combined = Resource.combine(dbResource, cacheResource);
|
|
2518
|
+
*
|
|
2519
|
+
* const result = await pipe(
|
|
2520
|
+
* combined,
|
|
2521
|
+
* Resource.use(([conn, cache]) => lookupWithFallback(conn, cache, userId))
|
|
2522
|
+
* )();
|
|
2523
|
+
* ```
|
|
2524
|
+
*/
|
|
2525
|
+
combine: <E, A, B>(resourceA: Resource<E, A>, resourceB: Resource<E, B>) => Resource<E, readonly [A, B]>;
|
|
2526
|
+
};
|
|
2527
|
+
//#endregion
|
|
2528
|
+
//#region src/Core/Result.d.ts
|
|
2529
|
+
/**
|
|
2530
|
+
* Result represents a value that can be one of two types: a success (Ok) or a failure (Err).
|
|
2531
|
+
* Use Result when an operation can fail with a meaningful error value.
|
|
2532
|
+
*
|
|
2533
|
+
* @example
|
|
2534
|
+
* ```ts
|
|
2535
|
+
* const divide = (a: number, b: number): Result<string, number> =>
|
|
2536
|
+
* b === 0 ? Result.make.err("Division by zero") : Result.make.ok(a / b);
|
|
2537
|
+
*
|
|
2538
|
+
* pipe(
|
|
2539
|
+
* divide(10, 2),
|
|
2540
|
+
* Result.map(n => n * 2),
|
|
2541
|
+
* Result.getOrElse(() => 0)
|
|
2542
|
+
* ); // 10
|
|
2543
|
+
* ```
|
|
2544
|
+
*/
|
|
2545
|
+
type Result<E, A> = Ok$1<A> | Err$1<E>;
|
|
2546
|
+
type Ok$1<A> = WithKind<"Ok"> & WithValue<A>;
|
|
2547
|
+
type Err$1<E> = WithKind<"Err"> & WithError<E>;
|
|
2548
|
+
declare const Result: {
|
|
2549
|
+
make: {
|
|
2550
|
+
/**
|
|
2551
|
+
* Creates a successful Result with the given value.
|
|
2552
|
+
*
|
|
2553
|
+
* @example
|
|
2554
|
+
* ```ts
|
|
2555
|
+
* Result.make.ok(42); // Ok(42)
|
|
2556
|
+
* ```
|
|
2557
|
+
*/
|
|
2558
|
+
ok: <A>(value: A) => Ok$1<A>;
|
|
2559
|
+
/**
|
|
2560
|
+
* Creates a failed Result with the given error.
|
|
2561
|
+
*
|
|
2562
|
+
* @example
|
|
2563
|
+
* ```ts
|
|
2564
|
+
* Result.make.err("Error message"); // Err("Error message")
|
|
2565
|
+
* ```
|
|
2566
|
+
*/
|
|
2567
|
+
err: <E>(e: E) => Err$1<E>;
|
|
2568
|
+
};
|
|
2569
|
+
is: {
|
|
2570
|
+
/**
|
|
2571
|
+
* Type guard that checks if a Result is Ok.
|
|
2572
|
+
*
|
|
2573
|
+
* @example
|
|
2574
|
+
* ```ts
|
|
2575
|
+
* const res = Result.make.ok(42);
|
|
2576
|
+
* if (Result.is.ok(res)) {
|
|
2577
|
+
* console.log(res.value); // 42
|
|
2578
|
+
* }
|
|
2579
|
+
* ```
|
|
2580
|
+
*/
|
|
2581
|
+
ok: <E, A>(data: Result<E, A>) => data is Ok$1<A>;
|
|
2582
|
+
/**
|
|
2583
|
+
* Type guard that checks if a Result is Err.
|
|
2584
|
+
*
|
|
2585
|
+
* @example
|
|
2586
|
+
* ```ts
|
|
2587
|
+
* const res = Result.make.err("failed");
|
|
2588
|
+
* if (Result.is.err(res)) {
|
|
2589
|
+
* console.log(res.error); // "failed"
|
|
2590
|
+
* }
|
|
2591
|
+
* ```
|
|
2592
|
+
*/
|
|
2593
|
+
err: <E, A>(data: Result<E, A>) => data is Err$1<E>;
|
|
2594
|
+
};
|
|
2595
|
+
/**
|
|
2596
|
+
* Creates a Result from a synchronous thunk that may throw.
|
|
2597
|
+
* Catches any errors and transforms them using the `onError` function.
|
|
2598
|
+
*
|
|
2599
|
+
* @example
|
|
2600
|
+
* ```ts
|
|
2601
|
+
* const result = Result.tryCatch(
|
|
2602
|
+
* () => JSON.parse(rawString),
|
|
2603
|
+
* { onError: (e) => `Parse error: ${e}` }
|
|
2604
|
+
* );
|
|
2605
|
+
* ```
|
|
2606
|
+
*/
|
|
2607
|
+
tryCatch: <E, A>(f: () => A, options: {
|
|
2608
|
+
onError: (e: unknown) => E;
|
|
2609
|
+
}) => Result<E, A>;
|
|
2610
|
+
/**
|
|
2611
|
+
* Transforms the success value inside a Result.
|
|
2612
|
+
*
|
|
2613
|
+
* @example
|
|
2614
|
+
* ```ts
|
|
2615
|
+
* pipe(Result.make.ok(5), Result.map(n => n * 2)); // Ok(10)
|
|
2616
|
+
* pipe(Result.make.err("error"), Result.map(n => n * 2)); // Err("error")
|
|
2617
|
+
* ```
|
|
2618
|
+
*/
|
|
2619
|
+
map: <E, A, B>(f: (a: A) => B) => (data: Result<E, A>) => Result<E, B>;
|
|
2620
|
+
/**
|
|
2621
|
+
* Transforms the error value inside a Result.
|
|
2622
|
+
*
|
|
2623
|
+
* @example
|
|
2624
|
+
* ```ts
|
|
2625
|
+
* pipe(Result.make.err("oops"), Result.mapError(e => e.toUpperCase())); // Err("OOPS")
|
|
2626
|
+
* ```
|
|
2627
|
+
*/
|
|
2628
|
+
mapError: <E, F, A>(f: (e: E) => F) => (data: Result<E, A>) => Result<F, A>;
|
|
2629
|
+
/**
|
|
2630
|
+
* Chains Result computations. If the first is Ok, passes the value to f.
|
|
2631
|
+
* If the first is Err, propagates the error.
|
|
2632
|
+
*
|
|
2633
|
+
* @example
|
|
2634
|
+
* ```ts
|
|
2635
|
+
* const validatePositive = (n: number): Result<string, number> =>
|
|
2636
|
+
* n > 0 ? Result.make.ok(n) : Result.make.err("Must be positive");
|
|
2637
|
+
*
|
|
2638
|
+
* pipe(Result.make.ok(5), Result.chain(validatePositive)); // Ok(5)
|
|
2639
|
+
* pipe(Result.make.ok(-1), Result.chain(validatePositive)); // Err("Must be positive")
|
|
2640
|
+
* ```
|
|
2641
|
+
*/
|
|
2642
|
+
chain: <E2, A, B>(f: (a: A) => Result<E2, B>) => <E1 = never>(data: Result<E1, A>) => Result<E1 | E2, B>;
|
|
2643
|
+
/**
|
|
2644
|
+
* Extracts the value from a Result by providing handlers for both cases.
|
|
2645
|
+
*
|
|
2646
|
+
* @example
|
|
2647
|
+
* ```ts
|
|
2648
|
+
* pipe(
|
|
2649
|
+
* Result.make.ok(5),
|
|
2650
|
+
* Result.fold(
|
|
2651
|
+
* e => `Error: ${e}`,
|
|
2652
|
+
* n => `Value: ${n}`
|
|
2653
|
+
* )
|
|
2654
|
+
* ); // "Value: 5"
|
|
2655
|
+
* ```
|
|
2656
|
+
*/
|
|
2657
|
+
fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: Result<E, A>) => B;
|
|
2658
|
+
/**
|
|
2659
|
+
* Pattern matches on a Result, returning the result of the matching case.
|
|
2660
|
+
*
|
|
2661
|
+
* @example
|
|
2662
|
+
* ```ts
|
|
2663
|
+
* pipe(
|
|
2664
|
+
* result,
|
|
2665
|
+
* Result.match({
|
|
2666
|
+
* ok: value => `Got ${value}`,
|
|
2667
|
+
* err: error => `Failed: ${error}`
|
|
2668
|
+
* })
|
|
2669
|
+
* );
|
|
2670
|
+
* ```
|
|
2671
|
+
*/
|
|
2672
|
+
match: <E, A, B>(cases: {
|
|
2673
|
+
ok: (a: A) => B;
|
|
2674
|
+
err: (e: E) => B;
|
|
2675
|
+
}) => (data: Result<E, A>) => B;
|
|
2676
|
+
/**
|
|
2677
|
+
* Returns the success value or a default value if the Result is an error.
|
|
2678
|
+
* The default is a thunk `() => B` — evaluated only when the Result is Err.
|
|
2679
|
+
* The default can be a different type, widening the result to `A | B`.
|
|
2680
|
+
*
|
|
2681
|
+
* @example
|
|
2682
|
+
* ```ts
|
|
2683
|
+
* pipe(Result.make.ok(5), Result.getOrElse(() => 0)); // 5
|
|
2684
|
+
* pipe(Result.make.err("error"), Result.getOrElse(() => 0)); // 0
|
|
2685
|
+
* pipe(Result.make.err("error"), Result.getOrElse(() => null)); // null — typed as number | null
|
|
2686
|
+
* ```
|
|
2687
|
+
*/
|
|
2688
|
+
getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Result<E, A>) => A | B;
|
|
2689
|
+
/**
|
|
2690
|
+
* Executes a side effect on the success value without changing the Result.
|
|
2691
|
+
* Useful for logging or debugging.
|
|
2692
|
+
*
|
|
2693
|
+
* @example
|
|
2694
|
+
* ```ts
|
|
2695
|
+
* pipe(
|
|
2696
|
+
* Result.make.ok(5),
|
|
2697
|
+
* Result.tap(n => console.log("Value:", n)),
|
|
2698
|
+
* Result.map(n => n * 2)
|
|
2699
|
+
* );
|
|
2700
|
+
* ```
|
|
2701
|
+
*/
|
|
2702
|
+
tap: <E, A>(f: (a: A) => void) => (data: Result<E, A>) => Result<E, A>;
|
|
2703
|
+
/**
|
|
2704
|
+
* Executes a side effect on the error value without changing the Result.
|
|
2705
|
+
* Useful for logging or reporting errors.
|
|
2706
|
+
*
|
|
2707
|
+
* @example
|
|
2708
|
+
* ```ts
|
|
2709
|
+
* pipe(
|
|
2710
|
+
* Result.make.err("not found"),
|
|
2711
|
+
* Result.tapError(e => console.error("validation failed:", e)),
|
|
2712
|
+
* Result.chain(save),
|
|
2713
|
+
* )
|
|
2714
|
+
* ```
|
|
2715
|
+
*/
|
|
2716
|
+
tapError: <E, A>(f: (e: E) => void) => (data: Result<E, A>) => Result<E, A>;
|
|
2717
|
+
from: {
|
|
2718
|
+
/**
|
|
2719
|
+
* Creates a Result from a predicate applied to a value.
|
|
2720
|
+
* Returns Ok if the predicate passes, Err from onFalse otherwise.
|
|
2721
|
+
*
|
|
2722
|
+
* @example
|
|
2723
|
+
* ```ts
|
|
2724
|
+
* pipe(5, Result.from.Predicate(n => n > 0, n => `${n} is not positive`)); // Ok(5)
|
|
2725
|
+
* pipe(-1, Result.from.Predicate(n => n > 0, n => `${n} is not positive`)); // Err("-1 is not positive")
|
|
2726
|
+
* pipe("", Result.from.Predicate(s => s.length > 0, () => "empty string")); // Err("empty string")
|
|
2727
|
+
* ```
|
|
2728
|
+
*/
|
|
2729
|
+
Predicate: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (a: A) => Result<E, A>;
|
|
2730
|
+
/**
|
|
2731
|
+
* Creates a Result from a nullable value.
|
|
2732
|
+
* Returns Ok if the value is not null or undefined, error from onNull otherwise.
|
|
2733
|
+
*
|
|
2734
|
+
* @example
|
|
2735
|
+
* ```ts
|
|
2736
|
+
* pipe(null, Result.from.nullable(() => "is null")); // Err("is null")
|
|
2737
|
+
* pipe(42, Result.from.nullable(() => "is null")); // Ok(42)
|
|
2738
|
+
* ```
|
|
2739
|
+
*/
|
|
2740
|
+
nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Result<E, A>;
|
|
2741
|
+
/**
|
|
2742
|
+
* Creates a Result from a Maybe.
|
|
2743
|
+
* Some becomes Ok, None becomes error from onNone.
|
|
2744
|
+
*
|
|
2745
|
+
* @example
|
|
2746
|
+
* ```ts
|
|
2747
|
+
* pipe(Maybe.make.none(), Result.from.Maybe(() => "is none")); // Err("is none")
|
|
2748
|
+
* pipe(Maybe.make.some(42), Result.from.Maybe(() => "is none")); // Ok(42)
|
|
2749
|
+
* ```
|
|
2750
|
+
*/
|
|
2751
|
+
Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Result<E, A>;
|
|
2752
|
+
/**
|
|
2753
|
+
* Converts a `Validation` to a `Result`, combining accumulated errors using `combineErrors`.
|
|
2754
|
+
* `Passed(a)` becomes `Ok(a)`; `Failed(errors)` becomes `Err(combineErrors(errors))`.
|
|
2755
|
+
*
|
|
2756
|
+
* @example
|
|
2757
|
+
* ```ts
|
|
2758
|
+
* Result.from.Validation((errors) => errors.join(", "))(Validation.make.failed("error1")); // Err("error1")
|
|
2759
|
+
* ```
|
|
2760
|
+
*/
|
|
2761
|
+
Validation: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (val: Validation<E1, A>) => Result<E2, A>;
|
|
2762
|
+
};
|
|
2763
|
+
/**
|
|
2764
|
+
* Recovers from an error by providing a fallback Result.
|
|
2765
|
+
* The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
|
|
2766
|
+
*/
|
|
2767
|
+
recover: <E, B>(fallback: (e: E) => Result<E, B>) => <A>(data: Result<E, A>) => Result<E, A | B>;
|
|
2768
|
+
/**
|
|
2769
|
+
* Recovers from an error unless the predicate `isBlocked` returns true for that error.
|
|
2770
|
+
* The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
|
|
2771
|
+
*
|
|
2772
|
+
* @example
|
|
2773
|
+
* ```ts
|
|
2774
|
+
* pipe(
|
|
2775
|
+
* Result.make.err(new Error("not found")),
|
|
2776
|
+
* Result.recoverUnless(e => e.message === "fatal", () => Result.make.ok(0))
|
|
2777
|
+
* ); // Ok(0)
|
|
2778
|
+
* ```
|
|
2779
|
+
*/
|
|
2780
|
+
recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: () => Result<E, B>) => <A>(data: Result<E, A>) => Result<E, A | B>;
|
|
2781
|
+
to: {
|
|
2782
|
+
/**
|
|
2783
|
+
* Converts a Result to a Maybe.
|
|
2784
|
+
* Ok becomes Some, Err becomes None (the error is discarded).
|
|
2785
|
+
*
|
|
2786
|
+
* @example
|
|
2787
|
+
* ```ts
|
|
2788
|
+
* Result.to.Maybe(Result.make.ok(42)); // Some(42)
|
|
2789
|
+
* Result.to.Maybe(Result.make.err("oops")); // None
|
|
2790
|
+
* ```
|
|
2791
|
+
*/
|
|
2792
|
+
Maybe: <E, A>(data: Result<E, A>) => Maybe<A>;
|
|
2793
|
+
/**
|
|
2794
|
+
* Converts a `Result` to a `Validation`. `Ok(a)` becomes `Passed(a)`; `Err(e)` becomes `Failed([e])`.
|
|
2795
|
+
*
|
|
2796
|
+
* @example
|
|
2797
|
+
* ```ts
|
|
2798
|
+
* Result.to.Validation(Result.make.ok(42)); // Passed(42)
|
|
2799
|
+
* Result.to.Validation(Result.make.err("bad")); // Failed(["bad"])
|
|
2800
|
+
* ```
|
|
2801
|
+
*/
|
|
2802
|
+
Validation: <E, A>(data: Result<E, A>) => Validation<E, A>;
|
|
2803
|
+
};
|
|
2804
|
+
/**
|
|
2805
|
+
* Swaps the outer `Result` and inner `Maybe` context.
|
|
2806
|
+
* `Ok(Some(a))` becomes `Some(Ok(a))`, `Ok(None)` becomes `None`, and `Err(e)` becomes `Some(Err(e))`.
|
|
2807
|
+
*
|
|
2808
|
+
* @example
|
|
2809
|
+
* ```ts
|
|
2810
|
+
* Result.transposeMaybe(Result.make.ok(Maybe.make.some(42))); // Some(Ok(42))
|
|
2811
|
+
* Result.transposeMaybe(Result.make.ok(Maybe.make.none())); // None
|
|
2812
|
+
* Result.transposeMaybe(Result.make.err("error")); // Some(Err("error"))
|
|
2813
|
+
* ```
|
|
2814
|
+
*/
|
|
2815
|
+
transposeMaybe: <E, A>(data: Result<E, Maybe<A>>) => Maybe<Result<E, A>>;
|
|
2816
|
+
/**
|
|
2817
|
+
* Applies a function wrapped in a Result to a value wrapped in a Result.
|
|
2818
|
+
*
|
|
2819
|
+
* @example
|
|
2820
|
+
* ```ts
|
|
2821
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
2822
|
+
* pipe(
|
|
2823
|
+
* Result.make.ok(add),
|
|
2824
|
+
* Result.ap(Result.make.ok(5)),
|
|
2825
|
+
* Result.ap(Result.make.ok(3))
|
|
2826
|
+
* ); // Ok(8)
|
|
2827
|
+
* ```
|
|
2828
|
+
*/
|
|
2829
|
+
ap: <E, A>(arg: Result<E, A>) => <B>(data: Result<E, (a: A) => B>) => Result<E, B>;
|
|
2830
|
+
/**
|
|
2831
|
+
* Converts a Result value into an object containing a single property.
|
|
2832
|
+
* Initiates the pipeline accumulator record.
|
|
2833
|
+
*
|
|
2834
|
+
* @example
|
|
2835
|
+
* ```ts
|
|
2836
|
+
* pipe(Result.make.ok(42), Result.bindTo("value")); // Ok({ value: 42 })
|
|
2837
|
+
* ```
|
|
2838
|
+
*/
|
|
2839
|
+
bindTo: <K extends string>(key: K) => <E, A>(data: Result<E, A>) => Result<E, { [P in K]: A; }>;
|
|
2840
|
+
/**
|
|
2841
|
+
* Evaluates a new Result using the current accumulator and attaches the output to a new key.
|
|
2842
|
+
*
|
|
2843
|
+
* @example
|
|
2844
|
+
* ```ts
|
|
2845
|
+
* pipe(
|
|
2846
|
+
* Result.make.ok({ a: 1 }),
|
|
2847
|
+
* Result.bind("b", ({ a }) => Result.make.ok(a + 1))
|
|
2848
|
+
* ); // Ok({ a: 1, b: 2 })
|
|
2849
|
+
* ```
|
|
2850
|
+
*/
|
|
2851
|
+
bind: <K extends string, E, A, B>(key: K, f: (a: A) => Result<E, B>) => (data: Result<E, A>) => Result<E, A & { [P in K]: B; }>;
|
|
2852
|
+
/**
|
|
2853
|
+
* Combines a record of Results into a single Result of a record.
|
|
2854
|
+
* Evaluates fields in key order and short-circuits on the first failure.
|
|
2855
|
+
*
|
|
2856
|
+
* @example
|
|
2857
|
+
* ```ts
|
|
2858
|
+
* Result.struct({
|
|
2859
|
+
* name: Result.make.ok("Alice"),
|
|
2860
|
+
* age: Result.make.ok(30)
|
|
2861
|
+
* }); // Ok({ name: "Alice", age: 30 })
|
|
2862
|
+
* ```
|
|
2863
|
+
*/
|
|
2864
|
+
struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Result<E, R[K]>; }) => Result<E, R>;
|
|
2865
|
+
/**
|
|
2866
|
+
* Narrows an `Ok` value with a predicate, converting to `Err(onFail(a))` if the predicate returns false.
|
|
2867
|
+
*
|
|
2868
|
+
* @example
|
|
2869
|
+
* ```ts
|
|
2870
|
+
* pipe(
|
|
2871
|
+
* Result.make.ok(15),
|
|
2872
|
+
* Result.ensure((n) => n >= 18, (n) => `Age ${n} is below 18`)
|
|
2873
|
+
* ); // Err("Age 15 is below 18")
|
|
2874
|
+
* ```
|
|
2875
|
+
*/
|
|
2876
|
+
ensure: <A, E2>(predicate: (a: A) => boolean, onFail: (a: A) => E2) => <E1 = never>(data: Result<E1, A>) => Result<E1 | E2, A>;
|
|
2877
|
+
/**
|
|
2878
|
+
* Transforms both branches of a Result simultaneously.
|
|
2879
|
+
* Applies `onErr` to `Err` values and `onOk` to `Ok` values.
|
|
2880
|
+
*
|
|
2881
|
+
* @example
|
|
2882
|
+
* ```ts
|
|
2883
|
+
* pipe(
|
|
2884
|
+
* Result.make.ok(5),
|
|
2885
|
+
* Result.bimap(
|
|
2886
|
+
* (e) => `Error: ${e}`,
|
|
2887
|
+
* (n) => n * 2
|
|
2888
|
+
* )
|
|
2889
|
+
* ); // Ok(10)
|
|
2890
|
+
* ```
|
|
2891
|
+
*/
|
|
2892
|
+
bimap: <E1, E2, A, B>(onErr: (e: E1) => E2, onOk: (a: A) => B) => (data: Result<E1, A>) => Result<E2, B>;
|
|
2893
|
+
};
|
|
2894
|
+
//#endregion
|
|
2895
|
+
//#region src/Core/State.d.ts
|
|
2896
|
+
/**
|
|
2897
|
+
* A synchronous computation that threads a piece of mutable state `S` through
|
|
2898
|
+
* a pipeline without exposing mutation at call sites.
|
|
2899
|
+
*
|
|
2900
|
+
* At runtime a `State<S, A>` is just a function from an initial state to a pair
|
|
2901
|
+
* `[value, nextState]`. Nothing runs until you supply the initial state with
|
|
2902
|
+
* `State.run`, `State.evaluate`, or `State.execute`.
|
|
2903
|
+
*
|
|
2904
|
+
* @example
|
|
2905
|
+
* ```ts
|
|
2906
|
+
* type Counter = number;
|
|
2907
|
+
*
|
|
2908
|
+
* const increment: State<Counter, undefined> = State.modify(n => n + 1);
|
|
2909
|
+
* const getCount: State<Counter, Counter> = State.get();
|
|
2910
|
+
*
|
|
2911
|
+
* const program = pipe(
|
|
2912
|
+
* increment,
|
|
2913
|
+
* State.chain(() => increment),
|
|
2914
|
+
* State.chain(() => getCount),
|
|
2915
|
+
* );
|
|
2916
|
+
*
|
|
2917
|
+
* State.run(0)(program); // [2, 2] — value is 2, final state is 2
|
|
2918
|
+
* ```
|
|
2919
|
+
*/
|
|
2920
|
+
type State$1<S, A> = (s: S) => readonly [A, S];
|
|
2921
|
+
declare const State$1: {
|
|
2922
|
+
/**
|
|
2923
|
+
* Lifts a pure value into a State computation. The state passes through unchanged.
|
|
2924
|
+
*
|
|
2925
|
+
* @example
|
|
2926
|
+
* ```ts
|
|
2927
|
+
* State.run(10)(State.resolve(42)); // [42, 10] — value 42, state unchanged
|
|
2928
|
+
* ```
|
|
2929
|
+
*/
|
|
2930
|
+
resolve: <S, A>(value: A) => State$1<S, A>;
|
|
2931
|
+
/**
|
|
2932
|
+
* Produces the current state as the value, without modifying it.
|
|
2933
|
+
*
|
|
2934
|
+
* @example
|
|
2935
|
+
* ```ts
|
|
2936
|
+
* const readStack: State<string[], string[]> = State.get();
|
|
2937
|
+
* State.run(["a", "b"])(readStack); // [["a", "b"], ["a", "b"]]
|
|
2938
|
+
* ```
|
|
2939
|
+
*/
|
|
2940
|
+
get: <S>() => State$1<S, S>;
|
|
2941
|
+
/**
|
|
2942
|
+
* Reads a projection of the state without modifying it.
|
|
2943
|
+
* Equivalent to `pipe(State.get(), State.map(f))` but more direct.
|
|
2944
|
+
*
|
|
2945
|
+
* @example
|
|
2946
|
+
* ```ts
|
|
2947
|
+
* type AppState = { count: number; label: string };
|
|
2948
|
+
* const readCount: State<AppState, number> = State.gets(s => s.count);
|
|
2949
|
+
* State.run({ count: 5, label: "x" })(readCount); // [5, { count: 5, label: "x" }]
|
|
2950
|
+
* ```
|
|
2951
|
+
*/
|
|
2952
|
+
gets: <S, A>(f: (s: S) => A) => State$1<S, A>;
|
|
2953
|
+
/**
|
|
2954
|
+
* Replaces the current state with a new value. Produces no meaningful value.
|
|
2955
|
+
*
|
|
2956
|
+
* @example
|
|
2957
|
+
* ```ts
|
|
2958
|
+
* const reset: State<number, undefined> = State.put(0);
|
|
2959
|
+
* State.run(99)(reset); // [undefined, 0]
|
|
2960
|
+
* ```
|
|
2961
|
+
*/
|
|
2962
|
+
put: <S>(newState: S) => State$1<S, undefined>;
|
|
2963
|
+
/**
|
|
2964
|
+
* Applies a function to the current state to produce the next state.
|
|
2965
|
+
* Produces no meaningful value.
|
|
2966
|
+
*
|
|
2967
|
+
* @example
|
|
2968
|
+
* ```ts
|
|
2969
|
+
* const push = (item: string): State<string[], undefined> =>
|
|
2970
|
+
* State.modify(stack => [...stack, item]);
|
|
2971
|
+
*
|
|
2972
|
+
* State.run(["a"])(push("b")); // [undefined, ["a", "b"]]
|
|
2973
|
+
* ```
|
|
2974
|
+
*/
|
|
2975
|
+
modify: <S>(f: (s: S) => S) => State$1<S, undefined>;
|
|
2976
|
+
/**
|
|
2977
|
+
* Transforms the value produced by a State computation.
|
|
2978
|
+
* The state transformation is unchanged.
|
|
2979
|
+
*
|
|
2980
|
+
* @example
|
|
2981
|
+
* ```ts
|
|
2982
|
+
* const readLength: State<string[], number> = pipe(
|
|
2983
|
+
* State.get<string[]>(),
|
|
2984
|
+
* State.map(stack => stack.length),
|
|
2985
|
+
* );
|
|
2986
|
+
*
|
|
2987
|
+
* State.run(["a", "b", "c"])(readLength); // [3, ["a", "b", "c"]]
|
|
2988
|
+
* ```
|
|
2989
|
+
*/
|
|
2990
|
+
map: <S, A, B>(f: (a: A) => B) => (st: State$1<S, A>) => State$1<S, B>;
|
|
2991
|
+
/**
|
|
2992
|
+
* Sequences two State computations. The state output of the first is passed
|
|
2993
|
+
* as the state input to the second.
|
|
2994
|
+
*
|
|
2995
|
+
* Data-last — the first computation is the data being piped.
|
|
2996
|
+
*
|
|
2997
|
+
* @example
|
|
2998
|
+
* ```ts
|
|
2999
|
+
* const push = (item: string): State<string[], undefined> =>
|
|
3000
|
+
* State.modify(stack => [...stack, item]);
|
|
3001
|
+
*
|
|
3002
|
+
* const program = pipe(
|
|
3003
|
+
* push("a"),
|
|
3004
|
+
* State.chain(() => push("b")),
|
|
3005
|
+
* State.chain(() => State.get<string[]>()),
|
|
3006
|
+
* );
|
|
3007
|
+
*
|
|
3008
|
+
* State.evaluate([])(program); // ["a", "b"]
|
|
3009
|
+
* ```
|
|
3010
|
+
*/
|
|
3011
|
+
chain: <S, A, B>(f: (a: A) => State$1<S, B>) => (st: State$1<S, A>) => State$1<S, B>;
|
|
3012
|
+
/**
|
|
3013
|
+
* Applies a function wrapped in a State to a value wrapped in a State.
|
|
3014
|
+
* The function computation runs first; its output state is the input to the
|
|
3015
|
+
* argument computation.
|
|
3016
|
+
*
|
|
3017
|
+
* @example
|
|
3018
|
+
* ```ts
|
|
3019
|
+
* const addCounted = (n: number) => (m: number) => n + m;
|
|
3020
|
+
* const program = pipe(
|
|
3021
|
+
* State.resolve<number, typeof addCounted>(addCounted),
|
|
3022
|
+
* State.ap(State.gets((s: number) => s * 2)),
|
|
3023
|
+
* State.ap(State.gets((s: number) => s)),
|
|
3024
|
+
* );
|
|
3025
|
+
*
|
|
3026
|
+
* State.evaluate(3)(program); // 6 + 3 = 9
|
|
3027
|
+
* ```
|
|
3028
|
+
*/
|
|
3029
|
+
ap: <S, A>(arg: State$1<S, A>) => <B>(fn: State$1<S, (a: A) => B>) => State$1<S, B>;
|
|
3030
|
+
/**
|
|
3031
|
+
* Runs a side effect on the produced value without changing the State computation.
|
|
3032
|
+
*
|
|
3033
|
+
* @example
|
|
3034
|
+
* ```ts
|
|
3035
|
+
* pipe(
|
|
3036
|
+
* State.get<number>(),
|
|
3037
|
+
* State.tap(n => console.log("current:", n)),
|
|
3038
|
+
* State.chain(() => State.modify(n => n + 1)),
|
|
3039
|
+
* );
|
|
3040
|
+
* ```
|
|
3041
|
+
*/
|
|
3042
|
+
tap: <S, A>(f: (a: A) => void) => (st: State$1<S, A>) => State$1<S, A>;
|
|
3043
|
+
/**
|
|
3044
|
+
* Runs a State computation with an initial state, returning both the
|
|
3045
|
+
* produced value and the final state as a pair.
|
|
3046
|
+
*
|
|
3047
|
+
* Data-last — the computation is the data being piped.
|
|
3048
|
+
*
|
|
3049
|
+
* @example
|
|
3050
|
+
* ```ts
|
|
3051
|
+
* const program = pipe(
|
|
3052
|
+
* State.modify<number>(n => n + 1),
|
|
3053
|
+
* State.chain(() => State.get<number>()),
|
|
3054
|
+
* );
|
|
3055
|
+
*
|
|
3056
|
+
* State.run(0)(program); // [1, 1]
|
|
3057
|
+
* ```
|
|
3058
|
+
*/
|
|
3059
|
+
run: <S>(initialState: S) => <A>(st: State$1<S, A>) => readonly [A, S];
|
|
3060
|
+
/**
|
|
3061
|
+
* Runs a State computation with an initial state, returning only the
|
|
3062
|
+
* produced value (discarding the final state).
|
|
3063
|
+
*
|
|
3064
|
+
* @example
|
|
3065
|
+
* ```ts
|
|
3066
|
+
* State.evaluate([])(pipe(
|
|
3067
|
+
* State.modify<string[]>(s => [...s, "x"]),
|
|
3068
|
+
* State.chain(() => State.get<string[]>()),
|
|
3069
|
+
* )); // ["x"]
|
|
3070
|
+
* ```
|
|
3071
|
+
*/
|
|
3072
|
+
evaluate: <S>(initialState: S) => <A>(st: State$1<S, A>) => A;
|
|
3073
|
+
/**
|
|
3074
|
+
* Runs a State computation with an initial state, returning only the
|
|
3075
|
+
* final state (discarding the produced value).
|
|
3076
|
+
*
|
|
3077
|
+
* @example
|
|
3078
|
+
* ```ts
|
|
3079
|
+
* State.execute(0)(pipe(
|
|
3080
|
+
* State.modify<number>(n => n + 10),
|
|
3081
|
+
* State.chain(() => State.modify<number>(n => n * 2)),
|
|
3082
|
+
* )); // 20
|
|
3083
|
+
* ```
|
|
3084
|
+
*/
|
|
3085
|
+
execute: <S>(initialState: S) => <A>(st: State$1<S, A>) => S;
|
|
3086
|
+
/**
|
|
3087
|
+
* Lifts a State value into an accumulator object.
|
|
3088
|
+
*
|
|
3089
|
+
* @example
|
|
3090
|
+
* ```ts
|
|
3091
|
+
* pipe(State.resolve(42), State.bindTo("value")); // State({ value: 42 })
|
|
3092
|
+
* ```
|
|
3093
|
+
*/
|
|
3094
|
+
bindTo: <K extends string>(key: K) => <S, A>(data: State$1<S, A>) => State$1<S, { [P in K]: A; }>;
|
|
3095
|
+
/**
|
|
3096
|
+
* Evaluates a new State using the current accumulator and attaches the output to a new key.
|
|
3097
|
+
*
|
|
3098
|
+
* @example
|
|
3099
|
+
* ```ts
|
|
3100
|
+
* pipe(
|
|
3101
|
+
* State.resolve({ a: 1 }),
|
|
3102
|
+
* State.bind("b", ({ a }) => State.resolve(a + 1))
|
|
3103
|
+
* ); // State({ a: 1, b: 2 })
|
|
3104
|
+
* ```
|
|
3105
|
+
*/
|
|
3106
|
+
bind: <K extends string, S, A, B>(key: K, f: (a: A) => State$1<S, B>) => (data: State$1<S, A>) => State$1<S, A & { [P in K]: B; }>;
|
|
3107
|
+
/**
|
|
3108
|
+
* Focuses a State computation on a sub-state using a Lens.
|
|
3109
|
+
*
|
|
3110
|
+
* @example
|
|
3111
|
+
* ```ts
|
|
3112
|
+
* type AppState = { count: number; name: string };
|
|
3113
|
+
* const countLens = Lens.from.property<AppState>()("count");
|
|
3114
|
+
* const increment = State.modify((c: number) => c + 1);
|
|
3115
|
+
* const focusedProgram = pipe(increment, State.focus(countLens));
|
|
3116
|
+
* ```
|
|
3117
|
+
*/
|
|
3118
|
+
focus: <S, A>(lens: Lens<S, A>) => <B>(stateOp: State$1<A, B>) => State$1<S, B>;
|
|
3119
|
+
};
|
|
3120
|
+
//#endregion
|
|
3121
|
+
//#region src/Core/Stream.d.ts
|
|
3122
|
+
/**
|
|
3123
|
+
* An event stream pipeline for a typed message schema `S`.
|
|
3124
|
+
*
|
|
3125
|
+
* `Stream` provides typed event emission, sequence matching, state reduction,
|
|
3126
|
+
* and structural stream forwarding.
|
|
3127
|
+
*
|
|
3128
|
+
* @example
|
|
3129
|
+
* ```ts
|
|
3130
|
+
* type AppMessages = {
|
|
3131
|
+
* userLoggedIn: { userId: string };
|
|
3132
|
+
* checkoutStarted: { amount: number };
|
|
3133
|
+
* };
|
|
3134
|
+
*
|
|
3135
|
+
* const appStream = Stream.make<AppMessages>();
|
|
3136
|
+
*
|
|
3137
|
+
* const subscription = Stream.listen(
|
|
3138
|
+
* appStream,
|
|
3139
|
+
* ["userLoggedIn", "checkoutStarted"],
|
|
3140
|
+
* { ordered: true }
|
|
3141
|
+
* ).reduce(
|
|
3142
|
+
* (msg, state) => {
|
|
3143
|
+
* if (msg.kind === "checkoutStarted") {
|
|
3144
|
+
* return { count: state.count + 1 };
|
|
3145
|
+
* }
|
|
3146
|
+
* return state;
|
|
3147
|
+
* },
|
|
3148
|
+
* { count: 0 }
|
|
3149
|
+
* );
|
|
3150
|
+
*
|
|
3151
|
+
* Stream.emit(appStream, {
|
|
3152
|
+
* kind: "userLoggedIn",
|
|
3153
|
+
* value: { userId: "user-1" },
|
|
3154
|
+
* });
|
|
3155
|
+
* ```
|
|
3156
|
+
*/
|
|
3157
|
+
type Stream<S extends Record<string, unknown>> = {
|
|
3158
|
+
readonly options?: Stream.Options;
|
|
3159
|
+
/** @internal */
|
|
3160
|
+
readonly _listeners: Set<(msg: Stream.Message<S>) => void>;
|
|
3161
|
+
/**
|
|
3162
|
+
* @internal
|
|
3163
|
+
* Lazy array snapshot of `_listeners`. Avoids allocating new array objects on every `emit` call
|
|
3164
|
+
* (2.98x emission speedup, 0 heap allocations). Rebuilt whenever `_listeners` is mutated,
|
|
3165
|
+
* guaranteeing reentrancy safety and preventing listeners subscribed mid-emission from executing early.
|
|
3166
|
+
*/
|
|
3167
|
+
_listenerArray: Array<(msg: Stream.Message<S>) => void> | null;
|
|
3168
|
+
/** @internal */
|
|
3169
|
+
readonly _queue: Array<Stream.Message<S>>;
|
|
3170
|
+
/** @internal */
|
|
3171
|
+
_isEmitting: boolean;
|
|
3172
|
+
};
|
|
3173
|
+
declare const Stream: {
|
|
3174
|
+
/**
|
|
3175
|
+
* Constructs a new `Stream` instance.
|
|
3176
|
+
*
|
|
3177
|
+
* @example
|
|
3178
|
+
* ```ts
|
|
3179
|
+
* const stream = Stream.make<AppMessages>({ name: "app" });
|
|
3180
|
+
* ```
|
|
3181
|
+
*/
|
|
3182
|
+
make: <S extends Record<string, unknown>>(options?: Stream.Options) => Stream<S>;
|
|
3183
|
+
/**
|
|
3184
|
+
* Emits a message payload to one or more target streams.
|
|
3185
|
+
*
|
|
3186
|
+
* Uses a synchronous breadth-first trampoline queue to handle re-entrant emissions deterministically.
|
|
3187
|
+
*
|
|
3188
|
+
* @example
|
|
3189
|
+
* ```ts
|
|
3190
|
+
* Stream.emit(streamA, {
|
|
3191
|
+
* kind: "userLoggedIn",
|
|
3192
|
+
* value: { userId: "user-1" },
|
|
3193
|
+
* });
|
|
3194
|
+
*
|
|
3195
|
+
* Stream.emit([streamA, streamB], {
|
|
3196
|
+
* kind: "userLoggedIn",
|
|
3197
|
+
* value: { userId: "user-1" },
|
|
3198
|
+
* });
|
|
3199
|
+
* ```
|
|
3200
|
+
*/
|
|
3201
|
+
emit: <S extends Record<string, unknown>, K extends keyof S & string>(target: Stream<S> | ReadonlyArray<Stream<S>>, message: WithKind<K> & WithValue<S[K]>) => void;
|
|
3202
|
+
/**
|
|
3203
|
+
* Forwards messages from one stream to another (or multiple).
|
|
3204
|
+
*
|
|
3205
|
+
* @example
|
|
3206
|
+
* ```ts
|
|
3207
|
+
* const stop = Stream.forward({
|
|
3208
|
+
* from: authStream,
|
|
3209
|
+
* to: analyticsStream,
|
|
3210
|
+
* only: ["userLoggedIn"],
|
|
3211
|
+
* });
|
|
3212
|
+
* ```
|
|
3213
|
+
*/
|
|
3214
|
+
forward: <S extends Record<string, unknown>>(options: Stream.ForwardOptions<S>) => () => void;
|
|
3215
|
+
/**
|
|
3216
|
+
* Initiates listener registration on a stream for specific event kind(s) or sequence.
|
|
3217
|
+
*
|
|
3218
|
+
* @example
|
|
3219
|
+
* ```ts
|
|
3220
|
+
* const sub = Stream.listen(
|
|
3221
|
+
* appStream,
|
|
3222
|
+
* ["userLoggedIn", "checkoutStarted"],
|
|
3223
|
+
* { ordered: true }
|
|
3224
|
+
* ).reduce(
|
|
3225
|
+
* (msg, state) => ({ count: state.count + 1 }),
|
|
3226
|
+
* { count: 0 }
|
|
3227
|
+
* );
|
|
3228
|
+
* ```
|
|
3229
|
+
*/
|
|
3230
|
+
listen: <S extends Record<string, unknown>, K extends keyof S & string>(stream: Stream<S>, events: K | ReadonlyArray<K>, options?: Stream.SequenceOptions<S>) => Stream.ListenerBuilder<S>;
|
|
3231
|
+
};
|
|
3232
|
+
declare namespace Stream {
|
|
3233
|
+
type Message<S extends Record<string, unknown>> = { [K in keyof S & string]: WithKind<K> & WithValue<S[K]>; }[keyof S & string];
|
|
3234
|
+
type Options = {
|
|
3235
|
+
readonly name?: string;
|
|
3236
|
+
readonly onError?: (error: unknown) => void;
|
|
3237
|
+
};
|
|
3238
|
+
type SequenceOptions<S extends Record<string, unknown>> = {
|
|
3239
|
+
readonly ordered?: boolean;
|
|
3240
|
+
readonly strict?: boolean;
|
|
3241
|
+
readonly once?: boolean;
|
|
3242
|
+
readonly reset?: (keyof S & string) | ReadonlyArray<keyof S & string>;
|
|
3243
|
+
readonly optional?: (keyof S & string) | ReadonlyArray<keyof S & string>;
|
|
3244
|
+
};
|
|
3245
|
+
type Subscription<State> = {
|
|
3246
|
+
readonly unsubscribe: () => void;
|
|
3247
|
+
readonly getState: () => State;
|
|
3248
|
+
};
|
|
3249
|
+
type ForwardOptions<S extends Record<string, unknown>> = {
|
|
3250
|
+
readonly from: Stream<S>;
|
|
3251
|
+
readonly to: Stream<S> | ReadonlyArray<Stream<S>>;
|
|
3252
|
+
readonly only?: ReadonlyArray<keyof S & string>;
|
|
3253
|
+
};
|
|
3254
|
+
type ListenerBuilder<S extends Record<string, unknown>> = {
|
|
3255
|
+
readonly reduce: <State>(reducer: (msg: Message<S>, state: State) => State, initialState: State) => Subscription<State>;
|
|
3256
|
+
readonly tap: (effect: (msg: Message<S>) => void) => () => void;
|
|
3257
|
+
};
|
|
3258
|
+
}
|
|
3259
|
+
//#endregion
|
|
3260
|
+
//#region src/Core/Validation.d.ts
|
|
3261
|
+
/**
|
|
3262
|
+
* Validation represents a value that is either passed with a success value,
|
|
3263
|
+
* or failed with accumulated errors.
|
|
3264
|
+
* Unlike Result, Validation can accumulate multiple errors instead of short-circuiting.
|
|
3265
|
+
*
|
|
3266
|
+
* Use Validation when you need to collect all errors (e.g., form validation).
|
|
3267
|
+
* Use Result when you want to fail fast on the first error.
|
|
3268
|
+
*
|
|
3269
|
+
* @example
|
|
3270
|
+
* ```ts
|
|
3271
|
+
* const validateName = (name: string): Validation<string, string> =>
|
|
3272
|
+
* name.length > 0 ? Validation.make.passed(name) : Validation.make.failed("Name is required");
|
|
3273
|
+
*
|
|
3274
|
+
* const validateAge = (age: number): Validation<string, number> =>
|
|
3275
|
+
* age >= 0 ? Validation.make.passed(age) : Validation.make.failed("Age must be positive");
|
|
3276
|
+
*
|
|
3277
|
+
* // Accumulates all errors using ap
|
|
3278
|
+
* pipe(
|
|
3279
|
+
* Validation.make.passed((name: string) => (age: number) => ({ name, age })),
|
|
3280
|
+
* Validation.ap(validateName("")),
|
|
3281
|
+
* Validation.ap(validateAge(-1))
|
|
3282
|
+
* );
|
|
3283
|
+
* // Failed(["Name is required", "Age must be positive"])
|
|
3284
|
+
* ```
|
|
3285
|
+
*/
|
|
3286
|
+
type Validation<E, A> = Passed<A> | Failed<E>;
|
|
3287
|
+
type Passed<A> = WithKind<"Passed"> & WithValue<A>;
|
|
3288
|
+
type Failed<E> = WithKind<"Failed"> & WithErrors<E>;
|
|
3289
|
+
declare function toResult<E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2): (val: Validation<E1, A>) => Result<E2, A>;
|
|
3290
|
+
declare function toResult<E, A>(data: Validation<E, A>): Result<NonEmptyArr<E>, A>;
|
|
3291
|
+
declare const Validation: {
|
|
3292
|
+
make: {
|
|
3293
|
+
/**
|
|
3294
|
+
* Wraps a value in a passed Validation.
|
|
3295
|
+
*
|
|
3296
|
+
* @example
|
|
3297
|
+
* ```ts
|
|
3298
|
+
* Validation.make.passed(42); // Passed(42)
|
|
3299
|
+
* ```
|
|
3300
|
+
*/
|
|
3301
|
+
passed: <E, A>(value: A) => Validation<E, A>;
|
|
3302
|
+
/**
|
|
3303
|
+
* Creates a failed Validation from a single error.
|
|
3304
|
+
*
|
|
3305
|
+
* @example
|
|
3306
|
+
* ```ts
|
|
3307
|
+
* Validation.make.failed("Invalid input");
|
|
3308
|
+
* ```
|
|
3309
|
+
*/
|
|
3310
|
+
failed: <E>(error: E) => Failed<E>;
|
|
3311
|
+
/**
|
|
3312
|
+
* Creates a failed Validation from multiple errors.
|
|
3313
|
+
*
|
|
3314
|
+
* @example
|
|
3315
|
+
* ```ts
|
|
3316
|
+
* Validation.make.failedAll(["Invalid input"]);
|
|
3317
|
+
* ```
|
|
3318
|
+
*/
|
|
3319
|
+
failedAll: <E>(errors: NonEmptyArr<E>) => Failed<E>;
|
|
3320
|
+
};
|
|
3321
|
+
is: {
|
|
3322
|
+
/**
|
|
3323
|
+
* Type guard that checks if a Validation is passed.
|
|
3324
|
+
*
|
|
3325
|
+
* @example
|
|
3326
|
+
* ```ts
|
|
3327
|
+
* const v = Validation.make.passed(42);
|
|
3328
|
+
* if (Validation.is.passed(v)) {
|
|
3329
|
+
* console.log(v.value); // 42
|
|
3330
|
+
* }
|
|
3331
|
+
* ```
|
|
3332
|
+
*/
|
|
3333
|
+
passed: <E, A>(data: Validation<E, A>) => data is Passed<A>;
|
|
3334
|
+
/**
|
|
3335
|
+
* Type guard that checks if a Validation is failed.
|
|
3336
|
+
*
|
|
3337
|
+
* @example
|
|
3338
|
+
* ```ts
|
|
3339
|
+
* const v = Validation.make.failed("invalid");
|
|
3340
|
+
* if (Validation.is.failed(v)) {
|
|
3341
|
+
* console.log(v.errors); // ["invalid"]
|
|
3342
|
+
* }
|
|
3343
|
+
* ```
|
|
3344
|
+
*/
|
|
3345
|
+
failed: <E, A>(data: Validation<E, A>) => data is Failed<E>;
|
|
3346
|
+
};
|
|
3347
|
+
/**
|
|
3348
|
+
* Creates a Validation from a synchronous thunk that may throw.
|
|
3349
|
+
* Catches any errors and transforms them using the `onError` function into a Failed validation.
|
|
3350
|
+
*
|
|
3351
|
+
* @example
|
|
3352
|
+
* ```ts
|
|
3353
|
+
* const result = Validation.tryCatch(
|
|
3354
|
+
* () => JSON.parse(rawString),
|
|
3355
|
+
* { onError: (e) => `Parse error: ${e}` }
|
|
3356
|
+
* );
|
|
3357
|
+
* ```
|
|
3358
|
+
*/
|
|
3359
|
+
tryCatch: <E, A>(f: () => A, options: {
|
|
3360
|
+
onError: (e: unknown) => E;
|
|
3361
|
+
}) => Validation<E, A>;
|
|
3362
|
+
from: {
|
|
3363
|
+
/**
|
|
3364
|
+
* Creates a Validation from a predicate applied to a value.
|
|
3365
|
+
* Returns Passed if the predicate passes, Failed from `onFalse` otherwise.
|
|
3366
|
+
*
|
|
3367
|
+
* @example
|
|
3368
|
+
* ```ts
|
|
3369
|
+
* const validateName = Validation.from.Predicate(
|
|
3370
|
+
* (s: string) => s.length > 0,
|
|
3371
|
+
* () => "Name is required"
|
|
3372
|
+
* );
|
|
3373
|
+
*
|
|
3374
|
+
* validateName("Alice"); // Passed("Alice")
|
|
3375
|
+
* validateName(""); // Failed(["Name is required"])
|
|
3376
|
+
* ```
|
|
3377
|
+
*/
|
|
3378
|
+
Predicate: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (a: A) => Validation<E, A>;
|
|
3379
|
+
/**
|
|
3380
|
+
* Creates a Validation from a nullable value.
|
|
3381
|
+
* If the value is null or undefined, returns Failed with the error from onNull.
|
|
3382
|
+
* Otherwise, returns Passed.
|
|
3383
|
+
*
|
|
3384
|
+
* @example
|
|
3385
|
+
* ```ts
|
|
3386
|
+
* pipe(null, Validation.from.nullable(() => "is null")); // Failed(["is null"])
|
|
3387
|
+
* pipe(42, Validation.from.nullable(() => "is null")); // Passed(42)
|
|
3388
|
+
* ```
|
|
3389
|
+
*/
|
|
3390
|
+
nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Validation<E, A>;
|
|
3391
|
+
/**
|
|
3392
|
+
* Creates a Validation from a Maybe.
|
|
3393
|
+
* If the Maybe is None, returns Failed with the error from onNone.
|
|
3394
|
+
* Otherwise, returns Passed.
|
|
3395
|
+
*
|
|
3396
|
+
* @example
|
|
3397
|
+
* ```ts
|
|
3398
|
+
* pipe(Maybe.make.none(), Validation.from.Maybe(() => "is none")); // Failed(["is none"])
|
|
3399
|
+
* pipe(Maybe.make.some(42), Validation.from.Maybe(() => "is none")); // Passed(42)
|
|
3400
|
+
* ```
|
|
3401
|
+
*/
|
|
3402
|
+
Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Validation<E, A>;
|
|
3403
|
+
/**
|
|
3404
|
+
* Converts a `Result` to a `Validation`. `Ok` becomes `Passed`; `Err(e)` becomes `Failed([e])`.
|
|
3405
|
+
*
|
|
3406
|
+
* Useful when bridging from error-short-circuiting `Result` pipelines into
|
|
3407
|
+
* error-accumulating `Validation` pipelines.
|
|
3408
|
+
*
|
|
3409
|
+
* @example
|
|
3410
|
+
* ```ts
|
|
3411
|
+
* Validation.from.Result(Result.make.ok(42)); // Passed(42)
|
|
3412
|
+
* Validation.from.Result(Result.make.err("bad")); // Failed(["bad"])
|
|
3413
|
+
* ```
|
|
3414
|
+
*/
|
|
3415
|
+
Result: <E, A>(data: Result<E, A>) => Validation<E, A>;
|
|
3416
|
+
};
|
|
3417
|
+
/**
|
|
3418
|
+
* Transforms the success value inside a Validation.
|
|
3419
|
+
*
|
|
3420
|
+
* @example
|
|
3421
|
+
* ```ts
|
|
3422
|
+
* pipe(Validation.make.passed(5), Validation.map(n => n * 2)); // Passed(10)
|
|
3423
|
+
* pipe(Validation.make.failed("oops"), Validation.map(n => n * 2)); // Failed(["oops"])
|
|
3424
|
+
* ```
|
|
3425
|
+
*/
|
|
3426
|
+
map: <A, B>(f: (a: A) => B) => <E>(data: Validation<E, A>) => Validation<E, B>;
|
|
3427
|
+
/**
|
|
3428
|
+
* Transforms the error list inside a Validation.
|
|
3429
|
+
*
|
|
3430
|
+
* @example
|
|
3431
|
+
* ```ts
|
|
3432
|
+
* pipe(Validation.make.failed("oops"), Validation.mapError(e => e.toUpperCase())); // Failed(["OOPS"])
|
|
3433
|
+
* ```
|
|
3434
|
+
*/
|
|
3435
|
+
mapError: <E, F, A>(f: (e: E) => F) => (data: Validation<E, A>) => Validation<F, A>;
|
|
3436
|
+
/**
|
|
3437
|
+
* Applies a function wrapped in a Validation to a value wrapped in a Validation.
|
|
3438
|
+
* Accumulates errors from both sides.
|
|
3439
|
+
*
|
|
3440
|
+
* @example
|
|
3441
|
+
* ```ts
|
|
3442
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
3443
|
+
* pipe(
|
|
3444
|
+
* Validation.make.passed(add),
|
|
3445
|
+
* Validation.ap(Validation.make.passed(5)),
|
|
3446
|
+
* Validation.ap(Validation.make.passed(3))
|
|
3447
|
+
* ); // Passed(8)
|
|
3448
|
+
*
|
|
3449
|
+
* pipe(
|
|
3450
|
+
* Validation.make.passed(add),
|
|
3451
|
+
* Validation.ap(Validation.make.failed<string>("bad a")),
|
|
3452
|
+
* Validation.ap(Validation.make.failed<string>("bad b"))
|
|
3453
|
+
* ); // Failed(["bad a", "bad b"])
|
|
3454
|
+
* ```
|
|
3455
|
+
*/
|
|
3456
|
+
ap: <E, A>(arg: Validation<E, A>) => <B>(data: Validation<E, (a: A) => B>) => Validation<E, B>;
|
|
3457
|
+
/**
|
|
3458
|
+
* Applies a function wrapped in a Validation to a value wrapped in a Validation,
|
|
3459
|
+
* using a custom error concatenator function when both sides fail.
|
|
3460
|
+
*
|
|
3461
|
+
* @example
|
|
3462
|
+
* ```ts
|
|
3463
|
+
* const concat = (e1: NonEmptyArr<string>, e2: NonEmptyArr<string>): NonEmptyArr<string> =>
|
|
3464
|
+
* [...e1, ...e2];
|
|
3465
|
+
* pipe(fnVal, Validation.apCustom(concat)(argVal));
|
|
3466
|
+
* ```
|
|
3467
|
+
*/
|
|
3468
|
+
apCustom: <E1, E2, E3>(concat: (e1: NonEmptyArr<E1>, e2: NonEmptyArr<E2>) => NonEmptyArr<E3>) => <A>(arg: Validation<E2, A>) => <B>(data: Validation<E1, (a: A) => B>) => Validation<E3, B>;
|
|
3469
|
+
/**
|
|
3470
|
+
* Extracts the value from a Validation by providing handlers for both cases.
|
|
3471
|
+
*
|
|
3472
|
+
* @example
|
|
3473
|
+
* ```ts
|
|
3474
|
+
* pipe(
|
|
3475
|
+
* Validation.make.passed(42),
|
|
3476
|
+
* Validation.fold(
|
|
3477
|
+
* errors => `Errors: ${errors.join(", ")}`,
|
|
3478
|
+
* value => `Value: ${value}`
|
|
3479
|
+
* )
|
|
3480
|
+
* );
|
|
3481
|
+
* ```
|
|
3482
|
+
*/
|
|
3483
|
+
fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: Validation<E, A>) => B;
|
|
3484
|
+
/**
|
|
3485
|
+
* Pattern matches on a Validation, returning the result of the matching case.
|
|
3486
|
+
*
|
|
3487
|
+
* @example
|
|
3488
|
+
* ```ts
|
|
3489
|
+
* pipe(
|
|
3490
|
+
* validation,
|
|
3491
|
+
* Validation.match({
|
|
3492
|
+
* passed: value => `Got ${value}`,
|
|
3493
|
+
* failed: errors => `Failed: ${errors.join(", ")}`
|
|
3494
|
+
* })
|
|
3495
|
+
* );
|
|
3496
|
+
* ```
|
|
3497
|
+
*/
|
|
3498
|
+
match: <E, A, B>(cases: {
|
|
3499
|
+
passed: (a: A) => B;
|
|
3500
|
+
failed: (errors: NonEmptyArr<E>) => B;
|
|
3501
|
+
}) => (data: Validation<E, A>) => B;
|
|
3502
|
+
/**
|
|
3503
|
+
* Returns the success value or a default value if the Validation is failed.
|
|
3504
|
+
* The default can be a different type, widening the result to `A | B`.
|
|
3505
|
+
*
|
|
3506
|
+
* @example
|
|
3507
|
+
* ```ts
|
|
3508
|
+
* pipe(Validation.make.passed(5), Validation.getOrElse(() => 0)); // 5
|
|
3509
|
+
* pipe(Validation.make.failed("oops"), Validation.getOrElse(() => 0)); // 0
|
|
3510
|
+
* pipe(Validation.make.failed("oops"), Validation.getOrElse(() => null)); // null — typed as number | null
|
|
3511
|
+
* ```
|
|
3512
|
+
*/
|
|
3513
|
+
getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Validation<E, A>) => A | B;
|
|
3514
|
+
/**
|
|
3515
|
+
* Executes a side effect on the success value without changing the Validation.
|
|
3516
|
+
*
|
|
3517
|
+
* @example
|
|
3518
|
+
* ```ts
|
|
3519
|
+
* pipe(
|
|
3520
|
+
* Validation.make.passed(5),
|
|
3521
|
+
* Validation.tap(n => console.log("Value:", n)),
|
|
3522
|
+
* Validation.map(n => n * 2)
|
|
3523
|
+
* );
|
|
3524
|
+
* ```
|
|
3525
|
+
*/
|
|
3526
|
+
tap: <E, A>(f: (a: A) => void) => (data: Validation<E, A>) => Validation<E, A>;
|
|
3527
|
+
/**
|
|
3528
|
+
* Executes a side effect on the accumulated errors without changing the Validation.
|
|
3529
|
+
* Useful for logging or reporting validation failures.
|
|
3530
|
+
*
|
|
3531
|
+
* @example
|
|
3532
|
+
* ```ts
|
|
3533
|
+
* pipe(
|
|
3534
|
+
* Validation.make.failed("Name required"),
|
|
3535
|
+
* Validation.tapError(errors => console.error("validation failed:", errors)),
|
|
3536
|
+
* Validation.map(toUser)
|
|
3537
|
+
* );
|
|
3538
|
+
* ```
|
|
3539
|
+
*/
|
|
3540
|
+
tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: Validation<E, A>) => Validation<E, A>;
|
|
3541
|
+
/**
|
|
3542
|
+
* Recovers from a Failed state by providing a fallback Validation.
|
|
3543
|
+
* The fallback receives the accumulated error list so callers can inspect which errors occurred.
|
|
3544
|
+
* The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
|
|
3545
|
+
*/
|
|
3546
|
+
recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
|
|
3547
|
+
/**
|
|
3548
|
+
* Recovers from a Failed state unless `isBlocked` returns true for any of the accumulated errors.
|
|
3549
|
+
* The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
|
|
3550
|
+
*
|
|
3551
|
+
* @example
|
|
3552
|
+
* ```ts
|
|
3553
|
+
* pipe(
|
|
3554
|
+
* Validation.make.failed("field-error"),
|
|
3555
|
+
* Validation.recoverUnless(e => e === "fatal", () => Validation.make.passed(0))
|
|
3556
|
+
* ); // Passed(0)
|
|
3557
|
+
* ```
|
|
3558
|
+
*/
|
|
3559
|
+
recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: () => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
|
|
3560
|
+
to: {
|
|
3561
|
+
/**
|
|
3562
|
+
* Converts a Validation to a Result.
|
|
3563
|
+
* Passed becomes Ok.
|
|
3564
|
+
* Direct call converts Failed to Err with accumulated error list `NonEmptyArr<E>`.
|
|
3565
|
+
* Curried call converts Failed to Err with combined error `E2` via `combineErrors`.
|
|
3566
|
+
*
|
|
3567
|
+
* @example
|
|
3568
|
+
* ```ts
|
|
3569
|
+
* Validation.to.Result(Validation.make.passed(42)); // Ok(42)
|
|
3570
|
+
* Validation.to.Result(Validation.make.failed("oops")); // Err(["oops"])
|
|
3571
|
+
* pipe(Validation.make.failed("oops"), Validation.to.Result(errors => errors.join(", "))); // Err("oops")
|
|
3572
|
+
* ```
|
|
3573
|
+
*/
|
|
3574
|
+
Result: typeof toResult;
|
|
3575
|
+
/**
|
|
3576
|
+
* Converts a Validation to a Maybe. `Passed` becomes `Some`; `Failed` becomes `None`
|
|
3577
|
+
* (errors are discarded).
|
|
3578
|
+
*
|
|
3579
|
+
* @example
|
|
3580
|
+
* ```ts
|
|
3581
|
+
* Validation.to.Maybe(Validation.make.passed(42)); // Some(42)
|
|
3582
|
+
* Validation.to.Maybe(Validation.make.failed("bad")); // None
|
|
3583
|
+
* ```
|
|
3584
|
+
*/
|
|
3585
|
+
Maybe: <E, A>(data: Validation<E, A>) => Maybe<A>;
|
|
3586
|
+
};
|
|
3587
|
+
/**
|
|
3588
|
+
* Combines two independent Validation instances into a tuple.
|
|
3589
|
+
* If both are Passed, returns Passed with both values as a tuple.
|
|
3590
|
+
* If either is Failed, accumulates errors from both sides.
|
|
3591
|
+
*
|
|
3592
|
+
* @example
|
|
3593
|
+
* ```ts
|
|
3594
|
+
* Validation.product(
|
|
3595
|
+
* Validation.make.passed("alice"),
|
|
3596
|
+
* Validation.make.passed(30)
|
|
3597
|
+
* ); // Passed(["alice", 30])
|
|
3598
|
+
*
|
|
3599
|
+
* Validation.product(
|
|
3600
|
+
* Validation.make.failed("Name required"),
|
|
3601
|
+
* Validation.make.failed("Age must be >= 0")
|
|
3602
|
+
* ); // Failed(["Name required", "Age must be >= 0"])
|
|
3603
|
+
* ```
|
|
3604
|
+
*/
|
|
3605
|
+
product: <E, A, B>(first: Validation<E, A>, second: Validation<E, B>) => Validation<E, readonly [A, B]>;
|
|
3606
|
+
/**
|
|
3607
|
+
* Combines a non-empty list of Validation instances, accumulating all errors.
|
|
3608
|
+
* If all are Passed, returns Passed with all values collected into an array.
|
|
3609
|
+
* If any are Failed, returns Failed with all accumulated errors.
|
|
3610
|
+
*
|
|
3611
|
+
* @example
|
|
3612
|
+
* ```ts
|
|
3613
|
+
* Validation.productAll([
|
|
3614
|
+
* validateName(name),
|
|
3615
|
+
* validateEmail(email),
|
|
3616
|
+
* validateAge(age)
|
|
3617
|
+
* ]);
|
|
3618
|
+
* // Passed([name, email, age]) or Failed([...all errors])
|
|
3619
|
+
* ```
|
|
3620
|
+
*/
|
|
3621
|
+
productAll: <E, A>(data: NonEmptyArr<Validation<E, A>>) => Validation<E, readonly A[]>;
|
|
3622
|
+
/**
|
|
3623
|
+
* Combines a record of Validations into a single Validation of a record.
|
|
3624
|
+
* Accumulates all failed branches' errors.
|
|
3625
|
+
*
|
|
3626
|
+
* @example
|
|
3627
|
+
* ```ts
|
|
3628
|
+
* Validation.struct({
|
|
3629
|
+
* name: Validation.make.passed("Alice"),
|
|
3630
|
+
* age: Validation.make.passed(30)
|
|
3631
|
+
* }); // Passed({ name: "Alice", age: 30 })
|
|
3632
|
+
*
|
|
3633
|
+
* Validation.struct({
|
|
3634
|
+
* name: Validation.make.failed("Name required"),
|
|
3635
|
+
* age: Validation.make.failed("Age must be >= 0")
|
|
3636
|
+
* }); // Failed(["Name required", "Age must be >= 0"])
|
|
3637
|
+
* ```
|
|
3638
|
+
*/
|
|
3639
|
+
struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Validation<E, R[K]>; }) => Validation<E, R>;
|
|
3640
|
+
};
|
|
3641
|
+
//#endregion
|
|
3642
|
+
//#region src/Core/Task.d.ts
|
|
3643
|
+
/**
|
|
3644
|
+
* A lazy async computation that always resolves.
|
|
3645
|
+
*
|
|
3646
|
+
* Two guarantees:
|
|
3647
|
+
* - **Lazy** — nothing starts until you call it.
|
|
3648
|
+
* - **Infallible** — it never rejects. If failure is possible, encode it in the
|
|
3649
|
+
* return type using `Task.Result<E, A>` instead.
|
|
3650
|
+
*
|
|
3651
|
+
* An optional `AbortSignal` can be passed at the call site. Combinators like
|
|
3652
|
+
* `retry`, `pollUntil`, and `timeout` thread it automatically to every inner
|
|
3653
|
+
* operation. Existing tasks that ignore the signal continue to work unchanged.
|
|
3654
|
+
*
|
|
3655
|
+
* Calling a Task returns a `Deferred<A>` — a one-shot async value that supports
|
|
3656
|
+
* `await` but has no `.catch()`, `.finally()`, or chainable `.then()`.
|
|
3657
|
+
*
|
|
3658
|
+
* **Consuming a Task:**
|
|
3659
|
+
*
|
|
3660
|
+
* Use `await task()` to run it and get the value directly:
|
|
3661
|
+
* ```ts
|
|
3662
|
+
* const value: number = await task();
|
|
3663
|
+
* ```
|
|
3664
|
+
*
|
|
3665
|
+
* When you need an explicit `Promise<A>` (e.g. for a third-party API), convert
|
|
3666
|
+
* the `Deferred` with `Deferred.to.Promise`:
|
|
3667
|
+
* ```ts
|
|
3668
|
+
* const p: Promise<number> = Deferred.to.Promise(task());
|
|
3669
|
+
* ```
|
|
3670
|
+
*
|
|
3671
|
+
* @example
|
|
3672
|
+
* ```ts
|
|
3673
|
+
* const getTimestamp: Task<number> = Task.resolve(Date.now());
|
|
3674
|
+
*
|
|
3675
|
+
* // Nothing runs yet — getTimestamp is just a description
|
|
3676
|
+
* const formatted = pipe(
|
|
3677
|
+
* getTimestamp,
|
|
3678
|
+
* Task.map(ts => new Date(ts).toISOString())
|
|
3679
|
+
* );
|
|
3680
|
+
*
|
|
3681
|
+
* // Execute when ready
|
|
3682
|
+
* const result = await formatted();
|
|
3683
|
+
* ```
|
|
3684
|
+
*/
|
|
3685
|
+
type Task<A> = (signal?: AbortSignal) => Deferred<A>;
|
|
3686
|
+
declare const Task: {
|
|
3687
|
+
/**
|
|
3688
|
+
* Creates a Task that immediately resolves to the given value.
|
|
3689
|
+
*
|
|
3690
|
+
* @example
|
|
3691
|
+
* ```ts
|
|
3692
|
+
* const task = Task.resolve(42);
|
|
3693
|
+
* const value = await task(); // 42
|
|
3694
|
+
* ```
|
|
3695
|
+
*/
|
|
3696
|
+
resolve: <A>(value: A) => Task<A>;
|
|
3697
|
+
from: {
|
|
3698
|
+
/**
|
|
3699
|
+
* Creates a Task from a lazy synchronous thunk.
|
|
3700
|
+
* Unlike `Task.resolve(f())`, `from.sync` does not evaluate `f` until the Task is called.
|
|
3701
|
+
*
|
|
3702
|
+
* @example
|
|
3703
|
+
* ```ts
|
|
3704
|
+
* const t = Task.from.sync(() => Date.now()); // Date.now() not called yet
|
|
3705
|
+
* const ts = await t(); // called here, every time
|
|
3706
|
+
* ```
|
|
3707
|
+
*/
|
|
3708
|
+
sync: <A>(f: () => A) => Task<A>;
|
|
3709
|
+
};
|
|
3710
|
+
/**
|
|
3711
|
+
* Wraps a Promise-returning thunk that may throw or reject,
|
|
3712
|
+
* trapping errors with a fallback function and returning a guaranteed `Task<A>`.
|
|
3713
|
+
*
|
|
3714
|
+
* @example
|
|
3715
|
+
* ```ts
|
|
3716
|
+
* const loadConfig = Task.tryCatch(
|
|
3717
|
+
* () => configStore.get("default"),
|
|
3718
|
+
* { onError: () => DEFAULT_CONFIG }
|
|
3719
|
+
* );
|
|
3720
|
+
* ```
|
|
3721
|
+
*/
|
|
3722
|
+
tryCatch: <A>(f: (signal?: AbortSignal) => globalThis.Promise<A>, options: {
|
|
3723
|
+
onError: (error: unknown) => A;
|
|
3724
|
+
}) => Task<A>;
|
|
3725
|
+
/**
|
|
3726
|
+
* Transforms the value inside a Task.
|
|
3727
|
+
*
|
|
3728
|
+
* @example
|
|
3729
|
+
* ```ts
|
|
3730
|
+
* pipe(
|
|
3731
|
+
* Task.resolve(5),
|
|
3732
|
+
* Task.map(n => n * 2)
|
|
3733
|
+
* )(); // Deferred<10>
|
|
3734
|
+
* ```
|
|
3735
|
+
*/
|
|
3736
|
+
map: <A, B>(f: (a: A) => B) => (data: Task<A>) => Task<B>;
|
|
3737
|
+
/**
|
|
3738
|
+
* Chains Task computations. Passes the resolved value of the first Task to f.
|
|
3739
|
+
*
|
|
3740
|
+
* @example
|
|
3741
|
+
* ```ts
|
|
3742
|
+
* const readUserId: Task<string> = Task.resolve(session.userId);
|
|
3743
|
+
* const loadPrefs = (id: string): Task<Preferences> =>
|
|
3744
|
+
* Task.resolve(prefsCache.get(id));
|
|
3745
|
+
*
|
|
3746
|
+
* pipe(
|
|
3747
|
+
* readUserId,
|
|
3748
|
+
* Task.chain(loadPrefs)
|
|
3749
|
+
* )(); // Deferred<Preferences>
|
|
3750
|
+
* ```
|
|
3751
|
+
*/
|
|
3752
|
+
chain: <A, B>(f: (a: A) => Task<B>) => (data: Task<A>) => Task<B>;
|
|
3753
|
+
/**
|
|
3754
|
+
* Applies a function wrapped in a Task to a value wrapped in a Task.
|
|
3755
|
+
* Both Tasks run in parallel.
|
|
3756
|
+
*
|
|
3757
|
+
* @example
|
|
3758
|
+
* ```ts
|
|
3759
|
+
* const add = (a: number) => (b: number) => a + b;
|
|
3760
|
+
* pipe(
|
|
3761
|
+
* Task.resolve(add),
|
|
3762
|
+
* Task.ap(Task.resolve(5)),
|
|
3763
|
+
* Task.ap(Task.resolve(3))
|
|
3764
|
+
* )(); // Deferred<8>
|
|
3765
|
+
* ```
|
|
3766
|
+
*/
|
|
3767
|
+
ap: <A>(arg: Task<A>) => <B>(data: Task<(a: A) => B>) => Task<B>;
|
|
3768
|
+
/**
|
|
3769
|
+
* Executes a side effect on the value without changing the Task.
|
|
3770
|
+
* Useful for logging or debugging.
|
|
3771
|
+
*
|
|
3772
|
+
* @example
|
|
3773
|
+
* ```ts
|
|
3774
|
+
* pipe(
|
|
3775
|
+
* loadConfig,
|
|
3776
|
+
* Task.tap(cfg => console.log("Config:", cfg)),
|
|
3777
|
+
* Task.map(buildReport)
|
|
3778
|
+
* );
|
|
3779
|
+
* ```
|
|
3780
|
+
*/
|
|
3781
|
+
tap: <A>(f: (a: A) => void) => (data: Task<A>) => Task<A>;
|
|
3782
|
+
/**
|
|
3783
|
+
* Runs multiple Tasks in parallel and collects their results.
|
|
3784
|
+
*
|
|
3785
|
+
* @example
|
|
3786
|
+
* ```ts
|
|
3787
|
+
* Task.all([loadConfig, detectLocale, loadTheme])();
|
|
3788
|
+
* // Deferred<[Config, string, Theme]>
|
|
3789
|
+
* ```
|
|
3790
|
+
*/
|
|
3791
|
+
all: <T extends readonly Task<unknown>[]>(tasks: T) => Task<{ [K in keyof T]: T[K] extends Task<infer A> ? A : never; }>;
|
|
3792
|
+
/**
|
|
3793
|
+
* Delays the execution of a Task by the specified duration.
|
|
3794
|
+
* Useful for debouncing or rate limiting.
|
|
3795
|
+
*
|
|
3796
|
+
* @example
|
|
3797
|
+
* ```ts
|
|
3798
|
+
* pipe(
|
|
3799
|
+
* Task.resolve(42),
|
|
3800
|
+
* Task.delay(Duration.seconds(1))
|
|
3801
|
+
* )(); // Resolves after 1 second
|
|
3802
|
+
* ```
|
|
3803
|
+
*/
|
|
3804
|
+
delay: (duration: Duration) => <A>(data: Task<A>) => Task<A>;
|
|
3805
|
+
/**
|
|
3806
|
+
* Runs a Task a fixed number of times sequentially, collecting all results into an array.
|
|
3807
|
+
* An optional delay duration can be inserted between runs.
|
|
3808
|
+
*
|
|
3809
|
+
* @example
|
|
3810
|
+
* ```ts
|
|
3811
|
+
* pipe(
|
|
3812
|
+
* pollSensor,
|
|
3813
|
+
* Task.repeat({ times: 5, delay: Duration.seconds(1) })
|
|
3814
|
+
* )(); // Task<Reading[]> — 5 readings, one per second
|
|
3815
|
+
* ```
|
|
3816
|
+
*/
|
|
3817
|
+
repeat: (options: {
|
|
3818
|
+
times: number;
|
|
3819
|
+
delay?: Duration;
|
|
3820
|
+
}) => <A>(task: Task<A>) => Task<readonly A[]>;
|
|
3821
|
+
/**
|
|
3822
|
+
* Runs a Task repeatedly until the result satisfies a predicate, returning that result.
|
|
3823
|
+
* An optional delay duration can be inserted between runs.
|
|
3824
|
+
* An optional `maxAttempts` cap stops the loop after N calls — the last value is returned
|
|
3825
|
+
* regardless of whether the predicate was satisfied.
|
|
3826
|
+
*
|
|
3827
|
+
* @example
|
|
3828
|
+
* ```ts
|
|
3829
|
+
* pipe(
|
|
3830
|
+
* checkStatus,
|
|
3831
|
+
* Task.repeatUntil({ when: (s) => s === "ready", delay: Duration.milliseconds(500) })
|
|
3832
|
+
* )(); // polls every 500ms until status is "ready"
|
|
3833
|
+
* ```
|
|
3834
|
+
*/
|
|
3835
|
+
repeatUntil: <A>(options: {
|
|
3836
|
+
when: (a: A) => boolean;
|
|
3837
|
+
delay?: Duration;
|
|
3838
|
+
maxAttempts?: number;
|
|
3839
|
+
}) => (task: Task<A>) => Task<A>;
|
|
3840
|
+
/**
|
|
3841
|
+
* Resolves with the value of the first Task to complete. All Tasks start
|
|
3842
|
+
* immediately. When one resolves, the other tasks are cancelled (aborted)
|
|
3843
|
+
* downstream.
|
|
3844
|
+
*
|
|
3845
|
+
* @example
|
|
3846
|
+
* ```ts
|
|
3847
|
+
* const fast = Task.resolve("fast");
|
|
3848
|
+
* const slow = Task.delay(Duration.milliseconds(200))(Task.resolve("slow"));
|
|
3849
|
+
*
|
|
3850
|
+
* await Task.race([fast, slow])(); // "fast"
|
|
3851
|
+
* ```
|
|
3852
|
+
*/
|
|
3853
|
+
race: <A>(tasks: ReadonlyArray<Task<A>>) => Task<A>;
|
|
3854
|
+
/**
|
|
3855
|
+
* Runs an array of Tasks concurrently and collects their results in an array.
|
|
3856
|
+
* Forward-propagates the call site's AbortSignal to all subtasks concurrently.
|
|
3857
|
+
*
|
|
3858
|
+
* @example
|
|
3859
|
+
* ```ts
|
|
3860
|
+
* Task.sequence([loadConfig, detectLocale, loadTheme])();
|
|
3861
|
+
* // Deferred<[Config, string, Theme]>
|
|
3862
|
+
* ```
|
|
3863
|
+
*/
|
|
3864
|
+
sequence: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
|
|
3865
|
+
/**
|
|
3866
|
+
* Runs an array of Tasks one at a time in order, collecting all results.
|
|
3867
|
+
* Each Task starts only after the previous one resolves.
|
|
3868
|
+
*
|
|
3869
|
+
* @example
|
|
3870
|
+
* ```ts
|
|
3871
|
+
* let log: number[] = [];
|
|
3872
|
+
* const makeTask = (n: number) => Task.resolve(n);
|
|
3873
|
+
*
|
|
3874
|
+
* await Task.sequential([makeTask(1), makeTask(2), makeTask(3)])();
|
|
3875
|
+
* // log = [1, 2, 3] — tasks ran in order
|
|
3876
|
+
* ```
|
|
3877
|
+
*/
|
|
3878
|
+
sequential: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
|
|
3879
|
+
/**
|
|
3880
|
+
* Converts a `Task<A>` into a `Task<Result<E, A>>`, resolving to `Err` if the
|
|
3881
|
+
* Task does not complete within the given duration. The inner Task receives an
|
|
3882
|
+
* `AbortSignal` that fires when the deadline passes, so asynchronous operations
|
|
3883
|
+
* that accept a signal are cancelled rather than left dangling.
|
|
3884
|
+
*
|
|
3885
|
+
* @example
|
|
3886
|
+
* ```ts
|
|
3887
|
+
* pipe(
|
|
3888
|
+
* heavyComputation,
|
|
3889
|
+
* Task.timeout({ duration: Duration.seconds(5), onTimeout: () => "timed out" }),
|
|
3890
|
+
* Task.Result.chain(processResult)
|
|
3891
|
+
* );
|
|
3892
|
+
* ```
|
|
3893
|
+
*/
|
|
3894
|
+
timeout: <E>(options: {
|
|
3895
|
+
duration: Duration;
|
|
3896
|
+
onTimeout: () => E;
|
|
3897
|
+
}) => <A>(task: Task<A>) => Task<Result<E, A>>;
|
|
3898
|
+
/**
|
|
3899
|
+
* Creates a Task paired with an `abort` handle. Calling `abort()` cancels the
|
|
3900
|
+
* current in-flight call immediately. Unlike a one-shot abort, calling `task()`
|
|
3901
|
+
* again after `abort()` starts a fresh call with a new signal.
|
|
3902
|
+
*
|
|
3903
|
+
* Each invocation of `task()` automatically cancels the previous in-flight call,
|
|
3904
|
+
* making it safe to call repeatedly (e.g. on user input) without leaking promises.
|
|
3905
|
+
*
|
|
3906
|
+
* If an outer signal is also present (passed at the call site), aborting it
|
|
3907
|
+
* propagates into the internal controller.
|
|
3908
|
+
*
|
|
3909
|
+
* @example
|
|
3910
|
+
* ```ts
|
|
3911
|
+
* const { task: poll, abort } = Task.abortable(
|
|
3912
|
+
* (signal) => waitForEvent(bus, "ready", { signal }),
|
|
3913
|
+
* );
|
|
3914
|
+
*
|
|
3915
|
+
* onUnmount(abort);
|
|
3916
|
+
* await poll();
|
|
3917
|
+
* ```
|
|
3918
|
+
*/
|
|
3919
|
+
abortable: <A>(factory: (signal: AbortSignal) => Thenable<A>) => {
|
|
3920
|
+
task: Task<A>;
|
|
3921
|
+
abort: () => void;
|
|
3922
|
+
};
|
|
3923
|
+
/**
|
|
3924
|
+
* Executes a task with an optional signal. Use as a terminal step in a `pipe` chain.
|
|
3925
|
+
*
|
|
3926
|
+
* @example
|
|
3927
|
+
* ```ts
|
|
3928
|
+
* const name = await pipe(
|
|
3929
|
+
* loadConfig,
|
|
3930
|
+
* Task.map(config => config.name),
|
|
3931
|
+
* Task.run(),
|
|
3932
|
+
* );
|
|
3933
|
+
* ```
|
|
3934
|
+
*/
|
|
3935
|
+
run: (signal?: AbortSignal) => <A>(task: Task<A>) => Deferred<A>;
|
|
3936
|
+
/**
|
|
3937
|
+
* Converts a Task value into an object containing a single property.
|
|
3938
|
+
* Initiates the pipeline accumulator record.
|
|
3939
|
+
*
|
|
3940
|
+
* @example
|
|
3941
|
+
* ```ts
|
|
3942
|
+
* pipe(Task.resolve(42), Task.bindTo("value")); // Task({ value: 42 })
|
|
3943
|
+
* ```
|
|
3944
|
+
*/
|
|
3945
|
+
bindTo: <K extends string>(key: K) => <A>(data: Task<A>) => Task<{ [P in K]: A; }>;
|
|
3946
|
+
/**
|
|
3947
|
+
* Evaluates a new Task using the current accumulator and attaches the output to a new key.
|
|
3948
|
+
*
|
|
3949
|
+
* @example
|
|
3950
|
+
* ```ts
|
|
3951
|
+
* pipe(
|
|
3952
|
+
* Task.resolve({ a: 1 }),
|
|
3953
|
+
* Task.bind("b", ({ a }) => Task.resolve(a + 1))
|
|
3954
|
+
* ); // Task({ a: 1, b: 2 })
|
|
3955
|
+
* ```
|
|
3956
|
+
*/
|
|
3957
|
+
bind: <K extends string, A, B>(key: K, f: (a: A) => Task<B>) => (data: Task<A>) => Task<A & { [P in K]: B; }>;
|
|
3958
|
+
/**
|
|
3959
|
+
* Creates a memoized version of a Task. The task is executed at most once on first call,
|
|
3960
|
+
* and its resolved value is cached for all subsequent calls.
|
|
3961
|
+
*
|
|
3962
|
+
* @example
|
|
3963
|
+
* ```ts
|
|
3964
|
+
* const loadToken = Task.memoize(loadAuthToken);
|
|
3965
|
+
* const token1 = await loadToken(); // loads token
|
|
3966
|
+
* const token2 = await loadToken(); // returns cached token immediately
|
|
3967
|
+
* ```
|
|
3968
|
+
*/
|
|
3969
|
+
memoize: <A>(task: Task<A>) => Task<A>;
|
|
3970
|
+
/**
|
|
3971
|
+
* Monitors progress of a Task by calling `onProgress(0)` before execution and `onProgress(1)` upon completion.
|
|
3972
|
+
*
|
|
3973
|
+
* @example
|
|
3974
|
+
* ```ts
|
|
3975
|
+
* const taskWithProgress = pipe(
|
|
3976
|
+
* readTask,
|
|
3977
|
+
* Task.withProgress((ratio) => console.log(`Progress: ${ratio * 100}%`))
|
|
3978
|
+
* );
|
|
3979
|
+
* ```
|
|
3980
|
+
*/
|
|
3981
|
+
withProgress: <A>(onProgress: (ratio: number) => void) => (task: Task<A>) => Task<A>;
|
|
3982
|
+
/**
|
|
3983
|
+
* Attaches a read-only `.label` property to a Task, preserving the literal string generic type for IDE tooltips.
|
|
3984
|
+
*
|
|
3985
|
+
* @example
|
|
3986
|
+
* ```ts
|
|
3987
|
+
* const labeledTask = pipe(readTask, Task.withLabel("readUser"));
|
|
3988
|
+
* console.log(labeledTask.label); // "readUser"
|
|
3989
|
+
* ```
|
|
3990
|
+
*/
|
|
3991
|
+
withLabel: <L extends string>(label: L) => <A>(task: Task<A>) => Task.LabeledTask<L, A>;
|
|
3992
|
+
Maybe: {
|
|
3993
|
+
make: {
|
|
3994
|
+
some: <A>(value: A) => Task.Maybe<A>;
|
|
3995
|
+
none: <A = never>() => Task.Maybe<A>;
|
|
3996
|
+
};
|
|
3997
|
+
from: {
|
|
3998
|
+
Maybe: <A>(option: Maybe<A>) => Task.Maybe<A>;
|
|
3999
|
+
nullable: <A>(value: A | null | undefined) => Task.Maybe<A>;
|
|
4000
|
+
Result: <E, A>(result: Result<E, A>) => Task.Maybe<A>;
|
|
4001
|
+
Task: <A>(task: Task<A>) => Task.Maybe<A>;
|
|
4002
|
+
};
|
|
4003
|
+
tryCatch: <A>(f: (signal?: AbortSignal) => Thenable<A>) => Task.Maybe<A>;
|
|
4004
|
+
map: <A, B>(f: (a: A) => B) => (data: Task.Maybe<A>) => Task.Maybe<B>;
|
|
4005
|
+
chain: <A, B>(f: (a: A) => Task.Maybe<B>) => (data: Task.Maybe<A>) => Task.Maybe<B>;
|
|
4006
|
+
ap: <A>(arg: Task.Maybe<A>) => <B>(data: Task.Maybe<(a: A) => B>) => Task.Maybe<B>;
|
|
4007
|
+
fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: Task.Maybe<A>) => Task<B>;
|
|
4008
|
+
match: <A, B>(cases: {
|
|
4009
|
+
none: () => B;
|
|
4010
|
+
some: (a: A) => B;
|
|
4011
|
+
}) => (data: Task.Maybe<A>) => Task<B>;
|
|
4012
|
+
getOrElse: <B>(defaultValue: () => B) => <A>(data: Task.Maybe<A>) => Task<A | B>;
|
|
4013
|
+
tap: <A>(f: (a: A) => void) => (data: Task.Maybe<A>) => Task.Maybe<A>;
|
|
4014
|
+
filter: <A>(predicate: (a: A) => boolean) => (data: Task.Maybe<A>) => Task.Maybe<A>;
|
|
4015
|
+
to: {
|
|
4016
|
+
Result: <E>(onNone: () => E) => <A>(data: Task.Maybe<A>) => Task.Result<E, A>;
|
|
4017
|
+
};
|
|
4018
|
+
bindTo: <K extends string>(key: K) => <A>(data: Task.Maybe<A>) => Task.Maybe<{ [P in K]: A; }>;
|
|
4019
|
+
bind: <K extends string, A, B>(key: K, f: (a: A) => Task.Maybe<B>) => (data: Task.Maybe<A>) => Task.Maybe<A & { [P in K]: B; }>;
|
|
4020
|
+
recover: <B>(fallback: () => Task.Maybe<B>) => <A>(data: Task.Maybe<A>) => Task.Maybe<A | B>;
|
|
4021
|
+
struct: <R extends Record<string, any>>(fields: { [K in keyof R]: Task.Maybe<R[K]>; }) => Task.Maybe<R>;
|
|
4022
|
+
memoize: <A>(task: Task.Maybe<A>) => Task.Maybe<A>;
|
|
4023
|
+
};
|
|
4024
|
+
Result: {
|
|
4025
|
+
make: {
|
|
4026
|
+
ok: <E = never, A = unknown>(value: A) => Task.Result<E, A>;
|
|
4027
|
+
err: <E, A = never>(error: E) => Task.Result<E, A>;
|
|
4028
|
+
};
|
|
4029
|
+
from: {
|
|
4030
|
+
nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Task.Result<E, A>;
|
|
4031
|
+
Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Task.Result<E, A>;
|
|
4032
|
+
Result: <E, A>(result: Result<E, A>) => Task.Result<E, A>;
|
|
4033
|
+
};
|
|
4034
|
+
to: {
|
|
4035
|
+
Maybe: <E, A>(data: Task.Result<E, A>) => Task.Maybe<A>;
|
|
4036
|
+
};
|
|
4037
|
+
tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
|
|
4038
|
+
onError: (error: unknown) => E;
|
|
4039
|
+
}) => Task.Result<E, A>;
|
|
4040
|
+
map: <E, A, B>(f: (a: A) => B) => (data: Task.Result<E, A>) => Task.Result<E, B>;
|
|
4041
|
+
mapError: <E, F, A>(f: (e: E) => F) => (data: Task.Result<E, A>) => Task.Result<F, A>;
|
|
4042
|
+
chain: <E2, A, B>(f: (a: A) => Task.Result<E2, B>) => <E1 = never>(data: Task.Result<E1, A>) => Task.Result<E1 | E2, B>;
|
|
4043
|
+
fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: Task.Result<E, A>) => Task<B>;
|
|
4044
|
+
match: <E, A, B>(cases: {
|
|
4045
|
+
err: (e: E) => B;
|
|
4046
|
+
ok: (a: A) => B;
|
|
4047
|
+
}) => (data: Task.Result<E, A>) => Task<B>;
|
|
4048
|
+
recover: <E, B>(fallback: (e: E) => Task.Result<E, B>) => <A>(data: Task.Result<E, A>) => Task.Result<E, A | B>;
|
|
4049
|
+
recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: (e: E) => Task.Result<E, B>) => <A>(data: Task.Result<E, A>) => Task.Result<E, A | B>;
|
|
4050
|
+
getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Task.Result<E, A>) => Task<A | B>;
|
|
4051
|
+
tap: <E, A>(f: (a: A) => void) => (data: Task.Result<E, A>) => Task.Result<E, A>;
|
|
4052
|
+
tapError: <E, A>(f: (e: E) => void) => (data: Task.Result<E, A>) => Task.Result<E, A>;
|
|
4053
|
+
ap: <E, A>(arg: Task.Result<E, A>) => <B>(data: Task.Result<E, (a: A) => B>) => Task.Result<E, B>;
|
|
4054
|
+
run: (signal?: AbortSignal) => <E, A>(task: Task.Result<E, A>) => Deferred<Result<E, A>>;
|
|
4055
|
+
bindTo: <K extends string>(key: K) => <E, A>(data: Task.Result<E, A>) => Task.Result<E, { [P in K]: A; }>;
|
|
4056
|
+
bind: <K extends string, E, A, B>(key: K, f: (a: A) => Task.Result<E, B>) => (data: Task.Result<E, A>) => Task.Result<E, A & { [P in K]: B; }>;
|
|
4057
|
+
struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Task.Result<E, R[K]>; }) => Task.Result<E, R>;
|
|
4058
|
+
retry: (policy: RetryPolicy) => <E, A>(task: Task.Result<E, A>) => Task.Result<E, A>;
|
|
4059
|
+
memoize: <E, A>(task: Task.Result<E, A>) => Task.Result<E, A>;
|
|
4060
|
+
timeout: <E2>(options: {
|
|
4061
|
+
duration: Duration;
|
|
4062
|
+
onTimeout: () => E2;
|
|
4063
|
+
}) => <E1 = never, A = unknown>(task: Task.Result<E1, A>) => Task.Result<E1 | E2, A>;
|
|
4064
|
+
allSettled: <E, A>(tasks: ReadonlyArray<Task.Result<E, A>>) => Task<ReadonlyArray<Result<E, A>>>;
|
|
4065
|
+
};
|
|
4066
|
+
Validation: {
|
|
4067
|
+
make: {
|
|
4068
|
+
passed: <E = never, A = unknown>(value: A) => Task.Validation<E, A>;
|
|
4069
|
+
failed: <E, A = never>(error: E) => Task.Validation<E, A>;
|
|
4070
|
+
failedAll: <E, A = never>(errors: NonEmptyArr<E>) => Task.Validation<E, A>;
|
|
4071
|
+
};
|
|
4072
|
+
from: {
|
|
4073
|
+
Validation: <E, A>(validation: Validation<E, A>) => Task.Validation<E, A>;
|
|
4074
|
+
nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Task.Validation<E, A>;
|
|
4075
|
+
Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Task.Validation<E, A>;
|
|
4076
|
+
Result: <E, A>(result: Result<E, A>) => Task.Validation<E, A>;
|
|
4077
|
+
};
|
|
4078
|
+
to: {
|
|
4079
|
+
Result: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (data: Task.Validation<E1, A>) => Task.Result<E2, A>;
|
|
4080
|
+
Maybe: <E, A>(data: Task.Validation<E, A>) => Task.Maybe<A>;
|
|
4081
|
+
};
|
|
4082
|
+
tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
|
|
4083
|
+
onError: (error: unknown) => E;
|
|
4084
|
+
}) => Task.Validation<E, A>;
|
|
4085
|
+
map: <E, A, B>(f: (a: A) => B) => (data: Task.Validation<E, A>) => Task.Validation<E, B>;
|
|
4086
|
+
ap: <E, A>(arg: Task.Validation<E, A>) => <B>(data: Task.Validation<E, (a: A) => B>) => Task.Validation<E, B>;
|
|
4087
|
+
fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: Task.Validation<E, A>) => Task<B>;
|
|
4088
|
+
match: <E, A, B>(cases: {
|
|
4089
|
+
passed: (a: A) => B;
|
|
4090
|
+
failed: (errors: NonEmptyArr<E>) => B;
|
|
4091
|
+
}) => (data: Task.Validation<E, A>) => Task<B>;
|
|
4092
|
+
getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Task.Validation<E, A>) => Task<A | B>;
|
|
4093
|
+
tap: <E, A>(f: (a: A) => void) => (data: Task.Validation<E, A>) => Task.Validation<E, A>;
|
|
4094
|
+
recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => Task.Validation<E, B>) => <A>(data: Task.Validation<E, A>) => Task.Validation<E, A | B>;
|
|
4095
|
+
recoverUnless: <E, B>(isBlocked: (errors: NonEmptyArr<E>) => boolean, fallback: (errors: NonEmptyArr<E>) => Task.Validation<E, B>) => <A>(data: Task.Validation<E, A>) => Task.Validation<E, A | B>;
|
|
4096
|
+
product: <E, A, B>(first: Task.Validation<E, A>, second: Task.Validation<E, B>) => Task.Validation<E, readonly [A, B]>;
|
|
4097
|
+
productAll: <E, A>(data: NonEmptyArr<Task.Validation<E, A>>) => Task.Validation<E, readonly A[]>;
|
|
4098
|
+
mapError: <E, F, A>(f: (e: E) => F) => (data: Task.Validation<E, A>) => Task.Validation<F, A>;
|
|
4099
|
+
tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: Task.Validation<E, A>) => Task.Validation<E, A>;
|
|
4100
|
+
struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Task.Validation<E, R[K]>; }) => Task.Validation<E, R>;
|
|
4101
|
+
memoize: <E, A>(task: Task.Validation<E, A>) => Task.Validation<E, A>;
|
|
4102
|
+
};
|
|
4103
|
+
};
|
|
4104
|
+
type _CoreMaybe<A> = Maybe<A>;
|
|
4105
|
+
type _CoreResult<E, A> = Result<E, A>;
|
|
4106
|
+
type _CoreValidation<E, A> = Validation<E, A>;
|
|
4107
|
+
declare namespace Task {
|
|
4108
|
+
type LabeledTask<L extends string, A> = Task<A> & {
|
|
4109
|
+
readonly label: L;
|
|
4110
|
+
};
|
|
4111
|
+
type Maybe<A> = Task<_CoreMaybe<A>>;
|
|
4112
|
+
type Result<E, A> = Task<_CoreResult<E, A>>;
|
|
4113
|
+
type Validation<E, A> = Task<_CoreValidation<E, A>>;
|
|
4114
|
+
}
|
|
4115
|
+
//#endregion
|
|
4116
|
+
//#region src/Core/These.d.ts
|
|
4117
|
+
/**
|
|
4118
|
+
* These<A, B> is an inclusive-OR type: it holds a first value (A), a second
|
|
4119
|
+
* value (B), or both simultaneously. Neither side carries a success/failure
|
|
4120
|
+
* connotation — it is a neutral pair where any combination is valid.
|
|
4121
|
+
*
|
|
4122
|
+
* - First(a) — only a first value
|
|
4123
|
+
* - Second(b) — only a second value
|
|
4124
|
+
* - Both(a, b) — first and second values simultaneously
|
|
4125
|
+
*
|
|
4126
|
+
* A common use: lenient parsers or processors that carry a diagnostic note
|
|
4127
|
+
* alongside a result, without losing either piece of information.
|
|
4128
|
+
*
|
|
4129
|
+
* @example
|
|
4130
|
+
* ```ts
|
|
4131
|
+
* const parse = (s: string): These<number, string> => {
|
|
4132
|
+
* const trimmed = s.trim();
|
|
4133
|
+
* const n = parseFloat(trimmed);
|
|
4134
|
+
* if (isNaN(n)) return These.make.second("Not a number");
|
|
4135
|
+
* if (s !== trimmed) return These.make.both(n, "Leading/trailing whitespace trimmed");
|
|
4136
|
+
* return These.make.first(n);
|
|
4137
|
+
* };
|
|
4138
|
+
* ```
|
|
4139
|
+
*/
|
|
4140
|
+
type These<A, B> = TheseFirst<A> | TheseSecond<B> | TheseBoth<A, B>;
|
|
4141
|
+
type TheseFirst<T> = WithKind<"First"> & WithFirst<T>;
|
|
4142
|
+
type TheseSecond<T> = WithKind<"Second"> & WithSecond<T>;
|
|
4143
|
+
type TheseBoth<First, Second> = WithKind<"Both"> & WithFirst<First> & WithSecond<Second>;
|
|
4144
|
+
declare const These: {
|
|
4145
|
+
make: {
|
|
4146
|
+
/**
|
|
4147
|
+
* Creates a These holding only a first value.
|
|
4148
|
+
*
|
|
4149
|
+
* @example
|
|
4150
|
+
* ```ts
|
|
4151
|
+
* These.make.first(42); // { kind: "First", first: 42 }
|
|
4152
|
+
* ```
|
|
4153
|
+
*/
|
|
4154
|
+
first: <A>(value: A) => TheseFirst<A>;
|
|
4155
|
+
/**
|
|
4156
|
+
* Creates a These holding only a second value.
|
|
4157
|
+
*
|
|
4158
|
+
* @example
|
|
4159
|
+
* ```ts
|
|
4160
|
+
* These.make.second("warning"); // { kind: "Second", second: "warning" }
|
|
4161
|
+
* ```
|
|
4162
|
+
*/
|
|
4163
|
+
second: <B>(value: B) => TheseSecond<B>;
|
|
4164
|
+
/**
|
|
4165
|
+
* Creates a These holding both a first and a second value simultaneously.
|
|
4166
|
+
*
|
|
4167
|
+
* @example
|
|
4168
|
+
* ```ts
|
|
4169
|
+
* These.make.both(42, "Deprecated API used"); // { kind: "Both", first: 42, second: "Deprecated API used" }
|
|
4170
|
+
* ```
|
|
4171
|
+
*/
|
|
4172
|
+
both: <A, B>(f: A, s: B) => TheseBoth<A, B>;
|
|
4173
|
+
};
|
|
4174
|
+
is: {
|
|
4175
|
+
/**
|
|
4176
|
+
* Type guard — checks if a These holds only a first value.
|
|
4177
|
+
*
|
|
4178
|
+
* @example
|
|
4179
|
+
* ```ts
|
|
4180
|
+
* const val = These.make.first(42);
|
|
4181
|
+
* if (These.is.first(val)) {
|
|
4182
|
+
* console.log(val.first); // 42
|
|
4183
|
+
* }
|
|
4184
|
+
* ```
|
|
4185
|
+
*/
|
|
4186
|
+
first: <A, B>(data: These<A, B>) => data is TheseFirst<A>;
|
|
4187
|
+
/**
|
|
4188
|
+
* Type guard — checks if a These holds only a second value.
|
|
4189
|
+
*
|
|
4190
|
+
* @example
|
|
4191
|
+
* ```ts
|
|
4192
|
+
* const val = These.make.second("warning");
|
|
4193
|
+
* if (These.is.second(val)) {
|
|
4194
|
+
* console.log(val.second); // "warning"
|
|
4195
|
+
* }
|
|
4196
|
+
* ```
|
|
4197
|
+
*/
|
|
4198
|
+
second: <A, B>(data: These<A, B>) => data is TheseSecond<B>;
|
|
4199
|
+
/**
|
|
4200
|
+
* Type guard — checks if a These holds both values simultaneously.
|
|
4201
|
+
*
|
|
4202
|
+
* @example
|
|
4203
|
+
* ```ts
|
|
4204
|
+
* const val = These.make.both(42, "warning");
|
|
4205
|
+
* if (These.is.both(val)) {
|
|
4206
|
+
* console.log(val.first, val.second); // 42 "warning"
|
|
4207
|
+
* }
|
|
4208
|
+
* ```
|
|
4209
|
+
*/
|
|
4210
|
+
both: <A, B>(data: These<A, B>) => data is TheseBoth<A, B>;
|
|
4211
|
+
};
|
|
4212
|
+
/**
|
|
4213
|
+
* Returns true if the These contains a first value (First or Both).
|
|
4214
|
+
*
|
|
4215
|
+
* @example
|
|
4216
|
+
* ```ts
|
|
4217
|
+
* These.hasFirst(These.make.first(42)); // true
|
|
4218
|
+
* These.hasFirst(These.make.both(42, "warn"));// true
|
|
4219
|
+
* These.hasFirst(These.make.second("warn")); // false
|
|
4220
|
+
* ```
|
|
4221
|
+
*/
|
|
4222
|
+
hasFirst: <A, B>(data: These<A, B>) => data is TheseFirst<A> | TheseBoth<A, B>;
|
|
4223
|
+
/**
|
|
4224
|
+
* Returns true if the These contains a second value (Second or Both).
|
|
4225
|
+
*
|
|
4226
|
+
* @example
|
|
4227
|
+
* ```ts
|
|
4228
|
+
* These.hasSecond(These.make.second("warn")); // true
|
|
4229
|
+
* These.hasSecond(These.make.both(42, "warn"));// true
|
|
4230
|
+
* These.hasSecond(These.make.first(42)); // false
|
|
4231
|
+
* ```
|
|
4232
|
+
*/
|
|
4233
|
+
hasSecond: <A, B>(data: These<A, B>) => data is TheseSecond<B> | TheseBoth<A, B>;
|
|
4234
|
+
/**
|
|
4235
|
+
* Transforms the first value, leaving the second unchanged.
|
|
4236
|
+
*
|
|
4237
|
+
* @example
|
|
4238
|
+
* ```ts
|
|
4239
|
+
* pipe(These.make.first(5), These.mapFirst(n => n * 2)); // First(10)
|
|
4240
|
+
* pipe(These.make.both(5, "warn"), These.mapFirst(n => n * 2)); // Both(10, "warn")
|
|
4241
|
+
* pipe(These.make.second("warn"), These.mapFirst(n => n * 2)); // Second("warn")
|
|
4242
|
+
* ```
|
|
4243
|
+
*/
|
|
4244
|
+
mapFirst: <A, C>(f: (a: A) => C) => <B>(data: These<A, B>) => These<C, B>;
|
|
4245
|
+
/**
|
|
4246
|
+
* Transforms the second value, leaving the first unchanged.
|
|
4247
|
+
*
|
|
4248
|
+
* @example
|
|
4249
|
+
* ```ts
|
|
4250
|
+
* pipe(These.make.second("warn"), These.mapSecond(e => e.toUpperCase())); // Second("WARN")
|
|
4251
|
+
* pipe(These.make.both(5, "warn"), These.mapSecond(e => e.toUpperCase())); // Both(5, "WARN")
|
|
4252
|
+
* ```
|
|
4253
|
+
*/
|
|
4254
|
+
mapSecond: <B, D>(f: (b: B) => D) => <A>(data: These<A, B>) => These<A, D>;
|
|
4255
|
+
/**
|
|
4256
|
+
* Transforms both the first and second values independently.
|
|
4257
|
+
*
|
|
4258
|
+
* @example
|
|
4259
|
+
* ```ts
|
|
4260
|
+
* pipe(
|
|
4261
|
+
* These.make.both(5, "warn"),
|
|
4262
|
+
* These.mapBoth(n => n * 2, e => e.toUpperCase())
|
|
4263
|
+
* ); // Both(10, "WARN")
|
|
4264
|
+
* ```
|
|
4265
|
+
*/
|
|
4266
|
+
mapBoth: <A, C, B, D>(onFirst: (a: A) => C, onSecond: (b: B) => D) => (data: These<A, B>) => These<C, D>;
|
|
4267
|
+
/**
|
|
4268
|
+
* Chains These computations by passing the first value to f.
|
|
4269
|
+
* Second propagates unchanged; First and Both apply f to the first value.
|
|
4270
|
+
*
|
|
4271
|
+
* @example
|
|
4272
|
+
* ```ts
|
|
4273
|
+
* const double = (n: number): These<number, string> => These.make.first(n * 2);
|
|
4274
|
+
*
|
|
4275
|
+
* pipe(These.make.first(5), These.chainFirst(double)); // First(10)
|
|
4276
|
+
* pipe(These.make.both(5, "warn"), These.chainFirst(double)); // First(10)
|
|
4277
|
+
* pipe(These.make.second("warn"), These.chainFirst(double)); // Second("warn")
|
|
4278
|
+
* ```
|
|
4279
|
+
*/
|
|
4280
|
+
chainFirst: <A, B, C>(f: (a: A) => These<C, B>) => (data: These<A, B>) => These<C, B>;
|
|
4281
|
+
/**
|
|
4282
|
+
* Chains These computations by passing the second value to f.
|
|
4283
|
+
* First propagates unchanged; Second and Both apply f to the second value.
|
|
4284
|
+
*
|
|
4285
|
+
* @example
|
|
4286
|
+
* ```ts
|
|
4287
|
+
* const shout = (s: string): These<number, string> => These.make.second(s.toUpperCase());
|
|
4288
|
+
*
|
|
4289
|
+
* pipe(These.make.second("warn"), These.chainSecond(shout)); // Second("WARN")
|
|
4290
|
+
* pipe(These.make.both(5, "warn"), These.chainSecond(shout)); // Second("WARN")
|
|
4291
|
+
* pipe(These.make.first(5), These.chainSecond(shout)); // First(5)
|
|
4292
|
+
* ```
|
|
4293
|
+
*/
|
|
4294
|
+
chainSecond: <A, B, D>(f: (b: B) => These<A, D>) => (data: These<A, B>) => These<A, D>;
|
|
4295
|
+
/**
|
|
4296
|
+
* Extracts a value from a These by providing handlers for all three cases.
|
|
4297
|
+
*
|
|
4298
|
+
* @example
|
|
4299
|
+
* ```ts
|
|
4300
|
+
* pipe(
|
|
4301
|
+
* these,
|
|
4302
|
+
* These.fold(
|
|
4303
|
+
* a => `First: ${a}`,
|
|
4304
|
+
* b => `Second: ${b}`,
|
|
4305
|
+
* (a, b) => `Both: ${a} / ${b}`
|
|
4306
|
+
* )
|
|
4307
|
+
* );
|
|
4308
|
+
* ```
|
|
4309
|
+
*/
|
|
4310
|
+
fold: <A, B, C>(onFirst: (a: A) => C, onSecond: (b: B) => C, onBoth: (a: A, b: B) => C) => (data: These<A, B>) => C;
|
|
4311
|
+
/**
|
|
4312
|
+
* Pattern matches on a These, returning the result of the matching case.
|
|
4313
|
+
*
|
|
4314
|
+
* @example
|
|
4315
|
+
* ```ts
|
|
4316
|
+
* pipe(
|
|
4317
|
+
* these,
|
|
4318
|
+
* These.match({
|
|
4319
|
+
* first: a => `First: ${a}`,
|
|
4320
|
+
* second: b => `Second: ${b}`,
|
|
4321
|
+
* both: (a, b) => `Both: ${a} / ${b}`
|
|
4322
|
+
* })
|
|
4323
|
+
* );
|
|
4324
|
+
* ```
|
|
4325
|
+
*/
|
|
4326
|
+
match: <A, B, C>(cases: {
|
|
4327
|
+
first: (a: A) => C;
|
|
4328
|
+
second: (b: B) => C;
|
|
4329
|
+
both: (a: A, b: B) => C;
|
|
4330
|
+
}) => (data: These<A, B>) => C;
|
|
4331
|
+
/**
|
|
4332
|
+
* Returns the first value, or a default if the These has no first value.
|
|
4333
|
+
* The default can be a different type, widening the result to `A | C`.
|
|
4334
|
+
*
|
|
4335
|
+
* @example
|
|
4336
|
+
* ```ts
|
|
4337
|
+
* pipe(These.make.first(5), These.getFirstOrElse(() => 0)); // 5
|
|
4338
|
+
* pipe(These.make.both(5, "warn"), These.getFirstOrElse(() => 0)); // 5
|
|
4339
|
+
* pipe(These.make.second("warn"), These.getFirstOrElse(() => 0)); // 0
|
|
4340
|
+
* pipe(These.make.second("warn"), These.getFirstOrElse(() => null)); // null — typed as number | null
|
|
4341
|
+
* ```
|
|
4342
|
+
*/
|
|
4343
|
+
getFirstOrElse: <A, C>(defaultValue: () => C) => <B>(data: These<A, B>) => A | C;
|
|
4344
|
+
/**
|
|
4345
|
+
* Returns the second value, or a default if the These has no second value.
|
|
4346
|
+
* The default can be a different type, widening the result to `B | D`.
|
|
4347
|
+
*
|
|
4348
|
+
* @example
|
|
4349
|
+
* ```ts
|
|
4350
|
+
* pipe(These.make.second("warn"), These.getSecondOrElse(() => "none")); // "warn"
|
|
4351
|
+
* pipe(These.make.both(5, "warn"), These.getSecondOrElse(() => "none")); // "warn"
|
|
4352
|
+
* pipe(These.make.first(5), These.getSecondOrElse(() => "none")); // "none"
|
|
4353
|
+
* pipe(These.make.first(5), These.getSecondOrElse(() => null)); // null — typed as string | null
|
|
4354
|
+
* ```
|
|
4355
|
+
*/
|
|
4356
|
+
getSecondOrElse: <B, D>(defaultValue: () => D) => <A>(data: These<A, B>) => B | D;
|
|
4357
|
+
/**
|
|
4358
|
+
* Runs a side effect on the first value without changing the These.
|
|
4359
|
+
* Useful for logging or debugging.
|
|
4360
|
+
*
|
|
4361
|
+
* @example
|
|
4362
|
+
* ```ts
|
|
4363
|
+
* pipe(These.make.first(5), These.tap(console.log)); // logs 5, returns First(5)
|
|
4364
|
+
* ```
|
|
4365
|
+
*/
|
|
4366
|
+
tap: <A>(f: (a: A) => void) => <B>(data: These<A, B>) => These<A, B>;
|
|
4367
|
+
/**
|
|
4368
|
+
* Swaps the roles of first and second values.
|
|
4369
|
+
* - First(a) → Second(a)
|
|
4370
|
+
* - Second(b) → First(b)
|
|
4371
|
+
* - Both(a, b) → Both(b, a)
|
|
4372
|
+
*
|
|
4373
|
+
* @example
|
|
4374
|
+
* ```ts
|
|
4375
|
+
* These.swap(These.make.first(5)); // Second(5)
|
|
4376
|
+
* These.swap(These.make.second("warn")); // First("warn")
|
|
4377
|
+
* These.swap(These.make.both(5, "warn")); // Both("warn", 5)
|
|
4378
|
+
* ```
|
|
4379
|
+
*/
|
|
4380
|
+
swap: <A, B>(data: These<A, B>) => These<B, A>;
|
|
4381
|
+
};
|
|
4382
|
+
//#endregion
|
|
4383
|
+
export { Logged as A, Pair as C, Maybe as D, Op as E, Lazy as M, Equality as N, None as O, Combinable as P, Predicate as S, Optional as T, NotAsked as _, Task as a, Refinement as b, Validation as c, Err$1 as d, Ok$1 as f, Loading as g, Failure as h, TheseSecond as i, Lens as j, Some as k, Stream as l, Resource as m, TheseBoth as n, Failed as o, Result as p, TheseFirst as r, Passed as s, These as t, State$1 as u, RemoteData as v, Ordering as w, Reader as x, Success as y };
|