@evolu/common 6.0.1-preview.2 → 6.0.1-preview.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/dist/src/Assert.d.ts +6 -3
  2. package/dist/src/Assert.d.ts.map +1 -1
  3. package/dist/src/Assert.js +7 -4
  4. package/dist/src/Brand.d.ts +75 -0
  5. package/dist/src/Brand.d.ts.map +1 -0
  6. package/dist/src/Brand.js +1 -0
  7. package/dist/src/Buffer.d.ts +1 -1
  8. package/dist/src/Buffer.d.ts.map +1 -1
  9. package/dist/src/Buffer.js +1 -1
  10. package/dist/src/CallbackRegistry.d.ts +53 -0
  11. package/dist/src/CallbackRegistry.d.ts.map +1 -0
  12. package/dist/src/CallbackRegistry.js +25 -0
  13. package/dist/src/Console.d.ts +31 -6
  14. package/dist/src/Console.d.ts.map +1 -1
  15. package/dist/src/Console.js +72 -9
  16. package/dist/src/Crypto.d.ts +61 -34
  17. package/dist/src/Crypto.d.ts.map +1 -1
  18. package/dist/src/Crypto.js +29 -42
  19. package/dist/src/Evolu/Db.d.ts +159 -66
  20. package/dist/src/Evolu/Db.d.ts.map +1 -1
  21. package/dist/src/Evolu/Db.js +300 -705
  22. package/dist/src/Evolu/Diff.d.ts +3 -3
  23. package/dist/src/Evolu/Diff.d.ts.map +1 -1
  24. package/dist/src/Evolu/Diff.js +7 -5
  25. package/dist/src/Evolu/Evolu.d.ts +200 -115
  26. package/dist/src/Evolu/Evolu.d.ts.map +1 -1
  27. package/dist/src/Evolu/Evolu.js +287 -157
  28. package/dist/src/Evolu/Internal.d.ts +0 -2
  29. package/dist/src/Evolu/Internal.d.ts.map +1 -1
  30. package/dist/src/Evolu/Internal.js +0 -2
  31. package/dist/src/Evolu/LocalAuth.d.ts +144 -0
  32. package/dist/src/Evolu/LocalAuth.d.ts.map +1 -0
  33. package/dist/src/Evolu/LocalAuth.js +171 -0
  34. package/dist/src/Evolu/Owner.d.ts +209 -124
  35. package/dist/src/Evolu/Owner.d.ts.map +1 -1
  36. package/dist/src/Evolu/Owner.js +118 -104
  37. package/dist/src/Evolu/Platform.d.ts +9 -7
  38. package/dist/src/Evolu/Platform.d.ts.map +1 -1
  39. package/dist/src/Evolu/Protocol.d.ts +256 -211
  40. package/dist/src/Evolu/Protocol.d.ts.map +1 -1
  41. package/dist/src/Evolu/Protocol.js +558 -359
  42. package/dist/src/Evolu/Public.d.ts +6 -8
  43. package/dist/src/Evolu/Public.d.ts.map +1 -1
  44. package/dist/src/Evolu/Public.js +2 -3
  45. package/dist/src/Evolu/PublicKysely.js +3 -3
  46. package/dist/src/Evolu/Query.d.ts +2 -1
  47. package/dist/src/Evolu/Query.d.ts.map +1 -1
  48. package/dist/src/Evolu/Relay.d.ts +72 -4
  49. package/dist/src/Evolu/Relay.d.ts.map +1 -1
  50. package/dist/src/Evolu/Relay.js +124 -13
  51. package/dist/src/Evolu/Schema.d.ts +129 -73
  52. package/dist/src/Evolu/Schema.d.ts.map +1 -1
  53. package/dist/src/Evolu/Schema.js +169 -89
  54. package/dist/src/Evolu/Storage.d.ts +159 -14
  55. package/dist/src/Evolu/Storage.d.ts.map +1 -1
  56. package/dist/src/Evolu/Storage.js +42 -32
  57. package/dist/src/Evolu/Sync.d.ts +68 -13
  58. package/dist/src/Evolu/Sync.d.ts.map +1 -1
  59. package/dist/src/Evolu/Sync.js +414 -20
  60. package/dist/src/Evolu/Timestamp.d.ts +35 -27
  61. package/dist/src/Evolu/Timestamp.d.ts.map +1 -1
  62. package/dist/src/Evolu/Timestamp.js +27 -18
  63. package/dist/src/ManyToManyMap.d.ts +74 -10
  64. package/dist/src/ManyToManyMap.d.ts.map +1 -1
  65. package/dist/src/ManyToManyMap.js +41 -6
  66. package/dist/src/Number.d.ts +2 -1
  67. package/dist/src/Number.d.ts.map +1 -1
  68. package/dist/src/Random.d.ts +3 -2
  69. package/dist/src/Random.d.ts.map +1 -1
  70. package/dist/src/RefCountedResourceManager.d.ts +119 -0
  71. package/dist/src/RefCountedResourceManager.d.ts.map +1 -0
  72. package/dist/src/RefCountedResourceManager.js +197 -0
  73. package/dist/src/Result.d.ts +176 -51
  74. package/dist/src/Result.d.ts.map +1 -1
  75. package/dist/src/Result.js +30 -241
  76. package/dist/src/Sqlite.d.ts +21 -4
  77. package/dist/src/Sqlite.d.ts.map +1 -1
  78. package/dist/src/Sqlite.js +50 -8
  79. package/dist/src/Task.d.ts +511 -0
  80. package/dist/src/Task.d.ts.map +1 -0
  81. package/dist/src/Task.js +410 -0
  82. package/dist/src/Time.d.ts +59 -0
  83. package/dist/src/Time.d.ts.map +1 -1
  84. package/dist/src/Time.js +87 -4
  85. package/dist/src/Type.d.ts +474 -327
  86. package/dist/src/Type.d.ts.map +1 -1
  87. package/dist/src/Type.js +502 -436
  88. package/dist/src/Types.d.ts +0 -74
  89. package/dist/src/Types.d.ts.map +1 -1
  90. package/dist/src/WebSocket.d.ts +5 -2
  91. package/dist/src/WebSocket.d.ts.map +1 -1
  92. package/dist/src/WebSocket.js +12 -13
  93. package/dist/src/Worker.d.ts +39 -11
  94. package/dist/src/Worker.d.ts.map +1 -1
  95. package/dist/src/Worker.js +22 -4
  96. package/dist/src/index.d.ts +3 -3
  97. package/dist/src/index.d.ts.map +1 -1
  98. package/dist/src/index.js +3 -3
  99. package/package.json +14 -13
  100. package/src/Assert.ts +8 -7
  101. package/src/Brand.ts +75 -0
  102. package/src/Buffer.ts +1 -1
  103. package/src/CallbackRegistry.ts +84 -0
  104. package/src/Console.ts +91 -11
  105. package/src/Crypto.ts +94 -79
  106. package/src/Evolu/Db.ts +528 -1027
  107. package/src/Evolu/Diff.ts +7 -5
  108. package/src/Evolu/Evolu.ts +682 -329
  109. package/src/Evolu/Internal.ts +0 -2
  110. package/src/Evolu/LocalAuth.ts +422 -0
  111. package/src/Evolu/Owner.ts +282 -227
  112. package/src/Evolu/Platform.ts +9 -9
  113. package/src/Evolu/Protocol.ts +788 -640
  114. package/src/Evolu/Public.ts +7 -14
  115. package/src/Evolu/PublicKysely.ts +3 -3
  116. package/src/Evolu/Query.ts +2 -1
  117. package/src/Evolu/Relay.ts +238 -18
  118. package/src/Evolu/Schema.ts +391 -191
  119. package/src/Evolu/Storage.ts +275 -55
  120. package/src/Evolu/Sync.ts +708 -37
  121. package/src/Evolu/Timestamp.ts +38 -35
  122. package/src/ManyToManyMap.ts +127 -24
  123. package/src/Number.ts +2 -6
  124. package/src/Random.ts +3 -2
  125. package/src/RefCountedResourceManager.ts +368 -0
  126. package/src/Result.ts +183 -53
  127. package/src/Sqlite.ts +59 -23
  128. package/src/Task.ts +779 -0
  129. package/src/Time.ts +168 -4
  130. package/src/Type.ts +708 -660
  131. package/src/Types.ts +0 -76
  132. package/src/WebSocket.ts +23 -17
  133. package/src/Worker.ts +72 -23
  134. package/src/index.ts +3 -3
  135. package/dist/src/Callbacks.d.ts +0 -20
  136. package/dist/src/Callbacks.d.ts.map +0 -1
  137. package/dist/src/Callbacks.js +0 -18
  138. package/dist/src/Evolu/Config.d.ts +0 -69
  139. package/dist/src/Evolu/Config.d.ts.map +0 -1
  140. package/dist/src/Evolu/Config.js +0 -9
  141. package/dist/src/Evolu/Kysely.d.ts +0 -6
  142. package/dist/src/Evolu/Kysely.d.ts.map +0 -1
  143. package/dist/src/Evolu/Kysely.js +0 -21
  144. package/dist/src/NanoId.d.ts +0 -27
  145. package/dist/src/NanoId.d.ts.map +0 -1
  146. package/dist/src/NanoId.js +0 -6
  147. package/dist/src/Promise.d.ts +0 -180
  148. package/dist/src/Promise.d.ts.map +0 -1
  149. package/dist/src/Promise.js +0 -176
  150. package/src/Callbacks.ts +0 -43
  151. package/src/Evolu/Config.ts +0 -83
  152. package/src/Evolu/Kysely.ts +0 -38
  153. package/src/NanoId.ts +0 -39
  154. package/src/Promise.ts +0 -295
