functype 1.5.0 → 1.6.1

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 (43) hide show
  1. package/dist/cli/exports.js +1 -1
  2. package/dist/cli/index.js +1 -1
  3. package/dist/conditional/index.d.ts +1 -1
  4. package/dist/conditional/index.js +1 -1
  5. package/dist/core/task/index.d.ts +1 -1
  6. package/dist/core/task/index.js +1 -1
  7. package/dist/decoder/index.d.ts +1 -1
  8. package/dist/decoder/index.js +1 -1
  9. package/dist/do/index.d.ts +1 -1
  10. package/dist/do/index.js +1 -1
  11. package/dist/either/index.d.ts +1 -1
  12. package/dist/either/index.js +1 -1
  13. package/dist/fetch/index.d.ts +1 -1
  14. package/dist/fetch/index.js +1 -1
  15. package/dist/{full-interfaces-ByZleoi8.js → full-interfaces-CIXqsyDI.js} +3 -5
  16. package/dist/functype/index.d.ts +1 -1
  17. package/dist/{index-CGVJBR_H.d.ts → index-CCuIZ-ut.d.ts} +140 -1
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +1 -1
  20. package/dist/io/index.d.ts +2 -2
  21. package/dist/io/index.js +1 -1
  22. package/dist/lazy/index.d.ts +1 -1
  23. package/dist/lazy/index.js +1 -1
  24. package/dist/list/index.d.ts +1 -1
  25. package/dist/list/index.js +1 -1
  26. package/dist/map/index.d.ts +1 -1
  27. package/dist/map/index.js +1 -1
  28. package/dist/obj/index.d.ts +1 -1
  29. package/dist/obj/index.js +1 -1
  30. package/dist/option/index.d.ts +1 -1
  31. package/dist/option/index.js +1 -1
  32. package/dist/serialization/index.d.ts +1 -1
  33. package/dist/serialization/index.js +1 -1
  34. package/dist/{serialization-EQGLX3e3.js → serialization-my_TLROv.js} +1 -1
  35. package/dist/set/index.d.ts +1 -1
  36. package/dist/set/index.js +1 -1
  37. package/dist/src-C4olFIr1.js +17 -0
  38. package/dist/try/index.d.ts +1 -1
  39. package/dist/try/index.js +1 -1
  40. package/dist/tuple/index.js +1 -1
  41. package/dist/typeclass/index.d.ts +1 -1
  42. package/package.json +3 -3
  43. package/dist/src-4UEC-cVf.js +0 -17
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"../full-interfaces-ByZleoi8.js";export{n as CATEGORIES,i as FULL_INTERFACES,r as INTERFACES,t as TYPES,e as VERSION};
1
+ import{a as e,i as t,n,r,t as i}from"../full-interfaces-CIXqsyDI.js";export{n as CATEGORIES,i as FULL_INTERFACES,r as INTERFACES,t as TYPES,e as VERSION};
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{At as e,Q as t,St as n}from"../src-4UEC-cVf.js";import{a as r,i,n as a,r as o,t as s}from"../full-interfaces-ByZleoi8.js";const c=()=>{let t=n([`functype ${r} - Scala-inspired FP for TypeScript`,``]);return n(Object.entries(a)).foldLeft(t)((t,[r,a])=>{let o=t.add(r.toUpperCase());return n(a).foldLeft(o)((t,n)=>e(i[n]).fold(()=>t,e=>{let r=e.interfaces.length>0?` [${e.interfaces.join(`, `)}]`:``;return t.add(` ${n}${r}`).add(` ${e.description}`)})).add(``)}).concat(n([`Use: npx functype <Type> for details`,`Use: npx functype interfaces for interface reference`])).toArray().join(`
2
+ import{At as e,Q as t,St as n}from"../src-C4olFIr1.js";import{a as r,i,n as a,r as o,t as s}from"../full-interfaces-CIXqsyDI.js";const c=()=>{let t=n([`functype ${r} - Scala-inspired FP for TypeScript`,``]);return n(Object.entries(a)).foldLeft(t)((t,[r,a])=>{let o=t.add(r.toUpperCase());return n(a).foldLeft(o)((t,n)=>e(i[n]).fold(()=>t,e=>{let r=e.interfaces.length>0?` [${e.interfaces.join(`, `)}]`:``;return t.add(` ${n}${r}`).add(` ${e.description}`)})).add(``)}).concat(n([`Use: npx functype <Type> for details`,`Use: npx functype interfaces for interface reference`])).toArray().join(`
3
3
  `)},l=(t,r)=>{let i=r.interfaces.length>0?` [${r.interfaces.join(`, `)}]`:``,a=n([`create`,`transform`,`extract`,`check`,`other`]),o=n([`${t}<T>${i}`,``,r.description,``]);return a.foldLeft(o)((t,i)=>e(r.methods[i]).filter(e=>e.length>0).fold(()=>t,e=>{let r=t.add(i.toUpperCase());return n(e).foldLeft(r)((e,t)=>e.add(` ${t}`)).add(``)})).toArray().join(`
4
4
  `).trimEnd()},u=()=>{let e=n([`INTERFACES`,``]);return n(Object.entries(o)).foldLeft(e)((e,[t,r])=>{let i=r.extends?` extends ${r.extends}`:``,a=e.add(`${t}<A>${i}`).add(` ${r.description}`);return n(r.methods).foldLeft(a)((e,t)=>e.add(` ${t}`)).add(``)}).toArray().join(`
5
5
  `).trimEnd()},d=e=>JSON.stringify(e,null,2),f=()=>({version:r,categories:a,types:i}),p=t=>e(i[t]).map(e=>({name:t,data:e})).or(n(Object.entries(i)).find(([e])=>e.toLowerCase()===t.toLowerCase()).map(([e,t])=>({name:e,data:t}))).orUndefined(),m=()=>Object.keys(i),h=()=>o,g=e=>{let t=n(e.slice(2));return{flags:{json:t.contains(`--json`),full:t.contains(`--full`),help:t.exists(e=>e===`--help`||e===`-h`)},args:t.filter(e=>!e.startsWith(`--`)&&e!==`-h`)}},_=t=>e(s[t]).or(n(Object.entries(s)).find(([e])=>e.toLowerCase()===t.toLowerCase()).map(([,e])=>e)),v=()=>{let e=n([`FULL INTERFACE DEFINITIONS`,`=`.repeat(60),``]);return n(Object.entries(s)).foldLeft(e)((e,[t,r])=>e.concat(n([`// ${t}`,r,``,`-`.repeat(60),``]))).toArray().join(`
@@ -1,2 +1,2 @@
1
- import { Tr as Cond, n as UntypedMatch, t as Match } from "../index-CGVJBR_H.js";
1
+ import { Er as Cond, n as UntypedMatch, t as Match } from "../index-CCuIZ-ut.js";
2
2
  export { Cond, Match, UntypedMatch };
@@ -1 +1 @@
1
- import{$ as e,Q as t}from"../src-4UEC-cVf.js";export{e as Cond,t as Match};
1
+ import{$ as e,Q as t}from"../src-C4olFIr1.js";export{e as Cond,t as Match};
@@ -1,2 +1,2 @@
1
- import { $t as TaskResult, Gt as Ok, Ht as CancellationToken, Jt as Task, Kt as Sync, Qt as TaskParams, Ut as CancellationTokenSource, Vt as Async, Wt as Err, Xt as TaskMetadata, Yt as TaskFailure, Zt as TaskOutcome, en as TaskSuccess, nn as isTaggedThrowable, qt as TaggedThrowable, tn as createCancellationTokenSource } from "../../index-CGVJBR_H.js";
1
+ import { $t as TaskParams, Gt as Err, Ht as Async, Jt as TaggedThrowable, Kt as Ok, Qt as TaskOutcome, Ut as CancellationToken, Wt as CancellationTokenSource, Xt as TaskFailure, Yt as Task, Zt as TaskMetadata, en as TaskResult, nn as createCancellationTokenSource, qt as Sync, rn as isTaggedThrowable, tn as TaskSuccess } from "../../index-CCuIZ-ut.js";
2
2
  export { Async, CancellationToken, CancellationTokenSource, Err, Ok, Sync, TaggedThrowable, Task, TaskFailure, TaskMetadata, TaskOutcome, TaskParams, TaskResult, TaskSuccess, createCancellationTokenSource, isTaggedThrowable };
@@ -1 +1 @@
1
- import{G as e,J as t,K as n,W as r,q as i}from"../../src-4UEC-cVf.js";export{r as Err,e as Ok,n as Task,i as createCancellationTokenSource,t as isTaggedThrowable};
1
+ import{G as e,J as t,K as n,W as r,q as i}from"../../src-C4olFIr1.js";export{r as Err,e as Ok,n as Task,i as createCancellationTokenSource,t as isTaggedThrowable};
@@ -1,2 +1,2 @@
1
- import { Bt as DecoderErrorLeaf, Lt as Decoder, Rt as DecoderError, zt as DecoderErrorComposite } from "../index-CGVJBR_H.js";
1
+ import { Bt as DecoderErrorComposite, Rt as Decoder, Vt as DecoderErrorLeaf, zt as DecoderError } from "../index-CCuIZ-ut.js";
2
2
  export { Decoder, DecoderError, type DecoderErrorComposite, type DecoderErrorLeaf };
@@ -1 +1 @@
1
- import{B as e,V as t}from"../src-4UEC-cVf.js";export{e as Decoder,t as DecoderError};
1
+ import{B as e,V as t}from"../src-C4olFIr1.js";export{e as Decoder,t as DecoderError};
@@ -1,2 +1,2 @@
1
- import { At as FailureError, Cr as DoResult, Dt as DoAsync, Et as Do, Ft as isDoCapable, It as unwrap, Mt as LeftError, Nt as LeftErrorType, Ot as DoGenerator, Pt as NoneError, Tt as $, jt as FailureErrorType, kt as EmptyListError, wr as Doable } from "../index-CGVJBR_H.js";
1
+ import { At as EmptyListError, Dt as Do, Et as $, Ft as NoneError, It as isDoCapable, Lt as unwrap, Mt as FailureErrorType, Nt as LeftError, Ot as DoAsync, Pt as LeftErrorType, Tr as Doable, jt as FailureError, kt as DoGenerator, wr as DoResult } from "../index-CCuIZ-ut.js";
2
2
  export { $, Do, DoAsync, DoGenerator, type DoResult, type Doable, EmptyListError, FailureError, FailureErrorType, LeftError, LeftErrorType, NoneError, isDoCapable, unwrap };
package/dist/do/index.js CHANGED
@@ -1 +1 @@
1
- import{F as e,I as t,L as n,M as r,N as i,P as a,R as o,j as s,z as c}from"../src-4UEC-cVf.js";export{s as $,r as Do,i as DoAsync,a as EmptyListError,e as FailureError,t as LeftError,n as NoneError,o as isDoCapable,c as unwrap};
1
+ import{F as e,I as t,L as n,M as r,N as i,P as a,R as o,j as s,z as c}from"../src-C4olFIr1.js";export{s as $,r as Do,i as DoAsync,a as EmptyListError,e as FailureError,t as LeftError,n as NoneError,o as isDoCapable,c as unwrap};
@@ -1,2 +1,2 @@
1
- import { $n as Left, Qn as EitherBase, Zn as Either, ar as TypeCheckRight, cr as tryCatch, er as LeftOf, ir as TypeCheckLeft, lr as tryCatchAsync, nr as RightOf, or as isLeft, rr as TestEither, sr as isRight, tr as Right } from "../index-CGVJBR_H.js";
1
+ import { $n as EitherBase, Qn as Either, ar as TypeCheckLeft, cr as isRight, er as Left, ir as TestEither, lr as tryCatch, nr as Right, or as TypeCheckRight, rr as RightOf, sr as isLeft, tr as LeftOf, ur as tryCatchAsync } from "../index-CCuIZ-ut.js";
2
2
  export { Either, EitherBase, Left, LeftOf, Right, RightOf, TestEither, TypeCheckLeft, TypeCheckRight, isLeft, isRight, tryCatch, tryCatchAsync };
@@ -1 +1 @@
1
- import{_t as e,bt as t,gt as n,ht as r,mt as i,pt as a,vt as o,xt as s,yt as c}from"../src-4UEC-cVf.js";export{a as Either,i as Left,r as Right,n as TypeCheckLeft,e as TypeCheckRight,o as isLeft,c as isRight,t as tryCatch,s as tryCatchAsync};
1
+ import{_t as e,bt as t,gt as n,ht as r,mt as i,pt as a,vt as o,xt as s,yt as c}from"../src-C4olFIr1.js";export{a as Either,i as Left,r as Right,n as TypeCheckLeft,e as TypeCheckRight,o as isLeft,c as isRight,t as tryCatch,s as tryCatchAsync};
@@ -1,2 +1,2 @@
1
- import { A as HttpQueryParams, B as ResponseDecodeError, D as HttpClient, E as Http, F as DecodeError, I as HttpError, L as HttpMethod, M as HttpRequestView, N as HttpResponse, O as HttpClientConfig, P as ParseMode, R as HttpStatusError, j as HttpRequestOptions, k as HttpMethodOptions, z as NetworkError } from "../index-CGVJBR_H.js";
1
+ import { A as HttpQueryParams, B as ResponseDecodeError, D as HttpClient, E as Http, F as DecodeError, I as HttpError, L as HttpMethod, M as HttpRequestView, N as HttpResponse, O as HttpClientConfig, P as ParseMode, R as HttpStatusError, j as HttpRequestOptions, k as HttpMethodOptions, z as NetworkError } from "../index-CCuIZ-ut.js";
2
2
  export { type DecodeError, Http, HttpClient, type HttpClientConfig, type HttpError, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, type NetworkError, type ParseMode, type ResponseDecodeError };
@@ -1 +1 @@
1
- import{d as e,f as t,u as n}from"../src-4UEC-cVf.js";export{n as Http,t as HttpClient,e as HttpErrors};
1
+ import{d as e,f as t,u as n}from"../src-C4olFIr1.js";export{n as Http,t as HttpClient,e as HttpErrors};
@@ -1,4 +1,4 @@
1
- var e=`1.5.0`;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(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()`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`],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()`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`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()`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`],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)`,`.dropWhile(p)`,`.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`,`.nonEmpty`,`.size`,`.contains(v)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.filter(p)`,`.union(s)`,`.intersection(s)`,`.difference(s)`,`.add(v)`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`]}},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()`],transform:[`.set(k, v)`,`.delete(k)`,`.map(f)`,`.filter(p)`,`.add(k, v)`],extract:[`.get(k)`,`.keys()`,`.values()`,`.entries()`,`.fold(z, f)`],check:[`.has(k)`,`.isEmpty`,`.size`]}},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(n, s)`,`.orElse(d)`,`.orThrow()`,`.get()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList.from(iter)`,`LazyList.range(start, end)`,`LazyList.infinite(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`,`.toArray()`,`.toJSON()`],check:[`.isEmpty`]}},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, ...)`]}},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.fromOption(o)`,`IO.fromTry(t)`],transform:[`.map(f)`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run()`,`.runOrThrow()`,`.runSync()`,`.runSyncOrThrow()`,`.runExit()`,`.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? })`,`.timeout(ms)`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...])`,`IO.race([...])`,`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()`]}},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:[`.first`,`.second`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},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()`],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)`,`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.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 ecosystem-wide logging interface (1.3.0+). Type-only — no runtime, no `console` dependency, no opinion on output format. Every functype-* package targets this shape. Reachable from the top barrel (`import type { Logger } from "functype"`) and the `functype/logger` subpath. Concrete impls live in consumer packages: `consoleBootLogger` in `functype-os/config`, `DirectLogger` from `functype-log/direct` (structurally satisfies Logger — no adapter). Clock/Random/Tracer NOT being added — those are framework abstractions; Logger is uniquely justified because every production TS app already has one.',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`]}}},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`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Task`,`TaskOutcome`,`TaskResult`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Brand`,`ValidatedBrand`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`]},s={Option:`export interface Option<out T extends Type>
1
+ var e=`1.6.1`;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(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()`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`],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()`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`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()`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`],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)`,`.dropWhile(p)`,`.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`,`.nonEmpty`,`.size`,`.contains(v)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.filter(p)`,`.union(s)`,`.intersection(s)`,`.difference(s)`,`.add(v)`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`]}},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()`],transform:[`.set(k, v)`,`.delete(k)`,`.map(f)`,`.filter(p)`,`.add(k, v)`],extract:[`.get(k)`,`.keys()`,`.values()`,`.entries()`,`.fold(z, f)`],check:[`.has(k)`,`.isEmpty`,`.size`]}},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(n, s)`,`.orElse(d)`,`.orThrow()`,`.get()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList.from(iter)`,`LazyList.range(start, end)`,`LazyList.infinite(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`,`.toArray()`,`.toJSON()`],check:[`.isEmpty`]}},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, ...)`]}},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.fromOption(o)`,`IO.fromTry(t)`],transform:[`.map(f)`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run()`,`.runOrThrow()`,`.runSync()`,`.runSyncOrThrow()`,`.runExit()`,`.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)`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...])`,`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()`]}},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:[`.first`,`.second`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},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()`],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)`,`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.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 ecosystem-wide logging interface (1.3.0+). Type-only — no runtime, no `console` dependency, no opinion on output format. Every functype-* package targets this shape. Reachable from the top barrel (`import type { Logger } from "functype"`) and the `functype/logger` subpath. Concrete impls live in consumer packages: `consoleBootLogger` in `functype-os/config`, `DirectLogger` from `functype-log/direct` (structurally satisfies Logger — no adapter). Clock/Random/Tracer NOT being added — those are framework abstractions; Logger is uniquely justified because every production TS app already has one.',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`]}}},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`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Task`,`TaskOutcome`,`TaskResult`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Brand`,`ValidatedBrand`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`]},s={Option:`export interface Option<out T extends Type>
2
2
  extends Functype<T, "Some" | "None">, Promisable<T>, Doable<T>, Reshapeable<T> {
3
3
  /** The contained value (undefined for None) */
4
4
  readonly value: T | undefined
@@ -430,8 +430,7 @@ export interface RightOf<out L extends Type, out R extends Type> extends EitherB
430
430
  * \`e.name\` survives round-trip but \`instanceof SomeError\` does not.
431
431
  */
432
432
  toJSON():
433
- | { "@functype": "Try"; _tag: "Success"; value: T }
434
- | { "@functype": "Try"; _tag: "Failure"; error: SerializedError }
433
+ { "@functype": "Try"; _tag: "Success"; value: T } | { "@functype": "Try"; _tag: "Failure"; error: SerializedError }
435
434
  }`,List:`export interface List<out A> extends FunctypeCollection<A, "List">, Doable<A>, Reshapeable<A> {
436
435
  readonly length: number
437
436
  readonly [Symbol.iterator]: () => Iterator<A>
@@ -690,8 +689,7 @@ export interface RightOf<out L extends Type, out R extends Type> extends EitherB
690
689
  * if the thunk threw — see error-envelope.ts for round-trip semantics.
691
690
  */
692
691
  toJSON():
693
- | { "@functype": "Lazy"; _tag: "Lazy"; value: T }
694
- | { "@functype": "Lazy"; _tag: "Lazy"; error: SerializedError }
692
+ { "@functype": "Lazy"; _tag: "Lazy"; value: T } | { "@functype": "Lazy"; _tag: "Lazy"; error: SerializedError }
695
693
  }`,LazyList:`export interface LazyList<out A extends Type>
696
694
  extends Foldable<A>, Pipe<LazyList<A>>, Serializable<LazyList<A>>, Typeable<"LazyList"> {
697
695
  readonly [Symbol.toStringTag]: string
@@ -1,2 +1,2 @@
1
- import { Cn as FunctypeBase, Sn as Functype, wn as FunctypeCollection, xn as FunctypeSum } from "../index-CGVJBR_H.js";
1
+ import { Cn as Functype, Sn as FunctypeSum, Tn as FunctypeCollection, wn as FunctypeBase } from "../index-CCuIZ-ut.js";
2
2
  export { Functype, FunctypeBase, FunctypeCollection, FunctypeSum };
@@ -3293,6 +3293,69 @@ declare class InterruptedError extends Error {
3293
3293
  readonly _tag: "InterruptedError";
3294
3294
  constructor(message?: string);
3295
3295
  }
3296
+ /**
3297
+ * Error surfaced by value-driven repeat combinators when the iteration bound is
3298
+ * reached without the predicate being satisfied. Carries the last observed
3299
+ * value so callers can report what the loop settled on.
3300
+ *
3301
+ * Type parameter `A` is the value type the loop was producing (or the state
3302
+ * type for `IO.iterate`).
3303
+ *
3304
+ * ## Narrowing when `E` is `unknown`
3305
+ *
3306
+ * If the step effect has `E = unknown` (common when lifting a Promise via
3307
+ * `IO(() => ...)` or `IO.async(...)` — see the JSDoc on those constructors),
3308
+ * TypeScript's union algebra collapses `unknown | RepeatExhausted<A>` back to
3309
+ * `unknown`, and `RepeatExhausted<A>` is lost from the surface type. The
3310
+ * runtime behavior is still correct (the `RepeatExhausted` instance is in the
3311
+ * `Left` at runtime — see reporter's JSON in issue #221) — but consumers need
3312
+ * a narrowing step to recover it. Use `RepeatExhausted.is`:
3313
+ *
3314
+ * @example
3315
+ * ```ts
3316
+ * const res = await IO.iterate(seed, step, done, { max: 20 }).run()
3317
+ * res.fold(
3318
+ * (e) => {
3319
+ * if (RepeatExhausted.is<StepState>(e)) {
3320
+ * // e is now RepeatExhausted<StepState>; e.lastValue is StepState
3321
+ * return e.lastValue
3322
+ * }
3323
+ * // e is still the collapsed E channel — handle as the caller sees fit
3324
+ * throw e as Error
3325
+ * },
3326
+ * (settled) => settled,
3327
+ * )
3328
+ * ```
3329
+ *
3330
+ * The alternative — annotating `step`'s error channel so `E` is a concrete
3331
+ * tagged type — also works and preserves `RepeatExhausted<A>` in the union:
3332
+ *
3333
+ * @example
3334
+ * ```ts
3335
+ * const step = (s: S): IO<never, never, S> =>
3336
+ * IO(() => runOnce(s)).mapError((_e) => _e as never)
3337
+ * // iterate result E channel: never | RepeatExhausted<S> === RepeatExhausted<S>
3338
+ * ```
3339
+ */
3340
+ declare class RepeatExhausted<A = unknown> extends Error {
3341
+ readonly max: number;
3342
+ readonly lastValue?: A | undefined;
3343
+ readonly _tag: "RepeatExhausted";
3344
+ constructor(max: number, lastValue?: A | undefined, message?: string);
3345
+ /**
3346
+ * Runtime type guard. Narrows an `unknown` (or wider) value to
3347
+ * `RepeatExhausted<A>` when the tag matches. Use this to recover typed
3348
+ * exhaustion when the `E` channel has collapsed to `unknown` — a common
3349
+ * situation when the step effect is lifted from a Promise via `IO(...)` or
3350
+ * `IO.async(...)`. See the class-level JSDoc for a full example.
3351
+ *
3352
+ * The type parameter `A` is an unchecked assertion — the guard confirms the
3353
+ * shape is a `RepeatExhausted`, but cannot verify `lastValue` matches `A` at
3354
+ * runtime. Callers pass the state/value type they expect the loop to have
3355
+ * been producing.
3356
+ */
3357
+ static is<A = unknown>(e: unknown): e is RepeatExhausted<A>;
3358
+ }
3296
3359
  /**
3297
3360
  * IO Effect type module - a lazy, composable effect type with typed errors.
3298
3361
  * @module IO
@@ -3574,6 +3637,46 @@ interface IO<in out R extends Type, out E extends Type, out A extends Type> {
3574
3637
  readonly jitter?: boolean;
3575
3638
  readonly while?: (error: E, attempt: number) => boolean;
3576
3639
  }): IO<R, E, A>;
3640
+ /**
3641
+ * Re-runs the effect until its output satisfies `done`, or the `max` bound is hit.
3642
+ *
3643
+ * Value-channel dual of `retryWhile`: this repeats on success values that
3644
+ * haven't yet met the predicate, whereas the retry* family repeats on failure.
3645
+ * The first failure short-circuits and propagates unchanged. Compose the two
3646
+ * axes when both matter:
3647
+ *
3648
+ * @example
3649
+ * ```ts
3650
+ * pollJob
3651
+ * .retry(3) // error axis
3652
+ * .repeatUntil((job) => job.done, { max: 20, delayMs: 500 }) // value axis
3653
+ * ```
3654
+ *
3655
+ * @param done - Pure sync predicate. Loop stops (successfully) when this returns true.
3656
+ * @param opts.max - Maximum iterations before exhaustion is signaled.
3657
+ * @param opts.delayMs - Optional fixed delay between iterations.
3658
+ * @returns The satisfying value, or `RepeatExhausted<A>` in the error channel
3659
+ * (carrying the last observed value) if the bound is reached first.
3660
+ */
3661
+ repeatUntil(done: (a: A) => boolean, opts: {
3662
+ readonly max: number;
3663
+ readonly delayMs?: number;
3664
+ }): IO<R, E | RepeatExhausted<A>, A>;
3665
+ /**
3666
+ * Re-runs the effect while `cont` holds, or until the `max` bound is hit.
3667
+ *
3668
+ * Symmetric sibling of `repeatUntil` — mirrors the naming of `retryWhile`.
3669
+ * `repeatWhile(cont)` is equivalent to `repeatUntil((a) => !cont(a))`; the
3670
+ * loop stops successfully as soon as `cont` returns false.
3671
+ *
3672
+ * @param cont - Pure sync predicate. Loop continues while this returns true.
3673
+ * @param opts.max - Maximum iterations before exhaustion is signaled.
3674
+ * @param opts.delayMs - Optional fixed delay between iterations.
3675
+ */
3676
+ repeatWhile(cont: (a: A) => boolean, opts: {
3677
+ readonly max: number;
3678
+ readonly delayMs?: number;
3679
+ }): IO<R, E | RepeatExhausted<A>, A>;
3577
3680
  /**
3578
3681
  * Sequences two IOs, keeping the second value.
3579
3682
  */
@@ -3966,6 +4069,42 @@ declare const IO: (<A extends Type>(f: () => A | Promise<A>) => IO<never, unknow
3966
4069
  * Creates an IO that sleeps for the specified duration.
3967
4070
  */
3968
4071
  sleep: (ms: number) => IO<never, never, void>;
4072
+ /**
4073
+ * Effectful stateful loop — the value-driven dual of the retry family.
4074
+ *
4075
+ * Threads state `S` through an effectful `step` until `done(state)` holds, or
4076
+ * the `max` bound is reached. Semantics:
4077
+ *
4078
+ * - `done(seed)` is evaluated **before** the first `step` — an already-satisfied
4079
+ * seed returns immediately without executing the effect.
4080
+ * - The first `E` failure short-circuits the loop and propagates.
4081
+ * - `max` defaults to `10_000` and caps total step invocations to keep every
4082
+ * loop bounded by construction. Callers running larger iterations must set
4083
+ * `max` explicitly.
4084
+ * - Stack-safe: recursion happens via IO's `flatMap` trampoline, not the JS
4085
+ * call stack.
4086
+ *
4087
+ * @example
4088
+ * ```ts
4089
+ * // Poll for a completed job, threading the response through state.
4090
+ * const settled = await IO.iterate(
4091
+ * { status: "pending" as JobStatus },
4092
+ * (state) => fetchJob(state.id),
4093
+ * (state) => state.status === "done" || state.status === "failed",
4094
+ * { max: 30 },
4095
+ * ).runEither()
4096
+ * ```
4097
+ *
4098
+ * @param seed - Initial state.
4099
+ * @param step - Effect producing the next state from the current state.
4100
+ * @param done - Pure sync predicate over the state.
4101
+ * @param opts.max - Maximum step invocations (default `10_000`).
4102
+ * @returns The satisfying state, or `RepeatExhausted<S>` (carrying the last
4103
+ * observed state) if the bound is reached first.
4104
+ */
4105
+ iterate: <R extends Type, E extends Type, S extends Type>(seed: S, step: (state: S) => IO<R, E, S>, done: (state: S) => boolean, opts?: {
4106
+ readonly max?: number;
4107
+ }) => IO<R, E | RepeatExhausted<S>, S>;
3969
4108
  /**
3970
4109
  * Creates an IO that never completes.
3971
4110
  */
@@ -5966,4 +6105,4 @@ declare const Match: (<T extends Type>(value: T) => UntypedMatch<T>) & {
5966
6105
  };
5967
6106
  };
5968
6107
  //#endregion
5969
- export { LayerOutput as $, Left as $n, TaskResult as $t, HttpQueryParams as A, List as An, FailureError as At, ResponseDecodeError as B, createSerializer as Bn, DecoderErrorLeaf as Bt, TryKind as C, FunctypeBase as Cn, DoResult as Cr, formatStackTrace as Ct, HttpClient as D, MatchableUtils as Dn, DoAsync as Dt, Http as E, Matchable as En, Do as Et, DecodeError as F, FUNCTYPE_MARKER as Fn, isDoCapable as Ft, InterruptedError as G, fromYAML as Gn, Ok as Gt, TestClockTag as H, envelope as Hn, CancellationToken as Ht, HttpError as I, FunctypeEnvelope as In, unwrap as It, TimeoutError as J, deserializeError as Jn, Task$1 as Jt, RIO as K, taggedEnvelope as Kn, Sync as Kt, HttpMethod as L, SerializationResult as Ln, Decoder as Lt, HttpRequestView as M, TypeNames as Mn, LeftError as Mt, HttpResponse as N, JSONValue as Nn, LeftErrorType as Nt, HttpClientConfig as O, Collection as On, DoGenerator as Ot, ParseMode as P, Serialization_d_exports as Pn, NoneError as Pt, LayerInput as Q, EitherBase as Qn, TaskParams as Qt, HttpStatusError as R, createCustomSerializer as Rn, DecoderError as Rt, OptionKind as S, Functype as Sn, ParseError as Sr, formatError as St, FoldableUtils as T, Traversable as Tn, Cond as Tr, $ as Tt, TestContext as U, fromBinary as Un, CancellationTokenSource as Ut, TestClock as V, createTaggedSerializer as Vn, Async as Vt, IO as W, fromJSON as Wn, Err as Wt, Layer as X, LazyList as Xn, TaskMetadata as Xt, UIO as Y, serializeError as Yn, TaskFailure as Yt, LayerError as Z, Either as Zn, TaskOutcome as Zt, Identity as _, UUID as _n, Monad as _r, ErrorChainElement as _t, OptionConstructor as a, ThrowableType as an, TypeCheckRight as ar, Tag as at, Kind as b, ValidatedBrandCompanion as bn, Extractable as br, TaskErrorInfo as bt, Valuable as c, BoundedString as cn, tryCatch as cr, FormValidation as ct, Obj as d, IntegerNumber as dn, reduceRightWiden as dr, Validator as dt, TaskSuccess as en, LeftOf as er, Exit as et, ESMap as f, NonEmptyString as fn, reduceWiden as fr, ErrorCode as ft, Lazy as g, PositiveNumber as gn, Functor as gr, TypedErrorContext as gt, KVTraversable as h, PositiveInteger as hn, AsyncMonad as hr, TypedError as ht, Option as i, Throwable as in, TypeCheckLeft as ir, HasService as it, HttpRequestOptions as j, Try as jn, FailureErrorType as jt, HttpMethodOptions as k, Set as kn, EmptyListError as kt, ValuableParams as l, EmailAddress as ln, tryCatchAsync as lr, Validation as lt, Map$1 as m, PatternString as mn, Applicative as mr, ErrorStatus as mt, UntypedMatch as n, isTaggedThrowable as nn, RightOf as nr, Context as nt, Some as o, Base as on, isLeft as or, TagService as ot, ESMapType as p, NonNegativeNumber as pn, Promisable as pr, ErrorMessage as pt, Task as q, SerializedError as qn, TaggedThrowable as qt, None as r, NAME as rn, TestEither as rr, ContextServices as rt, Stack as s, BoundedNumber as sn, isRight as sr, FieldValidation as st, Match as t, createCancellationTokenSource as tn, Right as tr, ExitTag as tt, Ref as u, ISO8601Date as un, Widen as ur, ValidationRule as ut, EitherKind as v, UrlString as vn, CollectionOps as vr, ErrorFormatterOptions as vt, UniversalContainer as w, FunctypeCollection as wn, Doable as wr, safeStringify as wt, ListKind as x, FunctypeSum as xn, isExtractable as xr, createErrorSerializer as xt, HKT as y, ValidatedBrand as yn, ContainerOps as yr, ErrorWithTaskInfo as yt, NetworkError as z, createSerializationCompanion as zn, DecoderErrorComposite as zt };
6108
+ export { LayerInput as $, EitherBase as $n, TaskParams as $t, HttpQueryParams as A, Set as An, EmptyListError as At, ResponseDecodeError as B, createSerializationCompanion as Bn, DecoderErrorComposite as Bt, TryKind as C, Functype as Cn, ParseError as Cr, formatError as Ct, HttpClient as D, Matchable as Dn, Do as Dt, Http as E, Traversable as En, Cond as Er, $ as Et, DecodeError as F, Serialization_d_exports as Fn, NoneError as Ft, InterruptedError as G, fromJSON as Gn, Err as Gt, TestClockTag as H, createTaggedSerializer as Hn, Async as Ht, HttpError as I, FUNCTYPE_MARKER as In, isDoCapable as It, Task as J, SerializedError as Jn, TaggedThrowable as Jt, RIO as K, fromYAML as Kn, Ok as Kt, HttpMethod as L, FunctypeEnvelope as Ln, unwrap as Lt, HttpRequestView as M, Try as Mn, FailureErrorType as Mt, HttpResponse as N, TypeNames as Nn, LeftError as Nt, HttpClientConfig as O, MatchableUtils as On, DoAsync as Ot, ParseMode as P, JSONValue as Pn, LeftErrorType as Pt, LayerError as Q, Either as Qn, TaskOutcome as Qt, HttpStatusError as R, SerializationResult as Rn, Decoder as Rt, OptionKind as S, FunctypeSum as Sn, isExtractable as Sr, createErrorSerializer as St, FoldableUtils as T, FunctypeCollection as Tn, Doable as Tr, safeStringify as Tt, TestContext as U, envelope as Un, CancellationToken as Ut, TestClock as V, createSerializer as Vn, DecoderErrorLeaf as Vt, IO as W, fromBinary as Wn, CancellationTokenSource as Wt, UIO as X, serializeError as Xn, TaskFailure as Xt, TimeoutError as Y, deserializeError as Yn, Task$1 as Yt, Layer as Z, LazyList as Zn, TaskMetadata as Zt, Identity as _, PositiveNumber as _n, Functor as _r, TypedErrorContext as _t, OptionConstructor as a, Throwable as an, TypeCheckLeft as ar, HasService as at, Kind as b, ValidatedBrand as bn, ContainerOps as br, ErrorWithTaskInfo as bt, Valuable as c, BoundedNumber as cn, isRight as cr, FieldValidation as ct, Obj as d, ISO8601Date as dn, Widen as dr, ValidationRule as dt, TaskResult as en, Left as er, LayerOutput as et, ESMap as f, IntegerNumber as fn, reduceRightWiden as fr, Validator as ft, Lazy as g, PositiveInteger as gn, AsyncMonad as gr, TypedError as gt, KVTraversable as h, PatternString as hn, Applicative as hr, ErrorStatus as ht, Option as i, NAME as in, TestEither as ir, ContextServices as it, HttpRequestOptions as j, List as jn, FailureError as jt, HttpMethodOptions as k, Collection as kn, DoGenerator as kt, ValuableParams as l, BoundedString as ln, tryCatch as lr, FormValidation as lt, Map$1 as m, NonNegativeNumber as mn, Promisable as mr, ErrorMessage as mt, UntypedMatch as n, createCancellationTokenSource as nn, Right as nr, ExitTag as nt, Some as o, ThrowableType as on, TypeCheckRight as or, Tag as ot, ESMapType as p, NonEmptyString as pn, reduceWiden as pr, ErrorCode as pt, RepeatExhausted as q, taggedEnvelope as qn, Sync as qt, None as r, isTaggedThrowable as rn, RightOf as rr, Context as rt, Stack as s, Base as sn, isLeft as sr, TagService as st, Match as t, TaskSuccess as tn, LeftOf as tr, Exit as tt, Ref as u, EmailAddress as un, tryCatchAsync as ur, Validation as ut, EitherKind as v, UUID as vn, Monad as vr, ErrorChainElement as vt, UniversalContainer as w, FunctypeBase as wn, DoResult as wr, formatStackTrace as wt, ListKind as x, ValidatedBrandCompanion as xn, Extractable as xr, TaskErrorInfo as xt, HKT as y, UrlString as yn, CollectionOps as yr, ErrorFormatterOptions as yt, NetworkError as z, createCustomSerializer as zn, DecoderError as zt };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as ExtractBrand, c as hasBrand, i as BrandedString, l as unwrapBrand, n as BrandedBoolean, o as Unwrap, r as BrandedNumber, s as createBrander, t as Brand } from "./Brand-bfnGXuum.js";
2
2
  import { i as Companion, n as InstanceType, r as isCompanion, t as CompanionMethods } from "./CompanionTypes-CAxuM7qS.js";
3
3
  import { a as isTypeable, c as SerializationMethods, d as Type, i as TypeableParams, l as Pipe, n as ExtractTag, o as Serializable, r as Typeable, s as SerializableEnvelope, t as Tuple, u as Foldable } from "./Tuple-8yRldBty.js";
4
- import { $ as LayerOutput, $n as Left, $t as TaskResult, A as HttpQueryParams, An as List, At as FailureError, B as ResponseDecodeError, Bn as createSerializer, Bt as DecoderErrorLeaf, C as TryKind, Cn as FunctypeBase, Cr as DoResult, Ct as formatStackTrace, D as HttpClient, Dn as MatchableUtils, Dt as DoAsync, E as Http, En as Matchable, Et as Do, F as DecodeError, Fn as FUNCTYPE_MARKER, Ft as isDoCapable, G as InterruptedError, Gn as fromYAML, Gt as Ok, H as TestClockTag, Hn as envelope, Ht as CancellationToken, I as HttpError, In as FunctypeEnvelope, It as unwrap, J as TimeoutError, Jn as deserializeError, Jt as Task$1, K as RIO, Kn as taggedEnvelope, Kt as Sync, L as HttpMethod, Ln as SerializationResult, Lt as Decoder, M as HttpRequestView, Mn as TypeNames, Mt as LeftError, N as HttpResponse, Nn as JSONValue, Nt as LeftErrorType, O as HttpClientConfig, On as Collection, Ot as DoGenerator, P as ParseMode, Pn as Serialization_d_exports, Pt as NoneError, Q as LayerInput, Qn as EitherBase, Qt as TaskParams, R as HttpStatusError, Rn as createCustomSerializer, Rt as DecoderError, S as OptionKind, Sn as Functype, Sr as ParseError, St as formatError, T as FoldableUtils, Tn as Traversable, Tr as Cond, Tt as $, U as TestContext, Un as fromBinary, Ut as CancellationTokenSource, V as TestClock, Vn as createTaggedSerializer, Vt as Async, W as IO, Wn as fromJSON, Wt as Err, X as Layer, Xn as LazyList, Xt as TaskMetadata, Y as UIO, Yn as serializeError, Yt as TaskFailure, Z as LayerError, Zn as Either, Zt as TaskOutcome, _ as Identity, _n as UUID, _r as Monad, _t as ErrorChainElement, a as OptionConstructor, an as ThrowableType, ar as TypeCheckRight, at as Tag, b as Kind, bn as ValidatedBrandCompanion, br as Extractable, bt as TaskErrorInfo, c as Valuable, cn as BoundedString, cr as tryCatch, ct as FormValidation, d as Obj, dn as IntegerNumber, dr as reduceRightWiden, dt as Validator, en as TaskSuccess, er as LeftOf, et as Exit, f as ESMap, fn as NonEmptyString, fr as reduceWiden, ft as ErrorCode, g as Lazy, gn as PositiveNumber, gr as Functor, gt as TypedErrorContext, h as KVTraversable, hn as PositiveInteger, hr as AsyncMonad, ht as TypedError, i as Option, in as Throwable, ir as TypeCheckLeft, it as HasService, j as HttpRequestOptions, jn as Try, jt as FailureErrorType, k as HttpMethodOptions, kn as Set, kt as EmptyListError, l as ValuableParams, ln as EmailAddress, lr as tryCatchAsync, lt as Validation, m as Map, mn as PatternString, mr as Applicative, mt as ErrorStatus, n as UntypedMatch, nn as isTaggedThrowable, nr as RightOf, nt as Context, o as Some, on as Base, or as isLeft, ot as TagService, p as ESMapType, pn as NonNegativeNumber, pr as Promisable, pt as ErrorMessage, q as Task, qn as SerializedError, qt as TaggedThrowable, r as None, rn as NAME, rr as TestEither, rt as ContextServices, s as Stack, sn as BoundedNumber, sr as isRight, st as FieldValidation, t as Match, tn as createCancellationTokenSource, tr as Right, tt as ExitTag, u as Ref, un as ISO8601Date, ur as Widen, ut as ValidationRule, v as EitherKind, vn as UrlString, vr as CollectionOps, vt as ErrorFormatterOptions, w as UniversalContainer, wn as FunctypeCollection, wr as Doable, wt as safeStringify, x as ListKind, xn as FunctypeSum, xr as isExtractable, xt as createErrorSerializer, y as HKT, yn as ValidatedBrand, yr as ContainerOps, yt as ErrorWithTaskInfo, z as NetworkError, zn as createSerializationCompanion, zt as DecoderErrorComposite } from "./index-CGVJBR_H.js";
4
+ import { $ as LayerInput, $n as EitherBase, $t as TaskParams, A as HttpQueryParams, An as Set, At as EmptyListError, B as ResponseDecodeError, Bn as createSerializationCompanion, Bt as DecoderErrorComposite, C as TryKind, Cn as Functype, Cr as ParseError, Ct as formatError, D as HttpClient, Dn as Matchable, Dt as Do, E as Http, En as Traversable, Er as Cond, Et as $, F as DecodeError, Fn as Serialization_d_exports, Ft as NoneError, G as InterruptedError, Gn as fromJSON, Gt as Err, H as TestClockTag, Hn as createTaggedSerializer, Ht as Async, I as HttpError, In as FUNCTYPE_MARKER, It as isDoCapable, J as Task, Jn as SerializedError, Jt as TaggedThrowable, K as RIO, Kn as fromYAML, Kt as Ok, L as HttpMethod, Ln as FunctypeEnvelope, Lt as unwrap, M as HttpRequestView, Mn as Try, Mt as FailureErrorType, N as HttpResponse, Nn as TypeNames, Nt as LeftError, O as HttpClientConfig, On as MatchableUtils, Ot as DoAsync, P as ParseMode, Pn as JSONValue, Pt as LeftErrorType, Q as LayerError, Qn as Either, Qt as TaskOutcome, R as HttpStatusError, Rn as SerializationResult, Rt as Decoder, S as OptionKind, Sn as FunctypeSum, Sr as isExtractable, St as createErrorSerializer, T as FoldableUtils, Tn as FunctypeCollection, Tr as Doable, Tt as safeStringify, U as TestContext, Un as envelope, Ut as CancellationToken, V as TestClock, Vn as createSerializer, Vt as DecoderErrorLeaf, W as IO, Wn as fromBinary, Wt as CancellationTokenSource, X as UIO, Xn as serializeError, Xt as TaskFailure, Y as TimeoutError, Yn as deserializeError, Yt as Task$1, Z as Layer, Zn as LazyList, Zt as TaskMetadata, _ as Identity, _n as PositiveNumber, _r as Functor, _t as TypedErrorContext, a as OptionConstructor, an as Throwable, ar as TypeCheckLeft, at as HasService, b as Kind, bn as ValidatedBrand, br as ContainerOps, bt as ErrorWithTaskInfo, c as Valuable, cn as BoundedNumber, cr as isRight, ct as FieldValidation, d as Obj, dn as ISO8601Date, dr as Widen, dt as ValidationRule, en as TaskResult, er as Left, et as LayerOutput, f as ESMap, fn as IntegerNumber, fr as reduceRightWiden, ft as Validator, g as Lazy, gn as PositiveInteger, gr as AsyncMonad, gt as TypedError, h as KVTraversable, hn as PatternString, hr as Applicative, ht as ErrorStatus, i as Option, in as NAME, ir as TestEither, it as ContextServices, j as HttpRequestOptions, jn as List, jt as FailureError, k as HttpMethodOptions, kn as Collection, kt as DoGenerator, l as ValuableParams, ln as BoundedString, lr as tryCatch, lt as FormValidation, m as Map, mn as NonNegativeNumber, mr as Promisable, mt as ErrorMessage, n as UntypedMatch, nn as createCancellationTokenSource, nr as Right, nt as ExitTag, o as Some, on as ThrowableType, or as TypeCheckRight, ot as Tag, p as ESMapType, pn as NonEmptyString, pr as reduceWiden, pt as ErrorCode, q as RepeatExhausted, qn as taggedEnvelope, qt as Sync, r as None, rn as isTaggedThrowable, rr as RightOf, rt as Context, s as Stack, sn as Base, sr as isLeft, st as TagService, t as Match, tn as TaskSuccess, tr as LeftOf, tt as Exit, u as Ref, un as EmailAddress, ur as tryCatchAsync, ut as Validation, v as EitherKind, vn as UUID, vr as Monad, vt as ErrorChainElement, w as UniversalContainer, wn as FunctypeBase, wr as DoResult, wt as formatStackTrace, x as ListKind, xn as ValidatedBrandCompanion, xr as Extractable, xt as TaskErrorInfo, y as HKT, yn as UrlString, yr as CollectionOps, yt as ErrorFormatterOptions, z as NetworkError, zn as createCustomSerializer, zt as DecoderError } from "./index-CCuIZ-ut.js";
5
5
  import { t as Logger } from "./Logger-BmprRS8v.js";
6
- export { $, type Applicative, Async, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, CancellationToken, CancellationTokenSource, Collection, type CollectionOps, Companion, CompanionMethods, Cond, type ContainerOps, Context, type Context as ContextType, type ContextServices, type DecodeError, Decoder, DecoderError, type DecoderErrorComposite, type DecoderErrorLeaf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherKind, EmailAddress, EmptyListError, Err, ErrorChainElement, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type Exit as ExitType, type ExitTag, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, FieldValidation, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeEnvelope, FunctypeSum, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpError, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IO as IOType, type Task as IOTask, ISO8601Date, Identity, InstanceType, IntegerNumber, InterruptedError, type JSONValue, KVTraversable, Kind, Layer, type Layer as LayerType, type LayerError, type LayerInput, type LayerOutput, Lazy, type Lazy as LazyType, LazyList, Left, LeftError, LeftErrorType, LeftOf, List, ListKind, type Logger, Map, Match, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, Obj, Ok, Option, OptionConstructor, OptionKind, ParseError, type ParseMode, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Ref, type Ref as RefType, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, Some, Stack, Sync, Tag, type Tag as TagType, type TagService, TaggedThrowable, Task$1 as Task, TaskErrorInfo, TaskFailure, TaskMetadata, TaskOutcome, TaskParams, TaskResult, TaskSuccess, TestClock, type TestClock as TestClockType, TestClockTag, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, Traversable, Try, TryKind, Tuple, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrand as ValidatedBrandType, type ValidatedBrandCompanion, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, createBrander, createCancellationTokenSource, createCustomSerializer, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, formatError, formatStackTrace, fromBinary, fromJSON, fromYAML, hasBrand, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
6
+ export { $, type Applicative, Async, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, CancellationToken, CancellationTokenSource, Collection, type CollectionOps, Companion, CompanionMethods, Cond, type ContainerOps, Context, type Context as ContextType, type ContextServices, type DecodeError, Decoder, DecoderError, type DecoderErrorComposite, type DecoderErrorLeaf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherKind, EmailAddress, EmptyListError, Err, ErrorChainElement, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type Exit as ExitType, type ExitTag, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, FieldValidation, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeEnvelope, FunctypeSum, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpError, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IO as IOType, type Task as IOTask, ISO8601Date, Identity, InstanceType, IntegerNumber, InterruptedError, type JSONValue, KVTraversable, Kind, Layer, type Layer as LayerType, type LayerError, type LayerInput, type LayerOutput, Lazy, type Lazy as LazyType, LazyList, Left, LeftError, LeftErrorType, LeftOf, List, ListKind, type Logger, Map, Match, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, Obj, Ok, Option, OptionConstructor, OptionKind, ParseError, type ParseMode, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Ref, type Ref as RefType, RepeatExhausted, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, Some, Stack, Sync, Tag, type Tag as TagType, type TagService, TaggedThrowable, Task$1 as Task, TaskErrorInfo, TaskFailure, TaskMetadata, TaskOutcome, TaskParams, TaskResult, TaskSuccess, TestClock, type TestClock as TestClockType, TestClockTag, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, Traversable, Try, TryKind, Tuple, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrand as ValidatedBrandType, type ValidatedBrandCompanion, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, createBrander, createCancellationTokenSource, createCustomSerializer, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, formatError, formatStackTrace, fromBinary, fromJSON, fromYAML, hasBrand, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{Brand as e,BrandedBoolean as t,BrandedNumber as n,BrandedString as r,createBrander as i,hasBrand as a,unwrap as o}from"./branded/index.js";import{t as s}from"./Companion-DiOMBHDG.js";import{a as c,c as l,d as u,f as d,i as f,l as p,n as m,o as h,r as g,s as _,t as v,u as y}from"./serialization-EQGLX3e3.js";import{$ as b,A as x,At as S,B as C,C as w,Ct as T,D as E,Dt as D,E as O,Et as k,F as A,G as j,H as M,I as N,J as P,K as F,L as I,M as L,Mt as R,N as z,O as B,Ot as V,P as H,Q as U,R as W,S as G,St as K,T as q,Tt as J,U as Y,V as X,W as Z,X as Q,Y as $,Z as ee,_ as te,_t as ne,a as re,at as ie,b as ae,bt as oe,c as se,ct as ce,d as le,dt as ue,et as de,f as fe,ft as pe,g as me,gt as he,h as ge,ht as _e,i as ve,it as ye,j as be,jt as xe,k as Se,kt as Ce,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,s as Le,st as Re,t as ze,tt as Be,u as Ve,ut as He,v as Ue,vt as We,w as Ge,wt as Ke,x as qe,xt as Je,y as Ye,yt as Xe,z as Ze}from"./src-4UEC-cVf.js";import{n as Qe,t as $e}from"./typeclass-C61yDVYd.js";import{t as et}from"./CompanionTypes-BVqO7Kc2.js";import{Tuple as tt}from"./tuple/index.js";export{be as $,ee as Base,de as BoundedNumber,Be as BoundedString,e as Brand,t as BrandedBoolean,n as BrandedNumber,r as BrandedString,s as Companion,b as Cond,G as Context,C as Decoder,X as DecoderError,L as Do,z as DoAsync,Y as ESMap,Ne as Either,ke as EmailAddress,H as EmptyListError,Z as Err,qe as Exit,v as FUNCTYPE_MARKER,A as FailureError,we as FoldableUtils,se as HKT,Ve as Http,fe as HttpClient,le as HttpErrors,Ue as IO,Ie as ISO8601Date,Le as Identity,ye as IntegerNumber,Ye as InterruptedError,te as Layer,Ae as Lazy,k as LazyList,De as Left,N as LeftError,K as List,M as Map,U as Match,re as MatchableUtils,$ as NAME,ie as NonEmptyString,je as NonNegativeNumber,Ce as None,I as NoneError,ve as Obj,j as Ok,S as Option,xe as OptionConstructor,O as ParseError,Re as PatternString,ce as PositiveInteger,Te as PositiveNumber,D as Ref,_e as Right,Oe as Serialization,V as Set,R as Some,Fe as Stack,me as Tag,F as Task,Me as TestClock,Ee as TestClockTag,ge as TestContext,Q as Throwable,ae as TimeoutError,J as Try,tt as Tuple,he as TypeCheckLeft,ne as TypeCheckRight,T as Typeable,q as TypedError,He as UUID,ue as UrlString,pe as ValidatedBrand,Ge as Validation,ze as Valuable,i as createBrander,Pe as createCancellationTokenSource,m as createCustomSerializer,E as createErrorSerializer,g as createSerializationCompanion,f as createSerializer,c as createTaggedSerializer,u as deserializeError,h as envelope,B as formatError,Se as formatStackTrace,_ as fromBinary,l as fromJSON,p as fromYAML,a as hasBrand,et as isCompanion,W as isDoCapable,w as isExtractable,We as isLeft,Xe as isRight,P as isTaggedThrowable,Ke as isTypeable,$e as reduceRightWiden,Qe as reduceWiden,x as safeStringify,d as serializeError,y as taggedEnvelope,oe as tryCatch,Je as tryCatchAsync,Ze as unwrap,o as unwrapBrand};
1
+ import{Brand as e,BrandedBoolean as t,BrandedNumber as n,BrandedString as r,createBrander as i,hasBrand as a,unwrap as o}from"./branded/index.js";import{$ as s,A as c,At as l,B as u,C as d,Ct as f,D as p,Dt as m,E as h,Et as g,F as _,G as v,H as y,I as b,J as x,K as S,L as C,M as w,Mt as T,N as E,Nt as D,O,Ot as k,P as A,Q as j,R as M,S as N,St as P,T as F,Tt as I,U as L,V as R,W as z,X as B,Y as V,Z as H,_ as U,_t as W,a as G,at as K,b as q,bt as J,c as Y,ct as X,d as Z,dt as Q,et as $,f as ee,ft as te,g as ne,gt as re,h as ie,ht as ae,i as oe,it as se,j as ce,jt as le,k as ue,kt as de,l as fe,lt as pe,m as me,mt as he,n as ge,nt as _e,o as ve,ot as ye,p as be,pt as xe,q as Se,r as Ce,rt as we,s as Te,st as Ee,t as De,tt as Oe,u as ke,ut as Ae,v as je,vt as Me,w as Ne,wt as Pe,x as Fe,xt as Ie,y as Le,yt as Re,z as ze}from"./src-C4olFIr1.js";import{t as Be}from"./Companion-DiOMBHDG.js";import{a as Ve,c as He,d as Ue,f as We,i as Ge,l as Ke,n as qe,o as Je,r as Ye,s as Xe,t as Ze,u as Qe}from"./serialization-my_TLROv.js";import{n as $e,t as et}from"./typeclass-C61yDVYd.js";import{t as tt}from"./CompanionTypes-BVqO7Kc2.js";import{Tuple as nt}from"./tuple/index.js";export{ce as $,H as Base,$ as BoundedNumber,Oe as BoundedString,e as Brand,t as BrandedBoolean,n as BrandedNumber,r as BrandedString,Be as Companion,s as Cond,d as Context,u as Decoder,R as DecoderError,w as Do,E as DoAsync,L as ESMap,xe as Either,_e as EmailAddress,A as EmptyListError,z as Err,N as Exit,Ze as FUNCTYPE_MARKER,_ as FailureError,fe as FoldableUtils,Y as HKT,ke as Http,ee as HttpClient,Z as HttpErrors,je as IO,we as ISO8601Date,Te as Identity,se as IntegerNumber,Le as InterruptedError,U as Layer,ve as Lazy,g as LazyList,he as Left,b as LeftError,P as List,y as Map,j as Match,G as MatchableUtils,V as NAME,K as NonEmptyString,ye as NonNegativeNumber,de as None,C as NoneError,oe as Obj,v as Ok,l as Option,le as OptionConstructor,D as ParseError,Ee as PatternString,X as PositiveInteger,pe as PositiveNumber,m as Ref,q as RepeatExhausted,ae as Right,ge as Serialization,k as Set,T as Some,Ce as Stack,ne as Tag,S as Task,be as TestClock,me as TestClockTag,ie as TestContext,B as Throwable,Fe as TimeoutError,I as Try,nt as Tuple,re as TypeCheckLeft,W as TypeCheckRight,f as Typeable,h as TypedError,Ae as UUID,Q as UrlString,te as ValidatedBrand,F as Validation,De as Valuable,i as createBrander,Se as createCancellationTokenSource,qe as createCustomSerializer,p as createErrorSerializer,Ye as createSerializationCompanion,Ge as createSerializer,Ve as createTaggedSerializer,Ue as deserializeError,Je as envelope,O as formatError,ue as formatStackTrace,Xe as fromBinary,He as fromJSON,Ke as fromYAML,a as hasBrand,tt as isCompanion,M as isDoCapable,Ne as isExtractable,Me as isLeft,Re as isRight,x as isTaggedThrowable,Pe as isTypeable,et as reduceRightWiden,$e as reduceWiden,c as safeStringify,We as serializeError,Qe as taggedEnvelope,J as tryCatch,Ie as tryCatchAsync,ze as unwrap,o as unwrapBrand};
@@ -1,2 +1,2 @@
1
- import { $ as LayerOutput, G as InterruptedError, H as TestClockTag, J as TimeoutError, K as RIO, Q as LayerInput, U as TestContext, V as TestClock, W as IO, X as Layer, Y as UIO, Z as LayerError, at as Tag, et as Exit, it as HasService, nt as Context, ot as TagService, q as Task, rt as ContextServices, tt as ExitTag } from "../index-CGVJBR_H.js";
2
- export { Context, type Context as ContextType, type ContextServices, Exit, type Exit as ExitType, type ExitTag, type HasService, IO, type IO as IOType, type Task as IOTask, InterruptedError, Layer, type Layer as LayerType, type LayerError, type LayerInput, type LayerOutput, type RIO, Tag, type Tag as TagType, type TagService, TestClock, type TestClock as TestClockType, TestClockTag, TestContext, type TestContext as TestContextType, TimeoutError, type UIO };
1
+ import { $ as LayerInput, G as InterruptedError, H as TestClockTag, J as Task, K as RIO, Q as LayerError, U as TestContext, V as TestClock, W as IO, X as UIO, Y as TimeoutError, Z as Layer, at as HasService, et as LayerOutput, it as ContextServices, nt as ExitTag, ot as Tag, q as RepeatExhausted, rt as Context, st as TagService, tt as Exit } from "../index-CCuIZ-ut.js";
2
+ export { Context, type Context as ContextType, type ContextServices, Exit, type Exit as ExitType, type ExitTag, type HasService, IO, type IO as IOType, type Task as IOTask, InterruptedError, Layer, type Layer as LayerType, type LayerError, type LayerInput, type LayerOutput, type RIO, RepeatExhausted, Tag, type Tag as TagType, type TagService, TestClock, type TestClock as TestClockType, TestClockTag, TestContext, type TestContext as TestContextType, TimeoutError, type UIO };
package/dist/io/index.js CHANGED
@@ -1 +1 @@
1
- import{S as e,_ as t,b as n,g as r,h as i,m as a,p as o,v as s,x as c,y as l}from"../src-4UEC-cVf.js";export{e as Context,c as Exit,s as IO,l as InterruptedError,t as Layer,r as Tag,o as TestClock,a as TestClockTag,i as TestContext,n as TimeoutError};
1
+ import{C as e,S as t,_ as n,b as r,g as i,h as a,m as o,p as s,v as c,x as l,y as u}from"../src-C4olFIr1.js";export{e as Context,t as Exit,c as IO,u as InterruptedError,n as Layer,r as RepeatExhausted,i as Tag,s as TestClock,o as TestClockTag,a as TestContext,l as TimeoutError};
@@ -1,2 +1,2 @@
1
- import { g as Lazy } from "../index-CGVJBR_H.js";
1
+ import { g as Lazy } from "../index-CCuIZ-ut.js";
2
2
  export { Lazy, type Lazy as LazyType };
@@ -1 +1 @@
1
- import{o as e}from"../src-4UEC-cVf.js";export{e as Lazy};
1
+ import{o as e}from"../src-C4olFIr1.js";export{e as Lazy};
@@ -1,2 +1,2 @@
1
- import { An as List } from "../index-CGVJBR_H.js";
1
+ import { jn as List } from "../index-CCuIZ-ut.js";
2
2
  export { List };
@@ -1 +1 @@
1
- import{St as e}from"../src-4UEC-cVf.js";export{e as List};
1
+ import{St as e}from"../src-C4olFIr1.js";export{e as List};
@@ -1,2 +1,2 @@
1
- import { m as Map } from "../index-CGVJBR_H.js";
1
+ import { m as Map } from "../index-CCuIZ-ut.js";
2
2
  export { Map };
package/dist/map/index.js CHANGED
@@ -1 +1 @@
1
- import{H as e}from"../src-4UEC-cVf.js";export{e as Map};
1
+ import{H as e}from"../src-C4olFIr1.js";export{e as Map};
@@ -1,2 +1,2 @@
1
- import { d as Obj } from "../index-CGVJBR_H.js";
1
+ import { d as Obj } from "../index-CCuIZ-ut.js";
2
2
  export { Obj };
package/dist/obj/index.js CHANGED
@@ -1 +1 @@
1
- import{i as e}from"../src-4UEC-cVf.js";export{e as Obj};
1
+ import{i as e}from"../src-C4olFIr1.js";export{e as Obj};
@@ -1,2 +1,2 @@
1
- import { a as OptionConstructor, i as Option, o as Some, r as None } from "../index-CGVJBR_H.js";
1
+ import { a as OptionConstructor, i as Option, o as Some, r as None } from "../index-CCuIZ-ut.js";
2
2
  export { None, Option, OptionConstructor, Some };
@@ -1 +1 @@
1
- import{At as e,Mt as t,jt as n,kt as r}from"../src-4UEC-cVf.js";export{r as None,e as Option,n as OptionConstructor,t as Some};
1
+ import{At as e,Mt as t,jt as n,kt as r}from"../src-C4olFIr1.js";export{r as None,e as Option,n as OptionConstructor,t as Some};
@@ -1,2 +1,2 @@
1
- import { Bn as createSerializer, Fn as FUNCTYPE_MARKER, Gn as fromYAML, Hn as envelope, In as FunctypeEnvelope, Jn as deserializeError, Kn as taggedEnvelope, Ln as SerializationResult, Nn as JSONValue, Rn as createCustomSerializer, Un as fromBinary, Vn as createTaggedSerializer, Wn as fromJSON, Yn as serializeError, qn as SerializedError, zn as createSerializationCompanion } from "../index-CGVJBR_H.js";
1
+ import { Bn as createSerializationCompanion, Gn as fromJSON, Hn as createTaggedSerializer, In as FUNCTYPE_MARKER, Jn as SerializedError, Kn as fromYAML, Ln as FunctypeEnvelope, Pn as JSONValue, Rn as SerializationResult, Un as envelope, Vn as createSerializer, Wn as fromBinary, Xn as serializeError, Yn as deserializeError, qn as taggedEnvelope, zn as createCustomSerializer } from "../index-CCuIZ-ut.js";
2
2
  export { FUNCTYPE_MARKER, FunctypeEnvelope, type JSONValue, SerializationResult, SerializedError, createCustomSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, fromBinary, fromJSON, fromYAML, serializeError, taggedEnvelope };
@@ -1 +1 @@
1
- import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,r as c,s as l,t as u,u as d}from"../serialization-EQGLX3e3.js";export{u as FUNCTYPE_MARKER,o as createCustomSerializer,c as createSerializationCompanion,i as createSerializer,e as createTaggedSerializer,n as deserializeError,s as envelope,l as fromBinary,t as fromJSON,a as fromYAML,r as serializeError,d as taggedEnvelope};
1
+ import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,r as c,s as l,t as u,u as d}from"../serialization-my_TLROv.js";export{u as FUNCTYPE_MARKER,o as createCustomSerializer,c as createSerializationCompanion,i as createSerializer,e as createTaggedSerializer,n as deserializeError,s as envelope,l as fromBinary,t as fromJSON,a as fromYAML,r as serializeError,d as taggedEnvelope};
@@ -1,4 +1,4 @@
1
1
  function e(e){if(e===void 0||typeof e==`symbol`||typeof e==`function`)return;let t=new Set;function n(e){if(e===null)return`null`;switch(typeof e){case`string`:return JSON.stringify(e);case`number`:return isFinite(e)?String(e):`null`;case`boolean`:return String(e);case`bigint`:return`"${e}"`;case`undefined`:case`symbol`:case`function`:return}let r=e;if(t.has(r))return`"[Circular]"`;t.add(r);try{if(`toJSON`in r&&typeof r.toJSON==`function`)return n(r.toJSON());if(Array.isArray(r))return`[${r.map(e=>n(e)??`null`).join(`,`)}]`;let e=Object.keys(r).sort(),t=[];for(let i of e){let e=n(r[i]);e!==void 0&&t.push(`${JSON.stringify(i)}:${e}`)}return`{${t.join(`,`)}}`}finally{t.delete(r)}}try{return n(e)}catch{return}}const t=t=>t instanceof Error?n(t):typeof t==`string`?t:e(t)??`<unserializable cause>`,n=n=>{if(n instanceof Error){let e={name:n.name,message:n.message};n.stack!==void 0&&(e.stack=n.stack);let{cause:r}=n;return r!==void 0&&(e.cause=t(r)),e}return{name:`NonErrorThrowable`,message:typeof n==`string`?n:e(n)??`<unserializable>`}},r=e=>{if(typeof e==`string`)return Error(e);let t=Error(e.message);if(e.name&&(t.name=e.name),e.stack!==void 0&&(t.stack=e.stack),e.cause!==void 0){let n=t;n.cause=r(e.cause)}return t},i=`@functype`,a=(e,t,n)=>({[i]:e,_tag:t??e,value:n}),o=(e,t,n)=>({[i]:e,_tag:t,...n});function s(t,n,r){let o=arguments.length===3,s=o?n:t,c=o?r:n,l=a(t,s,c);return{toJSON:()=>JSON.stringify(l),toYAML:()=>`${i}: ${t}\n_tag: ${s}\nvalue: ${e(c)}`,toBinary:()=>Buffer.from(JSON.stringify(l)).toString(`base64`)}}const c=(t,n,r)=>{let i=o(t,n,r);return{toJSON:()=>JSON.stringify(i),toYAML:()=>Object.entries(i).map(([t,n])=>`${t}: ${e(n)}`).join(`
2
2
  `),toBinary:()=>Buffer.from(JSON.stringify(i)).toString(`base64`)}},l=t=>({toJSON:()=>JSON.stringify(t),toYAML:()=>Object.entries(t).map(([t,n])=>`${t}: ${e(n)}`).join(`
3
3
  `),toBinary:()=>Buffer.from(JSON.stringify(t)).toString(`base64`)}),u=(e,t)=>t(JSON.parse(e)),d=(e,t)=>{let n=e.split(`
4
- `),r={};for(let e of n){let t=e.indexOf(`: `);if(t===-1)continue;let n=e.substring(0,t),i=e.substring(t+2);if(!i){r[n]=null;continue}try{r[n]=i===`null`?null:JSON.parse(i)}catch{r[n]=i}}return t(r)},f=(e,t)=>u(Buffer.from(e,`base64`).toString(),t),p=e=>({fromJSON:t=>u(t,e),fromYAML:t=>d(t,e),fromBinary:t=>f(t,e)});export{c as a,u as c,r as d,n as f,s as i,d as l,l as n,a as o,e as p,p as r,f as s,i as t,o as u};
4
+ `),r={};for(let e of n){let t=e.indexOf(`: `);if(t===-1)continue;let n=e.substring(0,t),i=e.substring(t+2);if(!i){r[n]=null;continue}try{r[n]=i===`null`?null:JSON.parse(i)}catch{r[n]=i}}return t(r)},f=(e,t)=>{let n=Buffer.from(e,`base64`).toString();return u(n,t)},p=e=>({fromJSON:t=>u(t,e),fromYAML:t=>d(t,e),fromBinary:t=>f(t,e)});export{c as a,u as c,r as d,n as f,s as i,d as l,l as n,a as o,e as p,p as r,f as s,i as t,o as u};
@@ -1,2 +1,2 @@
1
- import { kn as Set } from "../index-CGVJBR_H.js";
1
+ import { An as Set } from "../index-CCuIZ-ut.js";
2
2
  export { Set };
