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

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.
@@ -116,6 +116,25 @@ export declare abstract class Either<A, B> {
116
116
  * @returns The value of `Right` or `null`.
117
117
  */
118
118
  abstract getOrNull(): B | null;
119
+ /**
120
+ * Returns the value of this `Right`. For a `Left`, **throws**: use it to end a computation with a
121
+ * bug, a `Left` that the caller knows cannot happen. The thrown value is `toCause(left)`, or the
122
+ * left value itself without `toCause`; a primitive is wrapped in an `Error` that keeps it as
123
+ * `cause`, and whose message does not show it.
124
+ *
125
+ * It is a plain throw. Inside `IO.sync`, `map`, `flatMap` or `tap` it is a defect; inside
126
+ * `IO.lift`, `IO.cancellable`, `Either.catch` or a `forM` body with a `liftE`, it becomes a typed
127
+ * failure like any throw there. In those places use the effect form instead, which is a defect
128
+ * everywhere: `$(IO.from(either).orDefect())`.
129
+ *
130
+ * @param toCause - Builds what is thrown from the left value.
131
+ * @returns The value of this `Right`.
132
+ *
133
+ * @example
134
+ * // A port this program validated on startup.
135
+ * const port: number = Port.parse(env.PORT).getOrThrow((e) => new Error(`PORT was validated: ${e}`));
136
+ */
137
+ abstract getOrThrow(toCause?: (left: A) => unknown): B;
119
138
  /**
120
139
  * Swaps the `Left` and `Right` types.
121
140
  * @returns A new `Either` with the types swapped.
@@ -174,21 +193,21 @@ export declare abstract class Either<A, B> {
174
193
  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
194
  /**
176
195
  * 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
196
+ * `$(either)` returns the `Right` value; the first `Left` stops the body, and `forM` returns
178
197
  * that `Left`. The body's return value becomes the `Right`. An exception that is not a `Left`
179
198
  * is not caught: it propagates from `forM`. Use {@link forA} to collect every `Left` instead.
180
199
  *
181
- * `bind` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
200
+ * `$` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
182
201
  * not handle, and the body must be synchronous.
183
202
  *
184
203
  * @example
185
- * const total = Either.forM<ParseError, number>((bind) => {
186
- * const price = bind(parsePrice(input.price));
187
- * const quantity = bind(parseQuantity(input.quantity));
204
+ * const total = Either.forM<ParseError, number>(($) => {
205
+ * const price = $(parsePrice(input.price));
206
+ * const quantity = $(parseQuantity(input.quantity));
188
207
  * return price * quantity;
189
208
  * });
190
209
  */
191
- static forM<E, A>(operation: (bind: <B>(either: Either<E, B>) => B) => A & NotThenable): Either<E, A>;
210
+ static forM<E, A>(operation: ($: <B>(either: Either<E, B>) => B) => A & NotThenable): Either<E, A>;
192
211
  }
193
212
 
194
213
  /**
@@ -210,6 +229,11 @@ export declare interface Err<E> {
210
229
  readonly error: E;
211
230
  }
212
231
 
232
+ /** The error type of the `Err` case of `X`. */
233
+ declare type ErrorOf<X extends ReleaseExit<unknown, unknown>> = Extract<X, {
234
+ readonly type: "Err";
235
+ }>["error"];
236
+
213
237
  /**
214
238
  * `Eval` represents a deferred computation, which allows operations to be delayed, chained,
215
239
  * and lazily evaluated. It provides a foundation for creating different types of deferred operations
@@ -399,6 +423,70 @@ export declare class EvaluationError<E> extends Error {
399
423
  */
400
424
  export declare type Exit<E, A> = Ok<A> | Err<E> | Cancelled;
401
425
 
