forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresults.tsx
More file actions
411 lines (371 loc) · 13.8 KB
/
results.tsx
File metadata and controls
411 lines (371 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import { wait } from "./promises";
import { deindent, nicify } from "./strings";
export type Result<T, E = unknown> =
| {
status: "ok",
data: T,
}
| {
status: "error",
error: E,
};
export type AsyncResult<T, E = unknown, P = void> =
| Result<T, E>
| (
& {
status: "pending",
}
& {
progress: P,
}
);
export const Result = {
fromThrowing,
fromThrowingAsync,
fromPromise: promiseToResult,
ok<T>(data: T): Result<T, never> & { status: "ok" } {
return {
status: "ok",
data,
};
},
error<E>(error: E): Result<never, E> & { status: "error" } {
return {
status: "error",
error,
};
},
map: mapResult,
or: <T, E, U>(result: Result<T, E>, fallback: U): T | U => {
return result.status === "ok" ? result.data : fallback;
},
orThrow: <T, E>(result: Result<T, E>): T => {
if (result.status === "error") {
throw result.error;
}
return result.data;
},
orThrowAsync: async <T, E>(result: Promise<Result<T, E>>): Promise<T> => {
return Result.orThrow(await result);
},
retry,
};
import.meta.vitest?.test("Result.ok and Result.error", ({ expect }) => {
// Test Result.ok
const okResult = Result.ok(42);
expect(okResult.status).toBe("ok");
expect(okResult.data).toBe(42);
// Test Result.error
const error = new Error("Test error");
const errorResult = Result.error(error);
expect(errorResult.status).toBe("error");
expect(errorResult.error).toBe(error);
});
import.meta.vitest?.test("Result.or", ({ expect }) => {
// Test with ok result
const okResult: Result<number, string> = { status: "ok", data: 42 };
expect(Result.or(okResult, 0)).toBe(42);
// Test with error result
const errorResult: Result<number, string> = { status: "error", error: "error message" };
expect(Result.or(errorResult, 0)).toBe(0);
});
import.meta.vitest?.test("Result.orThrow", ({ expect }) => {
// Test with ok result
const okResult: Result<number, Error> = { status: "ok", data: 42 };
expect(Result.orThrow(okResult)).toBe(42);
// Test with error result
const error = new Error("Test error");
const errorResult: Result<number, Error> = { status: "error", error };
expect(() => Result.orThrow(errorResult)).toThrow(error);
});
import.meta.vitest?.test("Result.orThrowAsync", async ({ expect }) => {
// Test with ok result
const okPromise = Promise.resolve({ status: "ok", data: 42 } as Result<number, Error>);
expect(await Result.orThrowAsync(okPromise)).toBe(42);
// Test with error result
const error = new Error("Test error");
const errorPromise = Promise.resolve({ status: "error", error } as Result<number, Error>);
await expect(Result.orThrowAsync(errorPromise)).rejects.toThrow(error);
});
export const AsyncResult = {
fromThrowing,
fromPromise: promiseToResult,
ok: Result.ok,
error: Result.error,
pending,
map: mapResult,
or: <T, E, P, U>(result: AsyncResult<T, E, P>, fallback: U): T | U => {
if (result.status === "pending") {
return fallback;
}
return Result.or(result, fallback);
},
orThrow: <T, E, P>(result: AsyncResult<T, E, P>): T => {
if (result.status === "pending") {
throw new Error("Result still pending");
}
return Result.orThrow(result);
},
retry,
};
import.meta.vitest?.test("AsyncResult.or", ({ expect }) => {
// Test with ok result
const okResult: AsyncResult<number, string> = { status: "ok", data: 42 };
expect(AsyncResult.or(okResult, 0)).toBe(42);
// Test with error result
const errorResult: AsyncResult<number, string> = { status: "error", error: "error message" };
expect(AsyncResult.or(errorResult, 0)).toBe(0);
// Test with pending result
const pendingResult: AsyncResult<number, string> = { status: "pending", progress: undefined };
expect(AsyncResult.or(pendingResult, 0)).toBe(0);
});
import.meta.vitest?.test("AsyncResult.orThrow", ({ expect }) => {
// Test with ok result
const okResult: AsyncResult<number, Error> = { status: "ok", data: 42 };
expect(AsyncResult.orThrow(okResult)).toBe(42);
// Test with error result
const error = new Error("Test error");
const errorResult: AsyncResult<number, Error> = { status: "error", error };
expect(() => AsyncResult.orThrow(errorResult)).toThrow(error);
// Test with pending result
const pendingResult: AsyncResult<number, Error> = { status: "pending", progress: undefined };
expect(() => AsyncResult.orThrow(pendingResult)).toThrow("Result still pending");
});
function pending(): AsyncResult<never, never, void> & { status: "pending" };
function pending<P>(progress: P): AsyncResult<never, never, P> & { status: "pending" };
function pending<P>(progress?: P): AsyncResult<never, never, P> & { status: "pending" } {
return {
status: "pending",
progress: progress!,
};
}
import.meta.vitest?.test("pending", ({ expect }) => {
// Test without progress
const pendingResult = pending();
expect(pendingResult.status).toBe("pending");
expect(pendingResult.progress).toBe(undefined);
// Test with progress
const progressValue = { loaded: 50, total: 100 };
const pendingWithProgress = pending(progressValue);
expect(pendingWithProgress.status).toBe("pending");
expect(pendingWithProgress.progress).toBe(progressValue);
});
async function promiseToResult<T>(promise: Promise<T>): Promise<Result<T>> {
try {
const value = await promise;
return Result.ok(value);
} catch (error) {
return Result.error(error);
}
}
import.meta.vitest?.test("promiseToResult", async ({ expect }) => {
// Test with resolved promise
const resolvedPromise = Promise.resolve(42);
const resolvedResult = await promiseToResult(resolvedPromise);
expect(resolvedResult.status).toBe("ok");
if (resolvedResult.status === "ok") {
expect(resolvedResult.data).toBe(42);
}
// Test with rejected promise
const error = new Error("Test error");
const rejectedPromise = Promise.reject(error);
const rejectedResult = await promiseToResult(rejectedPromise);
expect(rejectedResult.status).toBe("error");
if (rejectedResult.status === "error") {
expect(rejectedResult.error).toBe(error);
}
});
function fromThrowing<T>(fn: () => T): Result<T, unknown> {
try {
return Result.ok(fn());
} catch (error) {
return Result.error(error);
}
}
import.meta.vitest?.test("fromThrowing", ({ expect }) => {
// Test with function that succeeds
const successFn = () => 42;
const successResult = fromThrowing(successFn);
expect(successResult.status).toBe("ok");
if (successResult.status === "ok") {
expect(successResult.data).toBe(42);
}
// Test with function that throws
const error = new Error("Test error");
const errorFn = () => {
throw error;
};
const errorResult = fromThrowing(errorFn);
expect(errorResult.status).toBe("error");
if (errorResult.status === "error") {
expect(errorResult.error).toBe(error);
}
});
async function fromThrowingAsync<T>(fn: () => Promise<T>): Promise<Result<T, unknown>> {
try {
return Result.ok(await fn());
} catch (error) {
return Result.error(error);
}
}
import.meta.vitest?.test("fromThrowingAsync", async ({ expect }) => {
// Test with async function that succeeds
const successFn = async () => 42;
const successResult = await fromThrowingAsync(successFn);
expect(successResult.status).toBe("ok");
if (successResult.status === "ok") {
expect(successResult.data).toBe(42);
}
// Test with async function that throws
const error = new Error("Test error");
const errorFn = async () => {
throw error;
};
const errorResult = await fromThrowingAsync(errorFn);
expect(errorResult.status).toBe("error");
if (errorResult.status === "error") {
expect(errorResult.error).toBe(error);
}
});
function mapResult<T, U, E = unknown, P = unknown>(result: Result<T, E>, fn: (data: T) => U): Result<U, E>;
function mapResult<T, U, E = unknown, P = unknown>(result: AsyncResult<T, E, P>, fn: (data: T) => U): AsyncResult<U, E, P>;
function mapResult<T, U, E = unknown, P = unknown>(result: AsyncResult<T, E, P>, fn: (data: T) => U): AsyncResult<U, E, P> {
if (result.status === "error") return {
status: "error",
error: result.error,
};
if (result.status === "pending") return {
status: "pending",
..."progress" in result ? { progress: result.progress } : {},
} as any;
return Result.ok(fn(result.data));
}
import.meta.vitest?.test("mapResult", ({ expect }) => {
// Test with ok result
const okResult: Result<number, string> = { status: "ok", data: 42 };
const mappedOk = mapResult(okResult, (n: number) => n * 2);
expect(mappedOk.status).toBe("ok");
if (mappedOk.status === "ok") {
expect(mappedOk.data).toBe(84);
}
// Test with error result
const errorResult: Result<number, string> = { status: "error", error: "error message" };
const mappedError = mapResult(errorResult, (n: number) => n * 2);
expect(mappedError.status).toBe("error");
if (mappedError.status === "error") {
expect(mappedError.error).toBe("error message");
}
// Test with pending result (no progress)
const pendingResult: AsyncResult<number, string, void> = { status: "pending", progress: undefined };
const mappedPending = mapResult(pendingResult, (n: number) => n * 2);
expect(mappedPending.status).toBe("pending");
// Test with pending result (with progress)
const progressValue = { loaded: 50, total: 100 };
const pendingWithProgress: AsyncResult<number, string, typeof progressValue> = {
status: "pending",
progress: progressValue
};
const mappedPendingWithProgress = mapResult(pendingWithProgress, (n: number) => n * 2);
expect(mappedPendingWithProgress.status).toBe("pending");
if (mappedPendingWithProgress.status === "pending") {
expect(mappedPendingWithProgress.progress).toBe(progressValue);
}
});
class RetryError extends AggregateError {
constructor(public readonly errors: unknown[]) {
const strings = errors.map(e => nicify(e));
const isAllSame = strings.length > 1 && strings.every(s => s === strings[0]);
super(
errors,
deindent`
Error after ${errors.length} attempts.
${isAllSame ? deindent`
Attempts 1-${errors.length}:
${strings[0]}
` : strings.map((s, i) => deindent`
Attempt ${i + 1}:
${s}
`).join("\n\n")}
`,
{ cause: errors[errors.length - 1] }
);
this.name = "RetryError";
}
get attempts() {
return this.errors.length;
}
}
RetryError.prototype.name = "RetryError";
import.meta.vitest?.test("RetryError", ({ expect }) => {
// Test with single error
const singleError = new Error("Single error");
const retryErrorSingle = new RetryError([singleError]);
expect(retryErrorSingle.name).toBe("RetryError");
expect(retryErrorSingle.errors).toEqual([singleError]);
expect(retryErrorSingle.attempts).toBe(1);
expect(retryErrorSingle.cause).toBe(singleError);
expect(retryErrorSingle.message).toContain("Error after 1 attempts");
// Test with multiple different errors
const error1 = new Error("Error 1");
const error2 = new Error("Error 2");
const retryErrorMultiple = new RetryError([error1, error2]);
expect(retryErrorMultiple.name).toBe("RetryError");
expect(retryErrorMultiple.errors).toEqual([error1, error2]);
expect(retryErrorMultiple.attempts).toBe(2);
expect(retryErrorMultiple.cause).toBe(error2);
expect(retryErrorMultiple.message).toContain("Error after 2 attempts");
expect(retryErrorMultiple.message).toContain("Attempt 1");
expect(retryErrorMultiple.message).toContain("Attempt 2");
// Test with multiple identical errors
const sameError = new Error("Same error");
const retryErrorSame = new RetryError([sameError, sameError]);
expect(retryErrorSame.name).toBe("RetryError");
expect(retryErrorSame.errors).toEqual([sameError, sameError]);
expect(retryErrorSame.attempts).toBe(2);
expect(retryErrorSame.cause).toBe(sameError);
expect(retryErrorSame.message).toContain("Error after 2 attempts");
expect(retryErrorSame.message).toContain("Attempts 1-2");
});
async function retry<T>(
fn: (attemptIndex: number) => Result<T> | Promise<Result<T>>,
totalAttempts: number,
{ exponentialDelayBase = 1000 } = {},
): Promise<Result<T, RetryError> & { attempts: number }> {
const errors: unknown[] = [];
for (let i = 0; i < totalAttempts; i++) {
const res = await fn(i);
if (res.status === "ok") {
return Object.assign(Result.ok(res.data), { attempts: i + 1 });
} else {
errors.push(res.error);
if (i < totalAttempts - 1) {
await wait((Math.random() + 0.5) * exponentialDelayBase * (2 ** i));
}
}
}
return Object.assign(Result.error(new RetryError(errors)), { attempts: totalAttempts });
}
import.meta.vitest?.test("retry", async ({ expect }) => {
// Test successful on first attempt
const successFn = async () => Result.ok("success");
const successResult = await retry(successFn, 3, { exponentialDelayBase: 0 });
expect(successResult).toEqual({ status: "ok", data: "success", attempts: 1 });
// Test successful after failures
let attemptCount = 0;
const eventualSuccessFn = async () => {
return ++attemptCount < 2 ? Result.error(new Error(`Attempt ${attemptCount} failed`))
: Result.ok("eventual success");
};
const eventualSuccessResult = await retry(eventualSuccessFn, 3, { exponentialDelayBase: 0 });
expect(eventualSuccessResult).toEqual({ status: "ok", data: "eventual success", attempts: 2 });
// Test all attempts fail
const errors = [new Error("Error 1"), new Error("Error 2"), new Error("Error 3")];
const allFailFn = async (attempt: number) => {
return Result.error(errors[attempt]);
};
const allFailResult = await retry(allFailFn, 3, { exponentialDelayBase: 0 });
expect(allFailResult).toEqual({ status: "error", error: expect.any(RetryError), attempts: 3 });
const retryError = (allFailResult as any).error as RetryError;
expect(retryError.errors).toEqual(errors);
expect(retryError.attempts).toBe(3);
});