package/src/Task.ts ADDED
@@ -0,0 +1,779 @@
1
+ /**
2
+ * ⚡ Lazy, cancellable Promise that returns Result instead of throwing
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { isNonEmptyArray, shiftArray } from "./Array.js";
8
+ import { Result, err, ok } from "./Result.js";
9
+ import { Duration, durationToNonNegativeInt } from "./Time.js";
10
+ import { NonNegativeInt, PositiveInt } from "./Type.js";
11
+
12
+ /**
13
+ * `Task` is a lazy, cancellable Promise that returns {@link Result} instead of
14
+ * throwing.
15
+ *
16
+ * In other words, Task is a function that creates a Promise when it's called.
17
+ * This laziness allows safe composition, e.g. retry logic because it prevents
18
+ * eager execution.
19
+ *
20
+ * ### Cancellation
21
+ *
22
+ * Tasks support optional cancellation via signal in {@link TaskContext}. When a
23
+ * Task is called without a signal, it cannot be cancelled and {@link AbortError}
24
+ * will never be returned. When called with a signal, the Task can be cancelled
25
+ * and AbortError is added to the error union with precise type safety.
26
+ *
27
+ * When composing Tasks, we typically have context and want to abort ASAP by
28
+ * passing it through. However, there are valid cases where we don't want to
29
+ * abort because we need some atomic unit to complete. For simple scripts and
30
+ * tests, omitting context is fine.
31
+ *
32
+ * ### Task Helpers
33
+ *
34
+ * - {@link toTask} - Convert async function to Task
35
+ * - {@link wait} - Delay execution for a specified {@link Duration}
36
+ * - {@link timeout} - Add timeout to any Task
37
+ * - {@link retry} - Retry failed Tasks with configurable backoff
38
+ *
39
+ * ### Example
40
+ *
41
+ * ```ts
42
+ * interface FetchError {
43
+ * readonly type: "FetchError";
44
+ * readonly error: unknown;
45
+ * }
46
+ *
47
+ * // Task version of fetch with proper error handling and cancellation support.
48
+ * const fetch = (url: string) =>
49
+ * toTask((context) =>
50
+ * tryAsync(
51
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
52
+ * (error): FetchError => ({ type: "FetchError", error }),
53
+ * ),
54
+ * );
55
+ *
56
+ * // `satisfies` shows the expected type signature.
57
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
58
+ *
59
+ * // Add timeout to prevent hanging
60
+ * const fetchWithTimeout = (url: string) => timeout("30s", fetch(url));
61
+ *
62
+ * fetchWithTimeout satisfies (
63
+ * url: string,
64
+ * ) => Task<Response, TimeoutError | FetchError>;
65
+ *
66
+ * // Add retry for resilience
67
+ * const fetchWithRetry = (url: string) =>
68
+ * retry(
69
+ * {
70
+ * retries: PositiveInt.orThrow(3),
71
+ * initialDelay: "100ms",
72
+ * },
73
+ * fetchWithTimeout(url),
74
+ * );
75
+ *
76
+ * fetchWithRetry satisfies (
77
+ * url: string,
78
+ * ) => Task<
79
+ * Response,
80
+ * TimeoutError | FetchError | RetryError<TimeoutError | FetchError>
81
+ * >;
82
+ *
83
+ * const semaphore = createSemaphore(PositiveInt.orThrow(2));
84
+ *
85
+ * // Control concurrency with semaphore
86
+ * const fetchWithPermit = (url: string) =>
87
+ * semaphore.withPermit(fetchWithRetry(url));
88
+ *
89
+ * fetchWithPermit satisfies (url: string) => Task<
90
+ * Response,
91
+ * | TimeoutError
92
+ * | FetchError
93
+ * | AbortError // Semaphore dispose aborts Tasks
94
+ * | RetryError<TimeoutError | FetchError>
95
+ * >;
96
+ *
97
+ * // Usage
98
+ * const results = await Promise.all(
99
+ * [
100
+ * "https://api.example.com/users",
101
+ * "https://api.example.com/posts",
102
+ * "https://api.example.com/comments",
103
+ * ]
104
+ * .map(fetchWithPermit)
105
+ * .map((task) => task()),
106
+ * );
107
+ *
108
+ * results satisfies Array<
109
+ * Result<
110
+ * Response,
111
+ * | AbortError
112
+ * | TimeoutError
113
+ * | FetchError
114
+ * | RetryError<TimeoutError | FetchError>
115
+ * >
116
+ * >;
117
+ *
118
+ * // Handle results
119
+ * for (const result of results) {
120
+ * if (result.ok) {
121
+ * // Process successful response
122
+ * const response = result.value;
123
+ * expect(response).toBeInstanceOf(Response);
124
+ * } else {
125
+ * // Handle error (TimeoutError, FetchError, RetryError, or AbortError)
126
+ * expect(result.error).toBeDefined();
127
+ * }
128
+ * }
129
+ *
130
+ * // Cancellation support
131
+ * const controller = new AbortController();
132
+ * const cancelableTask = fetchWithPermit("https://api.example.com/data");
133
+ *
134
+ * // Start task
135
+ * const promise = cancelableTask(controller);
136
+ *
137
+ * // Cancel after some time
138
+ * setTimeout(() => {
139
+ * controller.abort("User cancelled");
140
+ * }, 1000);
141
+ *
142
+ * const _result = await promise;
143
+ * // Result will be AbortError if cancelled
144
+ * ```
145
+ *
146
+ * ### Dependency Injection Integration
147
+ *
148
+ * Tasks integrate naturally with Evolu's DI pattern. Use `deps` for static
149
+ * dependencies and `TaskContext` for execution context like cancellation. Usage
150
+ * follows the pattern: deps → arguments → execution context.
151
+ */
152
+ export interface Task<T, E> {
153
+ /**
154
+ * Invoke the Task.
155
+ *
156
+ * Provide a context with an AbortSignal to enable cancellation. When called
157
+ * without a signal, {@link AbortError} cannot occur and the error type narrows
158
+ * accordingly.
159
+ *
160
+ * ### Example
161
+ *
162
+ * ```ts
163
+ * interface FetchError {
164
+ * readonly type: "FetchError";
165
+ * readonly error: unknown;
166
+ * }
167
+ *
168
+ * // Task version of fetch with proper error handling and cancellation support.
169
+ * const fetch = (url: string) =>
170
+ * toTask((context) =>
171
+ * tryAsync(
172
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
173
+ * (error): FetchError => ({ type: "FetchError", error }),
174
+ * ),
175
+ * );
176
+ *
177
+ * // `satisfies` shows the expected type signature.
178
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
179
+ *
180
+ * const result1 = await fetch("https://api.example.com/data")();
181
+ * expectTypeOf(result1).toEqualTypeOf<Result<Response, FetchError>>();
182
+ *
183
+ * // With AbortController
184
+ * const controller = new AbortController();
185
+ * const result2 = await fetch("https://api.example.com/data")(
186
+ * controller,
187
+ * );
188
+ * expectTypeOf(result2).toEqualTypeOf<
189
+ * Result<Response, FetchError | AbortError>
190
+ * >();
191
+ * ```
192
+ */
193
+ // eslint-disable-next-line @typescript-eslint/prefer-function-type
194
+ <TContext extends TaskContext | undefined = undefined>(
195
+ context?: TContext,
196
+ ): Promise<
197
+ Result<T, TContext extends { signal: AbortSignal } ? E | AbortError : E>
198
+ >;
199
+ }
200
+
201
+ /** Context passed to {@link Task}s for cancellation. */
202
+ export interface TaskContext {
203
+ /** Signal for cancellation */
204
+ readonly signal?: AbortSignal;
205
+ }
206
+
207
+ /** Error returned when a {@link Task} is cancelled via AbortSignal. */
208
+ export interface AbortError {
209
+ readonly type: "AbortError";
210
+ readonly reason?: unknown;
211
+ }
212
+
213
+ /** Narrower check to detect AbortError objects at runtime. */
214
+ const isAbortError = (error: unknown): error is AbortError =>
215
+ typeof error === "object" &&
216
+ error !== null &&
217
+ (error as { type?: unknown }).type === "AbortError";
218
+
219
+ /**
220
+ * Combines user signal from context with an internal signal.
221
+ *
222
+ * If the context has a signal, combines both signals using AbortSignal.any().
223
+ * Otherwise, returns just the internal signal.
224
+ */
225
+ const combineSignal = (
226
+ context: TaskContext | undefined,
227
+ internalSignal: AbortSignal,
228
+ ): AbortSignal =>
229
+ context?.signal
230
+ ? AbortSignal.any([context.signal, internalSignal])
231
+ : internalSignal;
232
+
233
+ /**
234
+ * Converts async function returning {@link Result} to a {@link Task}.
235
+ *
236
+ * ### Example
237
+ *
238
+ * ```ts
239
+ * interface FetchError {
240
+ * readonly type: "FetchError";
241
+ * readonly error: unknown;
242
+ * }
243
+ *
244
+ * // Task version of fetch with proper error handling and cancellation support.
245
+ * const fetch = (url: string) =>
246
+ * toTask((context) =>
247
+ * tryAsync(
248
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
249
+ * (error): FetchError => ({ type: "FetchError", error }),
250
+ * ),
251
+ * );
252
+ *
253
+ * // `satisfies` shows the expected type signature.
254
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
255
+ *
256
+ * const result1 = await fetch("https://api.example.com/data")();
257
+ * result1 satisfies Result<Response, FetchError>;
258
+ *
259
+ * // With AbortController
260
+ * const controller = new AbortController();
261
+ * const result2 = await fetch("https://api.example.com/data")(controller);
262
+ * result2 satisfies Result<Response, FetchError | AbortError>;
263
+ * ```
264
+ */
265
+ export const toTask = <T, E>(
266
+ fn: (context?: TaskContext) => Promise<Result<T, E>>,
267
+ ): Task<T, E> =>
268
+ // Note: Not using async to avoid Promise wrapper overhead in fast path
269
+ ((context) => {
270
+ const signal = context?.signal;
271
+
272
+ // Fast path when no signal – return promise directly
273
+ if (!signal) {
274
+ // Preserve future context fields (e.g., tracing) even without a signal
275
+ return fn(context);
276
+ }
277
+
278
+ if (signal.aborted) {
279
+ return Promise.resolve(
280
+ err({ type: "AbortError", reason: signal.reason as unknown }),
281
+ );
282
+ }
283
+
284
+ // Use Promise.withResolvers for clean abort handling and cleanup
285
+ const { promise: abortPromise, resolve: resolveAbort } =
286
+ Promise.withResolvers<Result<never, AbortError>>();
287
+
288
+ const handleAbort = () => {
289
+ resolveAbort(
290
+ err({ type: "AbortError", reason: signal.reason as unknown }),
291
+ );
292
+ };
293
+
294
+ signal.addEventListener("abort", handleAbort, { once: true });
295
+
296
+ // No finally: we expect no throws in normal flow; Result path removes listener.
297
+ // Unexpected throws indicate a bug and are allowed to crash (no recovery here).
298
+ return Promise.race([
299
+ abortPromise,
300
+ fn(context).then((result) => {
301
+ signal.removeEventListener("abort", handleAbort);
302
+ return result;
303
+ }),
304
+ ]);
305
+ }) as Task<T, E>;
306
+
307
+ /**
308
+ * Creates a {@link Task} that waits for the specified duration.
309
+ *
310
+ * ### Example
311
+ *
312
+ * ```ts
313
+ * const result1 = await wait("10ms")();
314
+ * result1 satisfies Result<void, never>;
315
+ *
316
+ * // With AbortController
317
+ * const controller = new AbortController();
318
+ * const result2 = await wait("10ms")(controller);
319
+ * result2 satisfies Result<void, AbortError>;
320
+ * ```
321
+ */
322
+ export const wait = (duration: Duration): Task<void, never> =>
323
+ toTask(
324
+ (context) =>
325
+ new Promise<Result<void, never>>((resolve) => {
326
+ const ms = durationToNonNegativeInt(duration);
327
+ const timeoutSignal = AbortSignal.timeout(ms);
328
+
329
+ const signal = combineSignal(context, timeoutSignal);
330
+
331
+ // Listen for abort - either from timeout completion or external abort
332
+ signal.addEventListener(
333
+ "abort",
334
+ () => {
335
+ resolve(ok());
336
+ },
337
+ { once: true },
338
+ );
339
+ }),
340
+ );
341
+
342
+ /** Error returned when {@link timeout} exceeds the specified duration. */
343
+ export interface TimeoutError {
344
+ readonly type: "TimeoutError";
345
+ readonly timeoutMs: number;
346
+ }
347
+
348
+ /**
349
+ * Adds timeout behavior to a {@link Task}.
350
+ *
351
+ * ### Example
352
+ *
353
+ * ```ts
354
+ * interface FetchError {
355
+ * readonly type: "FetchError";
356
+ * readonly error: unknown;
357
+ * }
358
+ *
359
+ * // Task version of fetch with proper error handling and cancellation support.
360
+ * const fetch = (url: string) =>
361
+ * toTask((context) =>
362
+ * tryAsync(
363
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
364
+ * (error): FetchError => ({ type: "FetchError", error }),
365
+ * ),
366
+ * );
367
+ *
368
+ * // `satisfies` shows the expected type signature.
369
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
370
+ *
371
+ * const fetchWithTimeout = (url: string) => timeout("2m", fetch(url));
372
+ *
373
+ * const result1 = await fetchWithTimeout("https://api.example.com/data")();
374
+ * result1 satisfies Result<Response, FetchError | TimeoutError>;
375
+ *
376
+ * // With AbortController
377
+ * const controller = new AbortController();
378
+ * const result2 = await fetchWithTimeout("https://api.example.com/data")(
379
+ * controller,
380
+ * );
381
+ * result2 satisfies Result<
382
+ * Response,
383
+ * FetchError | TimeoutError | AbortError
384
+ * >;
385
+ * ```
386
+ */
387
+ export const timeout = <T, E>(
388
+ duration: Duration,
389
+ task: Task<T, E>,
390
+ ): Task<T, E | TimeoutError> =>
391
+ toTask(async (context) => {
392
+ const timeoutMs = durationToNonNegativeInt(duration);
393
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
394
+
395
+ const signal = combineSignal(context, timeoutSignal);
396
+
397
+ const result = await task({ signal });
398
+
399
+ if (timeoutSignal.aborted) {
400
+ return err({ type: "TimeoutError", timeoutMs });
401
+ }
402
+
403
+ return result as Result<T, E | TimeoutError>;
404
+ });
405
+
406
+ /** Options for configuring {@link retry} behavior. */
407
+ export interface RetryOptions<E> {
408
+ /** Number of retry attempts after the initial failure. */
409
+ readonly retries: PositiveInt;
410
+
411
+ /**
412
+ * Initial delay for exponential backoff (1st retry uses this, 2nd uses
413
+ * this×factor, 3rd uses this×factor², etc.). Actual delays are randomized by
414
+ * {@link RetryOptions.jitter}.
415
+ */
416
+ readonly initialDelay?: Duration;
417
+
418
+ /** Maximum delay between retries. */
419
+ readonly maxDelay?: Duration;
420
+
421
+ /** Exponential backoff multiplier. */
422
+ readonly factor?: number;
423
+
424
+ /** Random jitter factor (0-1) to prevent thundering herd. */
425
+ readonly jitter?: number;
426
+
427
+ /**
428
+ * Predicate to determine if error should trigger retry. Receives AbortError
429
+ * too.
430
+ */
431
+ readonly retryable?: (error: E | AbortError) => boolean;
432
+
433
+ /** Callback invoked before each retry attempt. */
434
+ readonly onRetry?: (error: E, attempt: number, delay: number) => void;
435
+ }
436
+
437
+ /** Error returned when {@link retry} exhausts all retry attempts. */
438
+ export interface RetryError<E> {
439
+ readonly type: "RetryError";
440
+ readonly cause: E;
441
+ readonly attempts: number;
442
+ }
443
+
444
+ /**
445
+ * Adds retry logic with exponential backoff and jitter to a {@link Task}.
446
+ *
447
+ * ### Example
448
+ *
449
+ * ```ts
450
+ * interface FetchError {
451
+ * readonly type: "FetchError";
452
+ * readonly error: unknown;
453
+ * }
454
+ *
455
+ * // Task version of fetch with proper error handling and cancellation support.
456
+ * const fetch = (url: string) =>
457
+ * toTask((context) =>
458
+ * tryAsync(
459
+ * () => globalThis.fetch(url, { signal: context?.signal ?? null }),
460
+ * (error): FetchError => ({ type: "FetchError", error }),
461
+ * ),
462
+ * );
463
+ *
464
+ * // `satisfies` shows the expected type signature.
465
+ * fetch satisfies (url: string) => Task<Response, FetchError>;
466
+ *
467
+ * const fetchWithRetry = (url: string) =>
468
+ * retry({ retries: PositiveInt.orThrow(3) }, fetch(url));
469
+ *
470
+ * const result1 = await fetchWithRetry("https://api.example.com/data")();
471
+ * result1 satisfies Result<Response, FetchError | RetryError<FetchError>>;
472
+ *
473
+ * // With AbortController
474
+ * const controller = new AbortController();
475
+ * const result2 = await fetchWithRetry("https://api.example.com/data")(
476
+ * controller,
477
+ * );
478
+ * result2 satisfies Result<
479
+ * Response,
480
+ * FetchError | RetryError<FetchError> | AbortError
481
+ * >;
482
+ * ```
483
+ */
484
+ export const retry = <T, E>(
485
+ {
486
+ retries,
487
+ initialDelay = "1s",
488
+ maxDelay = "30s",
489
+ factor = 2,
490
+ jitter = 0.5,
491
+ retryable = (error: E | AbortError) => !isAbortError(error),
492
+ onRetry,
493
+ }: RetryOptions<E>,
494
+ task: Task<T, E>,
495
+ ): Task<T, E | RetryError<E>> =>
496
+ toTask(async (context): Promise<Result<T, E | RetryError<E>>> => {
497
+ const initialDelayMs = durationToNonNegativeInt(initialDelay);
498
+ const maxDelayMs = durationToNonNegativeInt(maxDelay);
499
+ const maxRetries = PositiveInt.orThrow(retries);
500
+
501
+ let attempt = 0;
502
+
503
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
504
+ while (true) {
505
+ const result = await task(context);
506
+
507
+ if (result.ok) {
508
+ return result;
509
+ }
510
+
511
+ // Never retry on AbortError; propagate it directly
512
+ if (isAbortError(result.error)) {
513
+ return err(result.error) as Result<T, E | RetryError<E>>;
514
+ }
515
+
516
+ attempt += 1;
517
+
518
+ if (attempt > maxRetries || !retryable(result.error)) {
519
+ return err({
520
+ type: "RetryError",
521
+ cause: result.error,
522
+ attempts: attempt,
523
+ });
524
+ }
525
+
526
+ // Calculate delay with exponential backoff
527
+ const exponentialDelay = initialDelayMs * Math.pow(factor, attempt - 1);
528
+ const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
529
+
530
+ // Apply jitter to prevent thundering herd problem
531
+ const randomFactor = 1 - jitter + Math.random() * jitter * 2;
532
+ const delay = Math.floor(cappedDelay * randomFactor);
533
+
534
+ if (onRetry) {
535
+ onRetry(result.error, attempt, delay);
536
+ }
537
+
538
+ // Wait before retry
539
+ const delayResult = await wait(delay as NonNegativeInt)(context);
540
+ if (!delayResult.ok) {
541
+ // If delay was aborted, return AbortError (will be handled by toTask)
542
+ return delayResult;
543
+ }
544
+ }
545
+ });
546
+
547
+ /**
548
+ * A semaphore that limits the number of concurrent async Tasks.
549
+ *
550
+ * For mutual exclusion (limiting to exactly one Task), consider using
551
+ * {@link Mutex} instead.
552
+ *
553
+ * @see {@link createSemaphore} to create a semaphore instance.
554
+ */
555
+ export interface Semaphore extends Disposable {
556
+ /**
557
+ * Executes a Task while holding a semaphore permit.
558
+ *
559
+ * The Task will wait until a permit is available before executing. Supports
560
+ * cancellation via AbortSignal - if the signal is aborted while waiting for a
561
+ * permit or during execution, the Task is cancelled and permits are properly
562
+ * released.
563
+ */
564
+ readonly withPermit: <T, E>(task: Task<T, E>) => Task<T, E | AbortError>;
565
+ }
566
+
567
+ /**
568
+ * Creates a semaphore that limits concurrent async Tasks to the specified
569
+ * count.
570
+ *
571
+ * A semaphore controls access to a resource by maintaining a count of available
572
+ * permits. Tasks acquire a permit before executing and release it when
573
+ * complete.
574
+ *
575
+ * For mutual exclusion (exactly one Task at a time), consider using
576
+ * {@link createMutex} instead.
577
+ *
578
+ * ### Example
579
+ *
580
+ * ```ts
581
+ * // Allow maximum 3 concurrent Tasks
582
+ * const semaphore = createSemaphore(PositiveInt.orThrow(3));
583
+ *
584
+ * let currentConcurrent = 0;
585
+ * const events: Array<string> = [];
586
+ *
587
+ * const fetchData = (id: number) =>
588
+ * toTask<number, never>(async (context) => {
589
+ * currentConcurrent++;
590
+ * events.push(`start ${id} (concurrent: ${currentConcurrent})`);
591
+ *
592
+ * await wait("10ms")(context);
593
+ *
594
+ * currentConcurrent--;
595
+ * events.push(`end ${id} (concurrent: ${currentConcurrent})`);
596
+ * return ok(id * 10);
597
+ * });
598
+ *
599
+ * // These will execute with at most 3 running concurrently
600
+ * const results = await Promise.all([
601
+ * semaphore.withPermit(fetchData(1))(),
602
+ * semaphore.withPermit(fetchData(2))(),
603
+ * semaphore.withPermit(fetchData(3))(),
604
+ * semaphore.withPermit(fetchData(4))(), // waits for one above to complete
605
+ * semaphore.withPermit(fetchData(5))(), // waits for permit
606
+ * ]);
607
+ *
608
+ * expect(results.map(getOrThrow)).toEqual([10, 20, 30, 40, 50]);
609
+ * expect(events).toMatchInlineSnapshot(`
610
+ * [
611
+ * "start 1 (concurrent: 1)",
612
+ * "start 2 (concurrent: 2)",
613
+ * "start 3 (concurrent: 3)",
614
+ * "end 1 (concurrent: 2)",
615
+ * "start 4 (concurrent: 3)",
616
+ * "end 2 (concurrent: 2)",
617
+ * "start 5 (concurrent: 3)",
618
+ * "end 3 (concurrent: 2)",
619
+ * "end 4 (concurrent: 1)",
620
+ * "end 5 (concurrent: 0)",
621
+ * ]
622
+ * `);
623
+ * ```
624
+ */
625
+ export const createSemaphore = (maxConcurrent: PositiveInt): Semaphore => {
626
+ let isDisposed = false;
627
+ let availablePermits = maxConcurrent;
628
+ const waitingQueue: Array<() => void> = [];
629
+ const semaphoreController = new AbortController();
630
+
631
+ const acquire = (): Promise<void> => {
632
+ if (availablePermits > 0) {
633
+ availablePermits--;
634
+ return Promise.resolve();
635
+ }
636
+
637
+ return new Promise<void>((resolve) => {
638
+ waitingQueue.push(resolve);
639
+ });
640
+ };
641
+
642
+ const release = (): void => {
643
+ if (isNonEmptyArray(waitingQueue)) {
644
+ shiftArray(waitingQueue)();
645
+ } else {
646
+ availablePermits++;
647
+ }
648
+ };
649
+
650
+ return {
651
+ withPermit: <T, E>(task: Task<T, E>): Task<T, E | AbortError> =>
652
+ toTask(async (context): Promise<Result<T, E | AbortError>> => {
653
+ await acquire();
654
+
655
+ // Check if semaphore was disposed while waiting
656
+ if (isDisposed) {
657
+ return err({
658
+ type: "AbortError",
659
+ reason: "Semaphore disposed",
660
+ });
661
+ }
662
+
663
+ const signal = combineSignal(context, semaphoreController.signal);
664
+
665
+ const result = await task({ signal });
666
+
667
+ release();
668
+
669
+ return result;
670
+ }),
671
+
672
+ [Symbol.dispose]: () => {
673
+ if (isDisposed) return;
674
+ isDisposed = true;
675
+
676
+ // Cancel all running and waiting tasks
677
+ semaphoreController.abort("Semaphore disposed");
678
+
679
+ // Release all waiting tasks so they can continue and check isDisposed
680
+ while (isNonEmptyArray(waitingQueue)) {
681
+ shiftArray(waitingQueue)();
682
+ }
683
+ },
684
+ };
685
+ };
686
+
687
+ /**
688
+ * A mutex (mutual exclusion) that ensures only one Task runs at a time.
689
+ *
690
+ * This is a specialized version of a {@link Semaphore} with a permit count of 1.
691
+ *
692
+ * @see {@link createMutex} to create a mutex instance.
693
+ */
694
+ export interface Mutex extends Disposable {
695
+ /**
696
+ * Executes a Task while holding the mutex lock.
697
+ *
698
+ * Only one Task can hold the lock at a time. Other Tasks will wait until the
699
+ * lock is released. Supports cancellation via AbortSignal.
700
+ */
701
+ readonly withLock: <T, E>(task: Task<T, E>) => Task<T, E | AbortError>;
702
+ }
703
+
704
+ /**
705
+ * Creates a new mutex for ensuring mutual exclusion.
706
+ *
707
+ * A mutex is a {@link createSemaphore} with exactly one permit, ensuring that
708
+ * only one Task can execute at a time.
709
+ *
710
+ * ### Example
711
+ *
712
+ * ```ts
713
+ * const mutex = createMutex();
714
+ *
715
+ * const updateTask = (id: number) =>
716
+ * toTask((context) =>
717
+ * tryAsync(
718
+ * () => updateSharedResource(id, context),
719
+ * (error): UpdateError => ({ type: "UpdateError", error }),
720
+ * ),
721
+ * );
722
+ *
723
+ * // These Tasks will execute one at a time
724
+ * const results = await Promise.all([
725
+ * mutex.withLock(updateTask(1))(),
726
+ * mutex.withLock(updateTask(2))(),
727
+ * mutex.withLock(updateTask(3))(),
728
+ * ]);
729
+ * ```
730
+ */
731
+ export const createMutex = (): Mutex => {
732
+ const mutex = createSemaphore(1 as PositiveInt);
733
+
734
+ return {
735
+ withLock: mutex.withPermit,
736
+ [Symbol.dispose]: mutex[Symbol.dispose],
737
+ };
738
+ };
739
+
740
+ // TODO: Add tracing support
741
+ // - Extend TaskContext with optional tracing field
742
+ // - Add traced(name, task) helper that wraps Task execution
743
+ // - Collect span data (name, timing, parent-child relationships, status)
744
+ // - Support OpenTelemetry export format with proper traceId/spanId generation
745
+ // - Automatic parent-child span relationships through context propagation
746
+
747
+ /**
748
+ * Schedule a task to run after all interactions (animations, gestures,
749
+ * navigation) have completed.
750
+ *
751
+ * This uses `requestIdleCallback` when available, otherwise falls back to
752
+ * `setTimeout(0)` for cross-platform compatibility.
753
+ *
754
+ * ### Example
755
+ *
756
+ * ```ts
757
+ * const processDataTask: Task<void, ProcessError> = toTask(async () => {
758
+ * // Heavy processing work
759
+ * return ok();
760
+ * });
761
+ *
762
+ * // Schedule the task to run when idle
763
+ * void requestIdleTask(processDataTask)();
764
+ * ```
765
+ */
766
+ export const requestIdleTask = <T, E>(task: Task<T, E>): Task<T, E> =>
767
+ toTask(
768
+ async (context?: TaskContext) =>
769
+ new Promise<Result<T, E>>((resolve) => {
770
+ idleCallback(() => {
771
+ void task(context).then(resolve);
772
+ });
773
+ }),
774
+ );
775
+
776
+ const idleCallback: (callback: () => void) => void =
777
+ typeof globalThis.requestIdleCallback === "function"
778
+ ? globalThis.requestIdleCallback
779
+ : (callback) => setTimeout(callback, 0);