426
+ export declare const Exit: {
427
+ /**
428
+ * Maps each case of an exit to a single type. Every case the exit's type can be needs a handler, so
429
+ * a missing one is a compile error: an `Exit` takes `onOk`, `onErr` and `onCancelled`, a
430
+ * `ReleaseExit` also takes `onDefect`, and what `unsafeRun()` without a signal returns takes `onOk`
431
+ * and `onErr` only.
432
+ *
433
+ * @template X The type of the exit.
434
+ * @template B The result type of every handler.
435
+ * @param {X} exit The exit to fold: what `unsafeRun()` or `fiber.join()` resolves to, or what a
436
+ * `bracket` release receives.
437
+ * @param handlers One handler for each case of `X`.
438
+ * @returns {B} What the handler of the exit's case returns.
439
+ * @throws {TypeError} When `exit` is not an exit: its `type` is not `Ok`, `Err`, `Cancelled` or `Defect`.
440
+ *
441
+ * @example
442
+ * const status = Exit.fold(await fiber.join(), {
443
+ * onOk: (user) => `loaded ${user.id}`,
444
+ * onErr: (error) => `failed: ${error.message}`,
445
+ * onCancelled: () => "stopped",
446
+ * });
447
+ *
448
+ * @example
449
+ * // A bracket release that acts on how `use` ended.
450
+ * IO.bracket(connect(), work, (conn, exit) =>
451
+ * Exit.fold(exit, {
452
+ * onOk: () => IO.sync(() => conn.release()),
453
+ * onErr: () => rollback(conn),
454
+ * onCancelled: () => IO.sync(() => conn.destroy()),
455
+ * onDefect: () => IO.sync(() => conn.destroy()),
456
+ * })
457
+ * );
458
+ */
459
+ fold: <X extends ReleaseExit<unknown, unknown>, B>(exit: X, handlers: ExitHandlers<X, B>) => B;
460
+ };
461
+
462
+ /**
463
+ * The handlers `Exit.fold` takes for an exit of type `X`: one for each case `X` can be, and none for
464
+ * the others. A handler for a case `X` cannot be is refused, so `onDefect` belongs to a `ReleaseExit`
465
+ * only, and `onCancelled` is refused for what `unsafeRun()` without a signal returns. When the error
466
+ * type is `never`, no `Err` can exist, so `onErr` is optional.
467
+ */
468
+ declare type ExitHandlers<X extends ReleaseExit<unknown, unknown>, B> = ("Ok" extends X["type"] ? {
469
+ readonly onOk: (value: Extract<X, {
470
+ readonly type: "Ok";
471
+ }>["value"]) => B;
472
+ } : {
473
+ readonly onOk?: never;
474
+ }) & ("Err" extends X["type"] ? [ErrorOf<X>] extends [never] ? {
475
+ readonly onErr?: (error: never) => B;
476
+ } : {
477
+ readonly onErr: (error: ErrorOf<X>) => B;
478
+ } : {
479
+ readonly onErr?: never;
480
+ }) & ("Cancelled" extends X["type"] ? {
481
+ readonly onCancelled: () => B;
482
+ } : {
483
+ readonly onCancelled?: never;
484
+ }) & ("Defect" extends X["type"] ? {
485
+ readonly onDefect: () => B;
486
+ } : {
487
+ readonly onDefect?: never;
488
+ });
489
+
402
490
  export declare interface Fiber<E, A> {
403
491
  /**
404
492
  * Wait for the computation to complete. Rejects with the original exception on a defect. A
@@ -686,6 +774,46 @@ export declare class IO<E, A> {
686
774
  * const result = await io.unsafeRun(); // { type: "Err", error: Error("something went wrong") }
687
775
  */
688
776
  static fail<E, A = never>(error: E): IO<E, A>;
777
+ /**
778
+ * Creates an IO that ends with a **defect** whose cause is `cause`: a bug that no caller can
779
+ * handle, such as an adapter that returns a value outside its contract. It is the counterpart of
780
+ * {@link IO.fail} for what is not an `E`, and the named form of a `throw` inside {@link IO.sync}.
781
+ *
782
+ * Nothing happens until the IO runs. Then it ends as a throw in `IO.sync` does: `unsafeRun()` and
783
+ * `join()` reject with `cause` itself, `onDefect` handlers and a `ReleaseExit` see a `Defect`, and
784
+ * no failure handler (`mapErr`, `flatMapErr`, `foldM`, `attempt`, `retry`, a `liftE`) sees it.
785
+ * Prefer an `Error` as the cause: it carries a stack trace.
786
+ *
787
+ * @template A The success type. It defaults to `never`; set it, or let a `fold` infer it, so
788
+ * that this IO has the type of the other branch.
789
+ * @param {unknown} cause What `unsafeRun()` and `join()` reject with.
790
+ * @returns {IO<never, A>} An IO that ends with a defect when it runs.
791
+ *
792
+ * @example
793
+ * // This program writes the settings file itself: a missing port is a bug, not a failure.
794
+ * const port: IO<never, number> = Option.ofNullable(settings.port).fold(
795
+ * () => IO.defect(new Error("The settings file has no port")),
796
+ * IO.of
797
+ * );
798
+ */
799
+ static defect<A = never>(cause: unknown): IO<never, A>;
800
+ /**
801
+ * Creates an IO that waits `ms` milliseconds, then succeeds with `undefined`.
802
+ *
803
+ * Nothing happens until the IO runs. The wait is cancellable: when the run is cancelled, the timer
804
+ * is cleared and the run ends as `Cancelled` at once. `retry` and `repeat` wait between attempts
805
+ * with the same timer.
806
+ *
807
+ * @param {number} ms How long to wait, in milliseconds. Must be a non-negative number: a negative or
808
+ * `NaN` time throws `RangeError` where it is written. A time above 2,147,483,647 ms (the
809
+ * `setTimeout` limit), including `Infinity`, is lowered to it instead of firing at once.
810
+ * @returns {IO<never, void>} An IO that succeeds after the wait.
811
+ *
812
+ * @example
813
+ * // Gives the device a second to restart before asking for its state.
814
+ * const state = device.restart().flatMap(() => IO.sleep(1000)).flatMap(() => device.state());
815
+ */
816
+ static sleep(ms: number): IO<never, void>;
689
817
  /**
690
818
  * Converts a value of another type into an `IO`. `from` is total: an `Either` carries its own
691
819
  * error, so it converts as-is; an `Option` has no error channel, so `onNone` must supply one.
@@ -828,39 +956,113 @@ export declare class IO<E, A> {
828
956
  * .flatMapErr(httpErr => refreshTokenThen(httpErr).mapErr(toDomainError));
829
957
  */
830
958
  flatMapErr<F>(f: (error: E) => IO<F, A>): IO<F, A>;
959
+ /**
960
+ * Turns every failure of this IO into a **defect** (see {@link IO.defect}), for a failure the
961
+ * caller knows cannot happen: a validation with a port that cannot refuse, a parse of a value
962
+ * this program wrote. The cause is `toCause(error)`, or the error itself without `toCause`.
963
+ *
964
+ * Success, cancellation and existing defects pass through unchanged. A handler before
965
+ * `orDefect` (a `retry`, say) still sees the failure; one after it sees nothing. A `toCause`
966
+ * that throws makes its own exception the defect.
967
+ *
968
+ * @param {(error: E) => unknown} [toCause] Builds the defect's cause from the error. Prefer one
969
+ * that returns an `Error`, for its stack trace.
970
+ * @returns {IO<never, A>} The same IO, with no failure left in its type.
971
+ *
972
+ * @example
973
+ * const config: IO<never, Config> = readBundledConfig() // IO<ParseError, Config>
974
+ * .orDefect((e) => new Error(`The bundled config does not parse: ${e.reason}`));
975
+ */
976
+ orDefect(toCause?: (error: E) => unknown): IO<never, A>;
977
+ /**
978
+ * Turns every failure into a value. The result cannot fail: what went wrong becomes part of the
979
+ * value, as `null`, a default or a state that describes the problem.
980
+ *
981
+ * Success, cancellation and defects pass through unchanged. A handler that throws makes its own
982
+ * exception a defect. The handler returns a plain value: a handler that returns an `IO` is
983
+ * refused at compile time, because that recovery is {@link IO.flatMapErr}.
984
+ *
985
+ * @template B The type of the value the handler returns.
986
+ * @param {(error: E) => B} f Builds the value from the error.
987
+ * @returns {IO<never, A | B>} An IO that succeeds with this IO's value or with the handler's.
988
+ *
989
+ * @example
990
+ * const invitations: IO<never, InvitationList> = account
991
+ * .myInvitations()
992
+ * .map(({ invitations }) => ({ invitations, problem: null }))
993
+ * .recover((problem) => ({ invitations: [], problem: describe(problem) }));
994
+ */
995
+ recover<B>(f: (error: E) => B & NotAnIO<B>): IO<never, A | B>;
996
+ /**
997
+ * Handles the failures `guard` accepts with `f`, and fails again with every other one, unchanged.
998
+ * The handled case leaves the error type: the result fails with what the guard refused, or with
999
+ * the handler's own error type `F`.
1000
+ *
1001
+ * Success, cancellation and defects pass through unchanged, and neither `guard` nor `f` is called.
1002
+ * A `guard` or `f` that throws makes its own exception a defect. `guard` must be a type guard: a
1003
+ * plain boolean predicate cannot narrow the error type, and {@link IO.flatMapErr} covers that case.
1004
+ *
1005
+ * @template E1 The case of `E` that `guard` accepts.
1006
+ * @template F The error type of the handler's IO.
1007
+ * @template B The value type of the handler's IO.
1008
+ * @param {(error: E) => error is E1} guard Decides which failures `f` handles.
1009
+ * @param {(error: E1) => IO<F, B>} f Recovers from a failure the guard accepted.
1010
+ * @returns {IO<Exclude<E, E1> | F, A | B>} An IO without the handled case in its error type.
1011
+ *
1012
+ * @example
1013
+ * const saved: IO<NotFound | Refused, Account> = repository
1014
+ * .save(account) // IO<NotFound | VersionConflict, Account>
1015
+ * .recoverIf(isVersionConflict, () => IO.fail(refused("ChangedMeanwhile")));
1016
+ */
1017
+ recoverIf<E1 extends E, F, B>(guard: (error: E) => error is E1, f: (error: E1) => IO<F, B>): IO<Exclude<E, E1> | F, A | B>;
831
1018
  /**
832
1019
  * Executes a side-effect on the success value without changing the result.
833
- * If this IO fails, the function is not called. The callback may be synchronous
834
- * or asynchronous — the interpreter awaits if it returns a Promise.
1020
+ * If this IO fails, the function is not called. The callback may be synchronous, return a
1021
+ * Promise (the interpreter awaits it), or return an `IO`.
1022
+ *
1023
+ * A returned `IO` runs as part of this run, with the same cancellation: its value is dropped,
1024
+ * and its failure fails the run, so the error type widens to `E | F`.
835
1025
  *
836
1026
  * If the side-effect throws or rejects, that is a **defect**, as a throw in `map` is: it is not
837
1027
  * 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)`.
1028
+ * should be ignored, catch it inside the callback, or return an `IO` that ends with `ignore()`.
840
1029
  *
841
- * @param {(a: A) => void | Promise<void>} f The side-effect function.
842
- * @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original result.
1030
+ * @template F The error type of a returned `IO`; `never` for a plain or async callback.
1031
+ * @param {(a: A) => void | Promise<void> | IO<F, unknown>} f The side-effect function.
1032
+ * @returns {IO<E | F, A>} A new IO that performs the side-effect but preserves the original result.
843
1033
  *
844
1034
  * @example
845
1035
  * const io = IO.of(42).tap(value => console.log("Got:", value));
1036
+ *
1037
+ * @example
1038
+ * // A side effect that is itself an IO.
1039
+ * const saved = save(order).tap((saved) => log.info(`order.saved.${saved.id}`));
846
1040
  */
847
- tap(f: (a: A) => void | Promise<void>): IO<E, A>;
1041
+ tap<F = never>(f: (a: A) => void | Promise<void> | IO<F, unknown>): IO<E | F, A>;
848
1042
  /**
849
1043
  * Executes a side-effect on the error value without changing the result.
850
- * If this IO succeeds, the function is not called. The callback may be synchronous
851
- * or asynchronous — the interpreter awaits if it returns a Promise.
1044
+ * If this IO succeeds, the function is not called. The callback may be synchronous, return a
1045
+ * Promise (the interpreter awaits it), or return an `IO` that cannot fail.
1046
+ *
1047
+ * A returned `IO` runs as part of this run, with the same cancellation; when it ends, the
1048
+ * original error continues. Its type is `IO<never, unknown>`, so it can never replace that error:
1049
+ * end an `IO` that can fail with `ignore()` first.
852
1050
  *
853
1051
  * If the side-effect throws or rejects, that is a **defect**, as a throw in `mapErr` is: it does
854
1052
  * not replace the error, and `unsafeRun()` rejects with it. For a side effect that may fail and
855
1053
  * whose failure should be ignored, catch it inside the callback.
856
1054
  *
857
- * @param {(e: E) => void | Promise<void>} f The side-effect function.
1055
+ * @param {(e: E) => void | Promise<void> | IO<never, unknown>} f The side-effect function.
858
1056
  * @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original error.
859
1057
  *
860
1058
  * @example
861
1059
  * const io = IO.fail(new Error("boom")).tapErr(e => logger.error(e));
1060
+ *
1061
+ * @example
1062
+ * // A log call that is itself an IO.
1063
+ * const checked = passkey.verify(request).tapErr((failure) => log.warn(`passkey.refused.${failure.reason}`));
862
1064
  */
863
- tapErr(f: (e: E) => void | Promise<void>): IO<E, A>;
1065
+ tapErr(f: (e: E) => void | Promise<void> | IO<never, unknown>): IO<E, A>;
864
1066
  /**
865
1067
  * Validates the success value against a type guard (Cats `ensure`). When the guard holds, the
866
1068
  * success channel is narrowed to `B`; when it does not, the value is converted into an error
@@ -959,9 +1161,9 @@ export declare class IO<E, A> {
959
1161
  */
960
1162
  ignore(): IO<never, void>;
961
1163
  /**
962
- * Executes the computation described by this IO and returns the result.
963
- * The interpreter walks the ADT tree using an explicit stack (trampoline),
964
- * ensuring stack safety for arbitrarily deep chains.
1164
+ * Executes the computation described by this IO and returns the result. It is the only way to
1165
+ * run an IO: call it at the edge of the program. The interpreter walks the ADT tree using an
1166
+ * explicit stack (trampoline), ensuring stack safety for arbitrarily deep chains.
965
1167
  *
966
1168
  * The promise resolves with `Ok` or `Err` (an `E`). It **rejects** only on a defect — an
967
1169
  * exception from an effect or callback that was not declared fallible — with the original
@@ -979,6 +1181,10 @@ export declare class IO<E, A> {
979
1181
  * // result: { type: "Ok", value: 42 }
980
1182
  *
981
1183
  * @example
1184
+ * // A value or null at the edge: recover first, so the run cannot fail and needs no onErr.
1185
+ * const user = Exit.fold(await findUser(id).recover(() => null).unsafeRun(), { onOk: (u) => u });
1186
+ *
1187
+ * @example
982
1188
  * // Stop the work when the client disconnects.
983
1189
  * const exit = await handle(request).unsafeRun({ signal: request.signal });
984
1190
  * if (exit.type === "Cancelled") return;
@@ -988,61 +1194,6 @@ export declare class IO<E, A> {
988
1194
  readonly signal: AbortSignal;
989
1195
  }): Promise<Exit<E, A>>;
990
1196
  unsafeRun(): Promise<Err<E> | Ok<A>>;
991
- /**
992
- * Executes the IO and folds both outcomes (success and error) into a single type.
993
- * This is a terminal operation — it runs the computation and returns a plain value.
994
- *
995
- * @template B The result type after folding.
996
- * @param {(e: E) => B} onErr Handler for the error case.
997
- * @param {(a: A) => B} onOk Handler for the success case.
998
- * @returns {Promise<B>} The folded result.
999
- *
1000
- * @example
1001
- * const message = await IO.of(42).fold(
1002
- * err => `Failed: ${err}`,
1003
- * val => `Got: ${val}`
1004
- * );
1005
- * // message: "Got: 42"
1006
- */
1007
- fold<B>(onErr: (e: E) => B, onOk: (a: A) => B): Promise<B>;
1008
- /**
1009
- * Executes the IO and returns the success value, or `null` if the computation fails.
1010
- *
1011
- * Note: if `A` itself can be `null`, the return value is ambiguous — a `null` result
1012
- * could mean either "succeeded with null" or "failed." Use `unsafeRun()` or `fold`
1013
- * when the distinction matters.
1014
- *
1015
- * @returns {Promise<A | null>} The success value or null.
1016
- *
1017
- * @example
1018
- * const value = await IO.of(42).getOrNull(); // 42
1019
- * const nope = await IO.fail("err").getOrNull(); // null
1020
- */
1021
- getOrNull(): Promise<A | null>;
1022
- /**
1023
- * Executes the IO and returns the success value, or evaluates the provided
1024
- * default function on error. The default is lazy to avoid unnecessary computation.
1025
- *
1026
- * @param {() => A} defaultValue A function that produces the fallback value.
1027
- * @returns {Promise<A>} The success value or the default.
1028
- *
1029
- * @example
1030
- * const value = await IO.fail("err").getOrElse(() => 0); // 0
1031
- */
1032
- getOrElse<B>(defaultValue: () => B): Promise<A | B>;
1033
- /**
1034
- * Executes the IO and returns the success value, or applies the handler
1035
- * function to the error to produce a fallback value.
1036
- *
1037
- * @param {(error: E) => A} handler A function that transforms the error into a success value.
1038
- * @returns {Promise<A>} The success value or the handled error.
1039
- *
1040
- * @example
1041
- * const value = await IO.fail(new Error("boom"))
1042
- * .getOrHandleErr(e => `Handled: ${e.message}`);
1043
- * // value: "Handled: boom"
1044
- */
1045
- getOrHandleErr<B>(handler: (error: E) => B): Promise<A | B>;
1046
1197
  /**
1047
1198
  * Runs this IO again after a failure, as the {@link Schedule} allows. Succeeds with the first
1048
1199
  * success; otherwise fails with the **last error, as-is** — once the schedule's attempts are
@@ -1151,8 +1302,8 @@ export declare class IO<E, A> {
1151
1302
  * @returns {IO<never, Fiber<E, A>>} An IO that, when executed, starts this IO and returns a Fiber.
1152
1303
  *
1153
1304
  * @example
1154
- * const io = IO.forM<AppError, string>(async bind => {
1155
- * const fiber = await bind(longRunningTask.fork());
1305
+ * const io = IO.forM<AppError, string>(async ($) => {
1306
+ * const fiber = await $(longRunningTask.fork());
1156
1307
  * // ... do other work ...
1157
1308
  * const outcome = await fiber.join(); // Ok | Err | Cancelled
1158
1309
  * return outcome.type === "Ok" ? outcome.value : "unavailable";
@@ -1225,13 +1376,13 @@ export declare class IO<E, A> {
1225
1376
  static race<E, A>(...ops: IO<E, A>[]): IO<NonEmptyList<E>, A>;
1226
1377
  /**
1227
1378
  * Monadic for-comprehension ("monadic for"). Sequences dependent IO operations using an
1228
- * imperative-style `bind` function that unwraps IO values or short-circuits on the first
1379
+ * imperative-style `$` function that unwraps IO values or short-circuits on the first
1229
1380
  * error. This is the sequential, fail-fast counterpart to the applicative {@link forA}
1230
1381
  * (which runs independent IOs in parallel and accumulates all errors).
1231
1382
  *
1232
- * Inside the `operation` callback, call `bind(io)` to execute an IO and extract its
1383
+ * Inside the `operation` callback, call `$(io)` to execute an IO and extract its
1233
1384
  * success value. If any bound IO fails, the whole comprehension short-circuits with that
1234
- * error — subsequent `bind` calls are not executed.
1385
+ * error — subsequent `$` calls are not executed.
1235
1386
  *
1236
1387
  * Uses an `IOEscape` sentinel internally to preserve the typed error `E` through
1237
1388
  * JavaScript's throw/catch mechanism, ensuring the error channel remains type-safe.
@@ -1242,19 +1393,19 @@ export declare class IO<E, A> {
1242
1393
  *
1243
1394
  * @template E The error type shared by all bound IO operations.
1244
1395
  * @template A The final success type produced by the comprehension.
1245
- * @param {(bind: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>} operation
1246
- * An async function that receives a `bind` callback for unwrapping IO values.
1396
+ * @param {($: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>} operation
1397
+ * An async function that receives a `$` callback for unwrapping IO values.
1247
1398
  * @param {(e: unknown) => E} [liftE] Optional function to transform non-IO exceptions into E.
1248
1399
  * @returns {IO<E, A>} An IO that, when executed, runs the comprehension.
1249
1400
  *
1250
1401
  * @example
1251
- * const io = IO.forM<AppError, number>(async bind => {
1252
- * const user = await bind(fetchUser(userId));
1253
- * const orders = await bind(fetchOrders(user.id));
1402
+ * const io = IO.forM<AppError, number>(async ($) => {
1403
+ * const user = await $(fetchUser(userId));
1404
+ * const orders = await $(fetchOrders(user.id));
1254
1405
  * return orders.length;
1255
1406
  * });
1256
1407
  */
1257
- static forM<E, A>(operation: (bind: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>, liftE?: (e: unknown) => E): IO<E, A>;
1408
+ static forM<E, A>(operation: ($: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>, liftE?: (e: unknown) => E): IO<E, A>;
1258
1409
  /**
1259
1410
  * Sequentially executes a function over each item, collecting results into an array.
1260
1411
  * Fail-fast: if any invocation fails, the remaining items are not processed and the
@@ -1352,6 +1503,7 @@ export declare class Left<A> extends Either<A, never> {
1352
1503
  flatMap<F, C>(_: (right: never) => Either<F, C>): Either<A | F, C>;
1353
1504
  getOrElse(defaultValue: (left: A) => never): never;
1354
1505
  getOrNull(): null;
1506
+ getOrThrow(toCause?: (left: A) => unknown): never;
1355
1507
  swap(): Either<never, A>;
1356
1508
  fold<C>(ifLeft: (left: A) => C, _: (right: never) => C): C;
1357
1509
  tap(_: (right: never) => void): Either<A, never>;
@@ -2169,6 +2321,7 @@ export declare class None extends Option<never> {
2169
2321
  fold<B>(ifNone: () => B, _: (right: never) => B): B;
2170
2322
  getOrElse(defaultValue: () => never): never;
2171
2323
  getOrNull(): null;
2324
+ getOrThrow(toCause?: () => unknown): never;
2172
2325
  tap(_: (value: never) => void): Option<never>;
2173
2326
  tapNone(f: () => void): Option<never>;
2174
2327
  }
@@ -2831,7 +2984,13 @@ export declare class NonEmptyList<A> {
2831
2984
  }
2832
2985
 
2833
2986
  /**
2834
- * A body result that is not a promise: an `async` body would return before its `bind`s ran, so
2987
+ * `unknown` when no part of `B` is an `IO`, `never` otherwise. Intersected with a callback's return
2988
+ * type, it refuses a callback that returns an `IO` where a plain value is expected.
2989
+ */
2990
+ declare type NotAnIO<B> = [Extract<B, IO<unknown, unknown>>] extends [never] ? unknown : never;
2991
+
2992
+ /**
2993
+ * A body result that is not a promise: an `async` body would return before its `$` calls ran, so
2835
2994
  * `forM` rejects it at compile time (and with a `TypeError` at run time).
2836
2995
  */
2837
2996
  declare type NotThenable = {
@@ -2975,21 +3134,21 @@ export declare abstract class Option<A> {
2975
3134
  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
3135
  /**
2977
3136
  * 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
3137
+ * `$(option)` returns the `Some` value; the first `None` stops the body, and `forM` returns
2979
3138
  * `None`. The body's return value becomes the result, `None` when it is `null` or `undefined`.
2980
3139
  * An exception is not caught: it propagates from `forM`.
2981
3140
  *
2982
- * `bind` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
3141
+ * `$` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
2983
3142
  * not handle, and the body must be synchronous.
2984
3143
  *
2985
3144
  * @example
2986
- * const city = Option.forM((bind) => {
2987
- * const user = bind(findUser(id));
2988
- * const address = bind(user.address);
3145
+ * const city = Option.forM(($) => {
3146
+ * const user = $(findUser(id));
3147
+ * const address = $(user.address);
2989
3148
  * return address.city;
2990
3149
  * }); // Option<string>
2991
3150
  */
2992
- static forM<A>(operation: (bind: <B>(option: Option<B>) => B) => A & NotThenable): Option<NonNullable<A>>;
3151
+ static forM<A>(operation: ($: <B>(option: Option<B>) => B) => A & NotThenable): Option<NonNullable<A>>;
2993
3152
  /**
2994
3153
  * Applies one of two provided functions based on the contents of this `Option`.
2995
3154
  * If it is `None`, it applies `ifNone`. If it is `Some`, it applies `ifSome`.
@@ -3016,6 +3175,21 @@ export declare abstract class Option<A> {
3016
3175
  *
3017
3176
  */
3018
3177
  abstract getOrElse(defaultValue: () => A): A;
3178
+ /**
3179
+ * Returns the contained value. For `None`, **throws**: use it to end a computation with a bug, a
3180
+ * missing value that the caller knows cannot happen. The thrown value is `toCause()`, or an
3181
+ * `Error` that says the `Option` is `None` without `toCause`; a primitive is wrapped in an
3182
+ * `Error` that keeps it as `cause`.
3183
+ *
3184
+ * It is a plain throw. Inside `IO.sync`, `map`, `flatMap` or `tap` it is a defect; inside
3185
+ * `IO.lift`, `IO.cancellable`, `Either.catch` or a `forM` body with a `liftE`, it becomes a typed
3186
+ * failure like any throw there. In those places use the effect form instead, which is a defect
3187
+ * everywhere: `$(IO.from(option, () => missing).orDefect())`.
3188
+ *
3189
+ * @example
3190
+ * const admin = Option.ofNullable(seed.admin).getOrThrow(() => new Error("The seed data has no admin"));
3191
+ */
3192
+ abstract getOrThrow(toCause?: () => unknown): A;
3019
3193
  }
3020
3194
 
3021
3195
  /**
@@ -3675,11 +3849,11 @@ export declare type Pipe<E, A, B> = (stream: Stream<E, A>) => Stream<E, B>;
3675
3849
  *
3676
3850
  * @example
3677
3851
  * // Turn an EventEmitter into a Stream
3678
- * const program = IO.forM<never, void>(async (bind) => {
3679
- * const queue = await bind(Queue.bounded<Message>(1024, OverflowStrategy.DropOldest));
3852
+ * const program = IO.forM<never, void>(async ($) => {
3853
+ * const queue = await $(Queue.bounded<Message>(1024, OverflowStrategy.DropOldest));
3680
3854
  * emitter.on("message", (m) => queue.unsafeOffer(m));
3681
3855
  * emitter.once("close", () => queue.unsafeClose());
3682
- * await bind(Stream.from(queue).runForEach((m) => handle(m)));
3856
+ * await $(Stream.from(queue).runForEach((m) => handle(m)));
3683
3857
  * });
3684
3858
  */
3685
3859
  export declare class Queue<in out A> {
@@ -4087,11 +4261,11 @@ declare type ReaderValue<T> = T extends Reader<never, infer A> ? A : never;
4087
4261
  * @typeParam A The type of the value held in the cell.
4088
4262
  *
4089
4263
  * @example
4090
- * const program = IO.forM<never, number>(async (bind) => {
4091
- * const counter = await bind(Ref.of(0));
4092
- * await bind(counter.update((n) => n + 1));
4093
- * await bind(counter.update((n) => n + 1));
4094
- * return bind(counter.get());
4264
+ * const program = IO.forM<never, number>(async ($) => {
4265
+ * const counter = await $(Ref.of(0));
4266
+ * await $(counter.update((n) => n + 1));
4267
+ * await $(counter.update((n) => n + 1));
4268
+ * return $(counter.get());
4095
4269
  * });
4096
4270
  * await program.unsafeRun(); // { type: "Ok", value: 2 }
4097
4271
  */
@@ -4179,6 +4353,222 @@ export declare class Ref<in out A> {
4179
4353
  /** How the `use` step of a `bracket` ended, as its release receives it. */
4180
4354
  export declare type ReleaseExit<E, A> = Exit<E, A> | Defect;
4181
4355
 
4356
+ /**
4357
+ * A resource that opens with an effect and closes with another: a database pool, an HTTP server, a
4358
+ * worker queue. A `Resource` is a description, like an {@link IO}: nothing opens until {@link use}
4359
+ * runs, and each `use` opens its own copy.
4360
+ *
4361
+ * Resources compose with {@link flatMap}, {@link zip} and {@link forM}. `use` opens them in order,
4362
+ * runs its body, and then closes them in reverse order, whatever happened: success, failure, defect
4363
+ * or cancellation. Each open stays next to its close, and the close order follows from the open
4364
+ * order.
4365
+ *
4366
+ * For one resource used inside one step, {@link IO.bracket} is enough. A `Resource` is for several
4367
+ * resources that live as long as a process.
4368
+ *
4369
+ * @typeParam E The error type of opening.
4370
+ * @typeParam A The value the resource gives to its use.
4371
+ *
4372
+ * @example
4373
+ * const server = Resource.forM<StartFailure, RunningServer>(async ($) => {
4374
+ * const db = await $(Resource.make(openPool(config), (pool) => closePool(pool)));
4375
+ * const http = await $(Resource.make(listen(db), (server) => stopListening(server)));
4376
+ * return { db, http };
4377
+ * });
4378
+ *
4379
+ * // Closes the HTTP server first, then the pool.
4380
+ * await server.use(() => untilSignal).unsafeRun();
4381
+ */
4382
+ export declare class Resource<E, A> {
4383
+ private readonly open;
4384
+ /** Build a `Resource` through its static constructors: `Resource.make`, `Resource.of`, `Resource.eval`. */
4385
+ private constructor();
4386
+ /**
4387
+ * A resource that opens with `acquire` and closes with `release`. `release` learns how the use
4388
+ * ended: `Ok` with the use's value, `Err` with its error, `Cancelled`, or `Defect`. When a later
4389
+ * resource fails to open, `release` receives that `Err`.
4390
+ *
4391
+ * `acquire` runs masked, as in {@link IO.bracket}. If the use is cancelled while `acquire` runs,
4392
+ * the use ends as `Cancelled` at once, and a value `acquire` still produces later is released as
4393
+ * soon as it arrives, with `Cancelled`.
4394
+ *
4395
+ * `release` runs to its end, without the abort signal. A release that never ends holds the use for
4396
+ * ever, even under `timeout`, so a release that may hang bounds its own time with `timeout`.
4397
+ *
4398
+ * If `release` fails (throws, even before it returns its `IO`, or rejects) after a successful use,
4399
+ * the use fails with that failure as a defect. After a failed, defective or cancelled use, and for a
4400
+ * value released after it arrived late, the failure is dropped and leaves no trace: a release whose
4401
+ * failure matters handles it itself, for example by logging it.
4402
+ *
4403
+ * @template E The error type of `acquire`.
4404
+ * @template A The value `acquire` produces.
4405
+ * @param {IO<E, A>} acquire Opens the resource.
4406
+ * @param {(a: A, exit: ReleaseExit<unknown, unknown>) => IO<never, void>} release Closes the
4407
+ * resource. Must not fail.
4408
+ * @returns {Resource<E, A>}
4409
+ *
4410
+ * @example
4411
+ * const pool = Resource.make(
4412
+ * IO.lift(() => createPool(config), toDbError),
4413
+ * (pool) => IO.promise(() => pool.end())
4414
+ * );
4415
+ */
4416
+ static make<E, A>(acquire: IO<E, A>, release: (a: A, exit: ReleaseExit<unknown, unknown>) => IO<never, void>): Resource<E, A>;
4417
+ /**
4418
+ * A step with nothing to open, whose `release` runs when the use ends, in its place in the reverse
4419
+ * order. `release` learns how the use ended and follows the rules of a {@link make} release. Use it
4420
+ * for a shutdown step that only closes, such as draining work that exists from the start.
4421
+ *
4422
+ * @param {(exit: ReleaseExit<unknown, unknown>) => IO<never, void>} release Runs when the use ends.
4423
+ * Must not fail.
4424
+ * @returns {Resource<never, void>}
4425
+ *
4426
+ * @example
4427
+ * await $(Resource.onClose(() => IO.promise(() => work.drain()))); // after serving stops, before the pool closes
4428
+ */
4429
+ static onClose(release: (exit: ReleaseExit<unknown, unknown>) => IO<never, void>): Resource<never, void>;
4430
+ /**
4431
+ * A plain value, with nothing to close.
4432
+ *
4433
+ * @template A The type of the value.
4434
+ * @param {A} value The value.
4435
+ * @returns {Resource<never, A>}
4436
+ *
4437
+ * @example
4438
+ * const config = Resource.of({ port: 8080 });
4439
+ */
4440
+ static of<A>(value: A): Resource<never, A>;
4441
+ /**
4442
+ * An effect with nothing to close. It runs each time the resource is used, not when it is built.
4443
+ *
4444
+ * @template E The error type of `io`.
4445
+ * @template A The success type of `io`.
4446
+ * @param {IO<E, A>} io The effect.
4447
+ * @returns {Resource<E, A>}
4448
+ *
4449
+ * @example
4450
+ * const app = Resource.eval(IO.sync(() => App.create(options)));
4451
+ */
4452
+ static eval<E, A>(io: IO<E, A>): Resource<E, A>;
4453
+ /**
4454
+ * Combines independent resources into one that gives a tuple of their values. They open in the
4455
+ * order given and close in reverse order. When one fails to open, the ones already open close.
4456
+ *
4457
+ * @template T The resources, as a tuple.
4458
+ * @param {T} resources The resources to combine.
4459
+ * @returns A resource whose error is the union of their errors, and whose value is the tuple of
4460
+ * their values.
4461
+ *
4462
+ * @example
4463
+ * const both = Resource.zip(pool, cache); // Resource<DbError | CacheError, readonly [Pool, Cache]>
4464
+ * await both.use(([pool, cache]) => serve(pool, cache)).unsafeRun();
4465
+ */
4466
+ static zip<const T extends readonly Resource<any, any>[]>(...resources: T): Resource<ResourceError<T[number]>, {
4467
+ [K in keyof T]: ResourceValue<T[K]>;
4468
+ }>;
4469
+ /**
4470
+ * Monadic for-comprehension, like {@link IO.forM}. Each `$(resource)` call opens a resource and
4471
+ * returns its value; the resource stays open until the use ends. Resources close in reverse order
4472
+ * of the `$` calls. When one fails to open, the comprehension stops with its error, and the ones
4473
+ * already open close.
4474
+ *
4475
+ * `$` takes a `Resource` only, so each step says whether it opens something that closes. A step
4476
+ * with nothing to close is `$(Resource.eval(io))`. Await every `$` call: one the body does not
4477
+ * await opens in an order nobody chose.
4478
+ *
4479
+ * When `liftE` is provided, exceptions thrown inside the body become errors of type `E`. Without
4480
+ * `liftE` such an exception is a defect.
4481
+ *
4482
+ * @template E The error type shared by all opened resources.
4483
+ * @template A The value the comprehension gives to its use.
4484
+ * @param {($: <B>(resource: Resource<E, B>) => Promise<B>) => Promise<A>} body An async function
4485
+ * that receives a `$` callback for opening resources.
4486
+ * @param {(e: unknown) => E} [liftE] Optional function to turn exceptions into E.
4487
+ * @returns {Resource<E, A>}
4488
+ *
4489
+ * @example
4490
+ * const server = Resource.forM<StartFailure, RunningServer>(async ($) => {
4491
+ * const app = await $(Resource.eval(IO.sync(() => App.create(options)))); // nothing to close
4492
+ * const account = await $(Resource.make(startAccount(app), (a) => a.close));
4493
+ * await $(Resource.make(listen(app), () => App.close(app))); // closed first
4494
+ * return { app, account };
4495
+ * });
4496
+ */
4497
+ static forM<E, A>(body: ($: <B>(resource: Resource<E, B>) => Promise<B>) => Promise<A>, liftE?: (e: unknown) => E): Resource<E, A>;
4498
+ /**
4499
+ * Opens the resource, runs `f` with its value, and then closes everything it opened, in reverse
4500
+ * order. The closes run after a success, a failure, a defect and a cancellation alike, to their end
4501
+ * and without the abort signal.
4502
+ *
4503
+ * - A failing release after a successful `f` makes the use fail with a defect.
4504
+ * - After a failed, defective or cancelled `f`, a failing release is dropped and `f`'s outcome is
4505
+ * kept.
4506
+ *
4507
+ * @template F The error type of `f`.
4508
+ * @template B The success type of `f`.
4509
+ * @param {(a: A) => IO<F, B>} f Uses the resource.
4510
+ * @returns {IO<E | F, B>} An IO that opens, uses and closes.
4511
+ *
4512
+ * @example
4513
+ * const count = pool.use((pool) => IO.lift(() => pool.query("SELECT count(*) FROM users"), toDbError));
4514
+ */
4515
+ use<F, B>(f: (a: A) => IO<F, B>): IO<E | F, B>;
4516
+ /**
4517
+ * Transforms the value. The release is unchanged.
4518
+ *
4519
+ * @template B The new value type.
4520
+ * @param {(a: A) => B} f The transformation.
4521
+ * @returns {Resource<E, B>}
4522
+ *
4523
+ * @example
4524
+ * const users = pool.map((pool) => new UserRepository(pool));
4525
+ */
4526
+ map<B>(f: (a: A) => B): Resource<E, B>;
4527
+ /**
4528
+ * Opens a second resource that may depend on the value of the first. The second closes before the
4529
+ * first.
4530
+ *
4531
+ * @template F The error type of the second resource.
4532
+ * @template B The value type of the second resource.
4533
+ * @param {(a: A) => Resource<F, B>} f Builds the second resource from the first value.
4534
+ * @returns {Resource<E | F, B>}
4535
+ *
4536
+ * @example
4537
+ * const server = pool.flatMap((pool) => Resource.make(listen(pool), (server) => server.stop()));
4538
+ */
4539
+ flatMap<F, B>(f: (a: A) => Resource<F, B>): Resource<E | F, B>;
4540
+ /**
4541
+ * Transforms the error of opening. The error of the body given to {@link use} is not changed.
4542
+ *
4543
+ * @template F The new error type.
4544
+ * @param {(e: E) => F} f The transformation.
4545
+ * @returns {Resource<F, A>}
4546
+ *
4547
+ * @example
4548
+ * const pool = Resource.make(openPool(config), closePool).mapErr((e) => new StartFailure("db", e));
4549
+ */
4550
+ mapErr<F>(f: (e: E) => F): Resource<F, A>;
4551
+ /**
4552
+ * Turns every failure to open into a **defect** (see {@link IO.defect}), for an open the caller
4553
+ * knows cannot fail. The cause is `toCause(error)`, or the error itself without `toCause`. What
4554
+ * was already open closes with a `Defect` exit. The use's own failure is not touched.
4555
+ *
4556
+ * @param {(e: E) => unknown} [toCause] Builds the defect's cause from the error.
4557
+ * @returns {Resource<never, A>}
4558
+ *
4559
+ * @example
4560
+ * const cache = Resource.make(openInMemoryCache(), closeCache) // Resource<CacheError, Cache>
4561
+ * .orDefect((e) => new Error(`An in-memory cache cannot fail to open: ${e.kind}`));
4562
+ */
4563
+ orDefect(toCause?: (e: E) => unknown): Resource<never, A>;
4564
+ }
4565
+
4566
+ /** The error type of a resource; distributes over a union of resources. */
4567
+ declare type ResourceError<R> = R extends Resource<infer E, any> ? E : never;
4568
+
4569
+ /** The value type of a resource. */
4570
+ declare type ResourceValue<R> = R extends Resource<any, infer A> ? A : never;
4571
+
4182
4572
  export declare class Right<B> extends Either<never, B> {
4183
4573
  readonly value: B;
4184
4574
  readonly type: "Right";
@@ -4200,6 +4590,7 @@ export declare class Right<B> extends Either<never, B> {
4200
4590
  flatMap<F, C>(f: (right: B) => Either<F, C>): Either<F, C>;
4201
4591
  getOrElse(_: (left: never) => B): B;
4202
4592
  getOrNull(): B;
4593
+ getOrThrow(_?: (left: never) => unknown): B;
4203
4594
  swap(): Either<B, never>;
4204
4595
  fold<C>(_: (left: never) => C, ifRight: (right: B) => C): C;
4205
4596
  tap(action: (right: B) => void): Either<never, B>;
@@ -4334,6 +4725,7 @@ export declare class Some<A> extends Option<NonNullable<A>> {
4334
4725
  fold<B>(_: () => B, ifSome: (right: NonNullable<A>) => B): B;
4335
4726
  getOrElse(_: () => NonNullable<A>): NonNullable<A>;
4336
4727
  getOrNull(): NonNullable<A>;
4728
+ getOrThrow(_?: () => unknown): NonNullable<A>;
4337
4729
  tap(f: (value: NonNullable<A>) => void): Option<NonNullable<A>>;
4338
4730
  tapNone(_: () => void): Option<NonNullable<A>>;
4339
4731
  }
@@ -4524,6 +4916,20 @@ export declare class Stream<E, A> {
4524
4916
  * Transforms the error channel with `f`, leaving emitted elements unchanged.
4525
4917
  */
4526
4918
  mapErr<F>(f: (e: E) => F): Stream<F, A>;
4919
+ /**
4920
+ * Turns every failure of this stream into a **defect** (see {@link IO.defect}), for a failure the
4921
+ * caller knows cannot happen. The cause is `toCause(error)`, or the error itself without
4922
+ * `toCause`. Elements emitted before the failure are emitted as usual; finalizers and `bracket`
4923
+ * releases receive a `Defect` exit.
4924
+ *
4925
+ * @param {(error: E) => unknown} [toCause] Builds the defect's cause from the error.
4926
+ * @returns {Stream<never, A>} The same stream, with no failure left in its type.
4927
+ *
4928
+ * @example
4929
+ * // Reading a file bundled with the program cannot fail unless the build is broken.
4930
+ * const lines: Stream<never, string> = Stream.fromAsync(bundledLines()).orDefect();
4931
+ */
4932
+ orDefect(toCause?: (error: E) => unknown): Stream<never, A>;
4527
4933
  /**
4528
4934
  * Keeps only the elements for which the type guard holds. The element type is narrowed to `B`.
4529
4935
  *