@openstage/monadyssey-core 3.0.0-rc.2 → 3.0.0-rc.3

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.
@@ -2,10 +2,20 @@ export declare interface Cancelled {
2
2
  readonly type: "Cancelled";
3
3
  }
4
4
 
5
+ /** How many items `parTraverse` / `parSequence` run at once. */
6
+ declare interface Concurrency {
7
+ /** At most this many items run at once: a positive integer, or `Infinity` (the default). */
8
+ readonly concurrency?: number;
9
+ }
10
+
5
11
  /**
6
- * Represents a type which is either a Left (failure) or a Right (success).
7
- * Left typically stores an error or failure state, while Right stores a success value.
12
+ * A run that ended with a defect: an exception that was not declared as an `E`. It carries no
13
+ * exception; the defect itself still reaches `unsafeRun()` / `join()`.
8
14
  */
15
+ export declare interface Defect {
16
+ readonly type: "Defect";
17
+ }
18
+
9
19
  export declare abstract class Either<A, B> {
10
20
  abstract readonly type: "Left" | "Right";
11
21
  /**
@@ -139,6 +149,46 @@ export declare abstract class Either<A, B> {
139
149
  * Left.of('Error').tapLeft(err => console.log(err)); // Logs "Error"
140
150
  */
141
151
  abstract tapLeft(action: (left: A) => void): Either<A, B>;
152
+ /**
153
+ * Applicative combine of independent `Either`s ("applicative for"): collects *every* `Left`
154
+ * into a `NonEmptyList`, in argument order, instead of stopping at the first. When all are
155
+ * `Right`, the last argument combines their values (in argument order). Use it to validate
156
+ * several fields and report every failure at once; {@link forM} stops at the first `Left`.
157
+ *
158
+ * Each `Either` may have a different error type; the result's is `NonEmptyList<E1 | E2 | …>`.
159
+ *
160
+ * @example
161
+ * const form = Either.forA(
162
+ * required("name", input.name), // Either<FieldError, string>
163
+ * validEmail(input.email), // Either<FieldError, Email>
164
+ * (name, email) => ({ name, email })
165
+ * ); // Either<NonEmptyList<FieldError>, { name, email }>
166
+ */
167
+ static forA<E1, E2, A1, A2, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, f: (a1: A1, a2: A2) => R): Either<NonEmptyList<E1 | E2>, R>;
168
+ static forA<E1, E2, E3, A1, A2, A3, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, f: (a1: A1, a2: A2, a3: A3) => R): Either<NonEmptyList<E1 | E2 | E3>, R>;
169
+ static forA<E1, E2, E3, E4, A1, A2, A3, A4, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Either<NonEmptyList<E1 | E2 | E3 | E4>, R>;
170
+ static forA<E1, E2, E3, E4, E5, A1, A2, A3, A4, A5, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5>, R>;
171
+ static forA<E1, E2, E3, E4, E5, E6, A1, A2, A3, A4, A5, A6, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6>, R>;
172
+ static forA<E1, E2, E3, E4, E5, E6, E7, A1, A2, A3, A4, A5, A6, A7, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7>, R>;
173
+ static forA<E1, E2, E3, E4, E5, E6, E7, E8, A1, A2, A3, A4, A5, A6, A7, A8, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, e8: Either<E8, A8>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8>, R>;
174
+ static forA<E1, E2, E3, E4, E5, E6, E7, E8, E9, A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, e8: Either<E8, A8>, e9: Either<E9, A9>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9>, R>;
175
+ /**
176
+ * Monadic comprehension ("monadic for") over `Either`, synchronous. Inside `operation`,
177
+ * `bind(either)` returns the `Right` value; the first `Left` stops the body, and `forM` returns
178
+ * that `Left`. The body's return value becomes the `Right`. An exception that is not a `Left`
179
+ * is not caught: it propagates from `forM`. Use {@link forA} to collect every `Left` instead.
180
+ *
181
+ * `bind` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
182
+ * not handle, and the body must be synchronous.
183
+ *
184
+ * @example
185
+ * const total = Either.forM<ParseError, number>((bind) => {
186
+ * const price = bind(parsePrice(input.price));
187
+ * const quantity = bind(parseQuantity(input.quantity));
188
+ * return price * quantity;
189
+ * });
190
+ */
191
+ static forM<E, A>(operation: (bind: <B>(either: Either<E, B>) => B) => A & NotThenable): Either<E, A>;
142
192
  }
143
193
 
144
194
  /**
@@ -344,7 +394,8 @@ export declare class EvaluationError<E> extends Error {
344
394
 
345
395
  /**
346
396
  * The outcome of a run: a value, a typed error, or cancellation. A forked fiber's `join()` resolves to
347
- * an `Exit`; `unsafeRun()` cannot be cancelled from outside, so it yields `Ok<A> | Err<E>`.
397
+ * an `Exit`, and so does `unsafeRun({ signal })`; `unsafeRun()` without a signal cannot be cancelled
398
+ * from outside, so it yields `Ok<A> | Err<E>`.
348
399
  */
