functype 1.27.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +70 -88
  2. package/dist/_virtual/_rolldown/runtime.js +1 -0
  3. package/dist/branded/ValidatedBrand.d.ts +122 -0
  4. package/dist/branded/ValidatedBrand.js +1 -0
  5. package/dist/branded/index.d.ts +52 -2
  6. package/dist/cli/data.d.ts +37 -0
  7. package/dist/cli/data.js +1 -0
  8. package/dist/cli/exports.d.ts +5 -46
  9. package/dist/cli/exports.js +1 -1
  10. package/dist/cli/formatters.js +4 -0
  11. package/dist/cli/full-interfaces.d.ts +6 -0
  12. package/dist/cli/full-interfaces.js +1150 -0
  13. package/dist/cli/index.js +3 -6
  14. package/dist/cli/interfaces.generated.js +1 -0
  15. package/dist/collections/index.d.ts +13 -0
  16. package/dist/companion/Companion.d.ts +23 -0
  17. package/dist/companion/Companion.js +1 -0
  18. package/dist/companion/CompanionTypes.d.ts +30 -0
  19. package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
  20. package/dist/companion/index.d.ts +2 -1
  21. package/dist/companion/index.js +1 -1
  22. package/dist/conditional/Cond.d.ts +147 -0
  23. package/dist/conditional/Cond.js +1 -0
  24. package/dist/conditional/Match.d.ts +295 -0
  25. package/dist/conditional/Match.js +1 -0
  26. package/dist/conditional/index.d.ts +3 -2
  27. package/dist/conditional/index.js +1 -1
  28. package/dist/core/base/Base.d.ts +12 -0
  29. package/dist/core/base/Base.js +1 -0
  30. package/dist/core/throwable/Throwable.d.ts +38 -0
  31. package/dist/core/throwable/Throwable.js +1 -0
  32. package/dist/decoder/Decoder.d.ts +15 -0
  33. package/dist/decoder/DecoderCompanion.js +1 -0
  34. package/dist/decoder/DecoderError.d.ts +56 -0
  35. package/dist/decoder/DecoderError.js +2 -0
  36. package/dist/decoder/Encoder.d.ts +15 -0
  37. package/dist/decoder/index.d.ts +71 -2
  38. package/dist/decoder/index.js +1 -1
  39. package/dist/decoder/tagged.js +1 -0
  40. package/dist/do/index.d.ts +246 -2
  41. package/dist/do/index.js +1 -1
  42. package/dist/do/protocol.d.ts +29 -0
  43. package/dist/either/index.d.ts +290 -2
  44. package/dist/either/index.js +1 -1
  45. package/dist/error/ErrorChain.d.ts +60 -0
  46. package/dist/error/ErrorChain.js +4 -0
  47. package/dist/error/ErrorFormatter.d.ts +67 -0
  48. package/dist/error/ErrorFormatter.js +6 -0
  49. package/dist/error/ParseError.d.ts +6 -0
  50. package/dist/error/ParseError.js +1 -0
  51. package/dist/error/typed/TypedError.d.ts +146 -0
  52. package/dist/error/typed/TypedError.js +1 -0
  53. package/dist/error/typed/Validation.d.ts +76 -0
  54. package/dist/error/typed/Validation.js +1 -0
  55. package/dist/extractable/Extractable.d.ts +62 -0
  56. package/dist/extractable/Extractable.js +1 -0
  57. package/dist/fetch/Http.d.ts +32 -0
  58. package/dist/fetch/Http.js +1 -0
  59. package/dist/fetch/HttpClient.d.ts +80 -0
  60. package/dist/fetch/HttpClient.js +1 -0
  61. package/dist/fetch/HttpError.d.ts +57 -0
  62. package/dist/fetch/HttpError.js +1 -0
  63. package/dist/fetch/HttpRequest.d.ts +103 -0
  64. package/dist/fetch/index.d.ts +5 -2
  65. package/dist/fetch/index.js +1 -1
  66. package/dist/foldable/Foldable.d.ts +27 -0
  67. package/dist/foldable/index.d.ts +55 -0
  68. package/dist/foldable/index.js +1 -0
  69. package/dist/functype/Functype.d.ts +76 -0
  70. package/dist/functype/FunctypeSum.d.ts +39 -0
  71. package/dist/functype/index.d.ts +4 -2
  72. package/dist/hkt/index.d.ts +68 -0
  73. package/dist/hkt/index.js +1 -0
  74. package/dist/identity/Identity.d.ts +34 -0
  75. package/dist/identity/Identity.js +1 -0
  76. package/dist/index.d.ts +74 -8
  77. package/dist/index.js +1 -1
  78. package/dist/internal/base64.js +1 -0
  79. package/dist/internal/call-alone.js +1 -0
  80. package/dist/internal/concurrency.d.ts +11 -0
  81. package/dist/internal/concurrency.js +1 -0
  82. package/dist/internal/define.js +1 -0
  83. package/dist/internal/mutation-utils.js +1 -0
  84. package/dist/internal/signal.js +1 -0
  85. package/dist/internal/stringify.js +1 -0
  86. package/dist/invariant/index.d.ts +32 -2
  87. package/dist/io/Context.d.ts +112 -0
  88. package/dist/io/Context.js +1 -0
  89. package/dist/io/Exit.d.ts +249 -0
  90. package/dist/io/Exit.js +1 -0
  91. package/dist/io/IO.d.ts +1263 -0
  92. package/dist/io/IO.js +1 -0
  93. package/dist/io/Layer.d.ts +139 -0
  94. package/dist/io/Layer.js +1 -0
  95. package/dist/io/SpanTracer.d.ts +78 -0
  96. package/dist/io/SpanTracer.js +1 -0
  97. package/dist/io/Tag.d.ts +75 -0
  98. package/dist/io/Tag.js +1 -0
  99. package/dist/io/TestClock.d.ts +133 -0
  100. package/dist/io/TestClock.js +1 -0
  101. package/dist/io/index.d.ts +41 -2
  102. package/dist/io/index.js +1 -1
  103. package/dist/lazy/Lazy.d.ts +312 -0
  104. package/dist/lazy/Lazy.js +1 -0
  105. package/dist/lazy/index.d.ts +2 -2
  106. package/dist/lazy/index.js +1 -1
  107. package/dist/list/LazyList.d.ts +182 -0
  108. package/dist/list/LazyList.js +1 -0
  109. package/dist/list/index.d.ts +137 -2
  110. package/dist/list/index.js +1 -1
  111. package/dist/logger/index.d.ts +24 -2
  112. package/dist/map/index.d.ts +95 -2
  113. package/dist/map/index.js +1 -1
  114. package/dist/map/shim.d.ts +13 -0
  115. package/dist/map/shim.js +1 -0
  116. package/dist/matchable/Matchable.d.ts +38 -0
  117. package/dist/matchable/Matchable.js +1 -0
  118. package/dist/obj/Obj.d.ts +212 -0
  119. package/dist/obj/Obj.js +1 -0
  120. package/dist/obj/index.d.ts +2 -2
  121. package/dist/obj/index.js +1 -1
  122. package/dist/option/index.d.ts +304 -2
  123. package/dist/option/index.js +1 -1
  124. package/dist/package.json.js +1 -0
  125. package/dist/pipe/index.d.ts +14 -0
  126. package/dist/ref/Ref.d.ts +77 -0
  127. package/dist/ref/Ref.js +1 -0
  128. package/dist/reshapeable/Reshapeable.d.ts +90 -0
  129. package/dist/serializable/Serializable.d.ts +39 -0
  130. package/dist/serialization/Serialization.d.ts +147 -0
  131. package/dist/serialization/Serialization.js +1 -0
  132. package/dist/serialization/SerializationCompanion.d.ts +125 -0
  133. package/dist/serialization/SerializationCompanion.js +1 -0
  134. package/dist/serialization/error-envelope.d.ts +44 -0
  135. package/dist/serialization/error-envelope.js +1 -0
  136. package/dist/serialization/index.d.ts +4 -2
  137. package/dist/serialization/index.js +1 -1
  138. package/dist/set/index.d.ts +106 -2
  139. package/dist/set/index.js +1 -1
  140. package/dist/stack/Stack.d.ts +120 -0
  141. package/dist/stack/Stack.js +1 -0
  142. package/dist/traced/TraceEvent.d.ts +27 -0
  143. package/dist/traced/TracedOption.d.ts +46 -0
  144. package/dist/traced/TracedOption.js +1 -0
  145. package/dist/traced/Tracer.d.ts +26 -0
  146. package/dist/traversable/KVTraversable.d.ts +14 -0
  147. package/dist/traversable/Traversable.d.ts +30 -0
  148. package/dist/try/index.d.ts +238 -2
  149. package/dist/try/index.js +1 -1
  150. package/dist/tuple/index.d.ts +92 -2
  151. package/dist/tuple/index.js +1 -1
  152. package/dist/typeable/Typeable.d.ts +40 -0
  153. package/dist/typeable/Typeable.js +1 -0
  154. package/dist/typeclass/ContainerOps.d.ts +131 -0
  155. package/dist/typeclass/Functor.d.ts +41 -0
  156. package/dist/typeclass/Promisable.d.ts +33 -0
  157. package/dist/typeclass/index.d.ts +4 -1
  158. package/dist/typeclass/index.js +1 -1
  159. package/dist/typeclass/variance.d.ts +54 -0
  160. package/dist/typeclass/variance.js +1 -0
  161. package/dist/types/index.d.ts +1 -0
  162. package/dist/util/index.d.ts +1 -3
  163. package/dist/valuable/Valuable.d.ts +28 -0
  164. package/dist/valuable/Valuable.js +1 -0
  165. package/dist/wire/index.d.ts +40 -2
  166. package/package.json +8 -13
  167. package/dist/Brand-bfnGXuum.d.ts +0 -54
  168. package/dist/Companion-DiOMBHDG.js +0 -1
  169. package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
  170. package/dist/Invariant-DEan-SxV.d.ts +0 -35
  171. package/dist/Logger-BmprRS8v.d.ts +0 -27
  172. package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
  173. package/dist/Wire-3hvw0Ogg.d.ts +0 -42
  174. package/dist/core/task/index.d.ts +0 -2
  175. package/dist/core/task/index.js +0 -1
  176. package/dist/full-interfaces-BadxJrCt.js +0 -1202
  177. package/dist/index-CLYh2qZu.d.ts +0 -6649
  178. package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
  179. package/dist/serialization-9_SyrfdG.js +0 -3
  180. package/dist/src-BQPeS6p2.js +0 -10
  181. package/dist/typeclass-C61yDVYd.js +0 -1