package/dist/set/index.js CHANGED
@@ -1 +1 @@
1
- import{Ot as e}from"../src-4UEC-cVf.js";export{e as Set};
1
+ import{Ot as e}from"../src-C4olFIr1.js";export{e as Set};
@@ -0,0 +1,17 @@
1
+ import{t as e}from"./rolldown-runtime-DK3Fl9T5.js";import{Brand as t}from"./branded/index.js";import{mergeObjects as n}from"./util/index.js";import{t as r}from"./Companion-DiOMBHDG.js";import{a as i,d as a,f as o,i as s,p as c,t as l}from"./serialization-my_TLROv.js";import{n as u,t as ee}from"./typeclass-C61yDVYd.js";import{Tuple as te}from"./tuple/index.js";const ne=e=>{let t=Error(e);return t.name=`ParseError`,t},d=e=>({[Symbol.toStringTag]:`Option`,_tag:`Some`,value:e,isEmpty:!1,isSome(){return!0},isNone(){return!1},orElse:t=>e,orThrow:()=>e,expect:t=>e,or:t=>d(e),orNull:()=>e,orUndefined:()=>e,map:t=>d(t(e)),ap:t=>t._tag===`Some`&&t.value?d(t.value(e)):f,filter(t){return t(e)?d(e):f},count:t=>+!!t(e),find:t=>t(e)?d(e):f,exists:t=>t(e),forEach:t=>t(e),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),match:t=>t.Some(e),flatMap:t=>t(e),flatMapAsync:async t=>await t(e),reduce:t=>e,reduceRight:t=>e,foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),contains:t=>t===e,toList:()=>C([e]),toArray:()=>[e],size:1,toOption:()=>d(e),toEither:t=>w(e),toTry:()=>x(()=>e),toPromise:()=>Promise.resolve(e),toString:()=>`Some(${c(e)})`,toValue:()=>({_tag:`Some`,value:e}),toJSON:()=>({"@functype":`Option`,_tag:`Some`,value:e}),pipe:t=>t(e),serialize:()=>s(`Option`,`Some`,e),doUnwrap(){return{ok:!0,value:e}}}),f={[Symbol.toStringTag]:`Option`,_tag:`None`,value:void 0,isEmpty:!0,isSome(){return!1},isNone(){return!0},orElse:e=>e,orThrow(e){throw e??Error(`Cannot extract value from None`)},expect(e){return e()},or:e=>e,orNull:()=>null,orUndefined:()=>void 0,map:e=>f,ap:e=>f,filter(e){return f},count:e=>0,find:e=>f,exists:e=>!1,forEach:e=>{},flatMap:e=>f,flatMapAsync:e=>Promise.resolve(f),reduce:e=>{throw Error(`Cannot reduce an empty Option`)},reduceRight:e=>{throw Error(`Cannot reduceRight an empty Option`)},fold:(e,t)=>e(),foldAsync:async(e,t)=>e(),match:e=>e.None(),foldLeft:e=>()=>e,foldRight:e=>()=>e,contains:()=>!1,toList:()=>C([]),toArray:()=>[],size:0,toOption:()=>f,toEither:e=>T(typeof e==`function`?e():e),toTry:()=>x(()=>{throw Error(`None`)}),toPromise:()=>Promise.reject(Error(`Cannot convert None to Promise`)),toString:()=>`None`,toValue:()=>({_tag:`None`,value:void 0}),toJSON:()=>({"@functype":`Option`,_tag:`None`,value:null}),pipe:e=>e(void 0),serialize:()=>s(`Option`,`None`,null),doUnwrap(){return{ok:!1,empty:!0}}},p=()=>f,re=e=>e==null?p():d(e),ie={from:e=>m(e),none:()=>p(),isSome:e=>e.isSome(),isNone:e=>e.isNone(),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Option`)throw Error(`Option.fromJSON: expected @functype="Option", got ${JSON.stringify(t[`@functype`])}`);return t._tag===`Some`?d(t.value):p()},fromYAML:e=>{let t=e.split(`
2
+ `),n=t[0]?.split(`: `)[1],r=t[1]?.split(`: `)[1];if(!n||!r)return p();let i=r===`null`?null:JSON.parse(r);return n===`Some`?d(i):p()},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return ie.fromJSON(t)},sequence:e=>e.reduce((e,t)=>e.isEmpty||t.isEmpty?p():d([...e.value,t.value]),d([])),traverse:(e,t)=>e.reduce((e,n,r)=>e.flatMap(e=>t(n,r).map(t=>[...e,t])),d([]))},m=r(re,ie),h=globalThis.Set,g=e=>{let t=new h(e),n={[Symbol.toStringTag]:`FunctypeSet`,_tag:`Set`,[Symbol.iterator]:()=>t[Symbol.iterator](),add:e=>g([...t,e]),remove:e=>{let n=new h(t);return n.delete(e),g(n)},contains:e=>t.has(e),has:e=>t.has(e),map:e=>g(Array.from(t).map(e)),ap:e=>{let n=new h;for(let r of t)for(let t of e)n.add(t(r));return g(n)},flatMap:e=>{let n=new h;for(let r of t)for(let t of e(r))n.add(t);return g(n)},flatMapAsync:async e=>{let n=new h;for(let r of t){let t=await e(r);for(let e of t)n.add(e)}return g(n)},fold:(e,n)=>{let r=e;for(let e of t)r=n(r,e);return r},foldLeft:e=>n=>{let r=e;for(let e of t)r=n(r,e);return r},foldRight:e=>n=>Array.from(t).reduceRight((e,t)=>n(t,e),e),get size(){return t.size},get isEmpty(){return t.size===0},reduce:e=>{let n=Array.from(t);if(n.length===0)throw Error(`Cannot reduce empty Set`);return u(n,e)},reduceRight:e=>{let n=Array.from(t);if(n.length===0)throw Error(`Cannot reduceRight empty Set`);return ee(n,e)},count:e=>{let n=0;for(let r of t)e(r)&&n++;return n},find:e=>{for(let n of t)if(e(n))return m(n);return m(null)},exists:e=>{for(let n of t)if(e(n))return!0;return!1},forEach:e=>{t.forEach(e)},filter:e=>{let n=new h;for(let r of t)e(r)&&n.add(r);return g(n)},filterNot:e=>{let n=new h;for(let r of t)e(r)||n.add(r);return g(n)},drop:e=>g(Array.from(t).slice(e)),dropRight:e=>g(Array.from(t).slice(0,-e)),dropWhile:e=>{let n=Array.from(t),r=n.findIndex(t=>!e(t));return g(r===-1?[]:n.slice(r))},flatten:()=>{let e=new h;for(let n of t)if(Array.isArray(n))for(let t of n)e.add(t);else if(n&&typeof n==`object`&&Symbol.iterator in n)for(let t of n)e.add(t);else e.add(n);return g(e)},get head(){return Array.from(t)[0]},get headOption(){let e=Array.from(t)[0];return m(e)},take:e=>g(Array.from(t).slice(0,Math.max(0,e))),takeWhile:e=>{let n=Array.from(t),r=[];for(let t of n){if(!e(t))break;r.push(t)}return g(r)},takeRight:e=>{let n=Array.from(t);return g(e<=0?[]:n.slice(-e))},get last(){let e=Array.from(t);return e[e.length-1]},get lastOption(){let e=Array.from(t);return m(e[e.length-1])},get tail(){return g(Array.from(t).slice(1))},get init(){let e=Array.from(t);return g(e.length===0?[]:e.slice(0,-1))},toList:()=>C(Array.from(t)),toSet:()=>n,toArray:()=>Array.from(t),toString:()=>`Set(${Array.from(t).toString()})`,toValue:()=>({_tag:`Set`,value:Array.from(t)}),toJSON:()=>({"@functype":`Set`,_tag:`Set`,value:Array.from(t)}),pipe:e=>e(Array.from(t)),serialize:()=>s(`Set`,Array.from(t))};return n},ae=e=>g(e),oe=g([]),se={empty:()=>oe,of:(...e)=>g(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Set`)throw Error(`Set.fromJSON: expected @functype="Set", got ${JSON.stringify(t[`@functype`])}`);return ce(t.value)},fromYAML:e=>{let t=e.split(`
3
+ `)[1]?.split(`: `)[1];if(!t)return ce([]);let n=JSON.parse(t);return ce(n)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return se.fromJSON(t)}},ce=r(ae,se),le=e=>{let t=e;return{get(){return t},set(e){t=e},update(e){t=e(t)},getAndSet(e){let n=t;return t=e,n},updateAndGet(e){return t=e(t),t},getAndUpdate(e){let n=t;return t=e(t),n},compareAndSet(e,n){return t===e?(t=n,!0):!1},modify(e){let[n,r]=e(t);return t=n,r}}},_=r(le,{of:e=>le(e)}),ue=(e=0)=>{let t=_(e),n=e;return{get:()=>t.get(),set:e=>t.set(e),increment:()=>t.updateAndGet(e=>e+1),decrement:()=>t.updateAndGet(e=>e-1),reset:()=>t.set(n),compareAndSet:(e,n)=>t.compareAndSet(e,n)}},de=()=>{let e=_([]);return{add:t=>e.update(e=>[...e,t]),addAll:t=>e.update(e=>[...e,...t]),build:()=>e.get(),clear:()=>e.set([]),size:()=>e.get().length}},v=e=>{let t={[Symbol.toStringTag]:`LazyList`,_tag:`LazyList`,[Symbol.iterator]:()=>e[Symbol.iterator](),map:t=>v((function*(){for(let n of e)yield t(n)})()),flatMap:t=>v((function*(){for(let n of e)yield*t(n)})()),filter:t=>v((function*(){for(let n of e)t(n)&&(yield n)})()),take:t=>v((function*(){let n=ue(0);for(let r of e){if(n.get()>=t)break;yield r,n.increment()}})()),drop:t=>v((function*(){let n=ue(0);for(let r of e)n.get()>=t&&(yield r),n.increment()})()),takeWhile:t=>v((function*(){for(let n of e){if(!t(n))break;yield n}})()),dropWhile:t=>v((function*(){let n=_(!0);for(let r of e)n.get()&&t(r)||(n.set(!1),yield r)})()),concat:t=>v((function*(){yield*e,yield*t})()),zip:t=>v((function*(){let n=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){let e=n.next(),t=r.next();if(e.done||t.done)break;yield[e.value,t.value]}})()),toList:()=>C(Array.from(e)),toArray:()=>Array.from(e),forEach:t=>{for(let n of e)t(n)},reduce:(t,n)=>{let r=_(n);for(let n of e)r.set(t(r.get(),n));return r.get()},find:t=>{for(let n of e)if(t(n))return m(n);return m.none()},some:t=>{for(let n of e)if(t(n))return!0;return!1},every:t=>{for(let n of e)if(!t(n))return!1;return!0},count:()=>{let t=ue(0);for(let n of e)t.increment();return t.get()},get head(){let t=e[Symbol.iterator]().next();return t.done?void 0:t.value},get headOption(){let t=e[Symbol.iterator]().next();return t.done?m.none():m(t.value)},get last(){let t;for(let n of e)t=n;return t},get lastOption(){let t=_(void 0),n=_(!1);for(let r of e)t.set(r),n.set(!0);return n.get()?m(t.get()):m.none()},get tail(){return v((function*(){let t=e[Symbol.iterator]();t.next();let n=t.next();for(;!n.done;)yield n.value,n=t.next()})())},get init(){let t=Array.from(e);return v(t.length===0?[]:t.slice(0,-1))},takeRight:t=>{let n=Array.from(e);return v(t<=0?[]:n.slice(-t))},reverse:()=>v(Array.from(e).reverse()),distinct:()=>v((function*(){let t=new globalThis.Set;for(let n of e)t.has(n)||(t.add(n),yield n)})()),zipWithIndex:()=>v((function*(){let t=ue(0);for(let n of e)yield[n,t.get()],t.increment()})()),fold:(t,n)=>{let r=t;for(let t of e)r=n(r,t);return r},foldLeft:t=>n=>{let r=_(t);for(let t of e)r.set(n(r.get(),t));return r.get()},foldRight:t=>n=>Array.from(e).reduceRight((e,t)=>n(t,e),t),pipe:e=>e(t),serialize:()=>s(`LazyList`,Array.from(e)),toJSON:()=>({"@functype":`LazyList`,_tag:`LazyList`,value:Array.from(e)}),toString:()=>{let t=[],n=ue(0),r=_(!1);for(let i of e)if(n.get()<10)t.push(i),n.increment();else{r.set(!0);break}let i=t.map(e=>String(e)).join(`, `);return r.get()?`LazyList(${i}, ...)`:`LazyList(${i})`}};return t},fe=r(e=>v(e),{empty:()=>v([]),of:e=>v([e]),from:(...e)=>v(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`LazyList`)throw Error(`LazyList.fromJSON: expected @functype="LazyList", got ${JSON.stringify(t[`@functype`])}`);return v(t.value)},iterate:(e,t)=>v((function*(){let n=_(e);for(;;)yield n.get(),n.set(t(n.get()))})()),generate:e=>v((function*(){for(;;)yield e()})()),range:(e,t,n=1)=>v((function*(){if(n===0)throw Error(`Step cannot be zero`);let r=_(e);if(n>0)for(;r.get()<t;)yield r.get(),r.set(r.get()+n);else for(;r.get()>t;)yield r.get(),r.set(r.get()+n)})()),repeat:(e,t)=>v((function*(){if(t===void 0)for(;;)yield e;else{let n=ue(0);for(;n.get()<t;)yield e,n.increment()}})()),cycle:e=>v((function*(){let t=Array.from(e);if(t.length!==0)for(;;)yield*t})())}),y=e=>({[Symbol.toStringTag]:`Try`,_tag:`Success`,error:void 0,isSuccess(){return!0},isFailure(){return!1},orElse:t=>e,orThrow:t=>e,expect:t=>e,or:t=>y(e),orNull:()=>e,orUndefined:()=>e,toEither:t=>w(e),map:t=>x(()=>t(e)),ap:t=>t.map(t=>t(e)),flatMap:t=>t(e),flatMapAsync:async t=>t(e),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),match:t=>t.Success(e),recover:t=>y(e),recoverWith:t=>y(e),filterOrElse:(t,n)=>{try{return t(e)?y(e):b(n(e))}catch(e){return b(e instanceof Error?e:Error(String(e)))}},foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),toString:()=>`Success(${c(e)})`,toPromise:()=>Promise.resolve(e),toValue:()=>({_tag:`Success`,value:e}),toJSON:()=>({"@functype":`Try`,_tag:`Success`,value:e}),toOption:()=>d(e),toList:()=>C([e]),toArray:()=>[e],toTry:()=>y(e),pipe:t=>t(e),serialize:()=>s(`Try`,`Success`,e),contains:t=>e===t,exists:t=>t(e),forEach:t=>t(e),doUnwrap(){return{ok:!0,value:e}}}),b=e=>({[Symbol.toStringTag]:`Try`,_tag:`Failure`,error:e,isSuccess(){return!1},isFailure(){return!0},orElse:e=>e,orThrow:t=>{throw t??e},expect:t=>t(e),or:e=>e,orNull:()=>null,orUndefined:()=>void 0,toEither:t=>T(typeof t==`function`?t(e):t),map:t=>b(e),ap:t=>b(e),flatMap:t=>b(e),flatMapAsync:t=>Promise.resolve(b(e)),fold:(t,n)=>t(e),foldAsync:async(t,n)=>t(e),match:t=>t.Failure(e),recover:t=>x(()=>t(e)),recoverWith:t=>{try{return t(e)}catch(e){return b(e instanceof Error?e:Error(String(e)))}},filterOrElse:(t,n)=>b(e),foldLeft:e=>t=>e,foldRight:e=>t=>e,toString:()=>`Failure(${c(e)}))`,toPromise:()=>Promise.reject(e),toValue:()=>({_tag:`Failure`,value:e}),toJSON:()=>({"@functype":`Try`,_tag:`Failure`,error:o(e)}),toOption:()=>m(null),toList:()=>C([]),toArray:()=>[],toTry:()=>b(e),pipe:t=>{throw e},serialize:()=>i(`Try`,`Failure`,{error:o(e)}),contains:e=>!1,exists:e=>!1,forEach:e=>{},doUnwrap(){return{ok:!1,empty:!1,error:e}}}),pe=e=>{try{return y(e())}catch(e){return b(e instanceof Error?e:Error(String(e)))}},me={success:e=>y(e),failure:e=>b(typeof e==`string`?Error(e):e),fromPromise:e=>e.then(e=>y(e)).catch(e=>b(e instanceof Error?e:Error(String(e)))),async:e=>{try{return e().then(e=>y(e)).catch(e=>b(e instanceof Error?e:Error(String(e))))}catch(e){return Promise.resolve(b(e instanceof Error?e:Error(String(e))))}},isSuccess:e=>e.isSuccess(),isFailure:e=>e.isFailure(),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Try`)throw Error(`Try.fromJSON: expected @functype="Try", got ${JSON.stringify(t[`@functype`])}`);if(t._tag===`Success`)return y(t.value);if(t.error!==void 0&&typeof t.error==`object`)return b(a(t.error));let n=Error(typeof t.error==`string`?t.error:``);return t.stack&&(n.stack=t.stack),b(n)},fromYAML:e=>{let t=e.split(`
4
+ `),n=t[0]?.split(`: `)[1];if(!n)return b(Error(`Invalid YAML format for Try`));if(n===`Success`){let e=t[1]?.split(`: `)[1];if(!e)return b(Error(`Invalid YAML format for Try Success`));let n=JSON.parse(e);return y(n)}else{let e=t[1]?.split(`: `)[1];if(!e)return b(Error(`Invalid YAML format for Try Failure`));let n=t[2]?.split(`: `),r=n&&n.length>1?n.slice(1).join(`: `):void 0,i=Error(e);return r&&(i.stack=r),b(i)}},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return me.fromJSON(t)},sequence:e=>x(()=>e.map(e=>e.orThrow())),traverse:(e,t)=>x(()=>e.map((e,n)=>t(e,n).orThrow()))},x=r(pe,me);function he({_tag:e,impl:t}){return{...t,_tag:e}}function ge(e,t){return!e||typeof e!=`object`||!(`_tag`in e)?!1:t?e._tag===t:!0}const S=e=>{let t=Array.from(e??[]),n={[Symbol.toStringTag]:`List`,_tag:`List`,[Symbol.iterator]:()=>t[Symbol.iterator](),get size(){return t.length},get length(){return t.length},map:e=>S(t.map(e)),ap:e=>S(t.flatMap(t=>Array.from(e).map(e=>e(t)))),flatMap:e=>S(t.flatMap(t=>Array.from(e(t)))),flatMapAsync:async e=>{let n=await Promise.all(t.map(async t=>await e(t)));return S(n.flatMap(e=>Array.from(e)))},forEach:e=>t.forEach(e),contains:e=>t.includes(e),count:e=>t.filter(e).length,exists:e=>t.some(e),filter:e=>S(t.filter(e)),filterNot:e=>S(t.filter(t=>!e(t))),filterType:e=>S(t.filter(t=>ge(t,e))),find:(e,n)=>m(t.find(t=>e(t)&&(n?ge(t,n):!0))),get head(){return t[0]},get headOption(){return t.length>0?m(t[0]):p()},get isEmpty(){return t.length===0},toArray:()=>[...t],reduce:e=>u(t,e),reduceRight:e=>ee(t,e),fold:(e,n)=>t.reduce(n,e),foldLeft:e=>n=>t.reduce(n,e),foldRight:e=>n=>t.reduceRight((e,t)=>n(t,e),e),match:e=>t.length===0?e.Empty():e.NonEmpty([...t]),remove:e=>S(t.filter(t=>t!==e)),removeAt:e=>e<0||e>=t.length?n:S([...t.slice(0,e),...t.slice(e+1)]),add:e=>S([...t,e]),get:e=>m(t[e]),concat:e=>S([...t,...e.toArray()]),take:e=>S(t.slice(0,Math.max(0,e))),takeWhile:e=>{let n=[];for(let r of t){if(!e(r))break;n.push(r)}return S(n)},takeRight:e=>S(e<=0?[]:t.slice(-e)),get last(){return t[t.length-1]},get lastOption(){return t.length>0?m(t[t.length-1]):p()},get tail(){return S(t.slice(1))},get init(){return S(t.length===0?[]:t.slice(0,-1))},reverse:()=>S([...t].reverse()),indexOf:e=>t.indexOf(e),prepend:e=>S([e,...t]),distinct:()=>{let e=new globalThis.Set,n=[];for(let r of t)e.has(r)||(e.add(r),n.push(r));return S(n)},sorted:e=>S([...t].sort(e)),sortBy:(e,n)=>S([...t].sort((t,r)=>{let i=e(t),a=e(r);return n?n(i,a):i<a?-1:+(i>a)})),zip:e=>{let n=e.toArray(),r=Math.min(t.length,n.length),i=[];for(let e=0;e<r;e++)i.push([t[e],n[e]]);return S(i)},zipWithIndex:()=>S(t.map((e,t)=>[e,t])),groupBy:e=>{let n=new globalThis.Map;for(let r of t){let t=e(r),i=n.get(t)??[];i.push(r),n.set(t,i)}let r=new globalThis.Map;for(let[e,t]of n)r.set(e,S(t));return r},partition:e=>{let n=[],r=[];for(let i of t)e(i)?n.push(i):r.push(i);return[S(n),S(r)]},span:e=>{let n=t.findIndex(t=>!e(t));return n===-1?[S([...t]),S([])]:[S(t.slice(0,n)),S(t.slice(n))]},slice:(e,n)=>S(t.slice(e,n)),drop:e=>S(t.slice(e)),dropRight:e=>S(t.slice(0,-e)),dropWhile:e=>S(t.slice(t.findIndex(t=>!e(t)))),flatten:()=>S(t.flatMap(e=>Array.isArray(e)?e:[e])),toList:()=>n,toSet:()=>ce(t),toOption:()=>t.length>0?m(t[0]):p(),toEither:e=>t.length>0?w(t[0]):T(e),toTry:()=>t.length>0?x(()=>t[0]):x(()=>{throw Error(`Empty list`)}),toString:()=>`List(${c(t)})`,toValue:()=>({_tag:`List`,value:t}),toJSON:()=>({"@functype":`List`,_tag:`List`,value:[...t]}),pipe:e=>e([...t]),serialize:()=>s(`List`,t),doUnwrap(){return t.length===0?{ok:!1,empty:!0}:{ok:!0,value:t[0]}}};return n},_e=e=>S(e),ve=S([]),ye={empty:()=>ve,of:(...e)=>S(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`List`)throw Error(`List.fromJSON: expected @functype="List", got ${JSON.stringify(t[`@functype`])}`);return C(t.value)},fromYAML:e=>{let t=e.split(`
5
+ `)[1]?.split(`: `)[1];if(!t)return C([]);let n=JSON.parse(t);return C(n)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return ye.fromJSON(t)}},C=r(_e,ye),be=e=>({[Symbol.toStringTag]:`Either`,_tag:`Right`,value:e,isLeft(){return!1},isRight(){return!0},orElse:t=>e,orThrow:()=>e,expect:t=>e,or:t=>w(e),orNull:()=>e,orUndefined:()=>e,map:t=>w(t(e)),ap:t=>t._tag===`Right`?w(t.value(e)):T(t.value),mapAsync:t=>t(e).then(e=>w(e)).catch(e=>Promise.resolve(T(e))),merge:t=>t.isLeft()?T(t.value):w([e,t.value]),flatMap:t=>t(e),flatMapAsync:t=>t(e).catch(e=>T(e)),toOption:()=>d(e),toList:()=>C([e]),toEither:t=>w(e),toTry:()=>x(()=>e),toJSON(){return{"@functype":`Either`,_tag:`Right`,value:e}},toString:()=>`Right(${c(e)})`,*[Symbol.iterator](){yield e},*yield(){yield e},traverse:t=>{let n=t(e);return n.isLeft()?T(n.value):w([n.value])},tap:t=>(t(e),w(e)),tapLeft:t=>w(e),mapLeft:t=>w(e),filterOrElse:(t,n)=>t(e)?w(e):T(n(e)),bimap:(t,n)=>w(n(e)),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),match:t=>t.Right(e),swap:()=>T(e),toPromise:()=>Promise.resolve(e),toValue:()=>({_tag:`Right`,value:e}),pipeEither:(t,n)=>n(e),pipe:t=>t(e),serialize:()=>s(`Either`,`Right`,e),contains:t=>e===t,exists:t=>t(e),forEach:t=>t(e),doUnwrap(){return{ok:!0,value:e}}}),xe=e=>({[Symbol.toStringTag]:`Either`,_tag:`Left`,value:e,isLeft(){return!0},isRight(){return!1},orElse:e=>e,orThrow:t=>{throw t??e},expect:t=>t(e),or:e=>e,orNull:()=>null,orUndefined:()=>void 0,map:t=>T(e),ap:t=>T(e),mapAsync:t=>Promise.resolve(T(e)),merge:t=>T(e),flatMap:t=>T(e),flatMapAsync:t=>Promise.resolve(T(e)),toOption:()=>p(),toList:()=>C(),toEither:e=>T(e),toTry:()=>x(()=>{throw Error(String(e))}),toJSON(){return{"@functype":`Either`,_tag:`Left`,value:e}},toString:()=>`Left(${c(e)})`,*[Symbol.iterator](){},*yield(){},traverse:t=>T(e),tap:t=>T(e),tapLeft:t=>(t(e),T(e)),mapLeft:t=>T(t(e)),filterOrElse:(t,n)=>T(e),bimap:(t,n)=>T(t(e)),fold:(t,n)=>t(e),foldAsync:async(t,n)=>t(e),foldLeft:e=>t=>e,foldRight:e=>t=>e,match:t=>t.Left(e),swap:()=>w(e),toPromise:()=>Promise.reject(e),toValue:()=>({_tag:`Left`,value:e}),pipeEither:(t,n)=>t(e),pipe:t=>t(e),serialize:()=>s(`Either`,`Left`,e),contains:e=>!1,exists:e=>!1,forEach:e=>{},doUnwrap(){return{ok:!1,empty:!1,error:e}}}),w=e=>be(e),T=e=>xe(e),Se=e=>e.isRight(),Ce=e=>e.isLeft(),we=(e,t)=>{try{return w(e())}catch(e){return T(t(e))}},Te=e=>be(e);console.assert(Te);const Ee=e=>xe(e);console.assert(Ee);const De=async(e,t)=>{try{let t=await e();return w(t)}catch(e){return T(t(e))}},Oe=(e,t)=>t?w(e):T(e),ke={left:e=>T(e),right:e=>w(e),void:()=>w(void 0),isRight:e=>e.isRight(),isLeft:e=>e.isLeft(),sequence:e=>e.reduce((e,t)=>e.isLeft()?e:t.isLeft()?T(t.value):e.map(e=>[...e,t.value]),w([])),traverse:(e,t)=>ke.sequence(e.map(t)),fromNullable:(e,t)=>e==null?T(t):w(e),fromPredicate:(e,t,n)=>t(e)?w(e):T(n),ap:(e,t)=>e.flatMap(e=>t.map(e)),fromPromise:async(e,t)=>{try{let t=await e;return w(t)}catch(e){return T(t(e))}},fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Either`)throw Error(`Either.fromJSON: expected @functype="Either", got ${JSON.stringify(t[`@functype`])}`);return t._tag===`Right`?w(t.value):T(t.value)},fromYAML:e=>{let t=e.split(`
6
+ `),n=t[0]?.split(`: `)[1],r=t[1]?.split(`: `)[1];if(!n||!r)throw Error(`Invalid YAML format for Either`);let i=JSON.parse(r);return n===`Right`?w(i):T(i)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return ke.fromJSON(t)}},Ae=r(Oe,ke);function E(e,n){return{brand:e,validate:n,of:r=>n(r)?m(t(e,r)):m.none(),from:r=>n(r)?w(t(e,r)):T(`Invalid ${e}: validation failed`),unsafeOf:r=>{if(!n(r))throw Error(`Invalid ${e}: validation failed`);return t(e,r)},is:e=>{try{return n(e)}catch{return!1}},unwrap:e=>e,refine:(e,t)=>E(e,e=>n(e)&&t(e))}}const je=E(`PositiveNumber`,e=>e>0),Me=E(`NonNegativeNumber`,e=>e>=0),Ne=E(`IntegerNumber`,e=>Number.isInteger(e)),Pe=je.refine(`PositiveInteger`,e=>Number.isInteger(e)),Fe=E(`NonEmptyString`,e=>e.length>0),Ie=E(`EmailAddress`,e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),Le=E(`UrlString`,e=>{try{return new URL(e),!0}catch{return!1}}),Re=E(`UUID`,e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),ze=E(`ISO8601Date`,e=>!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e));function Be(e,t,n){return E(e,e=>e>=t&&e<=n)}function Ve(e,t,n){return E(e,e=>e.length>=t&&e.length<=n)}function He(e,t){return E(e,e=>t.test(e))}const Ue=e=>{let t=e=>typeof e==`function`?e():e,n={when:(r,i)=>e.resolved?n:r?Ue({resolved:!0,value:t(i)}):n,elseWhen:(r,i)=>e.resolved?n:r?Ue({resolved:!0,value:t(i)}):n,else:n=>e.resolved?e.value:t(n),orThrow:()=>{if(!e.resolved)throw Error(`Conditional expression has no matching condition`);return e.value}};return n},We=()=>Ue({resolved:!1}),Ge=r(We,{of:()=>We(),match:e=>t=>{let n=t[e];if(n===void 0)throw Error(`No case defined for value: ${String(e)}`);return typeof n==`function`?n():n},lazy:()=>{let e={resolved:!1},t={when:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),elseWhen:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),else:t=>e.resolved?e.value:t()};return t}}),Ke=(e,t)=>t===e?!0:typeof t==`function`?t(e):t&&typeof t==`object`&&`_`in t?t._(e):typeof t==`object`&&t&&typeof e==`object`&&e?Object.entries(t).every(([t,n])=>{let r=e[t];return Ke(r,n)}):!1,D=e=>{let t=(e,t)=>typeof e==`function`?e(t):e,n=()=>{for(let{pattern:n,result:r}of e.patterns)if(Ke(e.value,n))return{matched:!0,result:t(r,e.value)};return{matched:!1}},r={case:(n,i)=>e.resolved?r:Ke(e.value,n)?D({value:e.value,resolved:!0,result:t(i,e.value),patterns:[]}):D({...e,patterns:[...e.patterns,{pattern:n,result:i}]}),caseValue:(t,n)=>{if(e.resolved)return r;if(e.value===t){let t=typeof n==`function`?n():n;return D({value:e.value,resolved:!0,result:t,patterns:[]})}return r},caseValues:(t,n)=>{if(e.resolved)return r;if(t.includes(e.value)){let t=typeof n==`function`?n():n;return D({value:e.value,resolved:!0,result:t,patterns:[]})}return r},when:(e,t)=>r.case(e,t),caseAny:(n,i)=>{if(e.resolved)return r;for(let r of n)if(Ke(e.value,r))return D({value:e.value,resolved:!0,result:t(i,e.value),patterns:[]});return D({...e,patterns:[...e.patterns,...n.map(e=>({pattern:e,result:i}))]})},default:n=>e.resolved?e.result:t(n,e.value),exhaustive:()=>{if(e.resolved)return e.result;let t=n();if(!t.matched)throw Error(`Non-exhaustive match. No pattern matched value: ${JSON.stringify(e.value)}`);return t.result},orThrow:t=>{if(e.resolved)return e.result;let r=n();if(!r.matched)throw Error(t??`No matching pattern for value: ${JSON.stringify(e.value)}`);return r.result},toOption:()=>{if(e.resolved)return m(e.result);let t=n();return t.matched?m(t.result):m.none()}};return r},qe=e=>{let t=(e,t)=>typeof e==`function`?e(t):e;return{case:(n,r)=>{let i={value:e,resolved:!1,patterns:[{pattern:n,result:r}]};return Ke(e,n)?D({...i,resolved:!0,result:t(r,e)}):D(i)},caseValue:(t,n)=>{if(e===t){let t=typeof n==`function`?n():n;return D({value:e,resolved:!0,result:t,patterns:[]})}return D({value:e,resolved:!1,patterns:[]})},caseValues:(t,n)=>{if(t.includes(e)){let t=typeof n==`function`?n():n;return D({value:e,resolved:!0,result:t,patterns:[]})}return D({value:e,resolved:!1,patterns:[]})},when:(n,r)=>{let i={value:e,resolved:!1,patterns:[{pattern:n,result:r}]};return n(e)?D({...i,resolved:!0,result:t(r,e)}):D(i)},caseAny:(n,r)=>{for(let i of n)if(Ke(e,i))return D({value:e,resolved:!0,result:t(r,e),patterns:n.map(e=>({pattern:e,result:r}))});return D({value:e,resolved:!1,patterns:n.map(e=>({pattern:e,result:r}))})}}},Je=r(e=>qe(e),{exhaustive:e=>t=>{let n=e[t];if(n===void 0)throw Error(`No case defined for value: ${String(t)}`);return n},partial:e=>({withDefault:t=>n=>{let r=e[n];return r===void 0?typeof t==`function`?t(n):t:typeof r==`function`?r(n):r}}),withGuards:e=>({withDefault:t=>n=>{for(let[t,r]of e)if(t(n))return typeof r==`function`?r(n):r;return typeof t==`function`?t(n):t}}),struct:()=>{let e=[],t={case:(n,r)=>(e.push({pattern:n,handler:r}),t),build:()=>t=>{for(let{pattern:n,handler:r}of e)if(Ke(t,n))return r(t);throw Error(`No matching pattern for value: ${JSON.stringify(t)}`)}};return t},builder:()=>{let e=[],t,n={case:(t,r)=>(e.push({pattern:t,result:r}),n),when:(t,r)=>(e.push({pattern:t,result:r}),n),default:n=>(t=n,{build:()=>n=>{for(let{pattern:t,result:r}of e)if(Ke(n,t))return typeof r==`function`?r(n):r;if(t!==void 0)return typeof t==`function`?t(n):t;throw Error(`No matching pattern for value: ${JSON.stringify(n)}`)}})};return n}});function Ye(e,t){return{...he({_tag:e,impl:t}),toString(){return`${e}()`},doUnwrap(){if(`isSome`in t&&`isNone`in t){if(typeof t.isSome==`function`&&t.isSome()&&`get`in t&&typeof t.get==`function`)return{ok:!0,value:t.get()};if(typeof t.isNone==`function`&&t.isNone())return{ok:!1,empty:!0}}if(`isLeft`in t&&`isRight`in t){if(typeof t.isRight==`function`&&t.isRight()&&`value`in t)return{ok:!0,value:t.value};if(typeof t.isLeft==`function`&&t.isLeft()&&`value`in t)return{ok:!1,empty:!1,error:t.value}}if(`isSuccess`in t&&`isFailure`in t){if(typeof t.isSuccess==`function`&&t.isSuccess()&&`get`in t&&typeof t.get==`function`)return{ok:!0,value:t.get()};if(typeof t.isFailure==`function`&&t.isFailure()&&`getError`in t&&typeof t.getError==`function`)return{ok:!1,empty:!1,error:t.getError()}}if(`isEmpty`in t&&`head`in t){if(typeof t.isEmpty==`function`&&t.isEmpty())return{ok:!1,empty:!0};if(typeof t.head==`function`)return{ok:!0,value:t.head()};if(`head`in t)return{ok:!0,value:t.head}}return{ok:!0,value:t}}}}const Xe=`Throwable`;var Ze=class e extends Error{constructor(e,t){super(e,{cause:t?.cause}),this._tag=Xe,this.name=t?.taskInfo?.name??`Throwable`,Object.defineProperties(this,{_tag:{value:Xe,writable:!1,configurable:!1},data:{value:t?.data,writable:!1,configurable:!1},taskInfo:{value:t?.taskInfo,writable:!1,configurable:!1},name:{value:t?.taskInfo?.name??`Throwable`,writable:!1,configurable:!1}}),t?.cause&&Object.defineProperty(this,"cause",{value:t.cause,writable:!1,configurable:!1}),t?.stack?this.stack=t.stack:Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static apply(t,n,r){if(t instanceof Error){let i=new e(t.message,{data:n,cause:t.cause??void 0,stack:t.stack??void 0,taskInfo:r});for(let e of Object.keys(t))if(!(e in i)){let n=i;n[e]=t[e]}return i}if(t&&typeof t==`object`){let i=t,a=typeof i.message==`string`?i.message:typeof i.error==`string`?i.error:`Object error: ${JSON.stringify(i,Object.getOwnPropertyNames(i).filter(e=>i[e]!==void 0))}`,o=new e(a,{data:n??i,taskInfo:r});for(let e of Object.keys(i))if(!(e in o)){let t=o;t[e]=i[e]}return o}if(typeof t==`function`){let i=t.name??`anonymous function`,a=t.toString().substring(0,100)+(t.toString().length>100?`...`:``);return new e(`Function error: ${i}`,{data:n??{functionType:typeof t,functionName:i,functionString:a},taskInfo:r})}let i=typeof t,a=t===null?`null`:t===void 0?`undefined`:String(t);if(i===`number`){let a=t,o=Number.isNaN(a)?`Number error: NaN`:Number.isFinite(a)?`Number error: ${a}`:`Number error: ${a>0?`Infinity`:`-Infinity`}`;return new e(o,{data:n??{errorType:i,errorValue:a,originalError:t},taskInfo:r})}if(i===`bigint`)return new e(`BigInt error: ${t}n`,{data:n??{errorType:i,errorValue:String(t),originalError:t},taskInfo:r});if(i===`boolean`)return new e(`Boolean error: ${t}`,{data:n??{errorType:i,errorValue:t,originalError:t},taskInfo:r});if(i===`symbol`){let a=t.description??`unnamed symbol`;return new e(`Symbol error: Symbol(${a})`,{data:n??{errorType:i,symbolDescription:a,originalError:t},taskInfo:r})}let o=typeof t==`string`?t:`${i.charAt(0).toUpperCase()+i.slice(1)} error: ${a}`;return new e(o,{data:n??{errorType:i,errorValue:a,originalError:t},taskInfo:r})}};function Qe(e){return e instanceof Error&&typeof e==`object`&&e._tag===`Throwable`}const $e=(e,t)=>{if(e.isRight())return k(e.orThrow(),t);if(e.isLeft())return O(e.fold(e=>e,()=>Error(`Unexpected right value`)),void 0,t);throw Error(`Unrecognized task outcome`)},O=(e,t,n)=>{let r={name:n?.name??`Task`,description:n?.description??``},a=Ze.apply(e,t,r),s={...Ye(`Err`,{error:a,meta:r}),[Symbol.toStringTag]:`TaskOutcome`,_tag:`Err`,_meta:r,value:void 0,error:a,isSuccess(){return!1},isFailure(){return!0},isOk(){return!1},isErr(){return!0},map:e=>O(a,t,n),flatMap:e=>O(a,t,n),ap:e=>O(a,t,n),mapAsync:e=>Promise.resolve(O(a,t,n)),flatMapAsync:e=>Promise.resolve(O(a,t,n)),mapError:e=>O(e(a),t,n),recover:e=>k(e,n),recoverWith:e=>k(e(a),n),orThrow:e=>{throw e??a},orElse:e=>e,or:e=>e,orNull:()=>null,orUndefined:()=>void 0,toEither:()=>T(a),toTry:()=>x(()=>{throw a}),toOption:()=>p(),toList:()=>C([]),fold:(e,t)=>e(a),match:e=>e.Err(a),foldLeft:e=>t=>e,foldRight:e=>t=>e,size:0,isEmpty:!0,contains:e=>!1,reduce:e=>{throw Error(`Cannot reduce empty Err`)},reduceRight:e=>{throw Error(`Cannot reduceRight empty Err`)},count:e=>0,find:e=>p(),exists:e=>!1,forEach:e=>{},toPromise:()=>Promise.reject(a),doUnwrap(){return{ok:!1,empty:!1,error:a}},toJSON:()=>({"@functype":`Task`,_tag:`Err`,error:o(a)}),serialize:()=>i(`Task`,`Err`,{error:o(a)}),pipe:e=>e(s)};return s},k=(e,t)=>{let n={name:t?.name??`Task`,description:t?.description??``},r={...Ye(`Ok`,{value:e,meta:n}),[Symbol.toStringTag]:`TaskOutcome`,_tag:`Ok`,_meta:n,value:e,error:void 0,isSuccess(){return!0},isFailure(){return!1},isOk(){return!0},isErr(){return!1},map:n=>k(n(e),t),flatMap:n=>{let r=n(e);return r&&typeof r==`object`&&`isLeft`in r&&`isRight`in r?$e(r,t):r},ap:n=>n.isOk()?k(n.value(e),t):O(n.error,void 0,t),mapAsync:async n=>k(await n(e),t),flatMapAsync:async t=>await t(e),mapError:n=>k(e,t),recover:n=>k(e,t),recoverWith:n=>k(e,t),orThrow:t=>e,orElse:t=>e,or:n=>k(e,t),orNull:()=>e,orUndefined:()=>e,toEither:()=>w(e),toTry:()=>x(()=>e),toOption:()=>d(e),toList:()=>C([e]),fold:(t,n)=>n(e),match:t=>t.Ok(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),size:1,isEmpty:!1,contains:t=>e===t,reduce:t=>e,reduceRight:t=>e,count:t=>+!!t(e),find:t=>t(e)?d(e):p(),exists:t=>t(e),forEach:t=>t(e),toPromise:()=>Promise.resolve(e),doUnwrap(){return{ok:!0,value:e}},toJSON:()=>({"@functype":`Task`,_tag:`Ok`,value:e}),serialize:()=>s(`Task`,`Ok`,e),pipe:e=>e(r)};return r},et=()=>{let e=new AbortController,t=de();return{token:{get isCancelled(){return e.signal.aborted},get signal(){return e.signal},onCancel(n){e.signal.aborted?n():t.add(n)}},cancel(){e.signal.aborted||(e.abort(),t.build().forEach(e=>{try{e()}catch(e){console.error(`Error in cancellation callback:`,e)}}))}}},tt=e=>{let t=e?.name??`Task`,n=e?.description??``,r={Async:(e,r=e=>e,i=()=>{},a)=>new Promise(o=>{(async()=>{let s=_(!1),c=_(null),l=_(()=>{});if(a){if(a.isCancelled){try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}o(O(Error(`Task was cancelled before execution started`),void 0,{name:t,description:n}));return}a.onCancel(()=>{s.set(!0),c.set(Error(`Task was cancelled during execution`))}),l.set(()=>{})}try{let r=await e();try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}if(s.get()){c.get()?o(O(c.get(),void 0,{name:t,description:n})):o(O(Error(`Task was cancelled during execution`),void 0,{name:t,description:n}));return}if(r&&typeof r==`object`&&`_tag`in r){let e=r;e._tag===`Ok`||e._tag===`Err`?o(e):o(k(r,{name:t,description:n}))}else o(k(r,{name:t,description:n}))}catch(e){try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}if(s.get()){c.get()?o(O(c.get(),void 0,{name:t,description:n})):o(O(Error(`Task was cancelled during execution`),void 0,{name:t,description:n}));return}try{if(e instanceof Error&&Qe(e)){let i=Error(`${t}: ${e.message}`),a=Ze.apply(i,void 0,{name:t,description:n});Object.defineProperty(a,"cause",{value:e,writable:!1,configurable:!1}),Promise.resolve().then(()=>{try{r(e)}catch(e){console.error(`Error in error handler:`,e)}}),o(O(a,void 0,{name:t,description:n}))}else{let i=await r(e);if(i&&typeof i==`object`&&`_tag`in i){let e=i;e._tag===`Ok`||e._tag===`Err`?o(e):o(O(i,void 0,{name:t,description:n}))}else o(O(i,void 0,{name:t,description:n}))}}catch(e){o(O(e,void 0,{name:t,description:n}))}}finally{l.get()()}})().catch(e=>o(O(e,void 0,{name:t,description:n})))}),Sync:(e,r=e=>e,i=()=>{})=>{try{return k(e(),{name:t,description:n})}catch(e){return O(r(e),void 0,{name:t,description:n})}finally{i()}},AsyncWithProgress:(e,t,n=e=>e,i=()=>{},a)=>{let o=e=>{let n=Math.max(0,Math.min(100,e));n<=100&&t(n)};return r.Async(()=>e(o),n,i,a)}};return{...Ye(`Task`,r),_type:`Task`}},nt={success:(e,t)=>k(e,t),fail:(e,t,n)=>O(e,t,n),ok:(e,t)=>k(e,t),err:(e,t,n)=>O(e,t,n),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Task`)throw Error(`Task.fromJSON: expected @functype="Task", got ${JSON.stringify(t[`@functype`])}`);if(t._tag===`Ok`)return k(t.value);if(t._tag===`Err`){let e=t.error!==void 0&&typeof t.error==`object`?a(t.error):Error(typeof t.error==`string`?t.error:`Unknown Task error`);return O(e)}throw Error(`Task.fromJSON: unrecognized _tag ${JSON.stringify(t._tag)}`)},fromEither:(e,t)=>$e(e,t),fromTry:(e,t)=>e.isSuccess()?k(e.orThrow(),t):O(e.fold(e=>e,()=>Error(`Unexpected success`)),void 0,t),getErrorChain:e=>{if(!e)return[];let t=de();t.add(e);let n=_(e);for(;n.get()&&n.get().cause;){let{cause:e}=n.get();if(e)t.add(e),n.set(e);else break;if(t.size()>100)break}return t.build()},formatErrorChain:(e,t)=>{let n=nt.getErrorChain(e),r=t?.separator??`
7
+ `;return n.map((e,n)=>{if(!e)return`${n>0?`↳ `:``}Unknown error`;let{taskInfo:r}=e,i=t?.includeTasks&&r?.name?`[${r.name}] `:``,a=e.message??`No message`,o=_(`${n>0?`↳ `:``}${i}${a}`);return t?.includeStackTrace&&e.stack&&o.set(`${o.get()}\n${e.stack.split(`
8
+ `).slice(1).join(`
9
+ `)}`),o.get()}).join(r)},fromPromise:(e,t)=>(...n)=>A(t??{name:`PromiseTask`,description:`Task from Promise`}).Async(()=>e(...n),e=>e),toPromise:e=>new Promise((t,n)=>{e.isSuccess()?t(e.orThrow()):n(e.error)}),race:(e,t,n)=>{let r={name:n?.name??`TaskRace`,description:n?.description??`Race between multiple tasks`};return A(r).Async(async()=>{let n=de();e.forEach(e=>n.add(e));let r=_(void 0);if(typeof t==`number`&&t>0){let e=new Promise((e,n)=>{r.set(setTimeout(()=>{n(Error(`Task race timed out after ${t}ms`))},t))});n.add(e)}try{return await new Promise((e,t)=>{n.build().forEach(n=>{n.then(n=>{if(n&&typeof n==`object`&&`_tag`in n){let r=n;r._tag===`Ok`?e(r.orThrow()):r._tag===`Err`?t(r.error):e(n)}else e(n)},e=>t(e))})})}finally{r.get()&&clearTimeout(r.get())}},e=>e)},fromNodeCallback:(e,t)=>{let n={name:t?.name??`NodeCallbackTask`,description:t?.description??`Task from Node.js callback function`};return(...t)=>A(n).Async(()=>new Promise((n,r)=>{try{e(...t,(e,t)=>{e?r(e):n(t)})}catch(e){r(e)}}),e=>e)},createCancellationTokenSource:et,cancellable:(e,t)=>{let n=et();return{task:A(t).Async(()=>e(n.token),e=>e,()=>{},n.token),cancel:()=>n.cancel()}},withProgress:(e,t=()=>{},n)=>{let r=et(),i=_(0),a=e=>{i.set(Math.max(0,Math.min(100,e))),t(i.get())};return{task:A(n).Async(()=>e(a,r.token),e=>e,()=>{},r.token),cancel:()=>r.cancel(),currentProgress:()=>i.get()}}},A=r(tt,nt),rt=Map,j=e=>{let t={values:new rt(e)},n=()=>Array.from(t.values.entries()).map(([e,t])=>te([e,t])),r=e=>j(new rt(t.values).set(e.toArray()[0],e.toArray()[1]).entries()),i=e=>{let n=new rt(t.values);return n.delete(e)?j(n.entries()):j(t.values.entries())},a=e=>{if(!e||typeof e.toArray!=`function`)return!1;let n=e.toArray();return t.values.get(n[0])===n[1]},o=()=>t.values.size,c=e=>j(Array.from(t.values.entries()).map(([t,n])=>[t,e(n)])),l=e=>{let n=j(t.values.entries()).toList();return j(n.flatMap(e).toArray())},u=e=>{let n=[];for(let[r,i]of t.values.entries()){let t=e.get(r);t._tag===`Some`&&t.value&&n.push([r,t.value(i)])}return j(n)},ee=async e=>{let n=new rt;for(let[r,i]of t.values.entries()){let t=await e(i);for(let e of t.toList()){let[t,r]=e.toArray();n.set(t,r)}}return j(n.entries())},ne=e=>C(n()).reduce(e),d=e=>C(n()).reduceRight(e),f=e=>t=>C(n()).foldLeft(e)(t),p=e=>t=>C(n()).foldRight(e)(t),re=e=>m(t.values.get(e)),ie=(e,n)=>m(t.values.get(e)).orElse(n),h=()=>t.values.size===0,g=(e,n)=>m(t.values.get(e)).or(n),ae=(e,t)=>C(n()).fold(e,t),oe=()=>C(n()),se=()=>ce(n()),le=()=>`Map(${n().toString()})`,_=e=>h()?e.Empty():e.NonEmpty(n());return{[Symbol.toStringTag]:`FunctypeMap`,_tag:`Map`,[Symbol.iterator]:()=>t.values.entries(),add:r,remove:i,contains:a,get size(){return o()},map:c,ap:u,flatMap:l,flatMapAsync:ee,reduce:ne,reduceRight:d,foldLeft:f,foldRight:p,fold:ae,match:_,get:re,getOrElse:ie,get isEmpty(){return h()},orElse:g,toList:oe,toSet:se,toString:le,toValue:()=>({_tag:`Map`,value:Array.from(t.values.entries())}),toJSON:()=>({"@functype":`Map`,_tag:`Map`,value:Array.from(t.values.entries())}),pipe:e=>e(Array.from(t.values.entries())),serialize:()=>s(`Map`,Array.from(t.values.entries()))}},it=e=>j(e),at=j([]),ot={empty:()=>at,of:(...e)=>j(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Map`)throw Error(`Map.fromJSON: expected @functype="Map", got ${JSON.stringify(t[`@functype`])}`);return st(t.value)},fromYAML:e=>{let t=e.split(`
10
+ `)[1]?.split(`: `)[1];if(!t)return st([]);let n=JSON.parse(t);return st(n)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return ot.fromJSON(t)}},st=r(it,ot),ct=(e,t,n)=>({_tag:`Leaf`,path:e,message:t,cause:n}),lt=(e,t)=>({_tag:`Composite`,path:e,children:t}),ut=e=>e._tag===`Leaf`,dt=e=>e._tag===`Composite`,ft=(e,t)=>e._tag===`Leaf`?t.Leaf(e):t.Composite(e),pt=(e,t)=>t._tag===`Leaf`?{...t,path:[e,...t.path]}:{...t,children:C(t.children.toArray().map(t=>pt(e,t)))},mt=e=>e._tag===`Leaf`?C([{path:e.path,message:e.message}]):C(e.children.toArray().flatMap(e=>mt(e).toArray())),ht=e=>mt(e).toArray().map(({path:e,message:t})=>`${gt(e)}: ${t}`).join(`
11
+ `),gt=e=>e.length===0?`(root)`:e.reduce((e,t)=>t.startsWith(`[`)&&t.endsWith(`]`)?`${e}${t}`:e===``?t:`${e}.${t}`,``),M=r({},{leaf:ct,composite:lt,isLeaf:ut,isComposite:dt,match:ft,prepend:pt,flatten:mt,format:ht}),_t=e=>typeof e==`string`?w(e):T(M.leaf([],`expected string`,{received:e})),vt=e=>typeof e==`number`?w(e):T(M.leaf([],`expected number`,{received:e})),yt=e=>typeof e==`boolean`?w(e):T(M.leaf([],`expected boolean`,{received:e})),bt=e=>w(e),xt=e=>t=>t==null?w(null):e(t),St=e=>t=>t==null?w(p()):e(t).fold(e=>T(e),e=>w(d(e))),Ct={envelope:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected envelope object {ok|err}`,{received:t}));let n=t;return`ok`in n?e.ok(n.ok).fold(e=>T(M.prepend(`ok`,e)),e=>w(w(e))):`err`in n?e.err(n.err).fold(e=>T(M.prepend(`err`,e)),e=>w(T(e))):T(M.leaf([],`expected envelope to have 'ok' or 'err' key`,{received:t}))},discriminated:(e,t,n)=>r=>{if(typeof r!=`object`||!r)return T(M.leaf([],`expected object with '${e.tag}' tag`,{received:r}));let i=r[e.tag];return i===e.rightTag?n(r).fold(e=>T(e),e=>w(w(e))):i===e.leftTag?t(r).fold(e=>T(e),e=>w(T(e))):T(M.leaf([],`expected '${e.tag}' to be '${e.rightTag}' or '${e.leftTag}'`,{received:i}))}},wt=e=>t=>{if(!Array.isArray(t))return T(M.leaf([],`expected array`,{received:t}));let n=[],r=[];return t.forEach((t,i)=>{e(t).fold(e=>{n.push(M.prepend(`[${i}]`,e))},e=>{r.push(e)})}),Ot(n,()=>C(r))},Tt=e=>t=>{if(!Array.isArray(t))return T(M.leaf([],`expected array`,{received:t}));let n=[],r=[];return t.forEach((t,i)=>{e(t).fold(e=>{n.push(M.prepend(`[${i}]`,e))},e=>{r.push(e)})}),Ot(n,()=>r)},Et=e=>t=>{if(typeof t!=`object`||!t||Array.isArray(t))return T(M.leaf([],`expected object (for Map)`,{received:t}));let n=t,r=[],i=[];for(let t of Object.keys(n))e(n[t]).fold(e=>{r.push(M.prepend(t,e))},e=>{i.push([t,e])});return Ot(r,()=>st(i))},Dt=e=>t=>{if(typeof t!=`object`||!t||Array.isArray(t))return T(M.leaf([],`expected object`,{received:t}));let n=t,r=[],i={};for(let t in e)e[t](n[t]).fold(e=>{r.push(M.prepend(t,e))},e=>{i[t]=e});return Ot(r,()=>i)},Ot=(e,t)=>e.length===0?w(t()):e.length===1?T(e[0]):T(M.composite([],C(e))),kt={string:_t,number:vt,boolean:yt,unknown:bt,nullable:xt,option:St,either:Ct,list:wt,array:Tt,map:Et,object:Dt},At=(e,t)=>M.prepend(e,t),jt=(e,t,n)=>M.prepend(e,M.prepend(`[${t}]`,n)),Mt={option:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Option object`,{received:t}));let n=t;return n._tag===`None`?w(p()):n._tag===`Some`?e(n.value).fold(e=>T(At(`value`,e)),e=>w(d(e))):T(M.leaf([`_tag`],`expected 'Some' or 'None'`,{received:n._tag}))},either:(e,t)=>n=>{if(typeof n!=`object`||!n)return T(M.leaf([],`expected tagged Either object`,{received:n}));let r=n;return r._tag===`Right`?t(r.value).fold(e=>T(At(`value`,e)),e=>w(w(e))):r._tag===`Left`?e(r.value).fold(e=>T(At(`value`,e)),e=>w(T(e))):T(M.leaf([`_tag`],`expected 'Left' or 'Right'`,{received:r._tag}))},try:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Try object`,{received:t}));let n=t;if(n._tag===`Success`)return e(n.value).fold(e=>T(At(`value`,e)),e=>w(x.success(e)));if(n._tag===`Failure`){let e=typeof n.error==`string`?n.error:`unknown error`,t=Error(e);return typeof n.stack==`string`&&(t.stack=n.stack),w(x.failure(t))}return T(M.leaf([`_tag`],`expected 'Success' or 'Failure'`,{received:n._tag}))},list:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged List object`,{received:t}));let n=t;if(n._tag!==`List`)return T(M.leaf([`_tag`],`expected 'List'`,{received:n._tag}));if(!Array.isArray(n.value))return T(M.leaf([`value`],`expected array`,{received:n.value}));let r=[],i=[];return n.value.forEach((t,n)=>{e(t).fold(e=>{r.push(jt(`value`,n,e))},e=>{i.push(e)})}),r.length===0?w(C(i)):r.length===1?T(r[0]):T(M.composite([],C(r)))},map:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Map object`,{received:t}));let n=t;if(n._tag!==`Map`)return T(M.leaf([`_tag`],`expected 'Map'`,{received:n._tag}));if(!Array.isArray(n.value))return T(M.leaf([`value`],`expected entries array`,{received:n.value}));let r=[],i=[];return n.value.forEach((t,n)=>{if(!Array.isArray(t)||t.length!==2){r.push(M.leaf([`value`,`[${n}]`],`expected [key, value] tuple`,{received:t}));return}let[a,o]=t;if(typeof a!=`string`){r.push(M.leaf([`value`,`[${n}]`,`[0]`],`expected string key`,{received:a}));return}e(o).fold(e=>{r.push(M.prepend(`value`,M.prepend(`[${n}]`,M.prepend(`[1]`,e))))},e=>{i.push([a,e])})}),r.length===0?w(st(i)):r.length===1?T(r[0]):T(M.composite([],C(r)))},obj:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Obj object`,{received:t}));let n=t;if(n._tag!==`Obj`)return T(M.leaf([`_tag`],`expected 'Obj'`,{received:n._tag}));if(typeof n.value!=`object`||n.value===null)return T(M.leaf([`value`],`expected object`,{received:n.value}));let r=n.value,i=[],a={};for(let t in e)e[t](r[t]).fold(e=>{i.push(M.prepend(`value`,M.prepend(t,e)))},e=>{a[t]=e});return i.length===0?w(a):i.length===1?T(i[0]):T(M.composite([],C(i)))}},Nt=r({},{...kt,tagged:Mt});function Pt(e){if(!e||typeof e!=`object`||!(`_tag`in e))return`unknown`;switch(e._tag){case`Some`:case`None`:return`Option`;case`Left`:case`Right`:return`Either`;case`List`:return`List`;case`Success`:case`Failure`:return`Try`;default:return`unknown`}}const Ft={Option:{of:e=>m(e),empty:()=>m.none()},Either:{of:e=>w(e),empty:e=>T(e)},List:{of:e=>C([e]),empty:()=>C([])},Try:{of:e=>x(()=>e),empty:e=>x(()=>{throw e??Error(`Try failed`)})}};function It(e){let t=e(),n=null,r;function i(a){let o=t.next(a);if(o.done)return r?r.of(o.value):C([o.value]);let s=o.value;if(typeof s!=`object`||!s)throw Error(`Do-notation error: All yielded values must be monadic. Use yield* $(Option(value)), yield* $(Right(value)), etc. Raw values should be assigned directly without yielding.`);if(!n&&`_tag`in s&&(n=Pt(s),n!==`unknown`&&n in Ft&&(r=Ft[n]),n===`List`))return Lt(e);if(`doUnwrap`in s){let e=s.doUnwrap();if(!e.ok){if(!r)return C([]);if(!e.empty&&`error`in e){if(n===`Either`)return r.empty(e.error);if(n===`Try`)return r.empty(e.error instanceof Error?e.error:Error(String(e.error)))}return r.empty()}return i(e.value)}throw Error(`Do-notation error: All yielded values must be monadic. Use yield* $(Option(value)), yield* $(Right(value)), etc. Raw values should be assigned directly without yielding.`)}return i()}function Lt(e){function t(e){if(typeof e!=`object`||!e||!(`doUnwrap`in e))return[e];let t=e;if(`toArray`in t){let e=t.toArray();return e.length===0?[]:e}let n=t.doUnwrap();return n.ok?[n.value]:[]}function n(r){let i=e(),a=[],o=[],s=0;function c(e){let l=i.next(e);if(l.done){a.push(l.value);return}if(s<r.length){let e=r[s];o.push(e),s++,c(e);return}let u=t(l.value);if(u.length!==0)if(u.length>1){let e=u.flatMap(e=>n([...o,e]));a.push(...e)}else o.push(u[0]),s++,c(u[0])}return c(void 0),a}return C(n([]))}async function Rt(e){let t=e(),n=null,r;async function i(e){let a=await t.next(e);if(a.done)return r?r.of(a.value):C([a.value]);let o=await Promise.resolve(a.value);if(typeof o!=`object`||!o)return i(o);if(!n&&`_tag`in o&&(n=Pt(o),n!==`unknown`&&n in Ft&&(r=Ft[n])),`doUnwrap`in o){let e=o.doUnwrap();if(!e.ok){if(!r)return C([]);if(!e.empty&&`error`in e){if(n===`Either`)return r.empty(e.error);if(n===`Try`)return r.empty(e.error instanceof Error?e.error:Error(String(e.error)))}return r.empty()}return i(e.value)}return i(o)}return i()}function zt(e){return typeof e==`object`&&!!e&&`doUnwrap`in e&&typeof e.doUnwrap==`function`}function Bt(e){let t=e.doUnwrap();if(t.ok)return t.value;throw`error`in t?t.error:Error(`Cannot unwrap empty monad`)}function*Vt(e){return yield e}const Ht=(e=`Cannot unwrap None in Do-notation`)=>{let t=Error(e),n=Object.create(Error.prototype);return n.message=t.message,n.stack=t.stack,n.name=`NoneError`,n},Ut=(e,t=`Cannot unwrap Left in Do-notation`)=>{let n=Error(t),r=Object.create(Error.prototype);return r.message=n.message,r.stack=n.stack,r.name=`LeftError`,r.value=e,r},Wt=(e=`Cannot unwrap empty List in Do-notation`)=>{let t=Error(e),n=Object.create(Error.prototype);return n.message=t.message,n.stack=t.stack,n.name=`EmptyListError`,n},Gt=(e,t=`Cannot unwrap Failure in Do-notation`)=>{let n=Error(t),r=Object.create(Error.prototype);return r.message=n.message,r.stack=n.stack,r.name=`FailureError`,r.cause=e,r},Kt={includeTasks:!0,includeStackTrace:!1,separator:`
12
+ `,includeData:!1,maxStackFrames:3,title:`Error`,colors:!1};function qt(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return`${n.toString()}n`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular Reference]`;t.add(n)}return e===`stack`&&typeof n==`string`?Jt(n):n},2)}function Jt(e){if(e===void 0||e===``)return``;let t=e.split(`
13
+ `);return[t[0],...t.slice(1).map(e=>e.trim())].join(`
14
+ `)}function Yt(e,t){let n={...Kt,...t},r=e instanceof Error?e:Ze.apply(e),i=A?.getErrorChain?A.getErrorChain(r):[r],a=`${n.colors?`\x1b[31m${n.title}:\x1b[0m ${r.message}`:`${n.title}: ${r.message}`}\n\n${i.map((e,t)=>{let r=` `.repeat(t),i=t>0?`↳ `:``,{taskInfo:a}=e,o=`${r}${i}${n.includeTasks&&a?.name?n.colors?`\x1b[36m[${a.name}]\x1b[0m `:`[${a.name}] `:``}${e.message}`;if(n.includeStackTrace&&e.stack){let t=Jt(e.stack).split(`
15
+ `).slice(1),i=n.maxStackFrames??Kt.maxStackFrames??3,a=t.slice(0,i).map(e=>`${r} ${n.colors?`\x1B[90m`:``}${e}${n.colors?`\x1B[0m`:``}`).join(`
16
+ `);o+=`\n${a}`,t.length>i&&(o+=`\n${r} ${n.colors?`\x1B[90m`:``}...${t.length-i} more stack frames${n.colors?`\x1B[0m`:``}`)}return o}).join(n.separator)}`;if(n.includeData){let{data:e}=r;if(e){let t=n.colors?`\n\n\x1b[33mContext:\x1b[0m\n${qt(e)}`:`\n\nContext:\n${qt(e)}`;a+=t}}return a}function Xt(){return function(e){if(!e)return e;let t=e instanceof Error?e:Error(String(e)),n={message:t.message,name:t.name||`Error`,stack:t.stack?Jt(t.stack):void 0};if(t.taskInfo&&(n.taskInfo=t.taskInfo),t.data&&(n.data=t.data),typeof A?.getErrorChain==`function`)try{let e=A.getErrorChain(t);e.length>1&&(n.errorChain=A.formatErrorChain(t,{includeTasks:!0}),n.structuredErrorChain=e.map(e=>({message:e.message,name:e.name,taskInfo:e.taskInfo,stack:e.stack?Jt(e.stack):void 0})))}catch{}return Object.getOwnPropertyNames(t).forEach(e=>{if(!n[e]){let r=t[e];n[e]=r}}),n}}const N=(e,t,r,i)=>n(Ze.apply(t,r,{name:e,description:t}),{code:e,message:t,status:Zt(e),context:r,timestamp:new Date().toISOString(),traceId:i?.traceId}),Zt=e=>({VALIDATION_FAILED:400,BAD_REQUEST:400,AUTH_REQUIRED:401,PERMISSION_DENIED:403,NOT_FOUND:404,TIMEOUT:408,CONFLICT:409,RATE_LIMITED:429,INTERNAL_ERROR:500,NETWORK_ERROR:503})[e],P=Object.assign(N,{validation:(e,t,n)=>N(`VALIDATION_FAILED`,`Validation failed: ${e} ${n}`,{field:e,value:t,rule:n}),network:(e,t,n)=>N(`NETWORK_ERROR`,`Network error: ${t} ${e}${n?` (${n})`:``}`,{url:e,method:t,statusCode:n}),auth:(e,t)=>N(`AUTH_REQUIRED`,`Authentication required: ${e}${t?` (role: ${t})`:``}`,{resource:e,requiredRole:t}),notFound:(e,t)=>N(`NOT_FOUND`,`Not found: ${e} with id ${t}`,{resource:e,id:t}),permission:(e,t,n)=>N(`PERMISSION_DENIED`,`Permission denied: cannot ${e} ${t}`,{action:e,resource:t,userId:n}),rateLimit:(e,t,n)=>N(`RATE_LIMITED`,`Rate limit exceeded: ${e} requests per ${t}`,{limit:e,window:t,retryAfter:n}),internal:e=>N(`INTERNAL_ERROR`,`Internal server error: ${e}`,{errorId:e,timestamp:new Date().toISOString()}),badRequest:(e,t)=>N(`BAD_REQUEST`,`Bad request: ${e}`,{reason:e,expected:t}),conflict:(e,t)=>N(`CONFLICT`,`Conflict: ${e} already exists with value ${t}`,{resource:e,conflictingValue:t}),timeout:(e,t)=>N(`TIMEOUT`,`Request timeout: ${t} exceeded ${e}ms`,{duration:e,operation:t}),isTypedError:e=>typeof e==`object`&&!!e&&`code`in e&&`message`in e&&`status`in e&&`context`in e&&`_tag`in e&&e._tag===`Throwable`,hasCode:(e,t)=>e.code===t}),F={rule:e=>t=>{if(e===`email`)return typeof t!=`string`||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?T(P.validation(`value`,t,`must be a valid email`)):w(t);if(e===`url`)try{return new URL(String(t)),w(t)}catch{return T(P.validation(`value`,t,`must be a valid URL`))}if(e===`uuid`)return typeof t!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)?T(P.validation(`value`,t,`must be a valid UUID`)):w(t);if(e===`required`)return t==null||t===``?T(P.validation(`value`,t,`is required`)):w(t);if(e===`numeric`)return typeof t!=`number`&&!/^\d+$/.test(String(t))?T(P.validation(`value`,t,`must be numeric`)):w(t);if(e===`alpha`)return typeof t!=`string`||!/^[a-zA-Z]+$/.test(t)?T(P.validation(`value`,t,`must contain only letters`)):w(t);if(e===`alphanumeric`)return typeof t!=`string`||!/^[a-zA-Z0-9]+$/.test(t)?T(P.validation(`value`,t,`must be alphanumeric`)):w(t);if(e.startsWith(`min:`)){let n=Number(e.split(`:`)[1]),r=Number(t);return isNaN(r)||r<n?T(P.validation(`value`,t,`must be at least ${n}`)):w(t)}if(e.startsWith(`max:`)){let n=Number(e.split(`:`)[1]),r=Number(t);return isNaN(r)||r>n?T(P.validation(`value`,t,`must be at most ${n}`)):w(t)}if(e.startsWith(`minLength:`)){let n=Number(e.split(`:`)[1]);return String(t).length<n?T(P.validation(`value`,t,`must be at least ${n} characters`)):w(t)}if(e.startsWith(`maxLength:`)){let n=Number(e.split(`:`)[1]);return String(t).length>n?T(P.validation(`value`,t,`must be at most ${n} characters`)):w(t)}if(e.startsWith(`pattern:`)){let n=e.substring(8);return new RegExp(n).test(String(t))?w(t):T(P.validation(`value`,t,`must match pattern ${n}`))}if(e.startsWith(`in:`)){let n=e.substring(3).split(`,`);return n.includes(String(t))?w(t):T(P.validation(`value`,t,`must be one of: ${n.join(`, `)}`))}if(e.startsWith(`notIn:`)){let n=e.substring(6).split(`,`);return n.includes(String(t))?T(P.validation(`value`,t,`must not be one of: ${n.join(`, `)}`)):w(t)}if(e===`date`){let e=new Date(String(t));return isNaN(e.getTime())?T(P.validation(`value`,t,`must be a valid date`)):w(t)}if(e===`future`){let e=new Date(String(t));return isNaN(e.getTime())||e<=new Date?T(P.validation(`value`,t,`must be a future date`)):w(t)}if(e===`past`){let e=new Date(String(t));return isNaN(e.getTime())||e>=new Date?T(P.validation(`value`,t,`must be a past date`)):w(t)}return w(t)},combine:(...e)=>t=>{for(let n of e){let e=n(t);if(e.isLeft())return e}return w(t)},custom:(e,t)=>n=>e(n)?w(n):T(P.validation(`value`,n,t)),form:(e,t)=>{let n=[],r={};for(let[i,a]of Object.entries(e)){let e=t[i],o=a(e);if(o.isLeft()){let t=o.fold(e=>e,()=>{throw Error(`Should not be left`)}),r=P.validation(i,e,t.context.rule);n.push(r)}else r[i]=o.orThrow()}return n.length>0?T(C(n)):w(r)}},Qt={...F,validators:{email:F.rule(`email`),url:F.rule(`url`),uuid:F.rule(`uuid`),required:F.rule(`required`),numeric:F.rule(`numeric`),positiveNumber:F.combine(F.rule(`numeric`),F.rule(`min:0`)),nonEmptyString:F.combine(F.rule(`required`),F.custom(e=>typeof e==`string`&&e.trim().length>0,`must not be empty`))}},$t=n(F.rule,Qt);function en(e){return typeof e==`object`&&!!e&&`orThrow`in e&&typeof e.orThrow==`function`}function tn(e){return en(e)&&`orElse`in e&&typeof e.orElse==`function`&&`or`in e&&typeof e.or==`function`&&`orNull`in e&&typeof e.orNull==`function`&&`orUndefined`in e&&typeof e.orUndefined==`function`}const nn=e=>({_tag:`Context`,services:e,get(t){let n=e.get(t.id);return n===void 0?p():d(n)},unsafeGet(t){let n=e.get(t.id);if(n===void 0)throw Error(`Service not found: ${t.id}`);return n},has(t){return e.has(t.id)},add(t,n){let r=new Map(e);return r.set(t.id,n),nn(r)},merge(t){let n=new Map(e);for(let[e,r]of t.services)n.set(e,r);return nn(n)},get size(){return e.size},toString(){return`Context(${Array.from(e.keys()).join(`, `)})`}}),I={empty:()=>nn(new Map),make:(e,t)=>{let n=new Map;return n.set(e.id,t),nn(n)},isContext:e=>typeof e==`object`&&!!e&&e._tag===`Context`},L=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Success`,isSuccess(){return!0},isFailure(){return!1},isInterrupted(){return!1},map(t){return L(t(e))},mapError(t){return L(e)},mapBoth(t,n){return L(n(e))},flatMap(t){return t(e)},fold(t,n,r){return n(e)},match(t){return t.Success(e)},orThrow(){return e},orElse(t){return e},toOption(){return d(e)},toEither(){return w(e)},toValue(){return{_tag:`Success`,value:e}},toString(){return`Exit.Success(${c(e)})`},toJSON(){return{_tag:`Success`,value:e}}}),rn=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Failure`,isSuccess(){return!1},isFailure(){return!0},isInterrupted(){return!1},map(t){return rn(e)},mapError(t){return rn(t(e))},mapBoth(t,n){return rn(t(e))},flatMap(t){return rn(e)},fold(t,n,r){return t(e)},match(t){return t.Failure(e)},orThrow(){throw e},orElse(e){return e},toOption(){return p()},toEither(){return T(e)},toValue(){return{_tag:`Failure`,error:e}},toString(){return`Exit.Failure(${c(e)})`},toJSON(){return{_tag:`Failure`,error:e}}}),an=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Interrupted`,isSuccess(){return!1},isFailure(){return!1},isInterrupted(){return!0},map(t){return an(e)},mapError(t){return an(e)},mapBoth(t,n){return an(e)},flatMap(t){return an(e)},fold(t,n,r){if(r)return r(e);throw Error(`Effect was interrupted: ${e}`)},match(t){return t.Interrupted(e)},orThrow(){throw Error(`Effect was interrupted: ${e}`)},orElse(e){return e},toOption(){return p()},toEither(){throw Error(`Cannot convert Interrupted Exit to Either: ${e}`)},toValue(){return{_tag:`Interrupted`,fiberId:e}},toString(){return`Exit.Interrupted(${e})`},toJSON(){return{_tag:`Interrupted`,fiberId:e}}}),R=r(e=>L(e),{succeed:e=>L(e),fail:e=>rn(e),interrupt:e=>an(e),interrupted:()=>an(`interrupted`),isSuccess:e=>e.isSuccess(),isFailure:e=>e.isFailure(),isInterrupted:e=>e.isInterrupted(),fromEither:e=>e.isRight()?L(e.value):rn(e.value),fromOption:(e,t)=>e.isSome()?L(e.value):rn(t()),zip:(e,t)=>e.isInterrupted()?e:t.isInterrupted()?t:e.isFailure()?e:t.isFailure()?t:L([e.orThrow(),t.orThrow()]),all:e=>{let t=[];for(let n of e){if(n.isInterrupted()||n.isFailure())return n;t.push(n.orThrow())}return L(t)}}),z=e=>e;var on=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},sn=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}},cn=class extends Error{constructor(e,t,n){super(n??`Repeat exhausted after ${e} iterations`),this.max=e,this.lastValue=t,this._tag=`RepeatExhausted`,this.name=`RepeatExhausted`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`RepeatExhausted`}};const ln=Symbol.for(`functype/IO/effect`),B=e=>e[ln],V=e=>{let t={[Symbol.toStringTag]:`IO`,[ln]:e,map(e){return V(z({_tag:`Map`,effect:t,f:e}))},flatMap(e){return V(z({_tag:`FlatMap`,effect:t,f:e}))},tap(e){return t.map(t=>(e(t),t))},tapEffect(e){return t.flatMap(t=>e(t).map(()=>t))},mapError(e){return V(z({_tag:`MapError`,effect:t,f:e}))},tapError(e){return t.mapError(t=>(e(t),t))},recover(e){return V(z({_tag:`Recover`,effect:t,fallback:e}))},recoverWith(e){return V(z({_tag:`RecoverWith`,effect:t,f:e}))},fold(e,n){return V(z({_tag:`Fold`,effect:t,onFailure:e,onSuccess:n}))},match(e){return t.fold(e.failure,e.success)},catchTag(e,n){return V(z({_tag:`RecoverWith`,effect:t,f:t=>typeof t==`object`&&t&&`_tag`in t&&t._tag===e?z(n(t)):z(W.fail(t))}))},catchAll(e){return t.recoverWith(e)},retry(e){return e<=0?t:t.recoverWith(()=>t.retry(e-1))},retryWithDelay(e,n){return e<=0?t:t.recoverWith(()=>W.sleep(n).flatMap(()=>t.retryWithDelay(e-1,n)))},retryWhile(e){let n=(r,i)=>t.recoverWith(t=>{if(r<=0||!e.while(t,i))return z(W.fail(t));let a=n(r-1,i+1);return e.delayMs===void 0?a:z(W.sleep(e.delayMs).flatMap(()=>a))});return n(e.n,1)},retryWithBackoff(e){let n=e.factor??2,r=e.maxMs??3e4,i=e.jitter??!0,a=e.while??(()=>!0),o=(s,c)=>t.recoverWith(t=>{if(s<=0||!a(t,c))return z(W.fail(t));let l=Math.min(r,e.baseMs*n**(c-1)),u=i?l*(.5+Math.random()*.5):l,ee=o(s-1,c+1);return z(W.sleep(u).flatMap(()=>ee))});return o(e.n,1)},repeatUntil(e,n){if(n.max<=0)return z(W.fail(new cn(n.max)));let r=i=>t.flatMap(t=>{if(e(t))return z(W.succeed(t));if(i<=1)return z(W.fail(new cn(n.max,t)));let a=r(i-1);return n.delayMs===void 0?a:z(W.sleep(n.delayMs).flatMap(()=>a))});return r(n.max)},repeatWhile(e,n){return t.repeatUntil(t=>!e(t),n)},zipRight(e){return t.flatMap(()=>e)},zipLeft(e){return t.flatMap(t=>e.map(()=>t))},zip(e){return t.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return V(z({_tag:`ProvideContext`,effect:t,context:e}))},provideService(e,n){let r=I.make(e,n);return V(z({_tag:`ProvideContext`,effect:t,context:r}))},provideLayer(e){let n=z(W.async(async()=>{let t=I.empty();return await e.build(z(t))}));return z(n.flatMap(e=>V(z({_tag:`ProvideContext`,effect:t,context:e}))))},async run(){let e=await U(B(this));return e.isSuccess()?w(e.orThrow()):T(e.isFailure()?e.toValue().error:new sn)},async runOrThrow(){let e=await U(B(this));if(e.isSuccess())return e.orThrow();throw e.isFailure()?e.toValue().error:new sn},runSync(){try{return w(H(B(this)))}catch(e){return T(e)}},runSyncOrThrow(){return H(B(this))},async runExit(){return U(B(this))},async runOption(){let e=await U(B(this));return e.isSuccess()?d(e.orThrow()):p()},async runTry(){let e=await U(B(this));if(e.isSuccess())return z(x(()=>e.orThrow()));let t=e.isFailure()?e.toValue().error:Error(`Effect was interrupted`);return z(x(()=>{throw t}))},pipe(e){return e(t)},delay(e){return z(W.async(()=>new Promise(t=>setTimeout(t,e))).flatMap(()=>t))},timeout(e){return V(z({_tag:`Timeout`,effect:t,duration:e}))},timeoutTo(e,n){return z(t.timeout(e).recover(z(n)))},toString(){return`IO(${c(e._tag)})`},toJSON(){return{_tag:`IO`,effect:e._tag}},*[Symbol.iterator](){return yield t}};return t},H=(e,t=I.empty())=>{switch(e._tag){case`Succeed`:return e.value;case`Fail`:throw e.error;case`Die`:throw e.defect;case`Sync`:return e.thunk();case`Async`:throw Error(`Cannot run async effect synchronously`);case`Auto`:{let t=e.thunk();if(t instanceof Promise)throw Error(`Cannot run async effect synchronously`);return t}case`Map`:{let n=H(B(e.effect),t);return e.f(n)}case`FlatMap`:{let n=H(B(e.effect),t),r=e.f(n);return H(B(r),t)}case`MapError`:try{return H(B(e.effect),t)}catch(t){throw e.f(t)}case`Recover`:try{return H(B(e.effect),t)}catch{return e.fallback}case`RecoverWith`:try{return z(H(B(e.effect),t))}catch(n){let r=e.f(n);return H(B(r),t)}case`Fold`:try{let n=H(B(e.effect),t);return e.onSuccess(n)}catch(t){return e.onFailure(t)}case`Service`:{let n=t.get(e.tag);if(n.isNone())throw Error(`Service not found: ${e.tag.id}`);return n.orThrow()}case`ProvideContext`:{let n=t.merge(e.context);return H(B(e.effect),n)}case`Interrupt`:throw new sn;case`Bracket`:{let n=H(B(e.acquire),t);try{return H(B(e.use(n)),t)}finally{H(B(e.release(n)),t)}}case`BracketExit`:{let n=H(B(e.acquire),t),r;try{let i=H(B(e.use(n)),t);return r=z(R.succeed(i)),i}catch(e){throw r=z(R.fail(e)),e}finally{H(B(e.release(n,r)),t)}}case`Race`:throw Error(`Cannot run race effect synchronously`);case`Timeout`:throw Error(`Cannot run timeout effect synchronously`)}},U=async(e,t=I.empty())=>{try{switch(e._tag){case`Succeed`:return z(R.succeed(e.value));case`Fail`:return z(R.fail(e.error));case`Die`:throw e.defect;case`Sync`:return z(R.succeed(e.thunk()));case`Async`:{let t=await e.thunk();return z(R.succeed(t))}case`Auto`:{let t=e.thunk();return t instanceof Promise?z(R.succeed(await t)):z(R.succeed(t))}case`Map`:{let n=await U(B(e.effect),t);return n.isSuccess()?z(R.succeed(e.f(n.orThrow()))):z(n)}case`FlatMap`:{let n=await U(B(e.effect),t);if(!n.isSuccess())return z(n);let r=e.f(n.orThrow());return U(B(r),t)}case`MapError`:{let n=await U(B(e.effect),t);return n.isSuccess()?z(n):n.isFailure()?z(R.fail(e.f(n.toValue().error))):z(n)}case`Recover`:{let n=await U(B(e.effect),t);return n.isSuccess()?n:R.succeed(e.fallback)}case`RecoverWith`:{let n=await U(B(e.effect),t);if(n.isSuccess())return z(n);if(n.isFailure()){let r=e.f(n.toValue().error);return U(B(r),t)}return z(n)}case`Fold`:{let n=await U(B(e.effect),t);return n.isSuccess()?R.succeed(e.onSuccess(n.orThrow())):n.isFailure()?R.succeed(e.onFailure(n.toValue().error)):n}case`Service`:{let n=t.get(e.tag);return n.isNone()?R.fail(Error(`Service not found: ${e.tag.id}`)):R.succeed(n.orThrow())}case`ProvideContext`:{let n=t.merge(e.context);return U(B(e.effect),n)}case`Interrupt`:return R.interrupted();case`Bracket`:{let n=await U(B(e.acquire),t);if(!n.isSuccess())return n;let r=n.orThrow();try{return await U(B(e.use(r)),t)}finally{await U(B(e.release(r)),t)}}case`BracketExit`:{let n=await U(B(e.acquire),t);if(!n.isSuccess())return n;let r=n.orThrow(),i=await U(B(e.use(r)),t);return await U(B(e.release(r,i)),t),i}case`Race`:return e.effects.length===0?R.fail(Error(`No effects to race`)):await Promise.race(e.effects.map(e=>U(B(e),t)));case`Timeout`:{let n=new Promise(t=>setTimeout(()=>t(R.fail(new on(e.duration))),e.duration)),r=U(B(e.effect),t);return Promise.race([r,n])}}}catch(e){return R.fail(e)}},W={sync:e=>V({_tag:`Sync`,thunk:e}),succeed:e=>V({_tag:`Succeed`,value:e}),fail:e=>V({_tag:`Fail`,error:e}),die:e=>V({_tag:`Die`,defect:e}),async:e=>V(z({_tag:`Async`,thunk:e})),tryPromise:e=>V({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,t)=>W.sync(()=>{try{return e()}catch(e){throw t(e)}}),liftSync:e=>(...t)=>W.sync(()=>e(...t)),liftPromise:e=>(...t)=>W.async(()=>e(...t)),fromEither:e=>z(e.isRight()?W.succeed(e.value):W.fail(e.value)),fromOption:e=>z(e.isSome()?W.succeed(e.value):W.fail(void 0)),fromOptionOrFail:(e,t)=>z(e.isSome()?W.succeed(e.value):W.fail(t())),fromTry:e=>z(e.isSuccess()?W.succeed(e.orThrow()):W.fail(e.error)),fromResult:e=>z(e.error?W.fail(e.error):W.succeed(m(e.data))),tryAsync:(e,t,n)=>n?.aborted?z(W.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):W.async(()=>e(n)).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return W.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>W.fromResult({data:e[r],error:e[i]}))},service:e=>V({_tag:`Service`,tag:e}),serviceWith:(e,t)=>W.service(e).map(t),serviceWithIO:(e,t)=>W.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return z(V({_tag:`Auto`,thunk:()=>t({})}));let r=z(W.succeed({})),i=n.reduce((e,[t,n])=>z(e.flatMap(e=>W.service(n).map(n=>({...e,[t]:n})))),r);return z(i.flatMap(e=>V({_tag:`Auto`,thunk:()=>t(e)})))},all:e=>{if(e.length===0)return z(W.succeed([]));let t=z(W.succeed([]));return z(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),t))},firstSuccessOf:e=>e.length===0?z(W.fail(Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>z(W.async(()=>new Promise(t=>setTimeout(t,e)))),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?z(W.succeed(e)):r<=0?z(W.fail(new cn(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>z(W.async(()=>new Promise(()=>{}))),get unit(){return z(V({_tag:`Succeed`,value:void 0}))},fromNullable:e=>z(e==null?W.fail(void 0):W.succeed(e)),interrupt:()=>V({_tag:`Interrupt`}),bracket:(e,t,n)=>V({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>W.bracket(e,t,n),bracketExit:(e,t,n)=>V({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>V({_tag:`Race`,effects:e}),any:e=>e.length===0?z(W.fail(Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),forEach:(e,t)=>{if(e.length===0)return z(W.succeed([]));let n=z(W.succeed([]));return z(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),n))},forEachPar:(e,t)=>W.forEach(e,t),timeout:(e,t)=>V(z({_tag:`Timeout`,effect:e,duration:t})),gen:e=>z(W.sync(()=>{let t=e(),n=e=>{let r=t.next(e);return r.done?z(W.succeed(r.value)):z(r.value.flatMap(e=>n(e)))};return n(void 0)}).flatMap(e=>e)),get Do(){return un(W.succeed({}))}},un=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return un(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return un(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return un(e.tap(t))},tapEffect(t){return un(e.tapEffect(t))},done(){return e}}),G=r(e=>V(z({_tag:`Auto`,thunk:e})),W),K=(e,t)=>({_tag:`Layer`,build:e,provideToAndMerge(t){return K(async n=>{let r=await e(n),i=n.merge(r),a=await t.build(i);return r.merge(a)})},merge(t){return K(async n=>{let[r,i]=await Promise.all([e(n),t.build(n)]);return r.merge(i)})},map(t){return K(async n=>t(await e(n)))},toString(){return`Layer(${t??`anonymous`})`}}),dn={succeed:(e,t)=>K(()=>Promise.resolve(I.make(e,t)),e.id),effect:(e,t)=>K(async()=>{let n=await t();return I.make(e,n)},e.id),sync:(e,t)=>K(()=>Promise.resolve(I.make(e,t())),e.id),fromService:(e,t,n)=>K(r=>{let i=r.unsafeGet(t);return Promise.resolve(I.make(e,n(i)))},e.id),fromServiceEffect:(e,t,n)=>K(async r=>{let i=await n(r.unsafeGet(t));return I.make(e,i)},e.id),fromContext:e=>K(()=>Promise.resolve(e)),empty:()=>K(()=>Promise.resolve(I.empty()),`empty`),mergeAll:(...e)=>K(async t=>(await Promise.all(e.map(e=>e.build(t)))).reduce((e,t)=>e.merge(t),I.empty()))},fn=e=>({id:e,_tag:`Tag`,toString(){return`Tag(${e})`}}),pn=()=>{let e=0,t=[],n=async()=>{for(t.sort((e,t)=>e.time-t.time);t.length>0&&t[0]!==void 0&&t[0].time<=e;){let e=t.shift();e&&(e.resolve(),await Promise.resolve())}};return{get currentTime(){return e},async advance(t){e+=t,await n()},async setTime(t){e=t,await n()},async runAll(){if(t.length>0){let n=t[t.length-1];n&&(e=n.time)}await n()},get pendingCount(){return t.length},sleep(n){return new Promise(r=>{t.push({time:e+n,resolve:r})})}}},mn=fn(`TestClock`),hn={make:pn,tag:mn,test:async e=>e(pn()),get:G.service(mn),advance:e=>G.serviceWithIO(mn,t=>G.async(()=>t.advance(e))),setTime:e=>G.serviceWithIO(mn,t=>G.async(()=>t.setTime(e))),runAll:G.serviceWithIO(mn,e=>G.async(()=>e.runAll())),context:()=>{let e=pn();return{clock:e,context:I.make(mn,e)}}},gn={make:()=>{let e=pn(),t=I.empty(),n={get context(){return t},get clock(){return e},withService(e,r){return t=t.add(e,r),n},async run(e){return e.provideContext(t).runOrThrow()}};return n},withClock:()=>{let e=pn();return gn.make().withService(mn,e)}},_n=fn(`HttpClient`),vn={},yn=r({},{networkError:(e,t,n)=>({_tag:`NetworkError`,url:e,method:t,cause:n}),httpStatusError:(e,t,n,r,i)=>({_tag:`HttpStatusError`,url:e,method:t,status:n,statusText:r,body:i}),decodeError:(e,t,n,r)=>({_tag:`DecodeError`,url:e,method:t,body:n,cause:r}),isNetworkError:e=>e._tag===`NetworkError`,isHttpStatusError:e=>e._tag===`HttpStatusError`,isDecodeError:e=>e._tag===`DecodeError`,match:(e,t)=>{switch(e._tag){case`NetworkError`:return t.NetworkError(e);case`HttpStatusError`:return t.HttpStatusError(e);case`DecodeError`:return t.DecodeError(e)}}}),bn=(e,t)=>!e||t.startsWith(`http://`)||t.startsWith(`https://`)?t:`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`,xn=(e,t)=>{let n=new URLSearchParams;for(let e of Object.keys(t)){let r=t[e];if(r!=null)if(Array.isArray(r))for(let t of r)n.append(e,String(t));else n.append(e,String(r))}let r=n.toString();return r?`${e}${e.includes(`?`)?`&`:`?`}${r}`:e},Sn=(e,t,n)=>{let r=bn(e,t);return n?xn(r,n):r},Cn=(e,t)=>e[Symbol.toStringTag]===t,q=(e,t)=>{if(typeof e!=`object`||!e||e instanceof Date||e instanceof RegExp||typeof Buffer<`u`&&e instanceof Buffer)return e;if(Cn(e,`Option`)){let n=e;return t===`tagged`?n._tag===`None`?{_tag:`None`,value:null}:{_tag:`Some`,value:q(n.value,t)}:n._tag===`None`?null:q(n.value,t)}if(Cn(e,`Either`)){let n=e;if(t===`tagged`)return{_tag:n._tag,value:q(n.value,t)};if(n._tag===`Left`)throw Error(`Cannot serialize a Left in a request body — Either's failure path should not cross the wire as data. Resolve the Left before sending, or omit the field. (Left value: ${JSON.stringify(n.value)})`);return q(n.value,t)}if(Cn(e,`Try`)){let n=e;if(t===`tagged`){if(n._tag===`Failure`){let e=n.error??Error(`unknown`);return{_tag:`Failure`,error:e.message,stack:e.stack}}return{_tag:`Success`,value:q(n.value,t)}}if(n._tag===`Failure`)throw n.error??Error(`Cannot serialize a Try Failure in a request body`);return q(n.value,t)}if(Cn(e,`List`)){let n=e.toArray().map(e=>q(e,t));return t===`tagged`?{_tag:`List`,value:n}:n}if(Cn(e,`FunctypeMap`)){let n=e.toValue().value;if(t===`tagged`)return{_tag:`Map`,value:n.map(([e,n])=>[e,q(n,t)])};let r={};for(let[e,i]of n){if(typeof e!=`string`)throw Error(`Cannot serialize Map with non-string keys to JSON (key: ${String(e)})`);r[e]=q(i,t)}return r}if(Array.isArray(e))return e.map(e=>q(e,t));let n={};for(let r of Object.keys(e))n[r]=q(e[r],t);return n},wn=(e,t)=>{if(e==null)return{serialized:void 0,contentType:void 0};if(typeof e==`string`)return{serialized:e,contentType:void 0};if(typeof e==`object`||Array.isArray(e)){let n=q(e,t?`primitive`:`tagged`);return{serialized:JSON.stringify(n),contentType:`application/json`}}return{serialized:String(e),contentType:void 0}},Tn=e=>{let t=e.get(`content-type`)??``;return t.includes(`application/json`)?`json`:t.startsWith(`text/`)?`text`:`raw`},En=async(e,t,n,r,i,a)=>{let o=t??Tn(e.headers),s,c={};switch(o){case`json`:{let t=await e.text();c.value=t;try{s=JSON.parse(t)}catch(e){throw yn.decodeError(n,r,t,e)}break}case`text`:s=await e.text(),c.value=s;break;case`blob`:s=await e.blob();break;case`arrayBuffer`:s=await e.arrayBuffer();break;case`raw`:s=e;break}let l;if(i){let e=i(s);if(e.isLeft()){let t=c.value??(typeof s==`string`?s:JSON.stringify(s));throw yn.decodeError(n,r,t,e.value)}l=e.value}else if(a)try{l=a(s)}catch(e){let t=c.value??(typeof s==`string`?s:JSON.stringify(s));throw yn.decodeError(n,r,t,e)}else l=s;return{data:l,status:e.status,statusText:e.statusText,headers:e.headers}},J=(e,t)=>{let n={url:Sn(e.baseUrl,t.url,t.params),method:t.method,headers:{...e.defaultHeaders,...t.headers},body:t.body,signal:t.signal,parseAs:t.parseAs,flatten:t.flatten};return(e.beforeRequest?e.beforeRequest(n):G.succeed(n)).flatMap(n=>{let r=n.flatten??!0,i=(()=>{try{return{ok:!0,value:wn(n.body,r)}}catch(e){return{ok:!1,cause:e}}})();if(!i.ok)return G.fail(yn.networkError(n.url,n.method,i.cause));let{serialized:a,contentType:o}=i.value,s={...n.headers,...o?{"Content-Type":o}:{}},c=G.tryAsync(r=>(e.fetch??globalThis.fetch)(n.url,{method:n.method,headers:s,body:a,signal:n.signal??r}).then(async e=>{if(!e.ok){let t=await e.text().catch(()=>``);throw yn.httpStatusError(n.url,n.method,e.status,e.statusText,t)}return En(e,n.parseAs,n.url,n.method,t.decode,t.validate)}),e=>typeof e==`object`&&e&&`_tag`in e?e:yn.networkError(n.url,n.method,e));return e.afterResponse?c.flatMap(t=>e.afterResponse(t).map(e=>e)):c})},Dn=e=>J(vn,e),On=r({},{request:Dn,get:(e,t)=>Dn({...t,url:e,method:`GET`}),post:(e,t)=>Dn({...t,url:e,method:`POST`}),put:(e,t)=>Dn({...t,url:e,method:`PUT`}),patch:(e,t)=>Dn({...t,url:e,method:`PATCH`}),delete:(e,t)=>Dn({...t,url:e,method:`DELETE`}),head:(e,t)=>Dn({...t,url:e,method:`HEAD`,parseAs:`raw`}),options:(e,t)=>Dn({...t,url:e,method:`OPTIONS`,parseAs:`raw`}),client:e=>({request:t=>J(e,t),get:(t,n)=>J(e,{...n,url:t,method:`GET`}),post:(t,n)=>J(e,{...n,url:t,method:`POST`}),put:(t,n)=>J(e,{...n,url:t,method:`PUT`}),patch:(t,n)=>J(e,{...n,url:t,method:`PATCH`}),delete:(t,n)=>J(e,{...n,url:t,method:`DELETE`}),head:(t,n)=>J(e,{...n,url:t,method:`HEAD`,parseAs:`raw`}),options:(t,n)=>J(e,{...n,url:t,method:`OPTIONS`,parseAs:`raw`})})}),kn={toOption:e=>e.fold(()=>p(),e=>d(e)),toList:e=>e.fold(()=>C([]),e=>C([e])),toEither:(e,t)=>e.fold(()=>T(t),e=>w(e)),isEmpty:e=>e.fold(()=>!0,()=>!1),size:e=>e.fold(()=>0,()=>1)},An=e=>typeof e==`object`&&!!e&&(e._tag===`Some`||e._tag===`None`),Y=e=>typeof e==`object`&&!!e&&e._tag===`List`,jn=e=>typeof e==`object`&&!!e&&(e._tag===`Left`||e._tag===`Right`),Mn=e=>typeof e==`object`&&!!e&&(e._tag===`Success`||e._tag===`Failure`),X=()=>{let e=(e,t)=>{if(An(e)||Y(e)||jn(e)||Mn(e))return e.map(e=>t(e));throw Error(`Unsupported functor type: ${JSON.stringify(e)}`)},t=e=>{if(An(e))return e.orThrow();if(Y(e)){let t=e.toArray();if(t.length>0&&Y(t[0])){let e=[];for(let n of t)Y(n)&&e.push(...n.toArray());return C(e)}return e.flatten()}if(jn(e))return e.isRight()?e.fold(()=>null,e=>e):e;if(Mn(e))return e.isSuccess()?e.orThrow():e;throw Error(`Unsupported functor type for flatten: ${JSON.stringify(e)}`)},n=(e,t)=>{if(An(e)||Y(e)||jn(e)||Mn(e))return e.flatMap(e=>t(e));throw Error(`Unsupported functor type for flatMap: ${JSON.stringify(e)}`)},r=(e,t)=>{if(An(e)&&An(t)||Y(e)&&Y(t)||jn(e)&&jn(t)||Mn(e)&&Mn(t))return e.flatMap(e=>t.map(t=>e(t)));throw Error(`Unsupported functor type for ap: ${JSON.stringify(e)}`)},i=e=>{if(An(e)){let t=e;if(t.isEmpty)return C([m.none()]);let n=t.orThrow();if(Y(n))return n.map(e=>m(e));throw Error(`Unsupported inner container type for sequence`)}if(Y(e)){let t=e.toArray();if(t.length===0)return m.none();let n=t[0];if(An(n)){for(let e of t)if(e.isEmpty)return m.none();return m(C(t.map(e=>e.orThrow())))}throw Error(`Unsupported inner container type for sequence`)}throw Error(`Unsupported outer container type for sequence: ${JSON.stringify(e)}`)};return{_tag:`HKT`,map:e,flatten:t,flatMap:n,ap:r,sequence:i,traverse:(t,n)=>i(e(t,e=>n(e))),_type:`HKT`}},Nn=X();X.map=(e,t)=>Nn.map(e,t),X.flatten=e=>Nn.flatten(e),X.flatMap=(e,t)=>Nn.flatMap(e,t),X.ap=(e,t)=>Nn.ap(e,t),X.sequence=e=>Nn.sequence(e),X.traverse=(e,t)=>Nn.traverse(e,t),X.isOption=An,X.isList=Y,X.isEither=jn,X.isTry=Mn;const Pn=e=>({id:e,isSame:t=>t.id===e}),Fn=r(Pn,{of:e=>Pn(e),pure:e=>Pn(e)}),In=e=>{let t=!1,n,r,a=!1,l=()=>{if(!t)try{n=e(),t=!0}catch(e){throw r=e,a=!0,t=!0,e}if(a)throw r;return n};return{[Symbol.toStringTag]:`Lazy`,_tag:`Lazy`,get isEvaluated(){return t},orElse:e=>{try{return l()}catch{return e}},orNull:()=>{try{return l()}catch{return null}},orThrow:e=>{try{return l()}catch(t){throw e??t}},or:e=>Z(()=>{try{return l()}catch{return e.orThrow()}}),orUndefined:()=>{try{return l()}catch{return}},map:e=>Z(()=>e(l())),ap:e=>Z(()=>e.orThrow()(l())),mapAsync:async e=>{let t=await e(l());return Z(()=>t)},flatMap:e=>Z(()=>e(l()).orThrow()),flatMapAsync:async e=>{let t=await e(l());return Z(()=>t.orThrow())},filter:e=>Z(()=>{let t=l();return e(t)?d(t):p}),recover:e=>Z(()=>{try{return l()}catch(t){return e(t)}}),recoverWith:e=>Z(()=>{try{return l()}catch(t){return e(t).orThrow()}}),toOption:()=>{try{return d(l())}catch{return p}},toEither:()=>{try{return w(l())}catch(e){return T(e)}},toEitherWith:e=>{try{return w(l())}catch(t){return T(e(t))}},toTry:()=>x(()=>l()),tap:e=>Z(()=>{let t=l();return e(t),t}),tapError:e=>Z(()=>{try{return l()}catch(t){throw e(t),t}}),fold:e=>e(l()),foldWith:(e,t)=>{try{return t(l())}catch(t){return e(t)}},foldLeft:e=>t=>t(e,l()),foldRight:e=>t=>t(l(),e),match:e=>e.Lazy(l()),toString:()=>t&&!a?`Lazy(${c(n)})`:t&&a?`Lazy(<error: ${r instanceof Error?r.message:String(r)}>)`:`Lazy(<not evaluated>)`,toValue:()=>{try{return{_tag:`Lazy`,value:l()}}catch(e){return{_tag:`Lazy`,error:e instanceof Error?e:Error(String(e))}}},get size(){try{return l(),1}catch{return 0}},get isEmpty(){try{return l(),!1}catch{return!0}},contains:e=>{try{return l()===e}catch{return!1}},reduce:e=>l(),reduceRight:e=>l(),count:e=>{try{return+!!e(l())}catch{return 0}},find:e=>{try{let t=l();return e(t)?d(t):p}catch{return p}},exists:e=>{try{return e(l())}catch{return!1}},forEach:e=>{try{e(l())}catch{}},pipe:e=>e(l()),toJSON:()=>{try{return{"@functype":`Lazy`,_tag:`Lazy`,value:l()}}catch(e){return{"@functype":`Lazy`,_tag:`Lazy`,error:o(e)}}},serialize:()=>{try{return s(`Lazy`,l())}catch(e){return i(`Lazy`,`Lazy`,{error:o(e)})}},typeable:`Lazy`}},Ln={of:e=>In(e),fromValue:e=>In(()=>e),fromOption:(e,t)=>In(()=>e._tag===`Some`?e.value:t()),fromTry:e=>In(()=>e.orThrow()),fromEither:e=>In(()=>e.fold(e=>{throw e},e=>e)),fromPromise:e=>In(()=>{throw Error(`Promise not yet resolved. Use await on the promise before creating Lazy.`)}),fail:e=>In(()=>{throw e}),evaluated:e=>In(()=>e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Lazy`)throw Error(`Lazy.fromJSON: expected @functype="Lazy", got ${JSON.stringify(t[`@functype`])}`);if(t.error!==void 0){let e=typeof t.error==`object`?a(t.error):Error(t.error);return Ln.fail(e)}return Ln.evaluated(t.value)}},Z=r(In,Ln),Rn={default:e=>t=>e(t),when:(e,t)=>n=>e(n)?t(n):void 0},Q=e=>({[Symbol.toStringTag]:`Obj`,_tag:`Obj`,data:e,get:t=>m(e[t]),set:(t,n)=>Q({...e,[t]:n}),assign:t=>Q({...e,...t}),merge:t=>Q({...e,...t}),when:(t,n)=>(typeof t==`function`?t():t)?Q({...e,...n}):Q(e),omit:(...t)=>{let n={...e};for(let e of t)delete n[e];return Q(n)},pick:(...t)=>{let n={};for(let r of t)r in e&&(n[r]=e[r]);return Q(n)},keys:()=>C(Object.keys(e)),values:()=>C(Object.values(e)),entries:()=>C(Object.entries(e).map(([e,t])=>te([e,t]))),has:t=>t in e,value:()=>e,get isEmpty(){return Object.keys(e).length===0},get size(){return Object.keys(e).length},map:t=>Q(t(e)),flatMap:t=>t(e),flatMapAsync:async t=>await t(e),ap:t=>{let n=t.data;return Q(n(e))},fold:(t,n)=>Object.keys(e).length===0?t():n(e),match:t=>t.Obj(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),count:t=>+!!t(e),find:t=>t(e)?m(e):m(void 0),exists:t=>t(e),forEach:t=>t(e),reduce:t=>e,reduceRight:t=>e,contains:t=>JSON.stringify(e)===JSON.stringify(t),orElse:t=>e,orThrow:t=>e,or:t=>Q(e),orNull:()=>e,orUndefined:()=>e,toOption:()=>m(e),toEither:t=>w(e),toList:()=>C([e]),toTry:()=>x(()=>e),toPromise:()=>Promise.resolve(e),toString:()=>`Obj(${c(e)})`,toValue:()=>({_tag:`Obj`,value:e}),toJSON:()=>({"@functype":`Obj`,_tag:`Obj`,value:e}),pipe:t=>t(e),serialize:()=>s(`Obj`,e),doUnwrap(){return{ok:!0,value:e}}}),zn=e=>Q(e),Bn={of:e=>Q(e),empty:()=>Q({}),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Obj`)throw Error(`Obj.fromJSON: expected @functype="Obj", got ${JSON.stringify(t[`@functype`])}`);return Q(t.value)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return Bn.fromJSON(t)}},Vn=r(zn,Bn),$=(e=[])=>{let t=[...e],n=()=>t.length,r=()=>t.length===0,i=e=>t.includes(e),a=e=>{if(t.length===0)throw Error(`Cannot reduce an empty stack`);return u(t,e)},o=e=>{if(t.length===0)throw Error(`Cannot reduce an empty stack`);return ee(t,e)},c=e=>$([...t,e]),l=()=>{if(r())return[$([]),m(null)];let e=[...t],n=e.pop();return[$(e),m(n)]},te=()=>r()?m(null):m(t[t.length-1]),ne=e=>$(t.map(e)),d=e=>r()?$([]):t.reduce((t,n)=>e(n).toArray().reduce((e,t)=>e.push(t),t),$([])),f=e=>{let n=[];return t.forEach(t=>{e.toArray().forEach(e=>{n.push(e(t))})}),$(n)},p=async e=>r()?$([]):(await Promise.all(t.map(async t=>await e(t)))).reduce((e,t)=>t.toArray().reduce((e,t)=>e.push(t),e),$([])),re=()=>C(t),ie=()=>[...t],h=()=>`Stack(${t.join(`, `)})`,g=(e,n)=>t.reduce(n,e),ae=e=>n=>t.reduce(n,e),oe=e=>n=>t.reduceRight((e,t)=>n(t,e),e),se=e=>r()?e.Empty():e.NonEmpty([...t]);return{[Symbol.toStringTag]:`Stack`,_tag:`Stack`,get size(){return n()},get isEmpty(){return r()},contains:i,reduce:a,reduceRight:o,push:c,pop:l,peek:te,map:ne,flatMap:d,ap:f,flatMapAsync:p,toList:re,toArray:ie,toString:h,fold:g,foldLeft:ae,foldRight:oe,match:se,toValue:()=>({_tag:`Stack`,value:t}),toJSON:()=>({"@functype":`Stack`,_tag:`Stack`,value:[...t]}),pipe:e=>e([...t]),serialize:()=>s(`Stack`,t)}},Hn=(e=[])=>$(e),Un={empty:()=>$([]),of:e=>$([e]),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Stack`)throw Error(`Stack.fromJSON: expected @functype="Stack", got ${JSON.stringify(t[`@functype`])}`);return Wn(t.value)},fromYAML:e=>{let t=e.split(`
17
+ `)[1]?.split(`: `)[1];if(!t)return Wn([]);let n=JSON.parse(t);return Wn(n)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return Un.fromJSON(t)}},Wn=r(Hn,Un);var Gn=e({deserialize:()=>Zn,deserializeStrict:()=>Qn,fromEnvelope:()=>tr,isFunctypeValue:()=>nr,serialize:()=>$n,toEnvelope:()=>er});let Kn;const qn=()=>(Kn===void 0&&(Kn={Option:e=>e._tag===`Some`?d(e.value):p(),Either:e=>e._tag===`Right`?w(e.value):T(e.value),Try:e=>{if(e._tag===`Success`)return x.success(e.value);let t=e.error!==void 0&&typeof e.error==`object`?a(e.error):Error(typeof e.error==`string`?e.error:``);return x.failure(t)},List:e=>C(e.value),Set:e=>ce(e.value),Map:e=>st(e.value),Obj:e=>Vn(e.value),Stack:e=>Wn(e.value),Tuple:e=>te(e.value),LazyList:e=>fe(e.value),Lazy:e=>{if(e.error!==void 0){let t=typeof e.error==`object`?a(e.error):Error(e.error);return Z.fail(t)}return Z.evaluated(e.value)},Task:e=>{if(e._tag===`Ok`)return A.ok(e.value);let t=e.error!==void 0&&typeof e.error==`object`?a(e.error):Error(typeof e.error==`string`?e.error:`Unknown Task error`);return A.err(t)}}),Kn),Jn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Yn=e=>Jn(e)&&typeof e[`@functype`]==`string`,Xn=e=>{if(Array.isArray(e))return e.map(Xn);if(Yn(e)){let t=e[l],n=qn()[t];if(n===void 0)throw Error(`Serialization.deserialize: unknown @functype marker ${JSON.stringify(t)}`);let r={};for(let t of Object.keys(e))r[t]=Xn(e[t]);return n(r)}if(Jn(e)){let t={};for(let n of Object.keys(e))t[n]=Xn(e[n]);return t}return e},Zn=e=>x(()=>Xn(JSON.parse(e))),Qn=e=>x(()=>{let t=JSON.parse(e);if(!Yn(t))throw Error(`Serialization.deserializeStrict: input is not a functype envelope (no @functype marker at the top level)`);return Xn(t)}),$n=e=>JSON.stringify(e??null),er=e=>JSON.parse(JSON.stringify(e??null)),tr=e=>x(()=>Xn(e)),nr=e=>typeof e==`object`&&!!e&&typeof e.serialize==`function`&&typeof e._tag==`string`;function rr(e){let t=he({_tag:e._tag,impl:e.impl});return{...t,toValue:()=>({_tag:t._tag,value:e.value})}}export{Ge as $,qt as A,m as At,Nt as B,I as C,he as Ct,Xt as D,_ as Dt,P as E,fe as Et,Gt as F,k as G,st as H,Ut as I,Qe as J,A as K,Ht as L,It as M,d as Mt,Rt as N,ne as Nt,Yt as O,ce as Ot,Wt as P,Je as Q,zt as R,R as S,C as St,$t as T,x as Tt,rt as U,M as V,O as W,Ze as X,Xe as Y,Ye as Z,dn as _,Te as _t,Rn as a,Fe as at,cn as b,we as bt,X as c,Pe as ct,yn as d,Le as dt,Be as et,_n as f,E as ft,fn as g,Ee as gt,gn as h,w as ht,Vn as i,Ne as it,Vt as j,re as jt,Jt as k,p as kt,kn as l,je as lt,mn as m,T as mt,Gn as n,Ie as nt,Z as o,Me as ot,hn as p,Ae as pt,et as q,Wn as r,ze as rt,Fn as s,He as st,rr as t,Ve as tt,On as u,Re as ut,G as v,Ce as vt,tn as w,ge as wt,on as x,De as xt,sn as y,Se as yt,Bt as z};
@@ -1,2 +1,2 @@
1
- import { Mn as TypeNames, jn as Try } from "../index-CGVJBR_H.js";
1
+ import { Mn as Try, Nn as TypeNames } from "../index-CCuIZ-ut.js";
2
2
  export { Try, TypeNames };
package/dist/try/index.js CHANGED
@@ -1 +1 @@
1
- import{Tt as e}from"../src-4UEC-cVf.js";export{e as Try};
1
+ import{Tt as e}from"../src-C4olFIr1.js";export{e as Try};
@@ -1 +1 @@
1
- import{t as e}from"../Companion-DiOMBHDG.js";import{i as t}from"../serialization-EQGLX3e3.js";const n=e=>{let n={[Symbol.toStringTag]:`Tuple`,_tag:`Tuple`,map:t=>r(t(e)),flatMap:t=>t(e),get:t=>e[t],toArray:()=>e,length:e.length,[Symbol.iterator](){let t=0;return{next:()=>t<e.length?{value:e[t++],done:!1}:{value:void 0,done:!0}}},fold:(t,n)=>e.reduce(n,t),foldLeft:t=>n=>e.reduce(n,t),foldRight:t=>n=>e.reduceRight((e,t)=>n(t,e),t),pipe:e=>e(n),serialize:()=>t(`Tuple`,e),toJSON:()=>({"@functype":`Tuple`,_tag:`Tuple`,value:[...e]}),toValue:()=>({_tag:`Tuple`,value:e}),toString:()=>`Tuple(${e.map(e=>String(e)).join(`, `)})`};return n},r=e(e=>n(e),{of:(...e)=>n(e),pair:(e,t)=>n([e,t]),triple:(e,t,r)=>n([e,t,r]),empty:()=>n([]),from:e=>n(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Tuple`)throw Error(`Tuple.fromJSON: expected @functype="Tuple", got ${JSON.stringify(t[`@functype`])}`);return n(t.value)}});export{r as Tuple};
1
+ import{t as e}from"../Companion-DiOMBHDG.js";import{i as t}from"../serialization-my_TLROv.js";const n=e=>{let n={[Symbol.toStringTag]:`Tuple`,_tag:`Tuple`,map:t=>{let n=t(e);return r(n)},flatMap:t=>t(e),get:t=>e[t],toArray:()=>e,length:e.length,[Symbol.iterator](){let t=0;return{next:()=>t<e.length?{value:e[t++],done:!1}:{value:void 0,done:!0}}},fold:(t,n)=>e.reduce(n,t),foldLeft:t=>n=>e.reduce(n,t),foldRight:t=>n=>e.reduceRight((e,t)=>n(t,e),t),pipe:e=>e(n),serialize:()=>t(`Tuple`,e),toJSON:()=>({"@functype":`Tuple`,_tag:`Tuple`,value:[...e]}),toValue:()=>({_tag:`Tuple`,value:e}),toString:()=>`Tuple(${e.map(e=>String(e)).join(`, `)})`};return n},r=e(e=>n(e),{of:(...e)=>n(e),pair:(e,t)=>n([e,t]),triple:(e,t,r)=>n([e,t,r]),empty:()=>n([]),from:e=>n(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Tuple`)throw Error(`Tuple.fromJSON: expected @functype="Tuple", got ${JSON.stringify(t[`@functype`])}`);return n(t.value)}});export{r as Tuple};
@@ -1,2 +1,2 @@
1
- import { _r as Monad, dr as reduceRightWiden, fr as reduceWiden, gr as Functor, hr as AsyncMonad, mr as Applicative, pr as Promisable, ur as Widen, vr as CollectionOps, yr as ContainerOps } from "../index-CGVJBR_H.js";
1
+ import { _r as Functor, br as ContainerOps, dr as Widen, fr as reduceRightWiden, gr as AsyncMonad, hr as Applicative, mr as Promisable, pr as reduceWiden, vr as Monad, yr as CollectionOps } from "../index-CCuIZ-ut.js";
2
2
  export { type Applicative, type AsyncMonad, type CollectionOps, type ContainerOps, type Functor, type Monad, type Promisable, type Widen, reduceRightWiden, reduceWiden };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "functype",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "type": "module",
5
5
  "description": "A functional programming library for TypeScript, using immutable data structures and type classes",
6
6
  "keywords": [
@@ -36,12 +36,12 @@
36
36
  "@types/node": "~24.10.15",
37
37
  "eslint-plugin-functional": "^9.0.5",
38
38
  "fast-check": "^4.8.0",
39
- "globals": "^17.6.0",
39
+ "globals": "^17.7.0",
40
40
  "ts-builds": "^3.2.1",
41
41
  "tsdown": "^0.22.3",
42
42
  "tsx": "^4.22.4",
43
43
  "typedoc": "^0.28.19",
44
- "eslint-config-functype": "2.105.0"
44
+ "eslint-config-functype": "2.106.1"
45
45
  },
46
46
  "types": "./dist/index.d.ts",
47
47
  "module": "./dist/index.js",
@@ -1,17 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-DK3Fl9T5.js";import{Brand as t}from"./branded/index.js";import{mergeObjects as n}from"./util/index.js";import{t as r}from"./Companion-DiOMBHDG.js";import{a as i,d as a,f as o,i as s,p as c,t as l}from"./serialization-EQGLX3e3.js";import{n as u,t as ee}from"./typeclass-C61yDVYd.js";import{Tuple as te}from"./tuple/index.js";const d=e=>({[Symbol.toStringTag]:`Option`,_tag:`Some`,value:e,isEmpty:!1,isSome(){return!0},isNone(){return!1},orElse:t=>e,orThrow:()=>e,expect:t=>e,or:t=>d(e),orNull:()=>e,orUndefined:()=>e,map:t=>d(t(e)),ap:t=>t._tag===`Some`&&t.value?d(t.value(e)):f,filter(t){return t(e)?d(e):f},count:t=>+!!t(e),find:t=>t(e)?d(e):f,exists:t=>t(e),forEach:t=>t(e),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),match:t=>t.Some(e),flatMap:t=>t(e),flatMapAsync:async t=>await t(e),reduce:t=>e,reduceRight:t=>e,foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),contains:t=>t===e,toList:()=>C([e]),toArray:()=>[e],size:1,toOption:()=>d(e),toEither:t=>w(e),toTry:()=>x(()=>e),toPromise:()=>Promise.resolve(e),toString:()=>`Some(${c(e)})`,toValue:()=>({_tag:`Some`,value:e}),toJSON:()=>({"@functype":`Option`,_tag:`Some`,value:e}),pipe:t=>t(e),serialize:()=>s(`Option`,`Some`,e),doUnwrap(){return{ok:!0,value:e}}}),f={[Symbol.toStringTag]:`Option`,_tag:`None`,value:void 0,isEmpty:!0,isSome(){return!1},isNone(){return!0},orElse:e=>e,orThrow(e){throw e??Error(`Cannot extract value from None`)},expect(e){return e()},or:e=>e,orNull:()=>null,orUndefined:()=>void 0,map:e=>f,ap:e=>f,filter(e){return f},count:e=>0,find:e=>f,exists:e=>!1,forEach:e=>{},flatMap:e=>f,flatMapAsync:e=>Promise.resolve(f),reduce:e=>{throw Error(`Cannot reduce an empty Option`)},reduceRight:e=>{throw Error(`Cannot reduceRight an empty Option`)},fold:(e,t)=>e(),foldAsync:async(e,t)=>e(),match:e=>e.None(),foldLeft:e=>()=>e,foldRight:e=>()=>e,contains:()=>!1,toList:()=>C([]),toArray:()=>[],size:0,toOption:()=>f,toEither:e=>T(typeof e==`function`?e():e),toTry:()=>x(()=>{throw Error(`None`)}),toPromise:()=>Promise.reject(Error(`Cannot convert None to Promise`)),toString:()=>`None`,toValue:()=>({_tag:`None`,value:void 0}),toJSON:()=>({"@functype":`Option`,_tag:`None`,value:null}),pipe:e=>e(void 0),serialize:()=>s(`Option`,`None`,null),doUnwrap(){return{ok:!1,empty:!0}}},p=()=>f,ne=e=>e==null?p():d(e),re={from:e=>m(e),none:()=>p(),isSome:e=>e.isSome(),isNone:e=>e.isNone(),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Option`)throw Error(`Option.fromJSON: expected @functype="Option", got ${JSON.stringify(t[`@functype`])}`);return t._tag===`Some`?d(t.value):p()},fromYAML:e=>{let t=e.split(`
2
- `),n=t[0]?.split(`: `)[1],r=t[1]?.split(`: `)[1];if(!n||!r)return p();let i=r===`null`?null:JSON.parse(r);return n===`Some`?d(i):p()},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return re.fromJSON(t)},sequence:e=>e.reduce((e,t)=>e.isEmpty||t.isEmpty?p():d([...e.value,t.value]),d([])),traverse:(e,t)=>e.reduce((e,n,r)=>e.flatMap(e=>t(n,r).map(t=>[...e,t])),d([]))},m=r(ne,re),h=globalThis.Set,g=e=>{let t=new h(e),n={[Symbol.toStringTag]:`FunctypeSet`,_tag:`Set`,[Symbol.iterator]:()=>t[Symbol.iterator](),add:e=>g([...t,e]),remove:e=>{let n=new h(t);return n.delete(e),g(n)},contains:e=>t.has(e),has:e=>t.has(e),map:e=>g(Array.from(t).map(e)),ap:e=>{let n=new h;for(let r of t)for(let t of e)n.add(t(r));return g(n)},flatMap:e=>{let n=new h;for(let r of t)for(let t of e(r))n.add(t);return g(n)},flatMapAsync:async e=>{let n=new h;for(let r of t){let t=await e(r);for(let e of t)n.add(e)}return g(n)},fold:(e,n)=>{let r=e;for(let e of t)r=n(r,e);return r},foldLeft:e=>n=>{let r=e;for(let e of t)r=n(r,e);return r},foldRight:e=>n=>Array.from(t).reduceRight((e,t)=>n(t,e),e),get size(){return t.size},get isEmpty(){return t.size===0},reduce:e=>{let n=Array.from(t);if(n.length===0)throw Error(`Cannot reduce empty Set`);return u(n,e)},reduceRight:e=>{let n=Array.from(t);if(n.length===0)throw Error(`Cannot reduceRight empty Set`);return ee(n,e)},count:e=>{let n=0;for(let r of t)e(r)&&n++;return n},find:e=>{for(let n of t)if(e(n))return m(n);return m(null)},exists:e=>{for(let n of t)if(e(n))return!0;return!1},forEach:e=>{t.forEach(e)},filter:e=>{let n=new h;for(let r of t)e(r)&&n.add(r);return g(n)},filterNot:e=>{let n=new h;for(let r of t)e(r)||n.add(r);return g(n)},drop:e=>g(Array.from(t).slice(e)),dropRight:e=>g(Array.from(t).slice(0,-e)),dropWhile:e=>{let n=Array.from(t),r=n.findIndex(t=>!e(t));return g(r===-1?[]:n.slice(r))},flatten:()=>{let e=new h;for(let n of t)if(Array.isArray(n))for(let t of n)e.add(t);else if(n&&typeof n==`object`&&Symbol.iterator in n)for(let t of n)e.add(t);else e.add(n);return g(e)},get head(){return Array.from(t)[0]},get headOption(){let e=Array.from(t)[0];return m(e)},take:e=>g(Array.from(t).slice(0,Math.max(0,e))),takeWhile:e=>{let n=Array.from(t),r=[];for(let t of n){if(!e(t))break;r.push(t)}return g(r)},takeRight:e=>{let n=Array.from(t);return g(e<=0?[]:n.slice(-e))},get last(){let e=Array.from(t);return e[e.length-1]},get lastOption(){let e=Array.from(t);return m(e[e.length-1])},get tail(){return g(Array.from(t).slice(1))},get init(){let e=Array.from(t);return g(e.length===0?[]:e.slice(0,-1))},toList:()=>C(Array.from(t)),toSet:()=>n,toArray:()=>Array.from(t),toString:()=>`Set(${Array.from(t).toString()})`,toValue:()=>({_tag:`Set`,value:Array.from(t)}),toJSON:()=>({"@functype":`Set`,_tag:`Set`,value:Array.from(t)}),pipe:e=>e(Array.from(t)),serialize:()=>s(`Set`,Array.from(t))};return n},ie=e=>g(e),ae=g([]),oe={empty:()=>ae,of:(...e)=>g(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Set`)throw Error(`Set.fromJSON: expected @functype="Set", got ${JSON.stringify(t[`@functype`])}`);return se(t.value)},fromYAML:e=>{let t=e.split(`
3
- `)[1]?.split(`: `)[1];return se(t?JSON.parse(t):[])},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return oe.fromJSON(t)}},se=r(ie,oe),ce=e=>{let t=e;return{get(){return t},set(e){t=e},update(e){t=e(t)},getAndSet(e){let n=t;return t=e,n},updateAndGet(e){return t=e(t),t},getAndUpdate(e){let n=t;return t=e(t),n},compareAndSet(e,n){return t===e?(t=n,!0):!1},modify(e){let[n,r]=e(t);return t=n,r}}},_=r(ce,{of:e=>ce(e)}),le=(e=0)=>{let t=_(e),n=e;return{get:()=>t.get(),set:e=>t.set(e),increment:()=>t.updateAndGet(e=>e+1),decrement:()=>t.updateAndGet(e=>e-1),reset:()=>t.set(n),compareAndSet:(e,n)=>t.compareAndSet(e,n)}},ue=()=>{let e=_([]);return{add:t=>e.update(e=>[...e,t]),addAll:t=>e.update(e=>[...e,...t]),build:()=>e.get(),clear:()=>e.set([]),size:()=>e.get().length}},v=e=>{let t={[Symbol.toStringTag]:`LazyList`,_tag:`LazyList`,[Symbol.iterator]:()=>e[Symbol.iterator](),map:t=>v((function*(){for(let n of e)yield t(n)})()),flatMap:t=>v((function*(){for(let n of e)yield*t(n)})()),filter:t=>v((function*(){for(let n of e)t(n)&&(yield n)})()),take:t=>v((function*(){let n=le(0);for(let r of e){if(n.get()>=t)break;yield r,n.increment()}})()),drop:t=>v((function*(){let n=le(0);for(let r of e)n.get()>=t&&(yield r),n.increment()})()),takeWhile:t=>v((function*(){for(let n of e){if(!t(n))break;yield n}})()),dropWhile:t=>v((function*(){let n=_(!0);for(let r of e)n.get()&&t(r)||(n.set(!1),yield r)})()),concat:t=>v((function*(){yield*e,yield*t})()),zip:t=>v((function*(){let n=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){let e=n.next(),t=r.next();if(e.done||t.done)break;yield[e.value,t.value]}})()),toList:()=>C(Array.from(e)),toArray:()=>Array.from(e),forEach:t=>{for(let n of e)t(n)},reduce:(t,n)=>{let r=_(n);for(let n of e)r.set(t(r.get(),n));return r.get()},find:t=>{for(let n of e)if(t(n))return m(n);return m.none()},some:t=>{for(let n of e)if(t(n))return!0;return!1},every:t=>{for(let n of e)if(!t(n))return!1;return!0},count:()=>{let t=le(0);for(let n of e)t.increment();return t.get()},get head(){let t=e[Symbol.iterator]().next();return t.done?void 0:t.value},get headOption(){let t=e[Symbol.iterator]().next();return t.done?m.none():m(t.value)},get last(){let t;for(let n of e)t=n;return t},get lastOption(){let t=_(void 0),n=_(!1);for(let r of e)t.set(r),n.set(!0);return n.get()?m(t.get()):m.none()},get tail(){return v((function*(){let t=e[Symbol.iterator]();t.next();let n=t.next();for(;!n.done;)yield n.value,n=t.next()})())},get init(){let t=Array.from(e);return v(t.length===0?[]:t.slice(0,-1))},takeRight:t=>{let n=Array.from(e);return v(t<=0?[]:n.slice(-t))},reverse:()=>v(Array.from(e).reverse()),distinct:()=>v((function*(){let t=new globalThis.Set;for(let n of e)t.has(n)||(t.add(n),yield n)})()),zipWithIndex:()=>v((function*(){let t=le(0);for(let n of e)yield[n,t.get()],t.increment()})()),fold:(t,n)=>{let r=t;for(let t of e)r=n(r,t);return r},foldLeft:t=>n=>{let r=_(t);for(let t of e)r.set(n(r.get(),t));return r.get()},foldRight:t=>n=>Array.from(e).reduceRight((e,t)=>n(t,e),t),pipe:e=>e(t),serialize:()=>s(`LazyList`,Array.from(e)),toJSON:()=>({"@functype":`LazyList`,_tag:`LazyList`,value:Array.from(e)}),toString:()=>{let t=[],n=le(0),r=_(!1);for(let i of e)if(n.get()<10)t.push(i),n.increment();else{r.set(!0);break}let i=t.map(e=>String(e)).join(`, `);return r.get()?`LazyList(${i}, ...)`:`LazyList(${i})`}};return t},de=r(e=>v(e),{empty:()=>v([]),of:e=>v([e]),from:(...e)=>v(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`LazyList`)throw Error(`LazyList.fromJSON: expected @functype="LazyList", got ${JSON.stringify(t[`@functype`])}`);return v(t.value)},iterate:(e,t)=>v((function*(){let n=_(e);for(;;)yield n.get(),n.set(t(n.get()))})()),generate:e=>v((function*(){for(;;)yield e()})()),range:(e,t,n=1)=>v((function*(){if(n===0)throw Error(`Step cannot be zero`);let r=_(e);if(n>0)for(;r.get()<t;)yield r.get(),r.set(r.get()+n);else for(;r.get()>t;)yield r.get(),r.set(r.get()+n)})()),repeat:(e,t)=>v((function*(){if(t===void 0)for(;;)yield e;else{let n=le(0);for(;n.get()<t;)yield e,n.increment()}})()),cycle:e=>v((function*(){let t=Array.from(e);if(t.length!==0)for(;;)yield*t})())}),y=e=>({[Symbol.toStringTag]:`Try`,_tag:`Success`,error:void 0,isSuccess(){return!0},isFailure(){return!1},orElse:t=>e,orThrow:t=>e,expect:t=>e,or:t=>y(e),orNull:()=>e,orUndefined:()=>e,toEither:t=>w(e),map:t=>x(()=>t(e)),ap:t=>t.map(t=>t(e)),flatMap:t=>t(e),flatMapAsync:async t=>t(e),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),match:t=>t.Success(e),recover:t=>y(e),recoverWith:t=>y(e),filterOrElse:(t,n)=>{try{return t(e)?y(e):b(n(e))}catch(e){return b(e instanceof Error?e:Error(String(e)))}},foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),toString:()=>`Success(${c(e)})`,toPromise:()=>Promise.resolve(e),toValue:()=>({_tag:`Success`,value:e}),toJSON:()=>({"@functype":`Try`,_tag:`Success`,value:e}),toOption:()=>d(e),toList:()=>C([e]),toArray:()=>[e],toTry:()=>y(e),pipe:t=>t(e),serialize:()=>s(`Try`,`Success`,e),contains:t=>e===t,exists:t=>t(e),forEach:t=>t(e),doUnwrap(){return{ok:!0,value:e}}}),b=e=>({[Symbol.toStringTag]:`Try`,_tag:`Failure`,error:e,isSuccess(){return!1},isFailure(){return!0},orElse:e=>e,orThrow:t=>{throw t??e},expect:t=>t(e),or:e=>e,orNull:()=>null,orUndefined:()=>void 0,toEither:t=>T(typeof t==`function`?t(e):t),map:t=>b(e),ap:t=>b(e),flatMap:t=>b(e),flatMapAsync:t=>Promise.resolve(b(e)),fold:(t,n)=>t(e),foldAsync:async(t,n)=>t(e),match:t=>t.Failure(e),recover:t=>x(()=>t(e)),recoverWith:t=>{try{return t(e)}catch(e){return b(e instanceof Error?e:Error(String(e)))}},filterOrElse:(t,n)=>b(e),foldLeft:e=>t=>e,foldRight:e=>t=>e,toString:()=>`Failure(${c(e)}))`,toPromise:()=>Promise.reject(e),toValue:()=>({_tag:`Failure`,value:e}),toJSON:()=>({"@functype":`Try`,_tag:`Failure`,error:o(e)}),toOption:()=>m(null),toList:()=>C([]),toArray:()=>[],toTry:()=>b(e),pipe:t=>{throw e},serialize:()=>i(`Try`,`Failure`,{error:o(e)}),contains:e=>!1,exists:e=>!1,forEach:e=>{},doUnwrap(){return{ok:!1,empty:!1,error:e}}}),fe=e=>{try{return y(e())}catch(e){return b(e instanceof Error?e:Error(String(e)))}},pe={success:e=>y(e),failure:e=>b(typeof e==`string`?Error(e):e),fromPromise:e=>e.then(e=>y(e)).catch(e=>b(e instanceof Error?e:Error(String(e)))),async:e=>{try{return e().then(e=>y(e)).catch(e=>b(e instanceof Error?e:Error(String(e))))}catch(e){return Promise.resolve(b(e instanceof Error?e:Error(String(e))))}},isSuccess:e=>e.isSuccess(),isFailure:e=>e.isFailure(),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Try`)throw Error(`Try.fromJSON: expected @functype="Try", got ${JSON.stringify(t[`@functype`])}`);if(t._tag===`Success`)return y(t.value);if(t.error!==void 0&&typeof t.error==`object`)return b(a(t.error));let n=Error(typeof t.error==`string`?t.error:``);return t.stack&&(n.stack=t.stack),b(n)},fromYAML:e=>{let t=e.split(`
4
- `),n=t[0]?.split(`: `)[1];if(!n)return b(Error(`Invalid YAML format for Try`));if(n===`Success`){let e=t[1]?.split(`: `)[1];return e?y(JSON.parse(e)):b(Error(`Invalid YAML format for Try Success`))}else{let e=t[1]?.split(`: `)[1];if(!e)return b(Error(`Invalid YAML format for Try Failure`));let n=t[2]?.split(`: `),r=n&&n.length>1?n.slice(1).join(`: `):void 0,i=Error(e);return r&&(i.stack=r),b(i)}},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return pe.fromJSON(t)},sequence:e=>x(()=>e.map(e=>e.orThrow())),traverse:(e,t)=>x(()=>e.map((e,n)=>t(e,n).orThrow()))},x=r(fe,pe);function me({_tag:e,impl:t}){return{...t,_tag:e}}function he(e,t){return!e||typeof e!=`object`||!(`_tag`in e)?!1:t?e._tag===t:!0}const S=e=>{let t=Array.from(e??[]),n={[Symbol.toStringTag]:`List`,_tag:`List`,[Symbol.iterator]:()=>t[Symbol.iterator](),get size(){return t.length},get length(){return t.length},map:e=>S(t.map(e)),ap:e=>S(t.flatMap(t=>Array.from(e).map(e=>e(t)))),flatMap:e=>S(t.flatMap(t=>Array.from(e(t)))),flatMapAsync:async e=>S((await Promise.all(t.map(async t=>await e(t)))).flatMap(e=>Array.from(e))),forEach:e=>t.forEach(e),contains:e=>t.includes(e),count:e=>t.filter(e).length,exists:e=>t.some(e),filter:e=>S(t.filter(e)),filterNot:e=>S(t.filter(t=>!e(t))),filterType:e=>S(t.filter(t=>he(t,e))),find:(e,n)=>m(t.find(t=>e(t)&&(n?he(t,n):!0))),get head(){return t[0]},get headOption(){return t.length>0?m(t[0]):p()},get isEmpty(){return t.length===0},toArray:()=>[...t],reduce:e=>u(t,e),reduceRight:e=>ee(t,e),fold:(e,n)=>t.reduce(n,e),foldLeft:e=>n=>t.reduce(n,e),foldRight:e=>n=>t.reduceRight((e,t)=>n(t,e),e),match:e=>t.length===0?e.Empty():e.NonEmpty([...t]),remove:e=>S(t.filter(t=>t!==e)),removeAt:e=>e<0||e>=t.length?n:S([...t.slice(0,e),...t.slice(e+1)]),add:e=>S([...t,e]),get:e=>m(t[e]),concat:e=>S([...t,...e.toArray()]),take:e=>S(t.slice(0,Math.max(0,e))),takeWhile:e=>{let n=[];for(let r of t){if(!e(r))break;n.push(r)}return S(n)},takeRight:e=>S(e<=0?[]:t.slice(-e)),get last(){return t[t.length-1]},get lastOption(){return t.length>0?m(t[t.length-1]):p()},get tail(){return S(t.slice(1))},get init(){return S(t.length===0?[]:t.slice(0,-1))},reverse:()=>S([...t].reverse()),indexOf:e=>t.indexOf(e),prepend:e=>S([e,...t]),distinct:()=>{let e=new globalThis.Set,n=[];for(let r of t)e.has(r)||(e.add(r),n.push(r));return S(n)},sorted:e=>S([...t].sort(e)),sortBy:(e,n)=>S([...t].sort((t,r)=>{let i=e(t),a=e(r);return n?n(i,a):i<a?-1:+(i>a)})),zip:e=>{let n=e.toArray(),r=Math.min(t.length,n.length),i=[];for(let e=0;e<r;e++)i.push([t[e],n[e]]);return S(i)},zipWithIndex:()=>S(t.map((e,t)=>[e,t])),groupBy:e=>{let n=new globalThis.Map;for(let r of t){let t=e(r),i=n.get(t)??[];i.push(r),n.set(t,i)}let r=new globalThis.Map;for(let[e,t]of n)r.set(e,S(t));return r},partition:e=>{let n=[],r=[];for(let i of t)e(i)?n.push(i):r.push(i);return[S(n),S(r)]},span:e=>{let n=t.findIndex(t=>!e(t));return n===-1?[S([...t]),S([])]:[S(t.slice(0,n)),S(t.slice(n))]},slice:(e,n)=>S(t.slice(e,n)),drop:e=>S(t.slice(e)),dropRight:e=>S(t.slice(0,-e)),dropWhile:e=>S(t.slice(t.findIndex(t=>!e(t)))),flatten:()=>S(t.flatMap(e=>Array.isArray(e)?e:[e])),toList:()=>n,toSet:()=>se(t),toOption:()=>t.length>0?m(t[0]):p(),toEither:e=>t.length>0?w(t[0]):T(e),toTry:()=>t.length>0?x(()=>t[0]):x(()=>{throw Error(`Empty list`)}),toString:()=>`List(${c(t)})`,toValue:()=>({_tag:`List`,value:t}),toJSON:()=>({"@functype":`List`,_tag:`List`,value:[...t]}),pipe:e=>e([...t]),serialize:()=>s(`List`,t),doUnwrap(){return t.length===0?{ok:!1,empty:!0}:{ok:!0,value:t[0]}}};return n},ge=e=>S(e),_e=S([]),ve={empty:()=>_e,of:(...e)=>S(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`List`)throw Error(`List.fromJSON: expected @functype="List", got ${JSON.stringify(t[`@functype`])}`);return C(t.value)},fromYAML:e=>{let t=e.split(`
5
- `)[1]?.split(`: `)[1];return C(t?JSON.parse(t):[])},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return ve.fromJSON(t)}},C=r(ge,ve),ye=e=>({[Symbol.toStringTag]:`Either`,_tag:`Right`,value:e,isLeft(){return!1},isRight(){return!0},orElse:t=>e,orThrow:()=>e,expect:t=>e,or:t=>w(e),orNull:()=>e,orUndefined:()=>e,map:t=>w(t(e)),ap:t=>t._tag===`Right`?w(t.value(e)):T(t.value),mapAsync:t=>t(e).then(e=>w(e)).catch(e=>Promise.resolve(T(e))),merge:t=>t.isLeft()?T(t.value):w([e,t.value]),flatMap:t=>t(e),flatMapAsync:t=>t(e).catch(e=>T(e)),toOption:()=>d(e),toList:()=>C([e]),toEither:t=>w(e),toTry:()=>x(()=>e),toJSON(){return{"@functype":`Either`,_tag:`Right`,value:e}},toString:()=>`Right(${c(e)})`,*[Symbol.iterator](){yield e},*yield(){yield e},traverse:t=>{let n=t(e);return n.isLeft()?T(n.value):w([n.value])},tap:t=>(t(e),w(e)),tapLeft:t=>w(e),mapLeft:t=>w(e),filterOrElse:(t,n)=>t(e)?w(e):T(n(e)),bimap:(t,n)=>w(n(e)),fold:(t,n)=>n(e),foldAsync:async(t,n)=>n(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),match:t=>t.Right(e),swap:()=>T(e),toPromise:()=>Promise.resolve(e),toValue:()=>({_tag:`Right`,value:e}),pipeEither:(t,n)=>n(e),pipe:t=>t(e),serialize:()=>s(`Either`,`Right`,e),contains:t=>e===t,exists:t=>t(e),forEach:t=>t(e),doUnwrap(){return{ok:!0,value:e}}}),be=e=>({[Symbol.toStringTag]:`Either`,_tag:`Left`,value:e,isLeft(){return!0},isRight(){return!1},orElse:e=>e,orThrow:t=>{throw t??e},expect:t=>t(e),or:e=>e,orNull:()=>null,orUndefined:()=>void 0,map:t=>T(e),ap:t=>T(e),mapAsync:t=>Promise.resolve(T(e)),merge:t=>T(e),flatMap:t=>T(e),flatMapAsync:t=>Promise.resolve(T(e)),toOption:()=>p(),toList:()=>C(),toEither:e=>T(e),toTry:()=>x(()=>{throw Error(String(e))}),toJSON(){return{"@functype":`Either`,_tag:`Left`,value:e}},toString:()=>`Left(${c(e)})`,*[Symbol.iterator](){},*yield(){},traverse:t=>T(e),tap:t=>T(e),tapLeft:t=>(t(e),T(e)),mapLeft:t=>T(t(e)),filterOrElse:(t,n)=>T(e),bimap:(t,n)=>T(t(e)),fold:(t,n)=>t(e),foldAsync:async(t,n)=>t(e),foldLeft:e=>t=>e,foldRight:e=>t=>e,match:t=>t.Left(e),swap:()=>w(e),toPromise:()=>Promise.reject(e),toValue:()=>({_tag:`Left`,value:e}),pipeEither:(t,n)=>t(e),pipe:t=>t(e),serialize:()=>s(`Either`,`Left`,e),contains:e=>!1,exists:e=>!1,forEach:e=>{},doUnwrap(){return{ok:!1,empty:!1,error:e}}}),w=e=>ye(e),T=e=>be(e),xe=e=>e.isRight(),Se=e=>e.isLeft(),Ce=(e,t)=>{try{return w(e())}catch(e){return T(t(e))}},we=e=>ye(e);console.assert(we);const Te=e=>be(e);console.assert(Te);const Ee=async(e,t)=>{try{return w(await e())}catch(e){return T(t(e))}},De=(e,t)=>t?w(e):T(e),Oe={left:e=>T(e),right:e=>w(e),void:()=>w(void 0),isRight:e=>e.isRight(),isLeft:e=>e.isLeft(),sequence:e=>e.reduce((e,t)=>e.isLeft()?e:t.isLeft()?T(t.value):e.map(e=>[...e,t.value]),w([])),traverse:(e,t)=>Oe.sequence(e.map(t)),fromNullable:(e,t)=>e==null?T(t):w(e),fromPredicate:(e,t,n)=>t(e)?w(e):T(n),ap:(e,t)=>e.flatMap(e=>t.map(e)),fromPromise:async(e,t)=>{try{return w(await e)}catch(e){return T(t(e))}},fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Either`)throw Error(`Either.fromJSON: expected @functype="Either", got ${JSON.stringify(t[`@functype`])}`);return t._tag===`Right`?w(t.value):T(t.value)},fromYAML:e=>{let t=e.split(`
6
- `),n=t[0]?.split(`: `)[1],r=t[1]?.split(`: `)[1];if(!n||!r)throw Error(`Invalid YAML format for Either`);let i=JSON.parse(r);return n===`Right`?w(i):T(i)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return Oe.fromJSON(t)}},ke=r(De,Oe);function E(e,n){return{brand:e,validate:n,of:r=>n(r)?m(t(e,r)):m.none(),from:r=>n(r)?w(t(e,r)):T(`Invalid ${e}: validation failed`),unsafeOf:r=>{if(!n(r))throw Error(`Invalid ${e}: validation failed`);return t(e,r)},is:e=>{try{return n(e)}catch{return!1}},unwrap:e=>e,refine:(e,t)=>E(e,e=>n(e)&&t(e))}}const Ae=E(`PositiveNumber`,e=>e>0),je=E(`NonNegativeNumber`,e=>e>=0),Me=E(`IntegerNumber`,e=>Number.isInteger(e)),Ne=Ae.refine(`PositiveInteger`,e=>Number.isInteger(e)),Pe=E(`NonEmptyString`,e=>e.length>0),Fe=E(`EmailAddress`,e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),Ie=E(`UrlString`,e=>{try{return new URL(e),!0}catch{return!1}}),Le=E(`UUID`,e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),Re=E(`ISO8601Date`,e=>!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e));function ze(e,t,n){return E(e,e=>e>=t&&e<=n)}function Be(e,t,n){return E(e,e=>e.length>=t&&e.length<=n)}function Ve(e,t){return E(e,e=>t.test(e))}const He=e=>{let t=e=>typeof e==`function`?e():e,n={when:(r,i)=>e.resolved?n:r?He({resolved:!0,value:t(i)}):n,elseWhen:(r,i)=>e.resolved?n:r?He({resolved:!0,value:t(i)}):n,else:n=>e.resolved?e.value:t(n),orThrow:()=>{if(!e.resolved)throw Error(`Conditional expression has no matching condition`);return e.value}};return n},Ue=()=>He({resolved:!1}),We=r(Ue,{of:()=>Ue(),match:e=>t=>{let n=t[e];if(n===void 0)throw Error(`No case defined for value: ${String(e)}`);return typeof n==`function`?n():n},lazy:()=>{let e={resolved:!1},t={when:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),elseWhen:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),else:t=>e.resolved?e.value:t()};return t}}),Ge=(e,t)=>t===e?!0:typeof t==`function`?t(e):t&&typeof t==`object`&&`_`in t?t._(e):typeof t==`object`&&t&&typeof e==`object`&&e?Object.entries(t).every(([t,n])=>{let r=e[t];return Ge(r,n)}):!1,D=e=>{let t=(e,t)=>typeof e==`function`?e(t):e,n=()=>{for(let{pattern:n,result:r}of e.patterns)if(Ge(e.value,n))return{matched:!0,result:t(r,e.value)};return{matched:!1}},r={case:(n,i)=>e.resolved?r:Ge(e.value,n)?D({value:e.value,resolved:!0,result:t(i,e.value),patterns:[]}):D({...e,patterns:[...e.patterns,{pattern:n,result:i}]}),caseValue:(t,n)=>{if(e.resolved)return r;if(e.value===t){let t=typeof n==`function`?n():n;return D({value:e.value,resolved:!0,result:t,patterns:[]})}return r},caseValues:(t,n)=>{if(e.resolved)return r;if(t.includes(e.value)){let t=typeof n==`function`?n():n;return D({value:e.value,resolved:!0,result:t,patterns:[]})}return r},when:(e,t)=>r.case(e,t),caseAny:(n,i)=>{if(e.resolved)return r;for(let r of n)if(Ge(e.value,r))return D({value:e.value,resolved:!0,result:t(i,e.value),patterns:[]});return D({...e,patterns:[...e.patterns,...n.map(e=>({pattern:e,result:i}))]})},default:n=>e.resolved?e.result:t(n,e.value),exhaustive:()=>{if(e.resolved)return e.result;let t=n();if(!t.matched)throw Error(`Non-exhaustive match. No pattern matched value: ${JSON.stringify(e.value)}`);return t.result},orThrow:t=>{if(e.resolved)return e.result;let r=n();if(!r.matched)throw Error(t??`No matching pattern for value: ${JSON.stringify(e.value)}`);return r.result},toOption:()=>{if(e.resolved)return m(e.result);let t=n();return t.matched?m(t.result):m.none()}};return r},Ke=e=>{let t=(e,t)=>typeof e==`function`?e(t):e;return{case:(n,r)=>{let i={value:e,resolved:!1,patterns:[{pattern:n,result:r}]};return Ge(e,n)?D({...i,resolved:!0,result:t(r,e)}):D(i)},caseValue:(t,n)=>D(e===t?{value:e,resolved:!0,result:typeof n==`function`?n():n,patterns:[]}:{value:e,resolved:!1,patterns:[]}),caseValues:(t,n)=>t.includes(e)?D({value:e,resolved:!0,result:typeof n==`function`?n():n,patterns:[]}):D({value:e,resolved:!1,patterns:[]}),when:(n,r)=>{let i={value:e,resolved:!1,patterns:[{pattern:n,result:r}]};return n(e)?D({...i,resolved:!0,result:t(r,e)}):D(i)},caseAny:(n,r)=>{for(let i of n)if(Ge(e,i))return D({value:e,resolved:!0,result:t(r,e),patterns:n.map(e=>({pattern:e,result:r}))});return D({value:e,resolved:!1,patterns:n.map(e=>({pattern:e,result:r}))})}}},qe=r(e=>Ke(e),{exhaustive:e=>t=>{let n=e[t];if(n===void 0)throw Error(`No case defined for value: ${String(t)}`);return n},partial:e=>({withDefault:t=>n=>{let r=e[n];return r===void 0?typeof t==`function`?t(n):t:typeof r==`function`?r(n):r}}),withGuards:e=>({withDefault:t=>n=>{for(let[t,r]of e)if(t(n))return typeof r==`function`?r(n):r;return typeof t==`function`?t(n):t}}),struct:()=>{let e=[],t={case:(n,r)=>(e.push({pattern:n,handler:r}),t),build:()=>t=>{for(let{pattern:n,handler:r}of e)if(Ge(t,n))return r(t);throw Error(`No matching pattern for value: ${JSON.stringify(t)}`)}};return t},builder:()=>{let e=[],t,n={case:(t,r)=>(e.push({pattern:t,result:r}),n),when:(t,r)=>(e.push({pattern:t,result:r}),n),default:n=>(t=n,{build:()=>n=>{for(let{pattern:t,result:r}of e)if(Ge(n,t))return typeof r==`function`?r(n):r;if(t!==void 0)return typeof t==`function`?t(n):t;throw Error(`No matching pattern for value: ${JSON.stringify(n)}`)}})};return n}});function Je(e,t){return{...me({_tag:e,impl:t}),toString(){return`${e}()`},doUnwrap(){if(`isSome`in t&&`isNone`in t){if(typeof t.isSome==`function`&&t.isSome()&&`get`in t&&typeof t.get==`function`)return{ok:!0,value:t.get()};if(typeof t.isNone==`function`&&t.isNone())return{ok:!1,empty:!0}}if(`isLeft`in t&&`isRight`in t){if(typeof t.isRight==`function`&&t.isRight()&&`value`in t)return{ok:!0,value:t.value};if(typeof t.isLeft==`function`&&t.isLeft()&&`value`in t)return{ok:!1,empty:!1,error:t.value}}if(`isSuccess`in t&&`isFailure`in t){if(typeof t.isSuccess==`function`&&t.isSuccess()&&`get`in t&&typeof t.get==`function`)return{ok:!0,value:t.get()};if(typeof t.isFailure==`function`&&t.isFailure()&&`getError`in t&&typeof t.getError==`function`)return{ok:!1,empty:!1,error:t.getError()}}if(`isEmpty`in t&&`head`in t){if(typeof t.isEmpty==`function`&&t.isEmpty())return{ok:!1,empty:!0};if(typeof t.head==`function`)return{ok:!0,value:t.head()};if(`head`in t)return{ok:!0,value:t.head}}return{ok:!0,value:t}}}}const Ye=`Throwable`;var Xe=class e extends Error{constructor(e,t){super(e,{cause:t?.cause}),this._tag=Ye,this.name=t?.taskInfo?.name??`Throwable`,Object.defineProperties(this,{_tag:{value:Ye,writable:!1,configurable:!1},data:{value:t?.data,writable:!1,configurable:!1},taskInfo:{value:t?.taskInfo,writable:!1,configurable:!1},name:{value:t?.taskInfo?.name??`Throwable`,writable:!1,configurable:!1}}),t?.cause&&Object.defineProperty(this,"cause",{value:t.cause,writable:!1,configurable:!1}),t?.stack?this.stack=t.stack:Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static apply(t,n,r){if(t instanceof Error){let i=new e(t.message,{data:n,cause:t.cause??void 0,stack:t.stack??void 0,taskInfo:r});for(let e of Object.keys(t))if(!(e in i)){let n=i;n[e]=t[e]}return i}if(t&&typeof t==`object`){let i=t,a=new e(typeof i.message==`string`?i.message:typeof i.error==`string`?i.error:`Object error: ${JSON.stringify(i,Object.getOwnPropertyNames(i).filter(e=>i[e]!==void 0))}`,{data:n??i,taskInfo:r});for(let e of Object.keys(i))if(!(e in a)){let t=a;t[e]=i[e]}return a}if(typeof t==`function`){let i=t.name??`anonymous function`,a=t.toString().substring(0,100)+(t.toString().length>100?`...`:``);return new e(`Function error: ${i}`,{data:n??{functionType:typeof t,functionName:i,functionString:a},taskInfo:r})}let i=typeof t,a=t===null?`null`:t===void 0?`undefined`:String(t);if(i===`number`){let a=t;return new e(Number.isNaN(a)?`Number error: NaN`:Number.isFinite(a)?`Number error: ${a}`:`Number error: ${a>0?`Infinity`:`-Infinity`}`,{data:n??{errorType:i,errorValue:a,originalError:t},taskInfo:r})}if(i===`bigint`)return new e(`BigInt error: ${t}n`,{data:n??{errorType:i,errorValue:String(t),originalError:t},taskInfo:r});if(i===`boolean`)return new e(`Boolean error: ${t}`,{data:n??{errorType:i,errorValue:t,originalError:t},taskInfo:r});if(i===`symbol`){let a=t.description??`unnamed symbol`;return new e(`Symbol error: Symbol(${a})`,{data:n??{errorType:i,symbolDescription:a,originalError:t},taskInfo:r})}return new e(typeof t==`string`?t:`${i.charAt(0).toUpperCase()+i.slice(1)} error: ${a}`,{data:n??{errorType:i,errorValue:a,originalError:t},taskInfo:r})}};function Ze(e){return e instanceof Error&&typeof e==`object`&&e._tag===`Throwable`}const Qe=(e,t)=>{if(e.isRight())return k(e.orThrow(),t);if(e.isLeft())return O(e.fold(e=>e,()=>Error(`Unexpected right value`)),void 0,t);throw Error(`Unrecognized task outcome`)},O=(e,t,n)=>{let r={name:n?.name??`Task`,description:n?.description??``},a=Xe.apply(e,t,r),s={...Je(`Err`,{error:a,meta:r}),[Symbol.toStringTag]:`TaskOutcome`,_tag:`Err`,_meta:r,value:void 0,error:a,isSuccess(){return!1},isFailure(){return!0},isOk(){return!1},isErr(){return!0},map:e=>O(a,t,n),flatMap:e=>O(a,t,n),ap:e=>O(a,t,n),mapAsync:e=>Promise.resolve(O(a,t,n)),flatMapAsync:e=>Promise.resolve(O(a,t,n)),mapError:e=>O(e(a),t,n),recover:e=>k(e,n),recoverWith:e=>k(e(a),n),orThrow:e=>{throw e??a},orElse:e=>e,or:e=>e,orNull:()=>null,orUndefined:()=>void 0,toEither:()=>T(a),toTry:()=>x(()=>{throw a}),toOption:()=>p(),toList:()=>C([]),fold:(e,t)=>e(a),match:e=>e.Err(a),foldLeft:e=>t=>e,foldRight:e=>t=>e,size:0,isEmpty:!0,contains:e=>!1,reduce:e=>{throw Error(`Cannot reduce empty Err`)},reduceRight:e=>{throw Error(`Cannot reduceRight empty Err`)},count:e=>0,find:e=>p(),exists:e=>!1,forEach:e=>{},toPromise:()=>Promise.reject(a),doUnwrap(){return{ok:!1,empty:!1,error:a}},toJSON:()=>({"@functype":`Task`,_tag:`Err`,error:o(a)}),serialize:()=>i(`Task`,`Err`,{error:o(a)}),pipe:e=>e(s)};return s},k=(e,t)=>{let n={name:t?.name??`Task`,description:t?.description??``},r={...Je(`Ok`,{value:e,meta:n}),[Symbol.toStringTag]:`TaskOutcome`,_tag:`Ok`,_meta:n,value:e,error:void 0,isSuccess(){return!0},isFailure(){return!1},isOk(){return!0},isErr(){return!1},map:n=>k(n(e),t),flatMap:n=>{let r=n(e);return r&&typeof r==`object`&&`isLeft`in r&&`isRight`in r?Qe(r,t):r},ap:n=>n.isOk()?k(n.value(e),t):O(n.error,void 0,t),mapAsync:async n=>k(await n(e),t),flatMapAsync:async t=>await t(e),mapError:n=>k(e,t),recover:n=>k(e,t),recoverWith:n=>k(e,t),orThrow:t=>e,orElse:t=>e,or:n=>k(e,t),orNull:()=>e,orUndefined:()=>e,toEither:()=>w(e),toTry:()=>x(()=>e),toOption:()=>d(e),toList:()=>C([e]),fold:(t,n)=>n(e),match:t=>t.Ok(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),size:1,isEmpty:!1,contains:t=>e===t,reduce:t=>e,reduceRight:t=>e,count:t=>+!!t(e),find:t=>t(e)?d(e):p(),exists:t=>t(e),forEach:t=>t(e),toPromise:()=>Promise.resolve(e),doUnwrap(){return{ok:!0,value:e}},toJSON:()=>({"@functype":`Task`,_tag:`Ok`,value:e}),serialize:()=>s(`Task`,`Ok`,e),pipe:e=>e(r)};return r},$e=()=>{let e=new AbortController,t=ue();return{token:{get isCancelled(){return e.signal.aborted},get signal(){return e.signal},onCancel(n){e.signal.aborted?n():t.add(n)}},cancel(){e.signal.aborted||(e.abort(),t.build().forEach(e=>{try{e()}catch(e){console.error(`Error in cancellation callback:`,e)}}))}}},et=e=>{let t=e?.name??`Task`,n=e?.description??``,r={Async:(e,r=e=>e,i=()=>{},a)=>new Promise(o=>{(async()=>{let s=_(!1),c=_(null),l=_(()=>{});if(a){if(a.isCancelled){try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}o(O(Error(`Task was cancelled before execution started`),void 0,{name:t,description:n}));return}a.onCancel(()=>{s.set(!0),c.set(Error(`Task was cancelled during execution`))}),l.set(()=>{})}try{let r=await e();try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}if(s.get()){c.get()?o(O(c.get(),void 0,{name:t,description:n})):o(O(Error(`Task was cancelled during execution`),void 0,{name:t,description:n}));return}if(r&&typeof r==`object`&&`_tag`in r){let e=r;e._tag===`Ok`||e._tag===`Err`?o(e):o(k(r,{name:t,description:n}))}else o(k(r,{name:t,description:n}))}catch(e){try{await i()}catch(e){o(O(e,void 0,{name:t,description:n}));return}if(s.get()){c.get()?o(O(c.get(),void 0,{name:t,description:n})):o(O(Error(`Task was cancelled during execution`),void 0,{name:t,description:n}));return}try{if(e instanceof Error&&Ze(e)){let i=Error(`${t}: ${e.message}`),a=Xe.apply(i,void 0,{name:t,description:n});Object.defineProperty(a,"cause",{value:e,writable:!1,configurable:!1}),Promise.resolve().then(()=>{try{r(e)}catch(e){console.error(`Error in error handler:`,e)}}),o(O(a,void 0,{name:t,description:n}))}else{let i=await r(e);if(i&&typeof i==`object`&&`_tag`in i){let e=i;e._tag===`Ok`||e._tag===`Err`?o(e):o(O(i,void 0,{name:t,description:n}))}else o(O(i,void 0,{name:t,description:n}))}}catch(e){o(O(e,void 0,{name:t,description:n}))}}finally{l.get()()}})().catch(e=>o(O(e,void 0,{name:t,description:n})))}),Sync:(e,r=e=>e,i=()=>{})=>{try{return k(e(),{name:t,description:n})}catch(e){return O(r(e),void 0,{name:t,description:n})}finally{i()}},AsyncWithProgress:(e,t,n=e=>e,i=()=>{},a)=>{let o=e=>{let n=Math.max(0,Math.min(100,e));n<=100&&t(n)};return r.Async(()=>e(o),n,i,a)}};return{...Je(`Task`,r),_type:`Task`}},tt={success:(e,t)=>k(e,t),fail:(e,t,n)=>O(e,t,n),ok:(e,t)=>k(e,t),err:(e,t,n)=>O(e,t,n),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Task`)throw Error(`Task.fromJSON: expected @functype="Task", got ${JSON.stringify(t[`@functype`])}`);if(t._tag===`Ok`)return k(t.value);if(t._tag===`Err`)return O(t.error!==void 0&&typeof t.error==`object`?a(t.error):Error(typeof t.error==`string`?t.error:`Unknown Task error`));throw Error(`Task.fromJSON: unrecognized _tag ${JSON.stringify(t._tag)}`)},fromEither:(e,t)=>Qe(e,t),fromTry:(e,t)=>e.isSuccess()?k(e.orThrow(),t):O(e.fold(e=>e,()=>Error(`Unexpected success`)),void 0,t),getErrorChain:e=>{if(!e)return[];let t=ue();t.add(e);let n=_(e);for(;n.get()&&n.get().cause;){let{cause:e}=n.get();if(e)t.add(e),n.set(e);else break;if(t.size()>100)break}return t.build()},formatErrorChain:(e,t)=>{let n=tt.getErrorChain(e),r=t?.separator??`
7
- `;return n.map((e,n)=>{if(!e)return`${n>0?`↳ `:``}Unknown error`;let{taskInfo:r}=e,i=t?.includeTasks&&r?.name?`[${r.name}] `:``,a=e.message??`No message`,o=_(`${n>0?`↳ `:``}${i}${a}`);return t?.includeStackTrace&&e.stack&&o.set(`${o.get()}\n${e.stack.split(`
8
- `).slice(1).join(`
9
- `)}`),o.get()}).join(r)},fromPromise:(e,t)=>(...n)=>A(t??{name:`PromiseTask`,description:`Task from Promise`}).Async(()=>e(...n),e=>e),toPromise:e=>new Promise((t,n)=>{e.isSuccess()?t(e.orThrow()):n(e.error)}),race:(e,t,n)=>A({name:n?.name??`TaskRace`,description:n?.description??`Race between multiple tasks`}).Async(async()=>{let n=ue();e.forEach(e=>n.add(e));let r=_(void 0);if(typeof t==`number`&&t>0){let e=new Promise((e,n)=>{r.set(setTimeout(()=>{n(Error(`Task race timed out after ${t}ms`))},t))});n.add(e)}try{return await new Promise((e,t)=>{n.build().forEach(n=>{n.then(n=>{if(n&&typeof n==`object`&&`_tag`in n){let r=n;r._tag===`Ok`?e(r.orThrow()):r._tag===`Err`?t(r.error):e(n)}else e(n)},e=>t(e))})})}finally{r.get()&&clearTimeout(r.get())}},e=>e),fromNodeCallback:(e,t)=>{let n={name:t?.name??`NodeCallbackTask`,description:t?.description??`Task from Node.js callback function`};return(...t)=>A(n).Async(()=>new Promise((n,r)=>{try{e(...t,(e,t)=>{e?r(e):n(t)})}catch(e){r(e)}}),e=>e)},createCancellationTokenSource:$e,cancellable:(e,t)=>{let n=$e();return{task:A(t).Async(()=>e(n.token),e=>e,()=>{},n.token),cancel:()=>n.cancel()}},withProgress:(e,t=()=>{},n)=>{let r=$e(),i=_(0),a=e=>{i.set(Math.max(0,Math.min(100,e))),t(i.get())};return{task:A(n).Async(()=>e(a,r.token),e=>e,()=>{},r.token),cancel:()=>r.cancel(),currentProgress:()=>i.get()}}},A=r(et,tt),nt=Map,j=e=>{let t={values:new nt(e)},n=()=>Array.from(t.values.entries()).map(([e,t])=>te([e,t])),r=e=>j(new nt(t.values).set(e.toArray()[0],e.toArray()[1]).entries()),i=e=>{let n=new nt(t.values);return n.delete(e)?j(n.entries()):j(t.values.entries())},a=e=>{if(!e||typeof e.toArray!=`function`)return!1;let n=e.toArray();return t.values.get(n[0])===n[1]},o=()=>t.values.size,c=e=>j(Array.from(t.values.entries()).map(([t,n])=>[t,e(n)])),l=e=>j(j(t.values.entries()).toList().flatMap(e).toArray()),u=e=>{let n=[];for(let[r,i]of t.values.entries()){let t=e.get(r);t._tag===`Some`&&t.value&&n.push([r,t.value(i)])}return j(n)},ee=async e=>{let n=new nt;for(let[r,i]of t.values.entries()){let t=await e(i);for(let e of t.toList()){let[t,r]=e.toArray();n.set(t,r)}}return j(n.entries())},d=e=>C(n()).reduce(e),f=e=>C(n()).reduceRight(e),p=e=>t=>C(n()).foldLeft(e)(t),ne=e=>t=>C(n()).foldRight(e)(t),re=e=>m(t.values.get(e)),h=(e,n)=>m(t.values.get(e)).orElse(n),g=()=>t.values.size===0,ie=(e,n)=>m(t.values.get(e)).or(n),ae=(e,t)=>C(n()).fold(e,t),oe=()=>C(n()),ce=()=>se(n()),_=()=>`Map(${n().toString()})`,le=e=>g()?e.Empty():e.NonEmpty(n());return{[Symbol.toStringTag]:`FunctypeMap`,_tag:`Map`,[Symbol.iterator]:()=>t.values.entries(),add:r,remove:i,contains:a,get size(){return o()},map:c,ap:u,flatMap:l,flatMapAsync:ee,reduce:d,reduceRight:f,foldLeft:p,foldRight:ne,fold:ae,match:le,get:re,getOrElse:h,get isEmpty(){return g()},orElse:ie,toList:oe,toSet:ce,toString:_,toValue:()=>({_tag:`Map`,value:Array.from(t.values.entries())}),toJSON:()=>({"@functype":`Map`,_tag:`Map`,value:Array.from(t.values.entries())}),pipe:e=>e(Array.from(t.values.entries())),serialize:()=>s(`Map`,Array.from(t.values.entries()))}},rt=e=>j(e),it=j([]),at={empty:()=>it,of:(...e)=>j(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Map`)throw Error(`Map.fromJSON: expected @functype="Map", got ${JSON.stringify(t[`@functype`])}`);return ot(t.value)},fromYAML:e=>{let t=e.split(`
10
- `)[1]?.split(`: `)[1];return ot(t?JSON.parse(t):[])},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return at.fromJSON(t)}},ot=r(rt,at),st=(e,t,n)=>({_tag:`Leaf`,path:e,message:t,cause:n}),ct=(e,t)=>({_tag:`Composite`,path:e,children:t}),lt=e=>e._tag===`Leaf`,ut=e=>e._tag===`Composite`,dt=(e,t)=>e._tag===`Leaf`?t.Leaf(e):t.Composite(e),ft=(e,t)=>t._tag===`Leaf`?{...t,path:[e,...t.path]}:{...t,children:C(t.children.toArray().map(t=>ft(e,t)))},pt=e=>e._tag===`Leaf`?C([{path:e.path,message:e.message}]):C(e.children.toArray().flatMap(e=>pt(e).toArray())),mt=e=>pt(e).toArray().map(({path:e,message:t})=>`${ht(e)}: ${t}`).join(`
11
- `),ht=e=>e.length===0?`(root)`:e.reduce((e,t)=>t.startsWith(`[`)&&t.endsWith(`]`)?`${e}${t}`:e===``?t:`${e}.${t}`,``),M=r({},{leaf:st,composite:ct,isLeaf:lt,isComposite:ut,match:dt,prepend:ft,flatten:pt,format:mt}),gt=e=>typeof e==`string`?w(e):T(M.leaf([],`expected string`,{received:e})),_t=e=>typeof e==`number`?w(e):T(M.leaf([],`expected number`,{received:e})),vt=e=>typeof e==`boolean`?w(e):T(M.leaf([],`expected boolean`,{received:e})),yt=e=>w(e),bt=e=>t=>t==null?w(null):e(t),xt=e=>t=>t==null?w(p()):e(t).fold(e=>T(e),e=>w(d(e))),St={envelope:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected envelope object {ok|err}`,{received:t}));let n=t;return`ok`in n?e.ok(n.ok).fold(e=>T(M.prepend(`ok`,e)),e=>w(w(e))):`err`in n?e.err(n.err).fold(e=>T(M.prepend(`err`,e)),e=>w(T(e))):T(M.leaf([],`expected envelope to have 'ok' or 'err' key`,{received:t}))},discriminated:(e,t,n)=>r=>{if(typeof r!=`object`||!r)return T(M.leaf([],`expected object with '${e.tag}' tag`,{received:r}));let i=r[e.tag];return i===e.rightTag?n(r).fold(e=>T(e),e=>w(w(e))):i===e.leftTag?t(r).fold(e=>T(e),e=>w(T(e))):T(M.leaf([],`expected '${e.tag}' to be '${e.rightTag}' or '${e.leftTag}'`,{received:i}))}},Ct=e=>t=>{if(!Array.isArray(t))return T(M.leaf([],`expected array`,{received:t}));let n=[],r=[];return t.forEach((t,i)=>{e(t).fold(e=>{n.push(M.prepend(`[${i}]`,e))},e=>{r.push(e)})}),Dt(n,()=>C(r))},wt=e=>t=>{if(!Array.isArray(t))return T(M.leaf([],`expected array`,{received:t}));let n=[],r=[];return t.forEach((t,i)=>{e(t).fold(e=>{n.push(M.prepend(`[${i}]`,e))},e=>{r.push(e)})}),Dt(n,()=>r)},Tt=e=>t=>{if(typeof t!=`object`||!t||Array.isArray(t))return T(M.leaf([],`expected object (for Map)`,{received:t}));let n=t,r=[],i=[];for(let t of Object.keys(n))e(n[t]).fold(e=>{r.push(M.prepend(t,e))},e=>{i.push([t,e])});return Dt(r,()=>ot(i))},Et=e=>t=>{if(typeof t!=`object`||!t||Array.isArray(t))return T(M.leaf([],`expected object`,{received:t}));let n=t,r=[],i={};for(let t in e)e[t](n[t]).fold(e=>{r.push(M.prepend(t,e))},e=>{i[t]=e});return Dt(r,()=>i)},Dt=(e,t)=>e.length===0?w(t()):e.length===1?T(e[0]):T(M.composite([],C(e))),Ot={string:gt,number:_t,boolean:vt,unknown:yt,nullable:bt,option:xt,either:St,list:Ct,array:wt,map:Tt,object:Et},kt=(e,t)=>M.prepend(e,t),At=(e,t,n)=>M.prepend(e,M.prepend(`[${t}]`,n)),jt={option:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Option object`,{received:t}));let n=t;return n._tag===`None`?w(p()):n._tag===`Some`?e(n.value).fold(e=>T(kt(`value`,e)),e=>w(d(e))):T(M.leaf([`_tag`],`expected 'Some' or 'None'`,{received:n._tag}))},either:(e,t)=>n=>{if(typeof n!=`object`||!n)return T(M.leaf([],`expected tagged Either object`,{received:n}));let r=n;return r._tag===`Right`?t(r.value).fold(e=>T(kt(`value`,e)),e=>w(w(e))):r._tag===`Left`?e(r.value).fold(e=>T(kt(`value`,e)),e=>w(T(e))):T(M.leaf([`_tag`],`expected 'Left' or 'Right'`,{received:r._tag}))},try:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Try object`,{received:t}));let n=t;if(n._tag===`Success`)return e(n.value).fold(e=>T(kt(`value`,e)),e=>w(x.success(e)));if(n._tag===`Failure`){let e=typeof n.error==`string`?n.error:`unknown error`,t=Error(e);return typeof n.stack==`string`&&(t.stack=n.stack),w(x.failure(t))}return T(M.leaf([`_tag`],`expected 'Success' or 'Failure'`,{received:n._tag}))},list:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged List object`,{received:t}));let n=t;if(n._tag!==`List`)return T(M.leaf([`_tag`],`expected 'List'`,{received:n._tag}));if(!Array.isArray(n.value))return T(M.leaf([`value`],`expected array`,{received:n.value}));let r=[],i=[];return n.value.forEach((t,n)=>{e(t).fold(e=>{r.push(At(`value`,n,e))},e=>{i.push(e)})}),r.length===0?w(C(i)):r.length===1?T(r[0]):T(M.composite([],C(r)))},map:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Map object`,{received:t}));let n=t;if(n._tag!==`Map`)return T(M.leaf([`_tag`],`expected 'Map'`,{received:n._tag}));if(!Array.isArray(n.value))return T(M.leaf([`value`],`expected entries array`,{received:n.value}));let r=[],i=[];return n.value.forEach((t,n)=>{if(!Array.isArray(t)||t.length!==2){r.push(M.leaf([`value`,`[${n}]`],`expected [key, value] tuple`,{received:t}));return}let[a,o]=t;if(typeof a!=`string`){r.push(M.leaf([`value`,`[${n}]`,`[0]`],`expected string key`,{received:a}));return}e(o).fold(e=>{r.push(M.prepend(`value`,M.prepend(`[${n}]`,M.prepend(`[1]`,e))))},e=>{i.push([a,e])})}),r.length===0?w(ot(i)):r.length===1?T(r[0]):T(M.composite([],C(r)))},obj:e=>t=>{if(typeof t!=`object`||!t)return T(M.leaf([],`expected tagged Obj object`,{received:t}));let n=t;if(n._tag!==`Obj`)return T(M.leaf([`_tag`],`expected 'Obj'`,{received:n._tag}));if(typeof n.value!=`object`||n.value===null)return T(M.leaf([`value`],`expected object`,{received:n.value}));let r=n.value,i=[],a={};for(let t in e)e[t](r[t]).fold(e=>{i.push(M.prepend(`value`,M.prepend(t,e)))},e=>{a[t]=e});return i.length===0?w(a):i.length===1?T(i[0]):T(M.composite([],C(i)))}},Mt=r({},{...Ot,tagged:jt});function Nt(e){if(!e||typeof e!=`object`||!(`_tag`in e))return`unknown`;switch(e._tag){case`Some`:case`None`:return`Option`;case`Left`:case`Right`:return`Either`;case`List`:return`List`;case`Success`:case`Failure`:return`Try`;default:return`unknown`}}const Pt={Option:{of:e=>m(e),empty:()=>m.none()},Either:{of:e=>w(e),empty:e=>T(e)},List:{of:e=>C([e]),empty:()=>C([])},Try:{of:e=>x(()=>e),empty:e=>x(()=>{throw e??Error(`Try failed`)})}};function Ft(e){let t=e(),n=null,r;function i(a){let o=t.next(a);if(o.done)return r?r.of(o.value):C([o.value]);let s=o.value;if(typeof s!=`object`||!s)throw Error(`Do-notation error: All yielded values must be monadic. Use yield* $(Option(value)), yield* $(Right(value)), etc. Raw values should be assigned directly without yielding.`);if(!n&&`_tag`in s&&(n=Nt(s),n!==`unknown`&&n in Pt&&(r=Pt[n]),n===`List`))return It(e);if(`doUnwrap`in s){let e=s.doUnwrap();if(!e.ok){if(!r)return C([]);if(!e.empty&&`error`in e){if(n===`Either`)return r.empty(e.error);if(n===`Try`)return r.empty(e.error instanceof Error?e.error:Error(String(e.error)))}return r.empty()}return i(e.value)}throw Error(`Do-notation error: All yielded values must be monadic. Use yield* $(Option(value)), yield* $(Right(value)), etc. Raw values should be assigned directly without yielding.`)}return i()}function It(e){function t(e){if(typeof e!=`object`||!e||!(`doUnwrap`in e))return[e];let t=e;if(`toArray`in t){let e=t.toArray();return e.length===0?[]:e}let n=t.doUnwrap();return n.ok?[n.value]:[]}function n(r){let i=e(),a=[],o=[],s=0;function c(e){let l=i.next(e);if(l.done){a.push(l.value);return}if(s<r.length){let e=r[s];o.push(e),s++,c(e);return}let u=t(l.value);if(u.length!==0)if(u.length>1){let e=u.flatMap(e=>n([...o,e]));a.push(...e)}else o.push(u[0]),s++,c(u[0])}return c(void 0),a}return C(n([]))}async function Lt(e){let t=e(),n=null,r;async function i(e){let a=await t.next(e);if(a.done)return r?r.of(a.value):C([a.value]);let o=await Promise.resolve(a.value);if(typeof o!=`object`||!o)return i(o);if(!n&&`_tag`in o&&(n=Nt(o),n!==`unknown`&&n in Pt&&(r=Pt[n])),`doUnwrap`in o){let e=o.doUnwrap();if(!e.ok){if(!r)return C([]);if(!e.empty&&`error`in e){if(n===`Either`)return r.empty(e.error);if(n===`Try`)return r.empty(e.error instanceof Error?e.error:Error(String(e.error)))}return r.empty()}return i(e.value)}return i(o)}return i()}function Rt(e){return typeof e==`object`&&!!e&&`doUnwrap`in e&&typeof e.doUnwrap==`function`}function zt(e){let t=e.doUnwrap();if(t.ok)return t.value;throw`error`in t?t.error:Error(`Cannot unwrap empty monad`)}function*Bt(e){return yield e}const Vt=(e=`Cannot unwrap None in Do-notation`)=>{let t=Error(e),n=Object.create(Error.prototype);return n.message=t.message,n.stack=t.stack,n.name=`NoneError`,n},Ht=(e,t=`Cannot unwrap Left in Do-notation`)=>{let n=Error(t),r=Object.create(Error.prototype);return r.message=n.message,r.stack=n.stack,r.name=`LeftError`,r.value=e,r},Ut=(e=`Cannot unwrap empty List in Do-notation`)=>{let t=Error(e),n=Object.create(Error.prototype);return n.message=t.message,n.stack=t.stack,n.name=`EmptyListError`,n},Wt=(e,t=`Cannot unwrap Failure in Do-notation`)=>{let n=Error(t),r=Object.create(Error.prototype);return r.message=n.message,r.stack=n.stack,r.name=`FailureError`,r.cause=e,r},Gt={includeTasks:!0,includeStackTrace:!1,separator:`
12
- `,includeData:!1,maxStackFrames:3,title:`Error`,colors:!1};function Kt(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return`${n.toString()}n`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular Reference]`;t.add(n)}return e===`stack`&&typeof n==`string`?qt(n):n},2)}function qt(e){if(e===void 0||e===``)return``;let t=e.split(`
13
- `);return[t[0],...t.slice(1).map(e=>e.trim())].join(`
14
- `)}function Jt(e,t){let n={...Gt,...t},r=e instanceof Error?e:Xe.apply(e),i=A?.getErrorChain?A.getErrorChain(r):[r],a=`${n.colors?`\x1b[31m${n.title}:\x1b[0m ${r.message}`:`${n.title}: ${r.message}`}\n\n${i.map((e,t)=>{let r=` `.repeat(t),i=t>0?`↳ `:``,{taskInfo:a}=e,o=`${r}${i}${n.includeTasks&&a?.name?n.colors?`\x1b[36m[${a.name}]\x1b[0m `:`[${a.name}] `:``}${e.message}`;if(n.includeStackTrace&&e.stack){let t=qt(e.stack).split(`
15
- `).slice(1),i=n.maxStackFrames??Gt.maxStackFrames??3,a=t.slice(0,i).map(e=>`${r} ${n.colors?`\x1B[90m`:``}${e}${n.colors?`\x1B[0m`:``}`).join(`
16
- `);o+=`\n${a}`,t.length>i&&(o+=`\n${r} ${n.colors?`\x1B[90m`:``}...${t.length-i} more stack frames${n.colors?`\x1B[0m`:``}`)}return o}).join(n.separator)}`;if(n.includeData){let{data:e}=r;if(e){let t=n.colors?`\n\n\x1b[33mContext:\x1b[0m\n${Kt(e)}`:`\n\nContext:\n${Kt(e)}`;a+=t}}return a}function Yt(){return function(e){if(!e)return e;let t=e instanceof Error?e:Error(String(e)),n={message:t.message,name:t.name||`Error`,stack:t.stack?qt(t.stack):void 0};if(t.taskInfo&&(n.taskInfo=t.taskInfo),t.data&&(n.data=t.data),typeof A?.getErrorChain==`function`)try{let e=A.getErrorChain(t);e.length>1&&(n.errorChain=A.formatErrorChain(t,{includeTasks:!0}),n.structuredErrorChain=e.map(e=>({message:e.message,name:e.name,taskInfo:e.taskInfo,stack:e.stack?qt(e.stack):void 0})))}catch{}return Object.getOwnPropertyNames(t).forEach(e=>{n[e]||(n[e]=t[e])}),n}}const Xt=e=>{let t=Error(e);return t.name=`ParseError`,t},N=(e,t,r,i)=>n(Xe.apply(t,r,{name:e,description:t}),{code:e,message:t,status:Zt(e),context:r,timestamp:new Date().toISOString(),traceId:i?.traceId}),Zt=e=>({VALIDATION_FAILED:400,BAD_REQUEST:400,AUTH_REQUIRED:401,PERMISSION_DENIED:403,NOT_FOUND:404,TIMEOUT:408,CONFLICT:409,RATE_LIMITED:429,INTERNAL_ERROR:500,NETWORK_ERROR:503})[e],P=Object.assign(N,{validation:(e,t,n)=>N(`VALIDATION_FAILED`,`Validation failed: ${e} ${n}`,{field:e,value:t,rule:n}),network:(e,t,n)=>N(`NETWORK_ERROR`,`Network error: ${t} ${e}${n?` (${n})`:``}`,{url:e,method:t,statusCode:n}),auth:(e,t)=>N(`AUTH_REQUIRED`,`Authentication required: ${e}${t?` (role: ${t})`:``}`,{resource:e,requiredRole:t}),notFound:(e,t)=>N(`NOT_FOUND`,`Not found: ${e} with id ${t}`,{resource:e,id:t}),permission:(e,t,n)=>N(`PERMISSION_DENIED`,`Permission denied: cannot ${e} ${t}`,{action:e,resource:t,userId:n}),rateLimit:(e,t,n)=>N(`RATE_LIMITED`,`Rate limit exceeded: ${e} requests per ${t}`,{limit:e,window:t,retryAfter:n}),internal:e=>N(`INTERNAL_ERROR`,`Internal server error: ${e}`,{errorId:e,timestamp:new Date().toISOString()}),badRequest:(e,t)=>N(`BAD_REQUEST`,`Bad request: ${e}`,{reason:e,expected:t}),conflict:(e,t)=>N(`CONFLICT`,`Conflict: ${e} already exists with value ${t}`,{resource:e,conflictingValue:t}),timeout:(e,t)=>N(`TIMEOUT`,`Request timeout: ${t} exceeded ${e}ms`,{duration:e,operation:t}),isTypedError:e=>typeof e==`object`&&!!e&&`code`in e&&`message`in e&&`status`in e&&`context`in e&&`_tag`in e&&e._tag===`Throwable`,hasCode:(e,t)=>e.code===t}),F={rule:e=>t=>{if(e===`email`)return typeof t!=`string`||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?T(P.validation(`value`,t,`must be a valid email`)):w(t);if(e===`url`)try{return new URL(String(t)),w(t)}catch{return T(P.validation(`value`,t,`must be a valid URL`))}if(e===`uuid`)return typeof t!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)?T(P.validation(`value`,t,`must be a valid UUID`)):w(t);if(e===`required`)return t==null||t===``?T(P.validation(`value`,t,`is required`)):w(t);if(e===`numeric`)return typeof t!=`number`&&!/^\d+$/.test(String(t))?T(P.validation(`value`,t,`must be numeric`)):w(t);if(e===`alpha`)return typeof t!=`string`||!/^[a-zA-Z]+$/.test(t)?T(P.validation(`value`,t,`must contain only letters`)):w(t);if(e===`alphanumeric`)return typeof t!=`string`||!/^[a-zA-Z0-9]+$/.test(t)?T(P.validation(`value`,t,`must be alphanumeric`)):w(t);if(e.startsWith(`min:`)){let n=Number(e.split(`:`)[1]),r=Number(t);return isNaN(r)||r<n?T(P.validation(`value`,t,`must be at least ${n}`)):w(t)}if(e.startsWith(`max:`)){let n=Number(e.split(`:`)[1]),r=Number(t);return isNaN(r)||r>n?T(P.validation(`value`,t,`must be at most ${n}`)):w(t)}if(e.startsWith(`minLength:`)){let n=Number(e.split(`:`)[1]);return String(t).length<n?T(P.validation(`value`,t,`must be at least ${n} characters`)):w(t)}if(e.startsWith(`maxLength:`)){let n=Number(e.split(`:`)[1]);return String(t).length>n?T(P.validation(`value`,t,`must be at most ${n} characters`)):w(t)}if(e.startsWith(`pattern:`)){let n=e.substring(8);return new RegExp(n).test(String(t))?w(t):T(P.validation(`value`,t,`must match pattern ${n}`))}if(e.startsWith(`in:`)){let n=e.substring(3).split(`,`);return n.includes(String(t))?w(t):T(P.validation(`value`,t,`must be one of: ${n.join(`, `)}`))}if(e.startsWith(`notIn:`)){let n=e.substring(6).split(`,`);return n.includes(String(t))?T(P.validation(`value`,t,`must not be one of: ${n.join(`, `)}`)):w(t)}if(e===`date`){let e=new Date(String(t));return isNaN(e.getTime())?T(P.validation(`value`,t,`must be a valid date`)):w(t)}if(e===`future`){let e=new Date(String(t));return isNaN(e.getTime())||e<=new Date?T(P.validation(`value`,t,`must be a future date`)):w(t)}if(e===`past`){let e=new Date(String(t));return isNaN(e.getTime())||e>=new Date?T(P.validation(`value`,t,`must be a past date`)):w(t)}return w(t)},combine:(...e)=>t=>{for(let n of e){let e=n(t);if(e.isLeft())return e}return w(t)},custom:(e,t)=>n=>e(n)?w(n):T(P.validation(`value`,n,t)),form:(e,t)=>{let n=[],r={};for(let[i,a]of Object.entries(e)){let e=t[i],o=a(e);if(o.isLeft()){let t=o.fold(e=>e,()=>{throw Error(`Should not be left`)}),r=P.validation(i,e,t.context.rule);n.push(r)}else r[i]=o.orThrow()}return n.length>0?T(C(n)):w(r)}},Qt={...F,validators:{email:F.rule(`email`),url:F.rule(`url`),uuid:F.rule(`uuid`),required:F.rule(`required`),numeric:F.rule(`numeric`),positiveNumber:F.combine(F.rule(`numeric`),F.rule(`min:0`)),nonEmptyString:F.combine(F.rule(`required`),F.custom(e=>typeof e==`string`&&e.trim().length>0,`must not be empty`))}},$t=n(F.rule,Qt);function en(e){return typeof e==`object`&&!!e&&`orThrow`in e&&typeof e.orThrow==`function`}function tn(e){return en(e)&&`orElse`in e&&typeof e.orElse==`function`&&`or`in e&&typeof e.or==`function`&&`orNull`in e&&typeof e.orNull==`function`&&`orUndefined`in e&&typeof e.orUndefined==`function`}const nn=e=>({_tag:`Context`,services:e,get(t){let n=e.get(t.id);return n===void 0?p():d(n)},unsafeGet(t){let n=e.get(t.id);if(n===void 0)throw Error(`Service not found: ${t.id}`);return n},has(t){return e.has(t.id)},add(t,n){let r=new Map(e);return r.set(t.id,n),nn(r)},merge(t){let n=new Map(e);for(let[e,r]of t.services)n.set(e,r);return nn(n)},get size(){return e.size},toString(){return`Context(${Array.from(e.keys()).join(`, `)})`}}),I={empty:()=>nn(new Map),make:(e,t)=>{let n=new Map;return n.set(e.id,t),nn(n)},isContext:e=>typeof e==`object`&&!!e&&e._tag===`Context`},L=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Success`,isSuccess(){return!0},isFailure(){return!1},isInterrupted(){return!1},map(t){return L(t(e))},mapError(t){return L(e)},mapBoth(t,n){return L(n(e))},flatMap(t){return t(e)},fold(t,n,r){return n(e)},match(t){return t.Success(e)},orThrow(){return e},orElse(t){return e},toOption(){return d(e)},toEither(){return w(e)},toValue(){return{_tag:`Success`,value:e}},toString(){return`Exit.Success(${c(e)})`},toJSON(){return{_tag:`Success`,value:e}}}),rn=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Failure`,isSuccess(){return!1},isFailure(){return!0},isInterrupted(){return!1},map(t){return rn(e)},mapError(t){return rn(t(e))},mapBoth(t,n){return rn(t(e))},flatMap(t){return rn(e)},fold(t,n,r){return t(e)},match(t){return t.Failure(e)},orThrow(){throw e},orElse(e){return e},toOption(){return p()},toEither(){return T(e)},toValue(){return{_tag:`Failure`,error:e}},toString(){return`Exit.Failure(${c(e)})`},toJSON(){return{_tag:`Failure`,error:e}}}),an=e=>({[Symbol.toStringTag]:`Exit`,_tag:`Interrupted`,isSuccess(){return!1},isFailure(){return!1},isInterrupted(){return!0},map(t){return an(e)},mapError(t){return an(e)},mapBoth(t,n){return an(e)},flatMap(t){return an(e)},fold(t,n,r){if(r)return r(e);throw Error(`Effect was interrupted: ${e}`)},match(t){return t.Interrupted(e)},orThrow(){throw Error(`Effect was interrupted: ${e}`)},orElse(e){return e},toOption(){return p()},toEither(){throw Error(`Cannot convert Interrupted Exit to Either: ${e}`)},toValue(){return{_tag:`Interrupted`,fiberId:e}},toString(){return`Exit.Interrupted(${e})`},toJSON(){return{_tag:`Interrupted`,fiberId:e}}}),R=r(e=>L(e),{succeed:e=>L(e),fail:e=>rn(e),interrupt:e=>an(e),interrupted:()=>an(`interrupted`),isSuccess:e=>e.isSuccess(),isFailure:e=>e.isFailure(),isInterrupted:e=>e.isInterrupted(),fromEither:e=>e.isRight()?L(e.value):rn(e.value),fromOption:(e,t)=>e.isSome()?L(e.value):rn(t()),zip:(e,t)=>e.isInterrupted()?e:t.isInterrupted()?t:e.isFailure()?e:t.isFailure()?t:L([e.orThrow(),t.orThrow()]),all:e=>{let t=[];for(let n of e){if(n.isInterrupted()||n.isFailure())return n;t.push(n.orThrow())}return L(t)}}),z=e=>e;var on=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},sn=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}};const cn=Symbol.for(`functype/IO/effect`),B=e=>e[cn],V=e=>{let t={[Symbol.toStringTag]:`IO`,[cn]:e,map(e){return V(z({_tag:`Map`,effect:t,f:e}))},flatMap(e){return V(z({_tag:`FlatMap`,effect:t,f:e}))},tap(e){return t.map(t=>(e(t),t))},tapEffect(e){return t.flatMap(t=>e(t).map(()=>t))},mapError(e){return V(z({_tag:`MapError`,effect:t,f:e}))},tapError(e){return t.mapError(t=>(e(t),t))},recover(e){return V(z({_tag:`Recover`,effect:t,fallback:e}))},recoverWith(e){return V(z({_tag:`RecoverWith`,effect:t,f:e}))},fold(e,n){return V(z({_tag:`Fold`,effect:t,onFailure:e,onSuccess:n}))},match(e){return t.fold(e.failure,e.success)},catchTag(e,n){return V(z({_tag:`RecoverWith`,effect:t,f:t=>typeof t==`object`&&t&&`_tag`in t&&t._tag===e?z(n(t)):z(W.fail(t))}))},catchAll(e){return t.recoverWith(e)},retry(e){return e<=0?t:t.recoverWith(()=>t.retry(e-1))},retryWithDelay(e,n){return e<=0?t:t.recoverWith(()=>W.sleep(n).flatMap(()=>t.retryWithDelay(e-1,n)))},retryWhile(e){let n=(r,i)=>t.recoverWith(t=>{if(r<=0||!e.while(t,i))return z(W.fail(t));let a=n(r-1,i+1);return e.delayMs===void 0?a:z(W.sleep(e.delayMs).flatMap(()=>a))});return n(e.n,1)},retryWithBackoff(e){let n=e.factor??2,r=e.maxMs??3e4,i=e.jitter??!0,a=e.while??(()=>!0),o=(s,c)=>t.recoverWith(t=>{if(s<=0||!a(t,c))return z(W.fail(t));let l=Math.min(r,e.baseMs*n**(c-1)),u=i?l*(.5+Math.random()*.5):l,ee=o(s-1,c+1);return z(W.sleep(u).flatMap(()=>ee))});return o(e.n,1)},zipRight(e){return t.flatMap(()=>e)},zipLeft(e){return t.flatMap(t=>e.map(()=>t))},zip(e){return t.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return V(z({_tag:`ProvideContext`,effect:t,context:e}))},provideService(e,n){return V(z({_tag:`ProvideContext`,effect:t,context:I.make(e,n)}))},provideLayer(e){return z(z(W.async(async()=>{let t=I.empty();return await e.build(z(t))})).flatMap(e=>V(z({_tag:`ProvideContext`,effect:t,context:e}))))},async run(){let e=await U(B(this));return e.isSuccess()?w(e.orThrow()):T(e.isFailure()?e.toValue().error:new sn)},async runOrThrow(){let e=await U(B(this));if(e.isSuccess())return e.orThrow();throw e.isFailure()?e.toValue().error:new sn},runSync(){try{return w(H(B(this)))}catch(e){return T(e)}},runSyncOrThrow(){return H(B(this))},async runExit(){return U(B(this))},async runOption(){let e=await U(B(this));return e.isSuccess()?d(e.orThrow()):p()},async runTry(){let e=await U(B(this));if(e.isSuccess())return z(x(()=>e.orThrow()));let t=e.isFailure()?e.toValue().error:Error(`Effect was interrupted`);return z(x(()=>{throw t}))},pipe(e){return e(t)},delay(e){return z(W.async(()=>new Promise(t=>setTimeout(t,e))).flatMap(()=>t))},timeout(e){return V(z({_tag:`Timeout`,effect:t,duration:e}))},timeoutTo(e,n){return z(t.timeout(e).recover(z(n)))},toString(){return`IO(${c(e._tag)})`},toJSON(){return{_tag:`IO`,effect:e._tag}},*[Symbol.iterator](){return yield t}};return t},H=(e,t=I.empty())=>{switch(e._tag){case`Succeed`:return e.value;case`Fail`:throw e.error;case`Die`:throw e.defect;case`Sync`:return e.thunk();case`Async`:throw Error(`Cannot run async effect synchronously`);case`Auto`:{let t=e.thunk();if(t instanceof Promise)throw Error(`Cannot run async effect synchronously`);return t}case`Map`:{let n=H(B(e.effect),t);return e.f(n)}case`FlatMap`:{let n=H(B(e.effect),t);return H(B(e.f(n)),t)}case`MapError`:try{return H(B(e.effect),t)}catch(t){throw e.f(t)}case`Recover`:try{return H(B(e.effect),t)}catch{return e.fallback}case`RecoverWith`:try{return z(H(B(e.effect),t))}catch(n){return H(B(e.f(n)),t)}case`Fold`:try{let n=H(B(e.effect),t);return e.onSuccess(n)}catch(t){return e.onFailure(t)}case`Service`:{let n=t.get(e.tag);if(n.isNone())throw Error(`Service not found: ${e.tag.id}`);return n.orThrow()}case`ProvideContext`:{let n=t.merge(e.context);return H(B(e.effect),n)}case`Interrupt`:throw new sn;case`Bracket`:{let n=H(B(e.acquire),t);try{return H(B(e.use(n)),t)}finally{H(B(e.release(n)),t)}}case`BracketExit`:{let n=H(B(e.acquire),t),r;try{let i=H(B(e.use(n)),t);return r=z(R.succeed(i)),i}catch(e){throw r=z(R.fail(e)),e}finally{H(B(e.release(n,r)),t)}}case`Race`:throw Error(`Cannot run race effect synchronously`);case`Timeout`:throw Error(`Cannot run timeout effect synchronously`)}},U=async(e,t=I.empty())=>{try{switch(e._tag){case`Succeed`:return z(R.succeed(e.value));case`Fail`:return z(R.fail(e.error));case`Die`:throw e.defect;case`Sync`:return z(R.succeed(e.thunk()));case`Async`:{let t=await e.thunk();return z(R.succeed(t))}case`Auto`:{let t=e.thunk();return t instanceof Promise?z(R.succeed(await t)):z(R.succeed(t))}case`Map`:{let n=await U(B(e.effect),t);return n.isSuccess()?z(R.succeed(e.f(n.orThrow()))):z(n)}case`FlatMap`:{let n=await U(B(e.effect),t);return n.isSuccess()?U(B(e.f(n.orThrow())),t):z(n)}case`MapError`:{let n=await U(B(e.effect),t);return n.isSuccess()?z(n):n.isFailure()?z(R.fail(e.f(n.toValue().error))):z(n)}case`Recover`:{let n=await U(B(e.effect),t);return n.isSuccess()?n:R.succeed(e.fallback)}case`RecoverWith`:{let n=await U(B(e.effect),t);return n.isSuccess()?z(n):n.isFailure()?U(B(e.f(n.toValue().error)),t):z(n)}case`Fold`:{let n=await U(B(e.effect),t);return n.isSuccess()?R.succeed(e.onSuccess(n.orThrow())):n.isFailure()?R.succeed(e.onFailure(n.toValue().error)):n}case`Service`:{let n=t.get(e.tag);return n.isNone()?R.fail(Error(`Service not found: ${e.tag.id}`)):R.succeed(n.orThrow())}case`ProvideContext`:{let n=t.merge(e.context);return U(B(e.effect),n)}case`Interrupt`:return R.interrupted();case`Bracket`:{let n=await U(B(e.acquire),t);if(!n.isSuccess())return n;let r=n.orThrow();try{return await U(B(e.use(r)),t)}finally{await U(B(e.release(r)),t)}}case`BracketExit`:{let n=await U(B(e.acquire),t);if(!n.isSuccess())return n;let r=n.orThrow(),i=await U(B(e.use(r)),t);return await U(B(e.release(r,i)),t),i}case`Race`:return e.effects.length===0?R.fail(Error(`No effects to race`)):await Promise.race(e.effects.map(e=>U(B(e),t)));case`Timeout`:{let n=new Promise(t=>setTimeout(()=>t(R.fail(new on(e.duration))),e.duration)),r=U(B(e.effect),t);return Promise.race([r,n])}}}catch(e){return R.fail(e)}},W={sync:e=>V({_tag:`Sync`,thunk:e}),succeed:e=>V({_tag:`Succeed`,value:e}),fail:e=>V({_tag:`Fail`,error:e}),die:e=>V({_tag:`Die`,defect:e}),async:e=>V(z({_tag:`Async`,thunk:e})),tryPromise:e=>V({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,t)=>W.sync(()=>{try{return e()}catch(e){throw t(e)}}),liftSync:e=>(...t)=>W.sync(()=>e(...t)),liftPromise:e=>(...t)=>W.async(()=>e(...t)),fromEither:e=>z(e.isRight()?W.succeed(e.value):W.fail(e.value)),fromOption:e=>z(e.isSome()?W.succeed(e.value):W.fail(void 0)),fromOptionOrFail:(e,t)=>z(e.isSome()?W.succeed(e.value):W.fail(t())),fromTry:e=>z(e.isSuccess()?W.succeed(e.orThrow()):W.fail(e.error)),fromResult:e=>z(e.error?W.fail(e.error):W.succeed(m(e.data))),tryAsync:(e,t,n)=>n?.aborted?z(W.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):W.async(()=>e(n)).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return W.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>W.fromResult({data:e[r],error:e[i]}))},service:e=>V({_tag:`Service`,tag:e}),serviceWith:(e,t)=>W.service(e).map(t),serviceWithIO:(e,t)=>W.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return z(V({_tag:`Auto`,thunk:()=>t({})}));let r=z(W.succeed({}));return z(n.reduce((e,[t,n])=>z(e.flatMap(e=>W.service(n).map(n=>({...e,[t]:n})))),r).flatMap(e=>V({_tag:`Auto`,thunk:()=>t(e)})))},all:e=>{if(e.length===0)return z(W.succeed([]));let t=z(W.succeed([]));return z(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),t))},firstSuccessOf:e=>e.length===0?z(W.fail(Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>z(W.async(()=>new Promise(t=>setTimeout(t,e)))),never:()=>z(W.async(()=>new Promise(()=>{}))),get unit(){return z(V({_tag:`Succeed`,value:void 0}))},fromNullable:e=>z(e==null?W.fail(void 0):W.succeed(e)),interrupt:()=>V({_tag:`Interrupt`}),bracket:(e,t,n)=>V({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>W.bracket(e,t,n),bracketExit:(e,t,n)=>V({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>V({_tag:`Race`,effects:e}),any:e=>e.length===0?z(W.fail(Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),forEach:(e,t)=>{if(e.length===0)return z(W.succeed([]));let n=z(W.succeed([]));return z(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),n))},forEachPar:(e,t)=>W.forEach(e,t),timeout:(e,t)=>V(z({_tag:`Timeout`,effect:e,duration:t})),gen:e=>z(W.sync(()=>{let t=e(),n=e=>{let r=t.next(e);return r.done?z(W.succeed(r.value)):z(r.value.flatMap(e=>n(e)))};return n(void 0)}).flatMap(e=>e)),get Do(){return ln(W.succeed({}))}},ln=e=>({effect:e,bind(t,n){return ln(e.flatMap(e=>n(e).map(n=>({...e,[t]:n}))))},let(t,n){return ln(e.map(e=>({...e,[t]:n(e)})))},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return ln(e.tap(t))},tapEffect(t){return ln(e.tapEffect(t))},done(){return e}}),G=r(e=>V(z({_tag:`Auto`,thunk:e})),W),K=(e,t)=>({_tag:`Layer`,build:e,provideToAndMerge(t){return K(async n=>{let r=await e(n),i=n.merge(r),a=await t.build(i);return r.merge(a)})},merge(t){return K(async n=>{let[r,i]=await Promise.all([e(n),t.build(n)]);return r.merge(i)})},map(t){return K(async n=>t(await e(n)))},toString(){return`Layer(${t??`anonymous`})`}}),un={succeed:(e,t)=>K(()=>Promise.resolve(I.make(e,t)),e.id),effect:(e,t)=>K(async()=>{let n=await t();return I.make(e,n)},e.id),sync:(e,t)=>K(()=>Promise.resolve(I.make(e,t())),e.id),fromService:(e,t,n)=>K(r=>{let i=r.unsafeGet(t);return Promise.resolve(I.make(e,n(i)))},e.id),fromServiceEffect:(e,t,n)=>K(async r=>{let i=await n(r.unsafeGet(t));return I.make(e,i)},e.id),fromContext:e=>K(()=>Promise.resolve(e)),empty:()=>K(()=>Promise.resolve(I.empty()),`empty`),mergeAll:(...e)=>K(async t=>(await Promise.all(e.map(e=>e.build(t)))).reduce((e,t)=>e.merge(t),I.empty()))},dn=e=>({id:e,_tag:`Tag`,toString(){return`Tag(${e})`}}),fn=()=>{let e=0,t=[],n=async()=>{for(t.sort((e,t)=>e.time-t.time);t.length>0&&t[0]!==void 0&&t[0].time<=e;){let e=t.shift();e&&(e.resolve(),await Promise.resolve())}};return{get currentTime(){return e},async advance(t){e+=t,await n()},async setTime(t){e=t,await n()},async runAll(){if(t.length>0){let n=t[t.length-1];n&&(e=n.time)}await n()},get pendingCount(){return t.length},sleep(n){return new Promise(r=>{t.push({time:e+n,resolve:r})})}}},pn=dn(`TestClock`),mn={make:fn,tag:pn,test:async e=>e(fn()),get:G.service(pn),advance:e=>G.serviceWithIO(pn,t=>G.async(()=>t.advance(e))),setTime:e=>G.serviceWithIO(pn,t=>G.async(()=>t.setTime(e))),runAll:G.serviceWithIO(pn,e=>G.async(()=>e.runAll())),context:()=>{let e=fn();return{clock:e,context:I.make(pn,e)}}},hn={make:()=>{let e=fn(),t=I.empty(),n={get context(){return t},get clock(){return e},withService(e,r){return t=t.add(e,r),n},async run(e){return e.provideContext(t).runOrThrow()}};return n},withClock:()=>{let e=fn();return hn.make().withService(pn,e)}},gn=dn(`HttpClient`),_n={},vn=r({},{networkError:(e,t,n)=>({_tag:`NetworkError`,url:e,method:t,cause:n}),httpStatusError:(e,t,n,r,i)=>({_tag:`HttpStatusError`,url:e,method:t,status:n,statusText:r,body:i}),decodeError:(e,t,n,r)=>({_tag:`DecodeError`,url:e,method:t,body:n,cause:r}),isNetworkError:e=>e._tag===`NetworkError`,isHttpStatusError:e=>e._tag===`HttpStatusError`,isDecodeError:e=>e._tag===`DecodeError`,match:(e,t)=>{switch(e._tag){case`NetworkError`:return t.NetworkError(e);case`HttpStatusError`:return t.HttpStatusError(e);case`DecodeError`:return t.DecodeError(e)}}}),yn=(e,t)=>!e||t.startsWith(`http://`)||t.startsWith(`https://`)?t:`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`,bn=(e,t)=>{let n=new URLSearchParams;for(let e of Object.keys(t)){let r=t[e];if(r!=null)if(Array.isArray(r))for(let t of r)n.append(e,String(t));else n.append(e,String(r))}let r=n.toString();return r?`${e}${e.includes(`?`)?`&`:`?`}${r}`:e},xn=(e,t,n)=>{let r=yn(e,t);return n?bn(r,n):r},Sn=(e,t)=>e[Symbol.toStringTag]===t,q=(e,t)=>{if(typeof e!=`object`||!e||e instanceof Date||e instanceof RegExp||typeof Buffer<`u`&&e instanceof Buffer)return e;if(Sn(e,`Option`)){let n=e;return t===`tagged`?n._tag===`None`?{_tag:`None`,value:null}:{_tag:`Some`,value:q(n.value,t)}:n._tag===`None`?null:q(n.value,t)}if(Sn(e,`Either`)){let n=e;if(t===`tagged`)return{_tag:n._tag,value:q(n.value,t)};if(n._tag===`Left`)throw Error(`Cannot serialize a Left in a request body — Either's failure path should not cross the wire as data. Resolve the Left before sending, or omit the field. (Left value: ${JSON.stringify(n.value)})`);return q(n.value,t)}if(Sn(e,`Try`)){let n=e;if(t===`tagged`){if(n._tag===`Failure`){let e=n.error??Error(`unknown`);return{_tag:`Failure`,error:e.message,stack:e.stack}}return{_tag:`Success`,value:q(n.value,t)}}if(n._tag===`Failure`)throw n.error??Error(`Cannot serialize a Try Failure in a request body`);return q(n.value,t)}if(Sn(e,`List`)){let n=e.toArray().map(e=>q(e,t));return t===`tagged`?{_tag:`List`,value:n}:n}if(Sn(e,`FunctypeMap`)){let n=e.toValue().value;if(t===`tagged`)return{_tag:`Map`,value:n.map(([e,n])=>[e,q(n,t)])};let r={};for(let[e,i]of n){if(typeof e!=`string`)throw Error(`Cannot serialize Map with non-string keys to JSON (key: ${String(e)})`);r[e]=q(i,t)}return r}if(Array.isArray(e))return e.map(e=>q(e,t));let n={};for(let r of Object.keys(e))n[r]=q(e[r],t);return n},Cn=(e,t)=>{if(e==null)return{serialized:void 0,contentType:void 0};if(typeof e==`string`)return{serialized:e,contentType:void 0};if(typeof e==`object`||Array.isArray(e)){let n=q(e,t?`primitive`:`tagged`);return{serialized:JSON.stringify(n),contentType:`application/json`}}return{serialized:String(e),contentType:void 0}},wn=e=>{let t=e.get(`content-type`)??``;return t.includes(`application/json`)?`json`:t.startsWith(`text/`)?`text`:`raw`},Tn=async(e,t,n,r,i,a)=>{let o=t??wn(e.headers),s,c={};switch(o){case`json`:{let t=await e.text();c.value=t;try{s=JSON.parse(t)}catch(e){throw vn.decodeError(n,r,t,e)}break}case`text`:s=await e.text(),c.value=s;break;case`blob`:s=await e.blob();break;case`arrayBuffer`:s=await e.arrayBuffer();break;case`raw`:s=e;break}let l;if(i){let e=i(s);if(e.isLeft()){let t=c.value??(typeof s==`string`?s:JSON.stringify(s));throw vn.decodeError(n,r,t,e.value)}l=e.value}else if(a)try{l=a(s)}catch(e){let t=c.value??(typeof s==`string`?s:JSON.stringify(s));throw vn.decodeError(n,r,t,e)}else l=s;return{data:l,status:e.status,statusText:e.statusText,headers:e.headers}},J=(e,t)=>{let n={url:xn(e.baseUrl,t.url,t.params),method:t.method,headers:{...e.defaultHeaders,...t.headers},body:t.body,signal:t.signal,parseAs:t.parseAs,flatten:t.flatten};return(e.beforeRequest?e.beforeRequest(n):G.succeed(n)).flatMap(n=>{let r=n.flatten??!0,i=(()=>{try{return{ok:!0,value:Cn(n.body,r)}}catch(e){return{ok:!1,cause:e}}})();if(!i.ok)return G.fail(vn.networkError(n.url,n.method,i.cause));let{serialized:a,contentType:o}=i.value,s={...n.headers,...o?{"Content-Type":o}:{}},c=G.tryAsync(r=>(e.fetch??globalThis.fetch)(n.url,{method:n.method,headers:s,body:a,signal:n.signal??r}).then(async e=>{if(!e.ok){let t=await e.text().catch(()=>``);throw vn.httpStatusError(n.url,n.method,e.status,e.statusText,t)}return Tn(e,n.parseAs,n.url,n.method,t.decode,t.validate)}),e=>typeof e==`object`&&e&&`_tag`in e?e:vn.networkError(n.url,n.method,e));return e.afterResponse?c.flatMap(t=>e.afterResponse(t).map(e=>e)):c})},En=e=>J(_n,e),Dn=r({},{request:En,get:(e,t)=>En({...t,url:e,method:`GET`}),post:(e,t)=>En({...t,url:e,method:`POST`}),put:(e,t)=>En({...t,url:e,method:`PUT`}),patch:(e,t)=>En({...t,url:e,method:`PATCH`}),delete:(e,t)=>En({...t,url:e,method:`DELETE`}),head:(e,t)=>En({...t,url:e,method:`HEAD`,parseAs:`raw`}),options:(e,t)=>En({...t,url:e,method:`OPTIONS`,parseAs:`raw`}),client:e=>({request:t=>J(e,t),get:(t,n)=>J(e,{...n,url:t,method:`GET`}),post:(t,n)=>J(e,{...n,url:t,method:`POST`}),put:(t,n)=>J(e,{...n,url:t,method:`PUT`}),patch:(t,n)=>J(e,{...n,url:t,method:`PATCH`}),delete:(t,n)=>J(e,{...n,url:t,method:`DELETE`}),head:(t,n)=>J(e,{...n,url:t,method:`HEAD`,parseAs:`raw`}),options:(t,n)=>J(e,{...n,url:t,method:`OPTIONS`,parseAs:`raw`})})}),On={toOption:e=>e.fold(()=>p(),e=>d(e)),toList:e=>e.fold(()=>C([]),e=>C([e])),toEither:(e,t)=>e.fold(()=>T(t),e=>w(e)),isEmpty:e=>e.fold(()=>!0,()=>!1),size:e=>e.fold(()=>0,()=>1)},kn=e=>typeof e==`object`&&!!e&&(e._tag===`Some`||e._tag===`None`),Y=e=>typeof e==`object`&&!!e&&e._tag===`List`,An=e=>typeof e==`object`&&!!e&&(e._tag===`Left`||e._tag===`Right`),jn=e=>typeof e==`object`&&!!e&&(e._tag===`Success`||e._tag===`Failure`),X=()=>{let e=(e,t)=>{if(kn(e)||Y(e)||An(e)||jn(e))return e.map(e=>t(e));throw Error(`Unsupported functor type: ${JSON.stringify(e)}`)},t=e=>{if(kn(e))return e.orThrow();if(Y(e)){let t=e.toArray();if(t.length>0&&Y(t[0])){let e=[];for(let n of t)Y(n)&&e.push(...n.toArray());return C(e)}return e.flatten()}if(An(e))return e.isRight()?e.fold(()=>null,e=>e):e;if(jn(e))return e.isSuccess()?e.orThrow():e;throw Error(`Unsupported functor type for flatten: ${JSON.stringify(e)}`)},n=(e,t)=>{if(kn(e)||Y(e)||An(e)||jn(e))return e.flatMap(e=>t(e));throw Error(`Unsupported functor type for flatMap: ${JSON.stringify(e)}`)},r=(e,t)=>{if(kn(e)&&kn(t)||Y(e)&&Y(t)||An(e)&&An(t)||jn(e)&&jn(t))return e.flatMap(e=>t.map(t=>e(t)));throw Error(`Unsupported functor type for ap: ${JSON.stringify(e)}`)},i=e=>{if(kn(e)){let t=e;if(t.isEmpty)return C([m.none()]);let n=t.orThrow();if(Y(n))return n.map(e=>m(e));throw Error(`Unsupported inner container type for sequence`)}if(Y(e)){let t=e.toArray();if(t.length===0)return m.none();let n=t[0];if(kn(n)){for(let e of t)if(e.isEmpty)return m.none();return m(C(t.map(e=>e.orThrow())))}throw Error(`Unsupported inner container type for sequence`)}throw Error(`Unsupported outer container type for sequence: ${JSON.stringify(e)}`)};return{_tag:`HKT`,map:e,flatten:t,flatMap:n,ap:r,sequence:i,traverse:(t,n)=>i(e(t,e=>n(e))),_type:`HKT`}},Mn=X();X.map=(e,t)=>Mn.map(e,t),X.flatten=e=>Mn.flatten(e),X.flatMap=(e,t)=>Mn.flatMap(e,t),X.ap=(e,t)=>Mn.ap(e,t),X.sequence=e=>Mn.sequence(e),X.traverse=(e,t)=>Mn.traverse(e,t),X.isOption=kn,X.isList=Y,X.isEither=An,X.isTry=jn;const Nn=e=>({id:e,isSame:t=>t.id===e}),Pn=r(Nn,{of:e=>Nn(e),pure:e=>Nn(e)}),Fn=e=>{let t=!1,n,r,a=!1,l=()=>{if(!t)try{n=e(),t=!0}catch(e){throw r=e,a=!0,t=!0,e}if(a)throw r;return n};return{[Symbol.toStringTag]:`Lazy`,_tag:`Lazy`,get isEvaluated(){return t},orElse:e=>{try{return l()}catch{return e}},orNull:()=>{try{return l()}catch{return null}},orThrow:e=>{try{return l()}catch(t){throw e??t}},or:e=>Z(()=>{try{return l()}catch{return e.orThrow()}}),orUndefined:()=>{try{return l()}catch{return}},map:e=>Z(()=>e(l())),ap:e=>Z(()=>e.orThrow()(l())),mapAsync:async e=>{let t=await e(l());return Z(()=>t)},flatMap:e=>Z(()=>e(l()).orThrow()),flatMapAsync:async e=>{let t=await e(l());return Z(()=>t.orThrow())},filter:e=>Z(()=>{let t=l();return e(t)?d(t):p}),recover:e=>Z(()=>{try{return l()}catch(t){return e(t)}}),recoverWith:e=>Z(()=>{try{return l()}catch(t){return e(t).orThrow()}}),toOption:()=>{try{return d(l())}catch{return p}},toEither:()=>{try{return w(l())}catch(e){return T(e)}},toEitherWith:e=>{try{return w(l())}catch(t){return T(e(t))}},toTry:()=>x(()=>l()),tap:e=>Z(()=>{let t=l();return e(t),t}),tapError:e=>Z(()=>{try{return l()}catch(t){throw e(t),t}}),fold:e=>e(l()),foldWith:(e,t)=>{try{return t(l())}catch(t){return e(t)}},foldLeft:e=>t=>t(e,l()),foldRight:e=>t=>t(l(),e),match:e=>e.Lazy(l()),toString:()=>t&&!a?`Lazy(${c(n)})`:t&&a?`Lazy(<error: ${r instanceof Error?r.message:String(r)}>)`:`Lazy(<not evaluated>)`,toValue:()=>{try{return{_tag:`Lazy`,value:l()}}catch(e){return{_tag:`Lazy`,error:e instanceof Error?e:Error(String(e))}}},get size(){try{return l(),1}catch{return 0}},get isEmpty(){try{return l(),!1}catch{return!0}},contains:e=>{try{return l()===e}catch{return!1}},reduce:e=>l(),reduceRight:e=>l(),count:e=>{try{return+!!e(l())}catch{return 0}},find:e=>{try{let t=l();return e(t)?d(t):p}catch{return p}},exists:e=>{try{return e(l())}catch{return!1}},forEach:e=>{try{e(l())}catch{}},pipe:e=>e(l()),toJSON:()=>{try{return{"@functype":`Lazy`,_tag:`Lazy`,value:l()}}catch(e){return{"@functype":`Lazy`,_tag:`Lazy`,error:o(e)}}},serialize:()=>{try{return s(`Lazy`,l())}catch(e){return i(`Lazy`,`Lazy`,{error:o(e)})}},typeable:`Lazy`}},In={of:e=>Fn(e),fromValue:e=>Fn(()=>e),fromOption:(e,t)=>Fn(()=>e._tag===`Some`?e.value:t()),fromTry:e=>Fn(()=>e.orThrow()),fromEither:e=>Fn(()=>e.fold(e=>{throw e},e=>e)),fromPromise:e=>Fn(()=>{throw Error(`Promise not yet resolved. Use await on the promise before creating Lazy.`)}),fail:e=>Fn(()=>{throw e}),evaluated:e=>Fn(()=>e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Lazy`)throw Error(`Lazy.fromJSON: expected @functype="Lazy", got ${JSON.stringify(t[`@functype`])}`);if(t.error!==void 0){let e=typeof t.error==`object`?a(t.error):Error(t.error);return In.fail(e)}return In.evaluated(t.value)}},Z=r(Fn,In),Ln={default:e=>t=>e(t),when:(e,t)=>n=>e(n)?t(n):void 0},Q=e=>({[Symbol.toStringTag]:`Obj`,_tag:`Obj`,data:e,get:t=>m(e[t]),set:(t,n)=>Q({...e,[t]:n}),assign:t=>Q({...e,...t}),merge:t=>Q({...e,...t}),when:(t,n)=>(typeof t==`function`?t():t)?Q({...e,...n}):Q(e),omit:(...t)=>{let n={...e};for(let e of t)delete n[e];return Q(n)},pick:(...t)=>{let n={};for(let r of t)r in e&&(n[r]=e[r]);return Q(n)},keys:()=>C(Object.keys(e)),values:()=>C(Object.values(e)),entries:()=>C(Object.entries(e).map(([e,t])=>te([e,t]))),has:t=>t in e,value:()=>e,get isEmpty(){return Object.keys(e).length===0},get size(){return Object.keys(e).length},map:t=>Q(t(e)),flatMap:t=>t(e),flatMapAsync:async t=>await t(e),ap:t=>{let n=t.data;return Q(n(e))},fold:(t,n)=>Object.keys(e).length===0?t():n(e),match:t=>t.Obj(e),foldLeft:t=>n=>n(t,e),foldRight:t=>n=>n(e,t),count:t=>+!!t(e),find:t=>t(e)?m(e):m(void 0),exists:t=>t(e),forEach:t=>t(e),reduce:t=>e,reduceRight:t=>e,contains:t=>JSON.stringify(e)===JSON.stringify(t),orElse:t=>e,orThrow:t=>e,or:t=>Q(e),orNull:()=>e,orUndefined:()=>e,toOption:()=>m(e),toEither:t=>w(e),toList:()=>C([e]),toTry:()=>x(()=>e),toPromise:()=>Promise.resolve(e),toString:()=>`Obj(${c(e)})`,toValue:()=>({_tag:`Obj`,value:e}),toJSON:()=>({"@functype":`Obj`,_tag:`Obj`,value:e}),pipe:t=>t(e),serialize:()=>s(`Obj`,e),doUnwrap(){return{ok:!0,value:e}}}),Rn=e=>Q(e),zn={of:e=>Q(e),empty:()=>Q({}),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Obj`)throw Error(`Obj.fromJSON: expected @functype="Obj", got ${JSON.stringify(t[`@functype`])}`);return Q(t.value)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return zn.fromJSON(t)}},Bn=r(Rn,zn),$=(e=[])=>{let t=[...e],n=()=>t.length,r=()=>t.length===0,i=e=>t.includes(e),a=e=>{if(t.length===0)throw Error(`Cannot reduce an empty stack`);return u(t,e)},o=e=>{if(t.length===0)throw Error(`Cannot reduce an empty stack`);return ee(t,e)},c=e=>$([...t,e]),l=()=>{if(r())return[$([]),m(null)];let e=[...t],n=e.pop();return[$(e),m(n)]},te=()=>r()?m(null):m(t[t.length-1]),d=e=>$(t.map(e)),f=e=>r()?$([]):t.reduce((t,n)=>e(n).toArray().reduce((e,t)=>e.push(t),t),$([])),p=e=>{let n=[];return t.forEach(t=>{e.toArray().forEach(e=>{n.push(e(t))})}),$(n)},ne=async e=>r()?$([]):(await Promise.all(t.map(async t=>await e(t)))).reduce((e,t)=>t.toArray().reduce((e,t)=>e.push(t),e),$([])),re=()=>C(t),h=()=>[...t],g=()=>`Stack(${t.join(`, `)})`,ie=(e,n)=>t.reduce(n,e),ae=e=>n=>t.reduce(n,e),oe=e=>n=>t.reduceRight((e,t)=>n(t,e),e),se=e=>r()?e.Empty():e.NonEmpty([...t]);return{[Symbol.toStringTag]:`Stack`,_tag:`Stack`,get size(){return n()},get isEmpty(){return r()},contains:i,reduce:a,reduceRight:o,push:c,pop:l,peek:te,map:d,flatMap:f,ap:p,flatMapAsync:ne,toList:re,toArray:h,toString:g,fold:ie,foldLeft:ae,foldRight:oe,match:se,toValue:()=>({_tag:`Stack`,value:t}),toJSON:()=>({"@functype":`Stack`,_tag:`Stack`,value:[...t]}),pipe:e=>e([...t]),serialize:()=>s(`Stack`,t)}},Vn=(e=[])=>$(e),Hn={empty:()=>$([]),of:e=>$([e]),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Stack`)throw Error(`Stack.fromJSON: expected @functype="Stack", got ${JSON.stringify(t[`@functype`])}`);return Un(t.value)},fromYAML:e=>{let t=e.split(`
17
- `)[1]?.split(`: `)[1];return Un(t?JSON.parse(t):[])},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return Hn.fromJSON(t)}},Un=r(Vn,Hn);var Wn=e({deserialize:()=>Xn,deserializeStrict:()=>Zn,fromEnvelope:()=>er,isFunctypeValue:()=>tr,serialize:()=>Qn,toEnvelope:()=>$n});let Gn;const Kn=()=>(Gn===void 0&&(Gn={Option:e=>e._tag===`Some`?d(e.value):p(),Either:e=>e._tag===`Right`?w(e.value):T(e.value),Try:e=>{if(e._tag===`Success`)return x.success(e.value);let t=e.error!==void 0&&typeof e.error==`object`?a(e.error):Error(typeof e.error==`string`?e.error:``);return x.failure(t)},List:e=>C(e.value),Set:e=>se(e.value),Map:e=>ot(e.value),Obj:e=>Bn(e.value),Stack:e=>Un(e.value),Tuple:e=>te(e.value),LazyList:e=>de(e.value),Lazy:e=>{if(e.error!==void 0){let t=typeof e.error==`object`?a(e.error):Error(e.error);return Z.fail(t)}return Z.evaluated(e.value)},Task:e=>{if(e._tag===`Ok`)return A.ok(e.value);let t=e.error!==void 0&&typeof e.error==`object`?a(e.error):Error(typeof e.error==`string`?e.error:`Unknown Task error`);return A.err(t)}}),Gn),qn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Jn=e=>qn(e)&&typeof e[`@functype`]==`string`,Yn=e=>{if(Array.isArray(e))return e.map(Yn);if(Jn(e)){let t=e[l],n=Kn()[t];if(n===void 0)throw Error(`Serialization.deserialize: unknown @functype marker ${JSON.stringify(t)}`);let r={};for(let t of Object.keys(e))r[t]=Yn(e[t]);return n(r)}if(qn(e)){let t={};for(let n of Object.keys(e))t[n]=Yn(e[n]);return t}return e},Xn=e=>x(()=>Yn(JSON.parse(e))),Zn=e=>x(()=>{let t=JSON.parse(e);if(!Jn(t))throw Error(`Serialization.deserializeStrict: input is not a functype envelope (no @functype marker at the top level)`);return Yn(t)}),Qn=e=>JSON.stringify(e??null),$n=e=>JSON.parse(JSON.stringify(e??null)),er=e=>x(()=>Yn(e)),tr=e=>typeof e==`object`&&!!e&&typeof e.serialize==`function`&&typeof e._tag==`string`;function nr(e){let t=me({_tag:e._tag,impl:e.impl});return{...t,toValue:()=>({_tag:t._tag,value:e.value})}}export{We as $,Kt as A,m as At,Mt as B,tn as C,me as Ct,Yt as D,_ as Dt,Xt as E,de as Et,Wt as F,k as G,ot as H,Ht as I,Ze as J,A as K,Vt as L,Ft as M,d as Mt,Lt as N,Jt as O,se as Ot,Ut as P,qe as Q,Rt as R,I as S,C as St,P as T,x as Tt,nt as U,M as V,O as W,Xe as X,Ye as Y,Je as Z,un as _,we as _t,Ln as a,Pe as at,on as b,Ce as bt,X as c,Ne as ct,vn as d,Ie as dt,ze as et,gn as f,E as ft,dn as g,Te as gt,hn as h,w as ht,Bn as i,Me as it,Bt as j,ne as jt,qt as k,p as kt,On as l,Ae as lt,pn as m,T as mt,Wn as n,Fe as nt,Z as o,je as ot,mn as p,ke as pt,$e as q,Un as r,Re as rt,Pn as s,Ve as st,nr as t,Be as tt,Dn as u,Le as ut,G as v,Se as vt,$t as w,he as wt,R as x,Ee as xt,sn as y,xe as yt,zt as z};