349
400
  export declare type Exit<E, A> = Ok<A> | Err<E> | Cancelled;
350
401
 
@@ -361,6 +412,19 @@ export declare interface Fiber<E, A> {
361
412
  readonly signal: AbortSignal;
362
413
  }
363
414
 
415
+ /** Options for {@link IO.fork} and {@link IO.forkDaemon}. */
416
+ export declare interface ForkOptions {
417
+ /**
418
+ * Receives the defect of the fiber when nobody joins it, right after the defect happens (one
419
+ * macrotask later), for `fork` and `forkDaemon` alike: the forking run keeps no record of the
420
+ * fiber, so a long-running run can fork any number of them. It is not called when the fiber is
421
+ * joined first (`join()` rejects with the defect as usual), nor for a typed error or a
422
+ * cancellation. A fiber joined after the handler was called still rejects `join()` with the
423
+ * defect. If the handler throws, that exception is reported as an unhandled rejection instead.
424
+ */
425
+ readonly onDefect?: (cause: unknown) => void;
426
+ }
427
+
364
428
  /**
365
429
  * `Ordering.GT` as a bare module constant.
366
430
  *
@@ -484,8 +548,8 @@ export declare class IO<E, A> {
484
548
  * Creates an IO from a function that receives an `AbortSignal` for cooperative cancellation.
485
549
  * Use this when the underlying operation supports cancellation (e.g., `fetch`, streams, timers).
486
550
  *
487
- * The signal is provided by the interpreter when the IO is forked. If the IO is run
488
- * without forking (via `unsafeRun`), the signal is never aborted.
551
+ * The signal is the run's: a fiber's, a `timeout`'s or `race`'s, or the one passed to
552
+ * `unsafeRun({ signal })`. Under a plain `unsafeRun()`, the signal is never aborted.
489
553
  *
490
554
  * On cancellation the interpreter does not wait for the returned promise: it runs the
491
555
  * finalizers and reports `Cancelled` straight away, and `f` is expected to stop its own work
@@ -517,9 +581,11 @@ export declare class IO<E, A> {
517
581
  * Semantics:
518
582
  * - If **acquire** fails, or is cancelled before producing a resource, `use` and `release` are
519
583
  * never called.
520
- * - **acquire** is never abandoned half-way: if cancellation arrives while it runs and it still
521
- * produces a resource, that resource is released and `Cancelled` is propagated. (A
522
- * cancellable acquire still sees the signal and may stop early.)
584
+ * - If cancellation arrives while **acquire** runs, the bracket ends as `Cancelled` at once,
585
+ * without waiting for it: a slow acquire cannot hold a cancellation or a timeout. A resource
586
+ * it still produces later is released as soon as it arrives, with `Cancelled` as the exit. (A
587
+ * cancellable acquire sees the signal and may stop early. To keep a step from being left
588
+ * behind, such as a commit, use {@link IO.uncancellable}.)
523
589
  * - If **use** succeeds, `release` runs and the success value is returned.
524
590
  * - If **use** fails, `release` runs and the original error is returned.
525
591
  * - If **use** is cancelled, `release` runs and `Cancelled` is propagated.
@@ -562,7 +628,34 @@ export declare class IO<E, A> {
562
628
  * (pool) => IO.promise(() => pool.shutdown())
563
629
  * ).mapErr(e => new AppError(e));
564
630
  */