@@ -1,1202 +0,0 @@
1
- var e=`1.27.2`;const t={Option:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Matchable`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`,`Traversable`],Either:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],Try:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],List:[`Collection`,`Doable`,`Iterable`,`Reshapeable`],Set:[`Collection`,`Iterable`],Map:[`Collection`,`Foldable`,`Iterable`,`KVTraversable`,`Serializable`],Obj:[`Doable`,`Promisable`,`Reshapeable`],Lazy:[`Applicative`,`AsyncMonad`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Serializable`,`Traversable`],LazyList:[`Foldable`,`Serializable`],Tuple:[`Foldable`,`Serializable`],Task:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Serializable`,`Traversable`]},n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.orElse(d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.orElse(d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.orElse(d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head`,`.headOption`,`.tail`,`.last`,`.lastOption`,`.init`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromYAML(yaml)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, d)`,`.orElse(k, Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.orElse(d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head`,`.headOption`,`.tail`,`.last`,`.lastOption`,`.init`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Task:{description:`Async operations with cancellation and progress tracking. Returns TaskOutcome<T> (Ok/Err) which implements Functor, AsyncMonad, Foldable, Extractable, Serializable`,interfaces:r(`Task`),methods:{create:[`Task(params).Async(fn, errFn)`,`Task(params).Sync(fn, errFn)`,`Task.ok(value)`,`Task.err(error)`,`Task.fromEither(either)`,`Task.fromTry(try)`,`Task.fromPromise(fn)`,`Task.fromNodeCallback(fn)`,`Task.fromJSON(json) — reconstruct from serialize() output`],transform:[`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.fold(onErr, onOk)`,`.match({Ok, Err})`,`.orElse(v)`,`.orThrow()`,`.toEither()`,`.toOption()`,`.toJSON()`],other:[`Task.cancellable(fn)`,`Task.withProgress(fn, onProgress)`,`Task.race(tasks, timeout?)`,`Task.getErrorChain(error)`,`Task.formatErrorChain(error)`]}},TaskOutcome:{description:`Result of a Task execution — Ok<T> or Err<T>. Implements Functor, AsyncMonad, Foldable, Extractable, Serializable. Construct via Ok(v) / Err(e) or as the resolved value of Task(...).Sync() / Task(...).Async().`,interfaces:[`AsyncMonad`,`Extractable`,`Foldable`,`Functor`,`Serializable`],methods:{create:[`Ok(value)`,`Err(error)`,`Task.ok(value)`,`Task.err(error)`],transform:[`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`,`.mapAsync(f)`,`.flatMapAsync(f)`],extract:[`.fold(onErr, onOk)`,`.match({Ok, Err})`,`.orElse(v)`,`.orThrow()`,`.toEither()`,`.toOption()`,`.toJSON()`],check:[`.isOk()`,`.isErr()`,`.isSuccess()`,`.isFailure()`]}},TaskResult:{description:"Type alias for `Promise<TaskOutcome<T>>`. Returned by Task(params).Async(...) and adapter functions like Fs.readFile, Process.exec. Await it to get the inner TaskOutcome; chain Promise methods on the outside, TaskOutcome methods after the await.",interfaces:[],methods:{create:[`Task(params).Async(fn, errFn) → TaskResult<T>`,`Task.fromPromise(fn) → (...args) => TaskResult<U>`],other:[`await taskResult → TaskOutcome<T>`,`// then use any TaskOutcome method (.fold, .map, .toEither, ...)`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() cannot show it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.orElse(v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — a defect or interruption arrives in the Left, raw`,`.runOrThrow()`,`.runSync()`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms)`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // in order by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...])`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.orElse(default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},Stack:{description:`Immutable LIFO stack`,interfaces:[`Foldable`,`Collection`,`Serializable`,`Traversable`],methods:{create:[`Stack()`,`Stack.of(...)`],transform:[`.push(v)`,`.pop()`],extract:[`.peek()`,`.toArray()`],check:[`.isEmpty`,`.size`]}},Http:{description:"HTTP fetch wrapper returning IO<never, HttpError, HttpResponse<T>>. Pass `decode: Decoder<T>` (Either-returning) for typed responses; the deprecated `validate: (data) => T` field is still accepted for throw-pattern back-compat. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse })`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`validate: (data) => T (deprecated, throws — for back-compat / Zod .parse)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 12 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy, Task)`,`Algebraic square: serialize ≡ JSON.stringify ∘ toEnvelope; deserialize ≡ fromEnvelope ∘ JSON.parse`,`No DBOS / SuperJSON facade — consumers wire host serializer in ~8 lines via toEnvelope/fromEnvelope`]}},SerializedError:{description:"Canonical Error projection used by Try.Failure, Task.Err, Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.orElse(d: T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toYAML(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Task`,`TaskOutcome`,`TaskResult`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`]},s={Option:`export interface Option<out T extends Type>
2
- extends Functype<T, "Some" | "None">, Promisable<T>, Doable<T>, Reshapeable<T> {
3
- /** The contained value (undefined for None) */
4
- readonly value: T | undefined
5
- /** Whether this Option contains no value */
6
- isEmpty: boolean
7
- /**
8
- * Returns true if this Option is a Some (contains a value)
9
- * @returns true if this Option contains a value, false otherwise
10
- */
11
- isSome(): this is Option<T> & { value: T; isEmpty: false }
12
- /**
13
- * Returns true if this Option is a None (contains no value)
14
- * @returns true if this Option is empty, false otherwise
15
- */
16
- isNone(): this is Option<T> & { value: undefined; isEmpty: true }
17
- /**
18
- * Returns the contained value or a default value if None. The default may be of a
19
- * different type; the result widens to \`T | T2\` so Option stays covariant in T.
20
- * @param defaultValue - The value to return if this Option is None
21
- * @returns The contained value or defaultValue, typed as \`T | T2\`
22
- */
23
- orElse<T2 extends Type>(defaultValue: T2): T | T2
24
- /**
25
- * Returns the contained value or throws an error if None
26
- * @param error - Optional error to throw, or a builder that makes one (called only on None). If not
27
- * provided, throws a default error
28
- * @returns The contained value
29
- * @throws The specified or built error, or a default error if the Option is None
30
- */
31
- orThrow(error?: Error | (() => Error)): T
32
- /**
33
- * Returns the contained value, or calls the never-returning handler if None.
34
- * Use this when you have a helper like \`(msg) => fail(msg, 2)\` that terminates the
35
- * program — the result type is unconditionally \`T\`, so you avoid the TypeScript
36
- * narrowing trap where \`if (o.isNone()) fail(...)\` fails to narrow \`o.value\` when
37
- * \`fail\` is an arrow function typed as \`(...): never\`.
38
- */
39
- expect(handler: () => never): T
40
- /**
41
- * Returns this Option if it contains a value, otherwise returns the alternative container.
42
- * The alternative may hold a different type; the result widens to \`Option<T | T2>\`.
43
- * @param alternative - The alternative Option to return if this is None
44
- * @returns This Option or the alternative, typed as \`Option<T | T2>\`
45
- */
46
- or<T2 extends Type>(alternative: Option<T2>): Option<T | T2>
47
- /**
48
- * Returns the contained value or null if None
49
- * @returns The contained value or null
50
- */
51
- orNull(): T | null
52
- /**
53
- * Returns the contained value or undefined if None
54
- * @returns The contained value or undefined
55
- */
56
- orUndefined(): T | undefined
57
- /**
58
- * Maps the value inside the Option using the provided function
59
- * @param f - The mapping function
60
- * @returns A new Option containing the mapped value, or None if this Option is None
61
- */
62
- map<U extends Type>(f: (value: T) => U): Option<U>
63
- /**
64
- * Applies a wrapped function to a wrapped value (Applicative pattern)
65
- * @param ff - An Option containing a function from T to U
66
- * @returns A new Option containing the result of applying the function
67
- */
68
- ap<U extends Type>(ff: Option<(value: T) => U>): Option<U>
69
- /**
70
- * Returns this Option if it contains a value that satisfies the predicate, otherwise returns None
71
- * @param predicate - The predicate function to test the value
72
- * @returns This Option or None
73
- */
74
- filter(predicate: (value: T) => boolean): Option<T>
75
- /**
76
- * Maps the value using a function that returns an Option
77
- * @param f - The mapping function returning an Option
78
- * @returns The result of applying f to the contained value, or None if this Option is None
79
- */
80
- flatMap<U extends Type>(f: (value: T) => Option<U>): Option<U>
81
- /**
82
- * Maps the value using an async function that returns an Option
83
- * @param f - The async mapping function returning an Option
84
- * @returns Promise of the result of applying f to the contained value, or None if this Option is None
85
- */
86
- flatMapAsync<U extends Type>(f: (value: T) => Promise<Option<U>>): Promise<Option<U>>
87
- /**
88
- * Pattern matches over the Option, applying onNone if None and onSome if Some
89
- * @param onNone - Function to apply if the Option is None
90
- * @param onSome - Function to apply if the Option has a value
91
- * @returns The result of applying the appropriate function
92
- */
93
- fold<U>(onNone: () => U, onSome: (value: T) => U): U
94
- /**
95
- * Async variant of fold. Accepts sync or async handlers on either branch and
96
- * always returns a Promise.
97
- */
98
- foldAsync<U>(onNone: () => U | Promise<U>, onSome: (value: T) => U | Promise<U>): Promise<U>
99
- /**
100
- * Left-associative fold using the provided zero value and operation
101
- * @param z - Zero/identity value
102
- * @returns A function that takes an operation to apply
103
- */
104
- foldLeft<B>(z: B): (op: (b: B, a: T) => B) => B
105
- /**
106
- * Right-associative fold using the provided zero value and operation
107
- * @param z - Zero/identity value
108
- * @returns A function that takes an operation to apply
109
- */
110
- foldRight<B>(z: B): (op: (a: T, b: B) => B) => B
111
- /**
112
- * Checks if this Option contains the specified value
113
- * @param value - The value to check for
114
- * @returns true if this Option contains the value, false otherwise
115
- */
116
- contains(value: T): boolean
117
- /**
118
- * Tests whether the value, if there is one, satisfies the predicate. The dual of \`exists\`, and
119
- * Scala's \`forall\`: \`None\` gives \`true\`, the same way \`[].every(p)\` does.
120
- * @param p - The predicate to test the value with
121
- * @returns \`true\` for None, otherwise \`p(value)\`
122
- * @example
123
- * \`\`\`typescript
124
- * Option("abc").every((s) => s.length > 2) // true
125
- * Option<string>(undefined).every((s) => s.length > 2) // true: nothing to fail
126
- * \`\`\`
127
- */
128
- every(p: (a: T) => boolean): boolean
129
- /**
130
- * Converts this Option to a List.
131
- * @returns A List containing the value if Some, or empty List if None
132
- */
133
- toList(): List<T>
134
- /**
135
- * Converts this Option to a plain readonly array.
136
- * @returns \`[value]\` if Some, \`[]\` if None. Symmetric with \`toList()\` but
137
- * skips the List wrapper for code that just wants Array-prototype methods
138
- * or spread into another array.
139
- */
140
- toArray(): readonly T[]
141
- /** The number of elements in this Option (0 or 1) */
142
- size: number
143
- /**
144
- * Converts this Option to an Either
145
- * @param leftOrBuilder - The Left value to use if None, or a thunk producing it.
146
- * Pass a thunk when the Left value is expensive to construct or carries
147
- * context (e.g. \`() => ConfigError(missing)\`) so the cost is paid only
148
- * on the None path. Eager value is fine for cheap errors.
149
- * @returns Right(value) if Some, else Left(leftOrBuilder()) / Left(leftOrBuilder)
150
- */
151
- toEither<E>(leftOrBuilder: E | (() => E)): Either<E, T>
152
- /**
153
- * Returns a string representation of this Option
154
- * @returns A string representation
155
- */
156
- toString(): string
157
- /**
158
- * Returns a simple object representation of this Option
159
- * @returns An object with _tag and value properties
160
- */
161
- toValue(): { _tag: "Some" | "None"; value: T }
162
- /**
163
- * Custom JSON serialization producing the canonical \`@functype\`-marked
164
- * envelope so native \`JSON.stringify\` recursion (e.g. inside a plain
165
- * object) emits a round-trip-able shape.
166
- */
167
- toJSON(): { "@functype": "Option"; _tag: "Some" | "None"; value: T | null }
168
- /**
169
- * Pattern matches over the Option, applying a handler function based on the variant
170
- * @param patterns - Object with handler functions for Some and None variants
171
- * @returns The result of applying the matching handler function
172
- */
173
- match<R>(patterns: { Some: (value: T) => R; None: () => R }): R
174
- }`,Either:`export type Either<L extends Type, R extends Type> = LeftOf<L, R> | RightOf<L, R>
175
-
176
- export type TestEither<L extends Type, R extends Type> = Either<L, R> & AsyncMonad<R>
177
-
178
- const RightConstructor = <L extends Type, R extends Type>(value: R): RightOf<L, R> => ({
179
- [Symbol.toStringTag]: "Either",
180
- _tag: "Right" as const,
181
- value,
182
- isLeft(): this is LeftOf<L, R> {
183
- return false
184
- },
185
- isRight(): this is RightOf<L, R> {
186
- return true
187
- },
188
- orElse: <R2 extends Type>(_defaultValue: R2): R | R2 => value,
189
- orThrow: () => value,
190
- expect: (_handler: (value: L) => never): R => value,
191
- or: <L2 extends Type, R2 extends Type>(_alternative: Either<L2, R2>): Either<L | L2, R | R2> =>
192
- Right<L | L2, R | R2>(value),
193
- orNull: () => value,
194
- orUndefined: () => value,
195
- map: <U extends Type>(f: (value: R) => U): Either<L, U> => Right(f(value)),
196
- ap: <L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>): Either<L | L2, U> =>
197
- ff._tag === "Right" ? Right<L | L2, U>((ff.value as (value: R) => U)(value)) : Left<L | L2, U>(ff.value as L2),
198
- mapAsync: async <U extends Type>(f: (value: R) => Promise<U>): Promise<Either<L, U>> => Right<L, U>(await f(value)),
199
- merge: <L1 extends Type, R1 extends Type>(other: Either<L1, R1>): Either<L | L1, [R, R1]> =>
200
- other.isLeft() ? Left<L | L1, [R, R1]>(other.value as L1) : Right<L | L1, [R, R1]>([value, other.value as R1]),
201
- flatMap: <L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U> => f(value),
202
- flatMapAsync: async <L2 extends Type, U extends Type>(
203
- f: (value: R) => Promise<Either<L2, U>>,
204
- ): Promise<Either<L | L2, U>> => await f(value),
205
- toOption: () => Some<R>(value),
206
- toList: () => List<R>([value]),
207
- toEither: <E extends Type>(_leftValue: E) => Right<E, R>(value),
208
- toTry: () => Try(() => value),
209
- toJSON() {
210
- return { "@functype": "Either" as const, _tag: "Right" as const, value }
211
- },
212
- toString: () => {
213
- return \`Right(\${showValue(value)})\`
214
- },
215
- *[Symbol.iterator]() {
216
- yield value
217
- },
218
- *yield() {
219
- yield value
220
- },
221
- traverse: <L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>): Either<L | L2, U[]> => {
222
- const result = f(value)
223
- return result.isLeft() ? Left<L | L2, U[]>(result.value as L2) : Right<L | L2, U[]>([result.value as U])
224
- },
225
- tap: (f: (value: R) => void) => {
226
- f(value)
227
- return Right<L, R>(value)
228
- },
229
- tapLeft: (_f: (value: L) => void) => Right<L, R>(value),
230
- mapLeft: <L2 extends Type>(_f: (value: L) => L2) => Right<L2, R>(value),
231
- filterOrElse: <L2 extends Type>(
232
- predicate: (value: R) => boolean,
233
- onUnsatisfied: (value: R) => L2,
234
- ): Either<L | L2, R> => (predicate(value) ? Right<L | L2, R>(value) : Left<L | L2, R>(onUnsatisfied(value))),
235
- bimap: <L2 extends Type, R2 extends Type>(_fl: (value: L) => L2, fr: (value: R) => R2) => Right<L2, R2>(fr(value)),
236
- fold: <T extends Type>(_onLeft: (value: L) => T, onRight: (value: R) => T) => onRight(value),
237
- foldAsync: async <T extends Type>(_onLeft: (value: L) => T | Promise<T>, onRight: (value: R) => T | Promise<T>) =>
238
- onRight(value),
239
- foldLeft:
240
- <B>(z: B) =>
241
- (op: (b: B, a: R) => B) =>
242
- op(z, value),
243
- foldRight:
244
- <B>(z: B) =>
245
- (op: (a: R, b: B) => B) =>
246
- op(value, z),
247
- match: <T>(patterns: { Left: (value: L) => T; Right: (value: R) => T }): T => patterns.Right(value),
248
- swap: () => Left<R, L>(value),
249
- toPromise: (): Promise<R> => Promise.resolve(value),
250
- toValue: () => ({ _tag: "Right", value }),
251
- pipeEither: <U extends Type>(_onLeft: (value: L) => U, onRight: (value: R) => U) => onRight(value),
252
- pipe: <U extends Type>(f: (value: L | R) => U) => f(value),
253
- serialize: () => createSerializer("Either", "Right", value),
254
- contains: (v: R) => value === v,
255
- exists: (p: (a: R) => boolean) => p(value),
256
- every: (p: (a: R) => boolean) => p(value),
257
- forEach: (f: (a: R) => void) => f(value),
258
- // Implement Doable interface for Do-notation
259
- doUnwrap(): DoResult<R> {
260
- return { ok: true, value }
261
- },
262
- })
263
-
264
- export interface EitherBase<out L extends Type, out R extends Type>
265
- extends FunctypeSum<R, "Left" | "Right">, Promisable<R>, Doable<R>, Reshapeable<R>, Extractable<R> {
266
- isLeft(): this is LeftOf<L, R>
267
- isRight(): this is RightOf<L, R>
268
- orElse<R2 extends Type>(defaultValue: R2): R | R2
269
- /**
270
- * Returns the Right value, or throws on a Left. Pass an \`Error\` to throw it, or a builder to make one
271
- * from the Left value — for code that must throw for a host (a retrying step runner, an MCP tool, a
272
- * React Query \`queryFn\`). With no argument, throws the Left value itself.
273
- */
274
- orThrow: (error?: Error | ((left: L) => Error)) => R
275
- /**
276
- * Returns the right value, or calls the never-returning handler with the Left's value.
277
- * Use this when you have a helper like \`(msg) => fail(msg, 2)\` that terminates the
278
- * program — the result type is unconditionally \`R\`, so you avoid the TypeScript
279
- * narrowing trap where \`if (e.isLeft()) fail(...)\` fails to narrow \`e.value\` when
280
- * \`fail\` is an arrow function typed as \`(...): never\`.
281
- */
282
- expect: (handler: (value: L) => never) => R
283
- or<L2 extends Type, R2 extends Type>(alternative: Either<L2, R2>): Either<L | L2, R | R2>
284
- orNull: () => R | null
285
- orUndefined: () => R | undefined
286
- readonly map: <U extends Type>(f: (value: R) => U) => Either<L, U>
287
- ap: <L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>) => Either<L | L2, U>
288
- merge: <L1 extends Type, R1 extends Type>(other: Either<L1, R1>) => Either<L | L1, [R, R1]>
289
- /**
290
- * Maps the Right value with an async function. A Left resolves unchanged.
291
- * If \`f\` rejects or throws, the returned Promise rejects with the same reason: it does not
292
- * become a Left, and it never throws synchronously. To turn a rejection into a Left, use \`Either.fromPromise(p, onRejected)\`
293
- * or \`tryCatchAsync\`, which take a function from the reason to \`L\`.
294
- */
295
- mapAsync: <U extends Type>(f: (value: R) => Promise<U>) => Promise<Either<L, U>>
296
- flatMap: <L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>) => Either<L | L2, U>
297
- /**
298
- * Chains an async function that returns an Either. A Left resolves unchanged.
299
- * If \`f\` rejects or throws, the returned Promise rejects with the same reason, as with \`mapAsync\`.
300
- */
301
- flatMapAsync: <L2 extends Type, U extends Type>(f: (value: R) => Promise<Either<L2, U>>) => Promise<Either<L | L2, U>>
302
- toOption: () => Option<R>
303
- toString: () => string
304
- [Symbol.iterator]: () => Iterator<R>
305
- yield: () => Generator<R, void, unknown>
306
- traverse: <L2 extends Type, U extends Type>(f: (value: R) => Either<L2, U>) => Either<L | L2, U[]>
307
- tap: (f: (value: R) => void) => Either<L, R>
308
- tapLeft: (f: (value: L) => void) => Either<L, R>
309
- mapLeft: <L2 extends Type>(f: (value: L) => L2) => Either<L2, R>
310
- /**
311
- * Applies a predicate to the Right value. If the predicate fails, short-circuits
312
- * to a Left carrying the value produced by \`onUnsatisfied\`. Left passes through
313
- * unchanged (predicate not evaluated). Lets you turn a value-level guard into the
314
- * Left channel without breaking the chain with an \`if/return Left(...)\` ladder.
315
- * @param predicate - The predicate to test the Right value
316
- * @param onUnsatisfied - Builds the new Left value when the predicate fails
317
- * @returns Right if the predicate holds, Left(onUnsatisfied(value)) otherwise
318
- */
319
- filterOrElse: <L2 extends Type>(
320
- predicate: (value: R) => boolean,
321
- onUnsatisfied: (value: R) => L2,
322
- ) => Either<L | L2, R>
323
- bimap: <L2 extends Type, R2 extends Type>(fl: (value: L) => L2, fr: (value: R) => R2) => Either<L2, R2>
324
- fold: <T extends Type>(onLeft: (value: L) => T, onRight: (value: R) => T) => T
325
- /**
326
- * Async variant of fold. Accepts sync or async handlers on either branch and
327
- * always returns a Promise, keeping chains fluent when at least one branch is async.
328
- */
329
- foldAsync: <T extends Type>(onLeft: (value: L) => T | Promise<T>, onRight: (value: R) => T | Promise<T>) => Promise<T>
330
- swap: () => Either<R, L>
331
- /**
332
- * Pipes the value through the provided function based on whether this is a Left or Right
333
- */
334
- pipeEither<U extends Type>(onLeft: (value: L) => U, onRight: (value: R) => U): U
335
-
336
- /**
337
- * Pipes the Either value through the provided function
338
- */
339
- pipe<U extends Type>(f: (value: L | R) => U): U
340
- /**
341
- * Pattern matches over the Either, applying a handler function based on the variant
342
- */
343
- match<T>(patterns: { Left: (value: L) => T; Right: (value: R) => T }): T
344
- /**
345
- * Returns the value and tag for inspection
346
- */
347
- toValue(): { _tag: "Left" | "Right"; value: L | R }
348
- /**
349
- * Custom JSON serialization that excludes getter properties.
350
- * Emits the canonical functype envelope with \`@functype: "Either"\` so
351
- * native \`JSON.stringify\` recursion (e.g. inside a plain object body)
352
- * produces a marker-bearing envelope that survives a round-trip through
353
- * \`Serialization.deserialize\`.
354
- */
355
- toJSON(): { "@functype": "Either"; _tag: "Left" | "Right"; value: L | R }
356
- }
357
-
358
- export interface LeftOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
359
- readonly _tag: "Left"
360
- readonly value: L
361
- }
362
-
363
- export interface RightOf<out L extends Type, out R extends Type> extends EitherBase<L, R> {
364
- readonly _tag: "Right"
365
- readonly value: R
366
- }`,Try:`export interface Try<out T>
367
- extends FunctypeSum<T, TypeNames>, Extractable<T>, Pipe<T>, Promisable<T>, Doable<T>, Reshapeable<T> {
368
- readonly _tag: TypeNames
369
- readonly error: Error | undefined
370
- isSuccess(): this is Try<T> & { readonly _tag: "Success"; error: undefined }
371
- isFailure(): this is Try<T> & { readonly _tag: "Failure"; error: Error }
372
- orElse<T2 extends Type>(defaultValue: T2): T | T2
373
- /**
374
- * Returns the value, or throws on a Failure. Pass an \`Error\` to throw it, or a builder to make one from
375
- * the failure's error. With no argument, rethrows the original error.
376
- */
377
- orThrow: (error?: Error | ((error: Error) => Error)) => T
378
- /**
379
- * Returns the success value, or calls the never-returning handler with the Failure's error.
380
- * Use this when you have a helper like \`(msg) => fail(msg, 2)\` that terminates the program —
381
- * the result type is unconditionally \`T\`, so you avoid the TypeScript narrowing trap where
382
- * \`if (t.isFailure()) fail(...)\` fails to narrow \`t.value\` when \`fail\` is an arrow function
383
- * typed as \`(...): never\`.
384
- */
385
- expect: (handler: (error: Error) => never) => T
386
- or<T2 extends Type>(alternative: Try<T2>): Try<T | T2>
387
- orNull: () => T | null
388
- orUndefined: () => T | undefined
389
- toOption: () => Option<T>
390
- /**
391
- * Converts to a plain readonly array: \`[value]\` for Success, \`[]\` for Failure.
392
- * Symmetric with \`Try.toList()\` but skips the List wrapper for code that
393
- * just wants to feed Array.prototype methods or spread into another array.
394
- */
395
- toArray: () => readonly T[]
396
- /**
397
- * Converts to Either<E, T>. Failure becomes Left(builder(error)) when given a function,
398
- * or Left(leftValue) when given a value. Success becomes Right(value).
399
- *
400
- * Prefer the function form to thread the underlying Error's context into the Left:
401
- *
402
- * Try.fromYAML(text).toEither((e) => \`parse failed: \${e.message}\`)
403
- */
404
- toEither: <E extends Type>(leftOrBuilder: E | ((err: Error) => E)) => Either<E, T>
405
- toTry: () => Try<T>
406
- map: <U>(f: (value: T) => U) => Try<U>
407
- ap: <U>(ff: Try<(value: T) => U>) => Try<U>
408
- flatMap: <U>(f: (value: T) => Try<U>) => Try<U>
409
- flatMapAsync: <U>(f: (value: T) => Promise<Try<U>>) => Promise<Try<U>>
410
- /**
411
- * Pattern matches over the Try, applying onFailure if Failure and onSuccess if Success
412
- * @param onFailure - Function to apply if the Try is Failure
413
- * @param onSuccess - Function to apply if the Try is Success
414
- * @returns The result of applying the appropriate function
415
- */
416
- fold: <U extends Type>(onFailure: (error: Error) => U, onSuccess: (value: T) => U) => U
417
- /**
418
- * Async variant of fold. Accepts sync or async handlers on either branch and
419
- * always returns a Promise.
420
- */
421
- foldAsync: <U extends Type>(
422
- onFailure: (error: Error) => U | Promise<U>,
423
- onSuccess: (value: T) => U | Promise<U>,
424
- ) => Promise<U>
425
- toString: () => string
426
- /**
427
- * Pattern matches over the Try, applying a handler function based on the variant
428
- * @param patterns - Object with handler functions for Success and Failure variants
429
- * @returns The result of applying the matching handler function
430
- */
431
- match<R>(patterns: { Success: (value: T) => R; Failure: (error: Error) => R }): R
432
- /**
433
- * Recovers from a Failure by applying a function to the error, returning a new Try.
434
- * The recovery value may be a wider type; the result is \`Try<T | U>\`, matching
435
- * Scala's \`recover[U >: T]\` shape so Try stays covariant in T.
436
- */
437
- recover<U extends Type>(f: (error: Error) => U): Try<T | U>
438
- /**
439
- * Recovers from a Failure by applying a function that returns a new Try.
440
- * As with \`recover\`, the recovery Try may carry a wider type; the result widens accordingly.
441
- */
442
- recoverWith<U extends Type>(f: (error: Error) => Try<U>): Try<T | U>
443
- /**
444
- * Applies a predicate to the success value. If the predicate fails, short-circuits
445
- * to a Failure with the error produced by \`onUnsatisfied\`. Failure passes through
446
- * unchanged (predicate not evaluated). Lets you turn a value-level guard into the
447
- * error channel without writing a manual \`throw\` inside a \`Try(() => ...)\` body.
448
- * @param predicate - The predicate to test the success value
449
- * @param onUnsatisfied - Builds the Error for the new Failure when the predicate fails
450
- * @returns A Success if the predicate holds, a Failure carrying \`onUnsatisfied(value)\` otherwise
451
- */
452
- filterOrElse(predicate: (value: T) => boolean, onUnsatisfied: (value: T) => Error): Try<T>
453
- toValue(): { _tag: TypeNames; value: T | Error }
454
- /**
455
- * Custom JSON serialization. Success emits \`{"@functype":"Try","_tag":"Success","value":T}\`.
456
- * Failure emits \`{"@functype":"Try","_tag":"Failure","error":SerializedError}\` where
457
- * SerializedError captures \`name\`, \`message\`, \`stack\`, and the full \`cause\` chain —
458
- * \`e.name\` survives round-trip but \`instanceof SomeError\` does not.
459
- */
460
- toJSON():
461
- { "@functype": "Try"; _tag: "Success"; value: T } | { "@functype": "Try"; _tag: "Failure"; error: SerializedError }
462
- }`,List:`export interface List<out A> extends FunctypeCollection<A, "List">, Doable<A>, Reshapeable<A> {
463
- readonly length: number
464
- readonly [Symbol.iterator]: () => Iterator<A>
465
- // Override these to return List instead of FunctypeCollection
466
- map: <B>(f: (a: A) => B) => List<B>
467
- ap: <B>(ff: List<(value: A) => B>) => List<B>
468
- flatMap: <B>(f: (a: A) => Iterable<B>) => List<B>
469
- /** Async flatMap. Starts every call at once unless \`options.concurrency\` caps it; \`{ concurrency: 1 }\` runs them in order. */
470
- flatMapAsync: <B>(f: (a: A) => PromiseLike<Iterable<B>>, options?: ConcurrencyOptions) => PromiseLike<List<B>>
471
- /**
472
- * Async map: awaits \`f\` for each element and keeps the results in input order.
473
- *
474
- * Runs one call at a time by default, which is what replacing a loop that awaits needs. Pass
475
- * \`{ concurrency: n }\` to allow up to \`n\` calls at once, or \`"unbounded"\` to start them all together.
476
- * (\`flatMapAsync\` defaults to \`"unbounded"\`; it keeps that default so existing callers don't change.)
477
- * A rejection rejects the result, and no further calls start.
478
- *
479
- * @example
480
- * \`\`\`typescript
481
- * const users = await List(ids).mapAsync(fetchUser) // in order, one at a time
482
- * const pages = await List(urls).mapAsync(fetchPage, { concurrency: 4 }) // up to 4 at once
483
- * \`\`\`
484
- */
485
- mapAsync: <B>(f: (a: A) => PromiseLike<B>, options?: ConcurrencyOptions) => Promise<List<B>>
486
- // Override filter for type guard support
487
- filter<S extends A>(predicate: (a: A) => a is S): List<S>
488
- filter(predicate: (a: A) => unknown): List<A>
489
- filterNot: (p: (a: A) => boolean) => List<A>
490
- // List-specific methods
491
- /** @internal */
492
- filterType: <T extends Typeable<string, unknown>>(tag: string) => List<T & A>
493
- /** Remove a value. Accepts \`unknown\` so an unrelated-type arg is a safe no-op (Scala: \`-(elem: Any)\`). */
494
- remove: (value: unknown) => List<A>
495
- removeAt: (index: number) => List<A>
496
- /** Add a value, possibly widening the element type (Scala: \`:+[B >: A]\`). */
497
- add<B>(item: B): List<A | B>
498
- get: (index: number) => Option<A>
499
- /** Concatenate with another list, possibly widening (Scala: \`++[B >: A]\`). */
500
- concat<B>(other: List<B>): List<A | B>
501
- take: (n: number) => List<A>
502
- takeWhile: (p: (a: A) => boolean) => List<A>
503
- takeRight: (n: number) => List<A>
504
- /** Drop the first \`n\` elements. \`n\` of 0 or less drops nothing. */
505
- drop: (n: number) => List<A>
506
- /** Drop the last \`n\` elements. \`n\` of 0 or less drops nothing. */
507
- dropRight: (n: number) => List<A>
508
- /** Drop elements while \`p\` holds. Gives an empty List when every element matches. */
509
- dropWhile: (p: (a: A) => boolean) => List<A>
510
- /**
511
- * Spread each element that's an array or another non-string iterable (List, Set, ...) into the result,
512
- * one level deep, keeping other elements, strings included, as they are.
513
- * @example
514
- * \`\`\`typescript
515
- * List([[1, 2], [3]]).flatten() // List([1, 2, 3])
516
- * List([List([1]), List([2])]).flatten() // List([1, 2])
517
- * \`\`\`
518
- */
519
- flatten<B = Flattened<A>>(): List<B>
520
- get last(): A | undefined
521
- get lastOption(): Option<A>
522
- get tail(): List<A>
523
- get init(): List<A>
524
- reverse: () => List<A>
525
- /** Find the index of a value. Accepts \`unknown\` (Scala: \`indexOf(elem: Any)\`). */
526
- indexOf: (value: unknown) => number
527
- /** Prepend a value, possibly widening (Scala: \`+:[B >: A]\`). */
528
- prepend<B>(item: B): List<A | B>
529
- distinct: () => List<A>
530
- sorted: (compareFn?: (a: A, b: A) => number) => List<A>
531
- sortBy: <B>(f: (a: A) => B, compareFn?: (a: B, b: B) => number) => List<A>
532
- zip: <B>(other: List<B>) => List<[A, B]>
533
- zipWithIndex: () => List<[A, number]>
534
- groupBy: <K>(f: (a: A) => K) => globalThis.Map<K, List<A>>
535
- partition: (p: (a: A) => boolean) => [List<A>, List<A>]
536
- span: (p: (a: A) => boolean) => [List<A>, List<A>]
537
- slice: (start: number, end: number) => List<A>
538
- /**
539
- * Pattern matches over the List, applying a handler function based on whether it's empty
540
- * @param patterns - Object with handler functions for Empty and NonEmpty variants
541
- * @returns The result of applying the matching handler function
542
- */
543
- match<R>(patterns: { Empty: () => R; NonEmpty: (values: A[]) => R }): R
544
- }`,Set:`export interface Set<out A> extends FunctypeCollection<A, "Set">, Collection<A> {
545
- add<B>(value: B): Set<A | B>
546
- remove: (value: unknown) => Set<A>
547
- has(value: unknown): boolean
548
- /**
549
- * Elements in this set or \`other\`. \`other\` can be any iterable: an array, a native Set or a functype Set.
550
- * Like every Set method, it compares elements as \`has\` does: by SameValueZero, so objects by identity and
551
- * \`NaN\` equal to \`NaN\`.
552
- *
553
- * @example
554
- * \`\`\`typescript
555
- * Set([1, 2]).union([2, 3]) // Set([1, 2, 3])
556
- * \`\`\`
557
- */
558
- union<B>(other: Iterable<B>): Set<A | B>
559
- /** Elements in both this set and \`other\`, in this set's order (native \`intersection\` follows the smaller set's). */
560
- intersection(other: Iterable<unknown>): Set<A>
561
- /** Elements in this set and not in \`other\`. */
562
- difference(other: Iterable<unknown>): Set<A>
563
- /** Elements in exactly one of this set and \`other\`. */
564
- symmetricDifference<B>(other: Iterable<B>): Set<A | B>
565
- /** True if every element of this set is in \`other\`. True for an empty set. */
566
- isSubsetOf(other: Iterable<unknown>): boolean
567
- /** True if every element of \`other\` is in this set. */
568
- isSupersetOf(other: Iterable<unknown>): boolean
569
- /** True if this set and \`other\` share no element. */
570
- isDisjointFrom(other: Iterable<unknown>): boolean
571
- map: <B>(f: (a: A) => B) => Set<B>
572
- flatMap: <B>(f: (a: A) => Iterable<B>) => Set<B>
573
- /**
574
- * Async map: awaits \`f\` for each element and collects the results into a Set, so equal results
575
- * collapse into one. Runs one call at a time by default; pass \`{ concurrency: n }\` to allow up to
576
- * \`n\` at once, or \`"unbounded"\`. A rejection rejects the result, and no further calls start.
577
- */
578
- mapAsync: <B>(f: (a: A) => PromiseLike<B>, options?: ConcurrencyOptions) => Promise<Set<B>>
579
- filter: (p: (a: A) => boolean) => Set<A>
580
- filterNot: (p: (a: A) => boolean) => Set<A>
581
- // Positional methods follow insertion order. Override them to return Set instead of FunctypeCollection.
582
- /** Keep the first \`n\` elements. \`n\` of 0 or less keeps none. */
583
- take: (n: number) => Set<A>
584
- takeWhile: (p: (a: A) => boolean) => Set<A>
585
- /** Keep the last \`n\` elements. \`n\` of 0 or less keeps none. */
586
- takeRight: (n: number) => Set<A>
587
- /** Drop the first \`n\` elements. \`n\` of 0 or less drops nothing. */
588
- drop: (n: number) => Set<A>
589
- /** Drop the last \`n\` elements. \`n\` of 0 or less drops nothing. */
590
- dropRight: (n: number) => Set<A>
591
- dropWhile: (p: (a: A) => boolean) => Set<A>
592
- get tail(): Set<A>
593
- get init(): Set<A>
594
- /**
595
- * Spread each element that's an array or another non-string iterable into the result, one level deep,
596
- * keeping other elements, strings included, as they are.
597
- */
598
- flatten<B = Flattened<A>>(): Set<B>
599
- fold: <B>(initial: B, fn: (acc: B, a: A) => B) => B
600
- toList: () => List<A>
601
- toSet: () => Set<A>
602
- toArray: <B = A>() => B[]
603
- toString: () => string
604
- }`,Map:`export interface Map<K, out V>
605
- extends
606
- KVTraversable<Tuple<[K, V]>>,
607
- Collection<Tuple<[K, V]>>,
608
- Typeable<"Map">,
609
- Serializable<[K, V][]>,
610
- Pipe<[K, V][]>,
611
- Foldable<Tuple<[K, V]>>,
612
- Iterable<[K, V]> {
613
- readonly [Symbol.toStringTag]: string
614
- readonly _tag: "Map"
615
- add(item: Tuple<[K, V]>): Map<K, V>
616
- remove(value: K): Map<K, V>
617
- map<U>(f: (value: V) => U): Map<K, U>
618
- ap<U>(ff: Map<K, (value: V) => U>): Map<K, U>
619
- flatMap<K2, V2>(f: (entry: Tuple<[K, V]>) => Iterable<[K2, V2]>): Map<K2, V2>
620
- flatMapAsync<U>(f: (value: V) => PromiseLike<Map<K, U>>): PromiseLike<Map<K, U>>
621
- get(key: K): Option<V>
622
- /**
623
- * Whether the map holds an entry for \`key\`. Keys compare like a native \`Map\`:
624
- * by identity for objects, by \`SameValueZero\` otherwise.
625
- *
626
- * True even when the stored value is \`undefined\`, where \`get(key)\` returns \`None\`.
627
- * For an entry check (key and value), use \`contains(Tuple([k, v]))\`, which
628
- * compares the value with \`===\`.
629
- * @param key - The key to look up
630
- * @returns true if the map has an entry for \`key\`
631
- */
632
- has(key: K): boolean
633
- /**
634
- * The keys, in insertion order. A List, like \`Obj.keys()\`.
635
- * @returns A List of the map's keys
636
- */
637
- keys(): List<K>
638
- /**
639
- * The values, in insertion order. Duplicates are kept.
640
- * @returns A List of the map's values
641
- */
642
- values(): List<V>
643
- getOrElse(key: K, defaultValue: V): V
644
- orElse(key: K, alternative: Option<V>): Option<V>
645
- fold<B>(initial: B, fn: (acc: B, a: Tuple<[K, V]>) => B): B
646
- foldLeft<B>(z: B): (op: (b: B, a: Tuple<[K, V]>) => B) => B
647
- foldRight<B>(z: B): (op: (a: Tuple<[K, V]>, b: B) => B) => B
648
- /**
649
- * Pattern matches over the Map, applying a handler function based on whether it's empty
650
- * @param patterns - Object with handler functions for Empty and NonEmpty variants
651
- * @returns The result of applying the matching handler function
652
- */
653
- match<R>(patterns: { Empty: () => R; NonEmpty: (entries: Array<Tuple<[K, V]>>) => R }): R
654
- toValue(): { _tag: "Map"; value: [K, V][] }
655
- }`,Lazy:`export interface Lazy<out T extends Type> extends FunctypeBase<T, "Lazy">, Extractable<T>, Pipe<T> {
656
- /** Tag identifying this as a Lazy type */
657
- readonly _tag: "Lazy"
658
- /** Whether the computation has been evaluated */
659
- readonly isEvaluated: boolean
660
- /**
661
- * Returns the computed value or a default value if computation fails.
662
- * Result widens to \`T | T2\` (Scala: \`getOrElse[B >: A](default: B): B\`).
663
- */
664
- orElse<T2 extends Type>(defaultValue: T2): T | T2
665
- /**
666
- * Returns the computed value or null if computation fails
667
- * @returns The computed value or null
668
- */
669
- orNull(): T | null
670
- /**
671
- * Returns the computed value or throws an error if computation fails
672
- * @param error - Optional custom error to throw. If not provided, throws the computation error or a default error
673
- * @returns The computed value
674
- * @throws The specified error, computation error, or a default error
675
- */
676
- orThrow(error?: Error): T
677
- /**
678
- * Returns this Lazy if computation succeeds, otherwise returns the alternative Lazy.
679
- * The alternative may carry a different type; result is \`Lazy<T | T2>\`.
680
- */
681
- or<T2 extends Type>(alternative: Lazy<T2>): Lazy<T | T2>
682
- /**
683
- * Maps the value inside the Lazy using the provided function
684
- * @param f - The mapping function
685
- * @returns A new Lazy containing the mapped value
686
- */
687
- map<U extends Type>(f: (value: T) => U): Lazy<U>
688
- /**
689
- * Applies a wrapped function to a wrapped value (Applicative pattern)
690
- * @param ff - A Lazy containing a function from T to U
691
- * @returns A new Lazy containing the result
692
- */
693
- ap<U extends Type>(ff: Lazy<(value: T) => U>): Lazy<U>
694
- /**
695
- * Maps the value inside the Lazy using an async function
696
- * @param f - The async mapping function
697
- * @returns A Promise of a new Lazy containing the mapped value
698
- */
699
- mapAsync<U extends Type>(f: (value: T) => Promise<U>): Promise<Lazy<U>>
700
- /**
701
- * Maps the value using a function that returns a Lazy
702
- * @param f - The mapping function returning a Lazy
703
- * @returns A new Lazy containing the flattened result
704
- */
705
- flatMap<U extends Type>(f: (value: T) => Lazy<U>): Lazy<U>
706
- /**
707
- * Maps the value using an async function that returns a Lazy
708
- * @param f - The async mapping function returning a Lazy
709
- * @returns A Promise of a new Lazy containing the flattened result
710
- */
711
- flatMapAsync<U extends Type>(f: (value: T) => Promise<Lazy<U>>): Promise<Lazy<U>>
712
- /**
713
- * Returns a Lazy that filters the value based on a predicate
714
- * @param predicate - The predicate function
715
- * @returns A Lazy containing an Option of the value
716
- */
717
- filter(predicate: (value: T) => boolean): Lazy<Option<T>>
718
- /**
719
- * Recovers from a failed computation by providing an alternative value
720
- * @param f - Function that takes the error and returns a recovery value
721
- * @returns A new Lazy that will use the recovery function if computation fails
722
- */
723
- recover(f: (error: unknown) => T): Lazy<T>
724
- /**
725
- * Recovers from a failed computation by providing an alternative Lazy
726
- * @param f - Function that takes the error and returns a recovery Lazy
727
- * @returns A new Lazy that will use the recovery Lazy if computation fails
728
- */
729
- recoverWith(f: (error: unknown) => Lazy<T>): Lazy<T>
730
- /**
731
- * Evaluates the computation and returns it as an Option
732
- * @returns Some containing the value if successful, None if computation fails
733
- */
734
- toOption(): Option<T>
735
- /**
736
- * Evaluates the computation and returns it as an Either
737
- * @returns Right containing the value if successful, Left containing the error if computation fails
738
- */
739
- toEither(): Either<unknown, T>
740
- /**
741
- * Evaluates the computation and returns it as an Either with a mapped error
742
- * @param mapError - Function to map the error
743
- * @returns Right containing the value if successful, Left containing the mapped error if computation fails
744
- */
745
- toEitherWith<E>(mapError: (error: unknown) => E): Either<E, T>
746
- /**
747
- * Evaluates the computation and returns it as a Try
748
- * @returns Try containing the result of the computation
749
- */
750
- toTry(): Try<T>
751
- /**
752
- * Applies an effect function to the value if computation succeeds
753
- * @param f - The effect function
754
- * @returns This Lazy for chaining
755
- */
756
- tap(f: (value: T) => void): Lazy<T>
757
- /**
758
- * Applies an effect function to the error if computation fails
759
- * @param f - The effect function for errors
760
- * @returns This Lazy for chaining
761
- */
762
- tapError(f: (error: unknown) => void): Lazy<T>
763
- /**
764
- * Pattern matching on the Lazy value
765
- * @param f - Function to apply to the computed value
766
- * @returns The result of applying f to the computed value
767
- */
768
- fold<U>(f: (value: T) => U): U
769
- /**
770
- * Pattern matching with success and failure handlers
771
- * @param onFailure - Function to handle computation failure
772
- * @param onSuccess - Function to handle successful computation
773
- * @returns The result of the appropriate handler
774
- */
775
- foldWith<U>(onFailure: (error: unknown) => U, onSuccess: (value: T) => U): U
776
- /**
777
- * Left fold operation
778
- * @param z - Initial value
779
- * @returns Function that takes an operator and applies it
780
- */
781
- foldLeft: <B>(z: B) => (op: (b: B, a: T) => B) => B
782
- /**
783
- * Right fold operation
784
- * @param z - Initial value
785
- * @returns Function that takes an operator and applies it
786
- */
787
- foldRight: <B>(z: B) => (op: (a: T, b: B) => B) => B
788
- /**
789
- * Pattern matching for the Lazy type
790
- * @param patterns - Object with handler for Lazy pattern
791
- * @returns The result of the matched handler
792
- */
793
- match<R>(patterns: { Lazy: (value: T) => R }): R
794
- /**
795
- * Creates a string representation of the Lazy
796
- * @returns String representation showing evaluation status
797
- */
798
- toString(): string
799
- /**
800
- * Converts the Lazy to a value object.
801
- *
802
- * **Forces the thunk** as a side effect — Lazy serialization (and projection
803
- * to a plain value object) cannot represent an unevaluated thunk in JSON;
804
- * forcing is the only way to produce a complete projection. If the thunk
805
- * threw, the failure is captured in the \`error\` field (real Error, with
806
- * full prototype intact for in-memory inspection — \`toJSON\` projects to
807
- * \`SerializedError\` for the wire).
808
- *
809
- * Changed in 1.2.0 — pre-1.2.0 Lazy emitted \`{_tag, evaluated, value?}\`
810
- * without forcing. See \`docs/archive/proposals/serializable-audit-q1-q2.md\`.
811
- */
812
- toValue(): { _tag: "Lazy"; value: T } | { _tag: "Lazy"; error: Error }
813
- /**
814
- * Custom JSON serialization. Forces the thunk (see \`toValue\` for the
815
- * side-effect contract). Emits \`{"@functype":"Lazy","_tag":"Lazy","value":T}\`
816
- * on success, or \`{"@functype":"Lazy","_tag":"Lazy","error":SerializedError}\`
817
- * if the thunk threw — see error-envelope.ts for round-trip semantics.
818
- */
819
- toJSON():
820
- { "@functype": "Lazy"; _tag: "Lazy"; value: T } | { "@functype": "Lazy"; _tag: "Lazy"; error: SerializedError }
821
- }`,LazyList:`export interface LazyList<out A extends Type>
822
- extends Foldable<A>, Pipe<LazyList<A>>, Serializable<LazyList<A>>, Typeable<"LazyList"> {
823
- readonly [Symbol.toStringTag]: string
824
- // Iterator protocol
825
- [Symbol.iterator](): Iterator<A>
826
-
827
- // Lazy operations
828
- map<B extends Type>(f: (a: A) => B): LazyList<B>
829
- flatMap<B extends Type>(f: (a: A) => LazyList<B>): LazyList<B>
830
- filter(predicate: (a: A) => boolean): LazyList<A>
831
- take(n: number): LazyList<A>
832
- drop(n: number): LazyList<A>
833
- takeWhile(predicate: (a: A) => boolean): LazyList<A>
834
- dropWhile(predicate: (a: A) => boolean): LazyList<A>
835
- /** Concatenate with another lazy list, possibly widening (Scala: \`++[B >: A]\`). */
836
- concat<B extends Type>(other: LazyList<B>): LazyList<A | B>
837
- zip<B extends Type>(other: LazyList<B>): LazyList<[A, B]>
838
-
839
- takeRight(n: number): LazyList<A>
840
- reverse(): LazyList<A>
841
- distinct(): LazyList<A>
842
- zipWithIndex(): LazyList<[A, number]>
843
-
844
- // Element access (properties)
845
- get head(): A | undefined
846
- get headOption(): Option<A>
847
- get last(): A | undefined
848
- get lastOption(): Option<A>
849
- get tail(): LazyList<A>
850
- get init(): LazyList<A>
851
-
852
- // Foldable
853
- fold<B>(initial: B, fn: (acc: B, a: A) => B): B
854
-
855
- // Terminal operations (force evaluation)
856
- toList(): List<A>
857
- toArray(): A[]
858
- forEach(f: (a: A) => void): void
859
- reduce<B extends Type>(f: (acc: B, a: A) => B, initial: B): B
860
- find(predicate: (a: A) => boolean): Option<A>
861
- some(predicate: (a: A) => boolean): boolean
862
- every(predicate: (a: A) => boolean): boolean
863
- count(): number
864
-
865
- // Additional methods for clarity
866
- toString(): string
867
- }`,TaskOutcome:`export interface TaskOutcome<out T>
868
- extends FunctypeBase<T, "Ok" | "Err">, Extractable<T>, AsyncMonad<T>, Promisable<T>, Doable<T> {
869
- readonly _tag: "Ok" | "Err"
870
- readonly _meta: TaskMetadata
871
-
872
- // Value access
873
- readonly value?: T
874
- readonly error?: Throwable
875
-
876
- // Functional methods
877
- readonly map: <U>(f: (value: T) => U) => TaskOutcome<U>
878
- readonly flatMap: <U>(f: (value: T) => TaskOutcome<U> | Either<Throwable, U>) => TaskOutcome<U>
879
- readonly ap: <U>(ff: TaskOutcome<(value: T) => U>) => TaskOutcome<U>
880
- readonly mapAsync: <U>(f: (value: T) => Promise<U>) => Promise<TaskOutcome<U>>
881
- readonly flatMapAsync: <U>(f: (value: T) => Promise<TaskOutcome<U>>) => Promise<TaskOutcome<U>>
882
-
883
- // Error handling methods
884
- readonly mapError: (f: (error: Throwable) => Throwable) => TaskOutcome<T>
885
- recover<U extends Type>(value: U): Ok<T | U>
886
- recoverWith<U extends Type>(f: (error: Throwable) => U): Ok<T | U>
887
-
888
- // Type guards
889
- readonly isSuccess: () => this is Ok<T>
890
- readonly isFailure: () => this is Err<T>
891
- readonly isOk: () => this is Ok<T>
892
- readonly isErr: () => this is Err<T>
893
-
894
- // Conversion methods
895
- readonly toEither: () => Either<Throwable, T>
896
- readonly toTry: () => Try<T>
897
- readonly toOption: () => Option<T>
898
- readonly toList: () => List<T>
899
-
900
- // Pattern matching
901
- readonly fold: <U>(onErr: (error: Throwable) => U, onOk: (value: T) => U) => U
902
- readonly match: <U>(patterns: { Ok: (value: T) => U; Err: (error: Throwable) => U }) => U
903
-
904
- /**
905
- * Custom JSON serialization. Ok emits \`{"@functype":"Task","_tag":"Ok","value":T}\`.
906
- * Err emits \`{"@functype":"Task","_tag":"Err","error":SerializedError}\` capturing the
907
- * Throwable's name, message, stack, and cause chain. See error-envelope.ts —
908
- * \`instanceof\` does NOT survive round-trip but \`error.name\` does.
909
- */
910
- toJSON(): { "@functype": "Task"; _tag: "Ok"; value: T } | { "@functype": "Task"; _tag: "Err"; error: SerializedError }
911
- }`,Exit:`export interface Exit<E extends Type, A extends Type> {
912
- readonly [Symbol.toStringTag]: string
913
- readonly _tag: ExitTag
914
-
915
- /**
916
- * Type guard to check if this is a Success
917
- */
918
- isSuccess(): this is Exit<E, A> & { readonly _tag: "Success"; value: A }
919
-
920
- /**
921
- * Type guard to check if this is a Failure
922
- */
923
- isFailure(): this is Exit<E, A> & { readonly _tag: "Failure"; error: E }
924
-
925
- /**
926
- * Type guard to check if this is a Die (a defect — the carried value is not an \`E\`)
927
- */
928
- isDie(): this is Exit<E, A> & { readonly _tag: "Die"; defect: unknown }
929
-
930
- /**
931
- * Type guard to check if this is Interrupted
932
- */
933
- isInterrupted(): this is Exit<E, A> & { readonly _tag: "Interrupted"; fiberId: string }
934
-
935
- /**
936
- * Maps the success value
937
- */
938
- map<B extends Type>(f: (a: A) => B): Exit<E, B>
939
-
940
- /**
941
- * Maps the error value
942
- */
943
- mapError<E2 extends Type>(f: (e: E) => E2): Exit<E2, A>
944
-
945
- /**
946
- * Maps both error and success values
947
- */
948
- mapBoth<E2 extends Type, B extends Type>(onError: (e: E) => E2, onSuccess: (a: A) => B): Exit<E2, B>
949
-
950
- /**
951
- * Flat maps the success value
952
- */
953
- flatMap<B extends Type>(f: (a: A) => Exit<E, B>): Exit<E, B>
954
-
955
- /**
956
- * Pattern matches over the Exit.
957
- *
958
- * \`onDie\` is optional and appended rather than inserted so existing three-argument
959
- * calls keep compiling. Omitting it routes a defect to \`onFailure\` — the pre-\`Die\`
960
- * behaviour, where defects were indistinguishable from typed failures. Supply it
961
- * when the distinction matters; note the value it receives is \`unknown\`, not \`E\`.
962
- */
963
- fold<T>(
964
- onFailure: (e: E) => T,
965
- onSuccess: (a: A) => T,
966
- onInterrupted?: (fiberId: string) => T,
967
- onDie?: (defect: unknown) => T,
968
- ): T
969
-
970
- /**
971
- * Pattern matches over the Exit with object patterns.
972
- *
973
- * \`Die\` is optional for the same back-compat reason as {@link fold}'s \`onDie\`, and
974
- * falls back to \`Failure\` when absent.
975
- */
976
- match<T>(patterns: {
977
- Success: (value: A) => T
978
- Failure: (error: E) => T
979
- Interrupted: (fiberId: string) => T
980
- Die?: (defect: unknown) => T
981
- }): T
982
-
983
- /**
984
- * Returns the success value or throws
985
- */
986
- orThrow(): A
987
-
988
- /**
989
- * Returns the success value or a default
990
- */
991
- orElse(defaultValue: A): A
992
-
993
- /**
994
- * Converts to Option (Some for Success, None otherwise)
995
- */
996
- toOption(): Option<A>
997
-
998
- /**
999
- * Converts to Either (Right for Success, Left for Failure)
1000
- * Throws if Interrupted
1001
- *
1002
- * A \`Die\` becomes \`Left(defect)\`, which widens the Left beyond \`E\` — the same
1003
- * lossiness \`IO.run()\` already has. Use {@link isDie} first if the distinction matters.
1004
- */
1005
- toEither(): Either<E, A>
1006
-
1007
- /**
1008
- * Returns the raw value for inspection
1009
- */
1010
- toValue(): { _tag: ExitTag; value?: A; error?: E; defect?: unknown; fiberId?: string }
1011
-
1012
- /**
1013
- * String representation
1014
- */
1015
- toString(): string
1016
-
1017
- /**
1018
- * JSON serialization
1019
- */
1020
- toJSON(): { _tag: ExitTag; value?: A; error?: E; defect?: unknown; fiberId?: string }
1021
- }`,Tuple:`export interface Tuple<out T extends Type[]>
1022
- extends Foldable<T[number]>, Pipe<Tuple<T>>, Serializable<Tuple<T>>, Typeable<"Tuple"> {
1023
- readonly [Symbol.toStringTag]: string
1024
- get<K extends number>(index: K): T[K]
1025
-
1026
- fold<B>(initial: B, fn: (acc: B, a: T[number]) => B): B
1027
-
1028
- map<U extends Type[]>(f: (value: T) => U): Tuple<U>
1029
-
1030
- flatMap<U extends Type[]>(f: (value: T) => Tuple<U>): Tuple<U>
1031
-
1032
- toArray(): T
1033
-
1034
- length: number
1035
-
1036
- [Symbol.iterator](): Iterator<T[number]>
1037
-
1038
- toString(): string
1039
-
1040
- toValue(): { _tag: "Tuple"; value: T }
1041
- }`,Stack:`export type Stack<A extends Type> = {
1042
- readonly [Symbol.toStringTag]: string
1043
- /**
1044
- * Push a value onto the top of the stack. The value may be a wider type;
1045
- * the result widens to \`Stack<A | B>\` (Scala: \`:+[B >: A]\`).
1046
- * @param value - The value to push
1047
- * @returns A new Stack with the value added
1048
- */
1049
- push<B extends Type>(value: B): Stack<A | B>
1050
-
1051
- /**
1052
- * Remove and return the top value from the stack
1053
- * @returns A tuple containing the new Stack and the value
1054
- */
1055
- pop(): [Stack<A>, Option<A>]
1056
-
1057
- /**
1058
- * Return the top value without removing it
1059
- * @returns The top value wrapped in an Option
1060
- */
1061
- peek(): Option<A>
1062
-
1063
- /**
1064
- * Transforms each element in the stack using the provided function
1065
- * @param f - The mapping function
1066
- * @returns A new Stack with transformed elements
1067
- */
1068
- map<B extends Type>(f: (a: A) => B): Stack<B>
1069
-
1070
- /**
1071
- * Maps each element to a Stack and flattens the result
1072
- * @param f - The mapping function returning a Stack
1073
- * @returns A new flattened Stack
1074
- */
1075
- flatMap<B extends Type>(f: (a: A) => Stack<B>): Stack<B>
1076
-
1077
- /**
1078
- * Applies a Stack of functions to this Stack
1079
- * @param ff - Stack of functions to apply
1080
- * @returns A new Stack with applied functions
1081
- */
1082
- ap<B extends Type>(ff: Stack<(value: A) => B>): Stack<B>
1083
-
1084
- /**
1085
- * Maps each element to an async Stack and flattens the result
1086
- * @param f - The async mapping function returning a Stack
1087
- * @returns A promise of the new flattened Stack
1088
- */
1089
- flatMapAsync<B extends Type>(f: (value: A) => PromiseLike<Stack<B>>): PromiseLike<Stack<B>>
1090
-
1091
- /**
1092
- * Convert the stack to a List
1093
- * @returns A List containing all elements
1094
- */
1095
- toList(): List<A>
1096
-
1097
- /**
1098
- * Convert the stack to an array
1099
- * @returns An array of all elements
1100
- */
1101
- toArray(): A[]
1102
-
1103
- /**
1104
- * Returns a string representation of the stack
1105
- * @returns A string representation
1106
- */
1107
- toString(): string
1108
-
1109
- /**
1110
- * Left-associative fold over all elements using an initial value and combining function.
1111
- */
1112
- fold<B>(initial: B, fn: (acc: B, a: A) => B): B
1113
-
1114
- /**
1115
- * Pattern matches over the Stack, applying a handler function based on whether it's empty
1116
- * @param patterns - Object with handler functions for Empty and NonEmpty variants
1117
- * @returns The result of applying the matching handler function
1118
- */
1119
- match<R>(patterns: { Empty: () => R; NonEmpty: (values: A[]) => R }): R
1120
- } & Traversable<A> &`,HttpError:`export type HttpError = NetworkError | HttpStatusError | DecodeError
1121
-
1122
- const networkError = (url: string, method: HttpMethod, cause: unknown): NetworkError => ({
1123
- _tag: "NetworkError",
1124
- url,
1125
- method,
1126
- cause,
1127
- })`,Http:`export interface HttpClientConfig {
1128
- readonly baseUrl?: string
1129
- readonly defaultHeaders?: Record<string, string>
1130
- readonly fetch?: typeof globalThis.fetch
1131
- /**
1132
- * Effectful transformer that runs after \`defaultHeaders\` and per-call headers
1133
- * are merged, but before the request is sent. Returning a failed IO short-
1134
- * circuits the call with the produced \`HttpError\`. Compose multiple concerns
1135
- * (request IDs, auth refresh, logging) with standard IO operators — the
1136
- * request side becomes symmetric with the response chain (\`.tap\`, \`.map\`,
1137
- * \`.flatMap\`, \`.catchTag\`).
1138
- *
1139
- * @example
1140
- * \`\`\`ts
1141
- * const addRequestId = (r: HttpRequestView): HttpRequestView => ({
1142
- * ...r,
1143
- * headers: { ...r.headers, "x-request-id": crypto.randomUUID() },
1144
- * })
1145
- *
1146
- * const addBearer = (getToken: () => Promise<string>) =>
1147
- * (r: HttpRequestView): IO<never, HttpError, HttpRequestView> =>
1148
- * IO.tryPromise({
1149
- * try: () => getToken(),
1150
- * catch: (e) => HttpError.networkError(r.url, r.method, e),
1151
- * }).map((token) => ({
1152
- * ...r,
1153
- * headers: { ...r.headers, Authorization: \`Bearer \${token}\` },
1154
- * }))
1155
- *
1156
- * const api = Http.client({
1157
- * baseUrl: "https://api.example.com",
1158
- * beforeRequest: (r) =>
1159
- * IO.succeed(r)
1160
- * .map(addRequestId)
1161
- * .flatMap(addBearer(getToken))
1162
- * .tap((req) => logger.info(req.method, req.url)),
1163
- * })
1164
- * \`\`\`
1165
- */
1166
- readonly beforeRequest?: (request: HttpRequestView) => IO<never, HttpError, HttpRequestView>
1167
-
1168
- /**
1169
- * Effectful transformer that runs after the response is parsed (and the
1170
- * decoder, if any, succeeds) but before the IO resolves to the caller.
1171
- * Returning a failed IO surfaces the error in place of the response.
1172
- *
1173
- * **Only runs on the success path.** \`HttpStatusError\` (non-2xx),
1174
- * \`DecodeError\` (validation failure), and \`NetworkError\` (fetch / abort)
1175
- * skip this hook and surface directly. For *error*-side observability and
1176
- * recovery (refresh-on-401, error logging), use \`.catchTag(...)\` /
1177
- * \`.tapError(...)\` at the call site.
1178
- *
1179
- * The hook receives \`HttpResponse<unknown>\` — body shape is opaque here
1180
- * because hooks are response-shape-agnostic. The per-call decoder narrows
1181
- * \`data\` to the typed value before the response reaches the caller, but
1182
- * the hook itself sees \`unknown\`.
1183
- *
1184
- * @example
1185
- * \`\`\`ts
1186
- * const api = Http.client({
1187
- * baseUrl: "https://api.example.com",
1188
- * afterResponse: (response) =>
1189
- * IO.succeed(response)
1190
- * .tap((r) => logger.info("response", { status: r.status }))
1191
- * .map((r) => ({ ...r, headers: redactSensitiveHeaders(r.headers) })),
1192
- * })
1193
- *
1194
- * // Refresh-on-401 is a .catchTag pattern, NOT an afterResponse pattern:
1195
- * api.get("/me", { decode })
1196
- * .catchTag("HttpStatusError", (e) =>
1197
- * e.status === 401 ? refreshToken().flatMap(() => api.get("/me", { decode })) : IO.fail(e),
1198
- * )
1199
- * \`\`\`
1200
- */
1201
- readonly afterResponse?: (response: HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>>
1202
- }`};export{n as a,i,o as n,a as r,s as t};