565
- static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => IO<F, A>, release: (r: R) => IO<never, void>): IO<E | F, A>;
631
+ static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => IO<F, A>, release: (r: R, exit: ReleaseExit<F, A>) => IO<never, void>): IO<E | F, A>;
632
+ /**
633
+ * Runs `io` to its end even when the run is cancelled while it runs. The cancellation takes
634
+ * effect right after `io` ends: the run then ends as `Cancelled`, and `io`'s value or error is
635
+ * dropped. Use it for a step that must not be abandoned half-way, such as a database commit, an
636
+ * `fsync` after a rename, or acknowledging a message.
637
+ *
638
+ * - The effects inside never see an abort: the signal they receive does not abort while they run.
639
+ * - An enclosing `timeout` or a lost `race` waits for `io` to end before it settles.
640
+ * - A run that is already cancelled when it reaches this step does not start `io`.
641
+ * - A fiber forked inside is a child of the outer run, but the outer cancellation reaches it only
642
+ * when `io` ends, so `io` can still join it. After that, it is cancelled with the outer run like
643
+ * any other child. A `forkDaemon` fiber has no parent, here as anywhere else.
644
+ *
645
+ * Failures and defects of `io` pass through unchanged.
646
+ *
647
+ * @template E The error type of `io`.
648
+ * @template A The success type of `io`.
649
+ * @param {IO<E, A>} io The IO to protect from cancellation.
650
+ * @returns {IO<E, A>} An IO that runs `io` to its end.
651
+ *
652
+ * @example
653
+ * const transaction = (conn: Connection): IO<DbError, Order> =>
654
+ * insertOrder(conn).flatMap((order) =>
655
+ * IO.uncancellable(IO.lift(() => conn.commit(), toDbError)).map(() => order)
656
+ * );
657
+ */
658
+ static uncancellable<E, A>(io: IO<E, A>): IO<E, A>;
566
659
  /**
567
660
  * Lifts an already-computed value into IO with no side effect.
568
661
  * The value is available immediately — no deferred computation takes place.
@@ -740,8 +833,10 @@ export declare class IO<E, A> {
740
833
  * If this IO fails, the function is not called. The callback may be synchronous
741
834
  * or asynchronous — the interpreter awaits if it returns a Promise.
742
835
  *
743
- * If the side-effect throws, the exception is swallowed and the original success
744
- * value is preserved. Use `map` or `flatMap` if failure should propagate.
836
+ * If the side-effect throws or rejects, that is a **defect**, as a throw in `map` is: it is not
837
+ * an `E`, and `unsafeRun()` rejects with it. For a side effect that may fail and whose failure
838
+ * should be ignored, catch it inside the callback; for one whose failure is an `E`, use
839
+ * `flatMap` with an `IO.lift(f, liftE)`.
745
840
  *
746
841
  * @param {(a: A) => void | Promise<void>} f The side-effect function.
747
842
  * @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original result.
@@ -755,8 +850,9 @@ export declare class IO<E, A> {
755
850
  * If this IO succeeds, the function is not called. The callback may be synchronous
756
851
  * or asynchronous — the interpreter awaits if it returns a Promise.
757
852
  *
758
- * If the side-effect throws, the exception is swallowed and the original error
759
- * is preserved. Use `mapErr` or `flatMapErr` if failure should propagate.
853
+ * If the side-effect throws or rejects, that is a **defect**, as a throw in `mapErr` is: it does
854
+ * not replace the error, and `unsafeRun()` rejects with it. For a side effect that may fail and
855
+ * whose failure should be ignored, catch it inside the callback.
760
856
  *
761
857
  * @param {(e: E) => void | Promise<void>} f The side-effect function.
762
858
  * @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original error.
@@ -871,12 +967,26 @@ export declare class IO<E, A> {
871
967
  * exception from an effect or callback that was not declared fallible — with the original
872
968
  * exception, after cleanup has run; handle it with `.catch` at the edge of the program.
873
969
  *
970
+ * With a `signal`, aborting it cancels the run as cancelling a fiber does: effects receive the
971
+ * signal, an effect that ignores it is abandoned, finalizers and `bracket` releases run, forked
972
+ * child fibers are cancelled, and the promise resolves with `Cancelled` once that is done. A
973
+ * signal that has already aborted gives `Cancelled` without running anything.
974
+ *
874
975
  * @returns {Promise<Err<E> | Ok<A>>} The result of the computation.
875
976
  *
876
977
  * @example
877
978
  * const result = await IO.of(42).unsafeRun();
878
979
  * // result: { type: "Ok", value: 42 }
980
+ *
981
+ * @example
982
+ * // Stop the work when the client disconnects.
983
+ * const exit = await handle(request).unsafeRun({ signal: request.signal });
984
+ * if (exit.type === "Cancelled") return;
879
985
  */
986
+ /** Runs the IO under `signal`; aborting it cancels the run, which then ends as `Cancelled`. */
987
+ unsafeRun(options: {
988
+ readonly signal: AbortSignal;
989
+ }): Promise<Exit<E, A>>;
880
990
  unsafeRun(): Promise<Err<E> | Ok<A>>;
881
991
  /**
882
992
  * Executes the IO and folds both outcomes (success and error) into a single type.
@@ -983,6 +1093,10 @@ export declare class IO<E, A> {
983
1093
  * returned once the cancelled computation has unwound (its finalizers have run); an effect that
984
1094
  * ignores the signal is abandoned rather than waited for.
985
1095
  *
1096
+ * The deadline bounds waiting, not work: it fires on a timer, so work that never waits for the
1097
+ * next macrotask (a long synchronous loop, a large `traverse` of synchronous steps) runs to its
1098
+ * end before the timeout can take effect.
1099
+ *
986
1100
  * This is a first-class replacement for the verbose `IO.race` workaround:
987
1101
  * ```typescript
988
1102
  * // Before — manual race
@@ -1030,8 +1144,10 @@ export declare class IO<E, A> {
1030
1144
  *
1031
1145
  * A defect in the fiber makes `join()` reject with it. If the fiber is never joined, the defect
1032
1146
  * is reported as an unhandled rejection once the run that forked it has ended, or straight away
1033
- * when it happens after that (a handle returned out of its run that nobody joins).
1147
+ * when it happens after that (a handle returned out of its run that nobody joins). With
1148
+ * `onDefect`, that defect goes to the handler instead, right after it happens.
1034
1149
  *
1150
+ * @param options `onDefect`: receives the defect of a fiber nobody joins. See {@link ForkOptions}.
1035
1151
  * @returns {IO<never, Fiber<E, A>>} An IO that, when executed, starts this IO and returns a Fiber.
1036
1152
  *
1037
1153
  * @example
@@ -1042,15 +1158,24 @@ export declare class IO<E, A> {
1042
1158
  * return outcome.type === "Ok" ? outcome.value : "unavailable";
1043
1159
  * });
1044
1160
  */
1045
- fork(): IO<never, Fiber<E, A>>;
1161
+ fork(options?: ForkOptions): IO<never, Fiber<E, A>>;
1046
1162
  /**
1047
1163
  * Like {@link fork}, but the fiber is not a child of the run that forks it: cancelling that run
1048
1164
  * does not cancel the fiber. Use it for work that must finish on its own (a flush, an audit
1049
1165
  * write) regardless of what happens to the code that started it; cancel it through its handle.
1050
1166
  *
1167
+ * A daemon often outlives the request that started it, so a defect in it has nobody to reach:
1168
+ * pass `onDefect` to log it instead of letting it become an unhandled rejection, which stops a
1169
+ * Node process by default. A daemon's `onDefect` is called right after the defect happens,
1170
+ * unless the fiber is joined before then, even while the run that forked it is still running.
1171
+ *
1172
+ * @param options `onDefect`: receives the defect of a fiber nobody joins. See {@link ForkOptions}.
1051
1173
  * @returns {IO<never, Fiber<E, A>>} An IO that, when executed, starts this IO and returns a Fiber.
1174
+ *
1175
+ * @example
1176
+ * audit(event).forkDaemon({ onDefect: (cause) => logger.error("audit write failed", cause) });
1052
1177
  */
1053
- forkDaemon(): IO<never, Fiber<E, A>>;
1178
+ forkDaemon(options?: ForkOptions): IO<never, Fiber<E, A>>;
1054
1179
  /**
1055
1180
  * Applicative combine of independent IOs ("applicative for"). The IOs do not depend on one
1056
1181
  * another, so they run concurrently via `Promise.all`, and — unlike the monadic {@link forM},
@@ -1153,18 +1278,28 @@ export declare class IO<E, A> {
1153
1278
  * are collected into a `NonEmptyList`. Results, and errors, keep the order of
1154
1279
  * `items`, not the order of completion.
1155
1280
  *
1281
+ * With `concurrency: n`, at most `n` items run at once; the next item starts as soon as one
1282
+ * ends. Every item still runs, so every error is still collected. After a defect, or once the
1283
+ * run is cancelled, no further item starts. A `concurrency` that is not a positive integer or
1284
+ * `Infinity` throws `RangeError` where the call is written.
1285
+ *
1156
1286
  * @template E The error type.
1157
1287
  * @template A The input item type.
1158
1288
  * @template B The output type for each item.
1159
1289
  * @param {A[]} items The items to traverse in parallel.
1160
1290
  * @param {(a: A) => IO<E, B>} f A function that produces an IO for each item.
1291
+ * @param options `concurrency`: how many items run at once (default `Infinity`).
1161
1292
  * @returns {IO<NonEmptyList<E>, List<B>>} An IO that succeeds with all results as a List, or fails with all errors.
1162
1293
  *
1163
1294
  * @example
1164
1295
  * const io = IO.parTraverse([1, 2, 3], n => IO.of(n * 2));
1165
1296
  * // result: { type: "Ok", value: List [2, 4, 6] }
1297
+ *
1298
+ * @example
1299
+ * // At most 5 queries at once, however many ids the request carries.
1300
+ * const users = IO.parTraverse(ids, (id) => findUser(id), { concurrency: 5 });
1166
1301
  */
1167
- static parTraverse<E, A, B>(items: readonly A[], f: (a: A) => IO<E, B>): IO<NonEmptyList<E>, List<B>>;
1302
+ static parTraverse<E, A, B>(items: readonly A[], f: (a: A) => IO<E, B>, options?: Concurrency): IO<NonEmptyList<E>, List<B>>;
1168
1303
  /**
1169
1304
  * Sequentially executes an array of IOs, collecting results into an array.
1170
1305
  * Equivalent to `traverse(ios, x => x)`. Fail-fast on the first error.
@@ -1181,18 +1316,19 @@ export declare class IO<E, A> {
1181
1316
  static sequence<E, A>(ios: readonly IO<E, A>[]): IO<E, List<A>>;
1182
1317
  /**
1183
1318
  * Executes an array of IOs in parallel, collecting all results or all errors.
1184
- * Equivalent to `parTraverse(ios, x => x)`. Results and errors keep the order of `ios`.
1319
+ * Equivalent to `parTraverse(ios, x => x, options)`. Results and errors keep the order of `ios`.
1185
1320
  *
1186
1321
  * @template E The error type.
1187
1322
  * @template A The success type of each IO.
1188
1323
  * @param {IO<E, A>[]} ios The IO operations to execute in parallel.
1324
+ * @param options `concurrency`: how many IOs run at once (default `Infinity`); see {@link parTraverse}.
1189
1325
  * @returns {IO<NonEmptyList<E>, List<A>>} An IO that succeeds with all results as a List, or fails with all errors.
1190
1326
  *
1191
1327
  * @example
1192
1328
  * const io = IO.parSequence([IO.of(1), IO.of(2), IO.of(3)]);
1193
1329
  * // result: { type: "Ok", value: List [1, 2, 3] }
1194
1330
  */
1195
- static parSequence<E, A>(ios: readonly IO<E, A>[]): IO<NonEmptyList<E>, List<A>>;
1331
+ static parSequence<E, A>(ios: readonly IO<E, A>[], options?: Concurrency): IO<NonEmptyList<E>, List<A>>;
1196
1332
  }
1197
1333
 
1198
1334
  export declare class Left<A> extends Either<A, never> {
@@ -1293,7 +1429,7 @@ export declare class List<A> {
1293
1429
  * @param {number} endExclusive The exclusive end value.
1294
1430
  * @param {number} [step=1] The increment between successive values. Must be non-zero.
1295
1431
  * @returns {List<number>} A `List<number>` of the requested range.
1296
- * @throws {Error} If `step` is zero.
1432
+ * @throws {RangeError} If `step` is zero, an argument is not finite, or the range would hold more than 2^32 − 1 elements.
1297
1433
  *
1298
1434
  * @example
1299
1435
  * List.range(0, 5).toArray(); // [0, 1, 2, 3, 4]
@@ -2694,6 +2830,14 @@ export declare class NonEmptyList<A> {
2694
2830
  toJSON(): A[];
2695
2831
  }
2696
2832
 
2833
+ /**
2834
+ * A body result that is not a promise: an `async` body would return before its `bind`s ran, so
2835
+ * `forM` rejects it at compile time (and with a `TypeError` at run time).
2836
+ */
2837
+ declare type NotThenable = {
2838
+ readonly then?: never;
2839
+ } | null | undefined;
2840
+
2697
2841
  export declare interface Ok<A> {
2698
2842
  readonly type: "Ok";
2699
2843
  readonly value: A;
@@ -2812,6 +2956,40 @@ export declare abstract class Option<A> {
2812
2956
  * Option.empty<number>().tapNone(() => console.log("No value")); // Logs "No value"
2813
2957
  */
2814
2958
  abstract tapNone(f: () => void): Option<A>;
2959
+ /**
2960
+ * Applicative combine of independent `Option`s ("applicative for"): `Some` of the last
2961
+ * argument applied to their values (in argument order) when all are `Some`, and `None` as soon
2962
+ * as one is `None` — the combiner is then not called. A `None` carries nothing, so unlike
2963
+ * `Either.forA` there is nothing to collect. A combiner result of `null` or `undefined` is `None`.
2964
+ *
2965
+ * @example
2966
+ * const contact = Option.forA(name, email, (n, e) => ({ name: n, email: e })); // Option<{ name, email }>
2967
+ */
2968
+ static forA<A1, A2, R>(o1: Option<A1>, o2: Option<A2>, f: (a1: A1, a2: A2) => R | null | undefined): Option<NonNullable<R>>;
2969
+ static forA<A1, A2, A3, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, f: (a1: A1, a2: A2, a3: A3) => R | null | undefined): Option<NonNullable<R>>;
2970
+ static forA<A1, A2, A3, A4, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R | null | undefined): Option<NonNullable<R>>;
2971
+ static forA<A1, A2, A3, A4, A5, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R | null | undefined): Option<NonNullable<R>>;
2972
+ static forA<A1, A2, A3, A4, A5, A6, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R | null | undefined): Option<NonNullable<R>>;
2973
+ static forA<A1, A2, A3, A4, A5, A6, A7, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => R | null | undefined): Option<NonNullable<R>>;
2974
+ static forA<A1, A2, A3, A4, A5, A6, A7, A8, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, o8: Option<A8>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => R | null | undefined): Option<NonNullable<R>>;
2975
+ static forA<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, o8: Option<A8>, o9: Option<A9>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) => R | null | undefined): Option<NonNullable<R>>;
2976
+ /**
2977
+ * Monadic comprehension ("monadic for") over `Option`, synchronous. Inside `operation`,
2978
+ * `bind(option)` returns the `Some` value; the first `None` stops the body, and `forM` returns
2979
+ * `None`. The body's return value becomes the result, `None` when it is `null` or `undefined`.
2980
+ * An exception is not caught: it propagates from `forM`.
2981
+ *
2982
+ * `bind` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
2983
+ * not handle, and the body must be synchronous.
2984
+ *
2985
+ * @example
2986
+ * const city = Option.forM((bind) => {
2987
+ * const user = bind(findUser(id));
2988
+ * const address = bind(user.address);
2989
+ * return address.city;
2990
+ * }); // Option<string>
2991
+ */
2992
+ static forM<A>(operation: (bind: <B>(option: Option<B>) => B) => A & NotThenable): Option<NonNullable<A>>;
2815
2993
  /**
2816
2994
  * Applies one of two provided functions based on the contents of this `Option`.
2817
2995
  * If it is `None`, it applies `ifNone`. If it is `Some`, it applies `ifSome`.
@@ -3504,7 +3682,7 @@ export declare type Pipe<E, A, B> = (stream: Stream<E, A>) => Stream<E, B>;
3504
3682
  * await bind(Stream.from(queue).runForEach((m) => handle(m)));
3505
3683
  * });
3506
3684
  */
3507
- export declare class Queue<A> {
3685
+ export declare class Queue<in out A> {
3508
3686
  private readonly capacity;
3509
3687
  private readonly onOverflow;
3510
3688
  private readonly items;
@@ -3571,7 +3749,8 @@ export declare class Queue<A> {
3571
3749
  * Offers a value. Resolves `true` when the value was accepted with nothing lost, `false` when
3572
3750
  * it was refused (queue closed, or `DropNewest` at capacity) or an older value was evicted
3573
3751
  * (`DropOldest` at capacity). Under `Suspend`, an offer at capacity waits for a `take`;
3574
- * cancelling the waiting fiber withdraws the offer.
3752
+ * cancelling the waiting fiber withdraws the offer, unless a `take` accepted the value at the
3753
+ * same moment: the run then ends `Cancelled` with the value in the queue all the same.
3575
3754
  *
3576
3755
  * @param {A} value The value to enqueue.
3577
3756
  * @returns {IO<never, boolean>}
@@ -3598,6 +3777,8 @@ export declare class Queue<A> {
3598
3777
  * if (next.type === "Ok" && !next.value.done) handle(next.value.value);
3599
3778
  */
3600
3779
  take(): IO<never, IteratorResult<A, void>>;
3780
+ /** Returns a value a cancelled taker received: to the next waiting taker, else to the front. */
3781
+ private putBack;
3601
3782
  /**
3602
3783
  * Closes the queue: every waiting `take` resumes with `{ done: true }`, every waiting `offer` resumes
3603
3784
  * with `false`, and later offers are refused. Values already buffered stay available to `take`.
@@ -3658,8 +3839,8 @@ export declare class Queue<A> {
3658
3839
  * const data = await fetchData.run({ multiplier: 1, apiEndpoint: 'https://api.example.com' });
3659
3840
  * ```
3660
3841
  */
3661
- export declare class Reader<R, A> {
3662
- private f;
3842
+ export declare class Reader<in R, out A> {
3843
+ private readonly f;
3663
3844
  /**
3664
3845
  * Initializes a new `Reader` instance.
3665
3846
  *
@@ -3734,6 +3915,10 @@ export declare class Reader<R, A> {
3734
3915
  * computation can determine the next computation. It is useful for creating complex
3735
3916
  * workflows that depend on the environment and previous results.
3736
3917
  *
3918
+ * The chain needs every environment its steps read: a `Reader<{ db: Db }, A>` chained with a
3919
+ * step that reads `{ cache: Cache }` is a `Reader<{ db: Db } & { cache: Cache }, B>`. A step
3920
+ * that reads the same environment, or none, keeps it.
3921
+ *
3737
3922
  * @param f - A function that takes the result of the current `Reader` and returns a new `Reader`.
3738
3923
  * @returns A new `Reader` instance that represents the chained computation.
3739
3924
  *
@@ -3750,6 +3935,8 @@ export declare class Reader<R, A> {
3750
3935
  * // Running the Reader with an environment will fetch and process the data
3751
3936
  * processData.run({ apiEndpoint: 'https://api.example.com' }).then(console.log);
3752
3937
  */
3938
+ flatMap<R2, B>(f: (a: A) => Reader<R2, B>): Reader<R & R2, B>;
3939
+ /** Chains a Reader that reads the same environment (explicit type argument `<B>`). */
3753
3940
  flatMap<B>(f: (a: A) => Reader<R, B>): Reader<R, B>;
3754
3941
  /**
3755
3942
  * Creates a `Reader` instance that provides access to the environment.
@@ -3781,6 +3968,10 @@ export declare class Reader<R, A> {
3781
3968
  * environment and collecting their results into a single value. It is purely
3782
3969
  * sequential — a `Reader` performs no concurrency.
3783
3970
  *
3971
+ * The combined `Reader` needs every environment its parts read: zipping a
3972
+ * `Reader<{ db: Db }, A>` with a `Reader<{ cache: Cache }, B>` gives a
3973
+ * `Reader<{ db: Db } & { cache: Cache }, readonly [A, B]>`.
3974
+ *
3784
3975
  * @param readers - An array of `Reader` instances to be combined.
3785
3976
  * @returns A new `Reader` instance that returns a tuple of the results of the given `Reader` instances.
3786
3977
  *
@@ -3797,6 +3988,10 @@ export declare class Reader<R, A> {
3797
3988
  * const env = { valueA: 42, valueB: "hello", valueC: true };
3798
3989
  * console.log(combinedReader.run(env)); // [42, "hello", true]
3799
3990
  */
3991
+ static zip<const T extends readonly Reader<never, unknown>[]>(...readers: T): Reader<ReaderEnvs<T>, {
3992
+ [K in keyof T]: ReaderValue<T[K]>;
3993
+ }>;
3994
+ /** Combines Readers that share an environment (explicit type arguments `<R, A>`). */
3800
3995
  static zip<R, const A extends readonly unknown[]>(...readers: {
3801
3996
  [K in keyof A]: Reader<R, A[K]>;
3802
3997
  }): Reader<R, A>;
@@ -3861,6 +4056,18 @@ export declare class Reader<R, A> {
3861
4056
  run(env: R): A;
3862
4057
  }
3863
4058
 
4059
+ /** The environment a Reader reads. */
4060
+ declare type ReaderEnv<T> = T extends Reader<infer R, unknown> ? R : never;
4061
+
4062
+ /**
4063
+ * The environment that every Reader of a tuple reads: the intersection of their environments. A
4064
+ * plain array (not a tuple) gives the environment of its element type.
4065
+ */
4066
+ declare type ReaderEnvs<T extends readonly unknown[]> = T extends readonly [] ? unknown : T extends readonly [infer Head, ...infer Rest] ? ReaderEnv<Head> & ReaderEnvs<Rest> : ReaderEnv<T[number]>;
4067
+
4068
+ /** The value a Reader produces. */
4069
+ declare type ReaderValue<T> = T extends Reader<never, infer A> ? A : never;
4070
+
3864
4071
  /**
3865
4072
  * A mutable cell whose every operation is an `IO<never, _>`. `Ref` is how state lives *inside* an
3866
4073
  * `IO` program — a session, a cache, a counter — instead of in a closure variable the effect
@@ -3888,7 +4095,7 @@ export declare class Reader<R, A> {
3888
4095
  * });
3889
4096
  * await program.unsafeRun(); // { type: "Ok", value: 2 }
3890
4097
  */
3891
- export declare class Ref<A> {
4098
+ export declare class Ref<in out A> {
3892
4099
  private value;
3893
4100
  private constructor();
3894
4101
  /**
@@ -3969,6 +4176,9 @@ export declare class Ref<A> {
3969
4176
  getAndSet(value: A): IO<never, A>;
3970
4177
  }
3971
4178
 
4179
+ /** How the `use` step of a `bracket` ended, as its release receives it. */
4180
+ export declare type ReleaseExit<E, A> = Exit<E, A> | Defect;
4181
+
3972
4182
  export declare class Right<B> extends Either<never, B> {
3973
4183
  readonly value: B;
3974
4184
  readonly type: "Right";
@@ -4178,7 +4388,7 @@ export declare class Stream<E, A> {
4178
4388
  * (conn) => IO.promise(() => conn.close())
4179
4389
  * );
4180
4390
  */
4181
- static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => Stream<F, A>, release: (r: R) => IO<never, void>): Stream<E | F, A>;
4391
+ static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => Stream<F, A>, release: (r: R, exit: ReleaseExit<unknown, void>) => IO<never, void>): Stream<E | F, A>;
4182
4392
  /**
4183
4393
  * Builds a stream by repeatedly running an effectful step over a threaded seed. The step
4184
4394
  * returns `Some([element, nextSeed])` to emit and continue, or `None` to end the stream.
@@ -4227,6 +4437,30 @@ export declare class Stream<E, A> {
4227
4437
  * const events = Stream.from(queue).map(parse).runForEach(handle);
4228
4438
  */
4229
4439
  static from<A>(queue: Queue<A>): Stream<never, A>;
4440
+ /**
4441
+ * Builds a stream that pulls from an async iterable — a Node `Readable`, a `ReadableStream`, a
4442
+ * `Response.body`, an async generator — one value at a time, only when the consumer asks: the
4443
+ * source is never read ahead.
4444
+ *
4445
+ * A `next()` that rejects, or an iterable that cannot give an iterator, fails the stream with
4446
+ * `liftE(error)`, or with the error itself (typed `unknown`) without `liftE`. When the stream
4447
+ * stops before the source ends — the consumer stops early, the run fails or is cancelled — the
4448
+ * iterator's `return()` is called, so the source can release what it holds (a Node `Readable` is
4449
+ * destroyed). It is called without waiting, so a source whose `return()` never settles cannot
4450
+ * hold the stream's end, a `timeout` or a cancellation; the source may still be closing when the
4451
+ * stream ends. A `return()` that fails is ignored. A source that ends by itself is not asked to
4452
+ * return.
4453
+ *
4454
+ * @template A The element type.
4455
+ * @template E The error type `liftE` produces.
4456
+ * @param source The async iterable to read.
4457
+ * @param liftE Turns a rejection of `next()` into an `E`.
4458
+ *
4459
+ * @example
4460
+ * const lines = Stream.fromAsync(readline.createInterface({ input: file }), toReadError);
4461
+ */
4462
+ static fromAsync<A>(source: AsyncIterable<A>): Stream<unknown, A>;
4463
+ static fromAsync<A, E>(source: AsyncIterable<A>, liftE: (e: unknown) => E): Stream<E, A>;
4230
4464
  /**
4231
4465
  * Builds a stream from a callback-based source. `register` attaches the listeners and receives
4232
4466
  * three synchronous functions — `emit` (a {@link Queue.unsafeOffer}), `end` (a
@@ -4236,7 +4470,11 @@ export declare class Stream<E, A> {
4236
4470
  *
4237
4471
  * Values are buffered in a bounded {@link Queue} (default capacity 1024, `OverflowStrategy.DropOldest`),
4238
4472
  * so a source that outpaces its consumer never grows memory without limit; a `Suspend` queue
4239
- * makes no sense here because `emit` is synchronous, so it is not offered.
4473
+ * makes no sense here because `emit` is synchronous, so it is not offered. `DropOldest` and
4474
+ * `DropNewest` lose values, so they suit signals where the newest value is enough (a position, a
4475
+ * status). For data that must arrive whole, pass a function as `onOverflow`: when the buffer is
4476
+ * full, the stream fails with the error it returns, after the values already buffered, and
4477
+ * `emit` returns `false` for that value and every later one. A function that throws is a defect.
4240
4478
  *
4241
4479
  * `register` runs when the stream starts — on the first pull of each **run** (each terminal
4242
4480
  * operation), not when `Stream.async` is called — so a value emitted before that point cannot
@@ -4254,17 +4492,29 @@ export declare class Stream<E, A> {
4254
4492
  * @template A The element type.
4255
4493
  * @template E The error type passed to `fail` (default `never`: a source that cannot fail).
4256
4494
  * @param register Attaches listeners; returns the detach effect, if any.
4257
- * @param options `capacity` (positive integer, default 1024) and `onOverflow` (default `OverflowStrategy.DropOldest`).
4495
+ * @param options `capacity` (positive integer, default 1024) and `onOverflow`: `OverflowStrategy.DropOldest`
4496
+ * (the default), `OverflowStrategy.DropNewest`, or a function from the capacity to the error to fail with.
4258
4497
  *
4259
4498
  * @example
4260
4499
  * const clicks = Stream.async<MouseEvent>((emit) => {
4261
4500
  * button.addEventListener("click", emit);
4262
4501
  * return IO.sync(() => button.removeEventListener("click", emit));
4263
4502
  * });
4503
+ *
4504
+ * @example
4505
+ * // An upload must arrive whole: fail instead of dropping chunks.
4506
+ * const chunks = Stream.async<Uint8Array, UploadError>(
4507
+ * (emit, end, fail) => {
4508
+ * request.on("data", emit);
4509
+ * request.on("end", end);
4510
+ * request.on("error", (e) => fail(toUploadError(e)));
4511
+ * },
4512
+ * { capacity: 64, onOverflow: () => ({ kind: "uploadTooFast" }) }
4513
+ * );
4264
4514
  */
4265
4515
  static async<A, E = never>(register: (emit: (a: A) => boolean, end: () => void, fail: (error: E) => void) => IO<never, void> | void, options?: {
4266
4516
  readonly capacity?: number;
4267
- readonly onOverflow?: Exclude<OverflowStrategy, typeof OverflowStrategy.Suspend>;
4517
+ readonly onOverflow?: Exclude<OverflowStrategy, typeof OverflowStrategy.Suspend> | ((capacity: number) => E);
4268
4518
  }): Stream<E, A>;
4269
4519
  /**
4270
4520
  * Transforms each emitted element with `f`. Lazy — nothing runs until the stream is consumed.
@@ -4406,6 +4656,11 @@ export declare class Stream<E, A> {
4406
4656
  * stream consumed by a fallible `f` is simply `IO<F, void>`).
4407
4657
  */
4408
4658
  runForEach<F>(f: (a: A) => IO<F, void>): IO<E | F, void>;
4659
+ /**
4660
+ * Runs `drive` over this stream in a new root scope, and closes the scope with how the run
4661
+ * ended. `drive` pulls until it decides to stop; stopping early is the end of the stream.
4662
+ */
4663
+ private runScoped;
4409
4664
  /**
4410
4665
  * Runs the stream purely for its effects, discarding emitted elements.
4411
4666
  */