functype 1.6.2 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CompanionTypes-CAxuM7qS.d.ts → CompanionTypes-Cc90cQ4P.d.ts} +1 -1
- package/dist/{Tuple-8yRldBty.d.ts → Tuple-B8KM-H8Y.d.ts} +1 -4
- package/dist/cli/exports.js +1 -1
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +5 -5
- package/dist/companion/index.d.ts +1 -1
- package/dist/conditional/index.d.ts +1 -1
- package/dist/conditional/index.js +1 -1
- package/dist/core/task/index.d.ts +1 -1
- package/dist/core/task/index.js +1 -1
- package/dist/decoder/index.d.ts +1 -1
- package/dist/decoder/index.js +1 -1
- package/dist/do/index.d.ts +1 -1
- package/dist/do/index.js +1 -1
- package/dist/either/index.d.ts +1 -1
- package/dist/either/index.js +1 -1
- package/dist/fetch/index.d.ts +1 -1
- package/dist/fetch/index.js +1 -1
- package/dist/{full-interfaces-CEcwPTzt.js → full-interfaces-npeBihi2.js} +1 -1
- package/dist/functype/index.d.ts +1 -1
- package/dist/{index-CCuIZ-ut.d.ts → index-j0hrJjoo.d.ts} +48 -20
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/io/index.d.ts +2 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/index.d.ts +1 -1
- package/dist/lazy/index.js +1 -1
- package/dist/list/index.d.ts +1 -1
- package/dist/list/index.js +1 -1
- package/dist/map/index.d.ts +1 -1
- package/dist/map/index.js +1 -1
- package/dist/obj/index.d.ts +1 -1
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +1 -1
- package/dist/option/index.js +1 -1
- package/dist/serialization/index.d.ts +1 -1
- package/dist/set/index.d.ts +1 -1
- package/dist/set/index.js +1 -1
- package/dist/{src-C4olFIr1.js → src-dCt7rWSB.js} +3 -3
- package/dist/try/index.d.ts +1 -1
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +1 -1
- package/dist/typeclass/index.d.ts +1 -1
- package/package.json +7 -7
|
@@ -37,7 +37,7 @@ declare function Companion<ObjectF extends object, CompanionF extends object>(ob
|
|
|
37
37
|
* // { from: ..., none: ..., fromJSON: ..., etc. }
|
|
38
38
|
* ```
|
|
39
39
|
*/
|
|
40
|
-
type CompanionMethods<T> = T extends ((...args: never[]) => unknown) & infer C ? C : never;
|
|
40
|
+
type CompanionMethods<T> = T extends ((...args: never[]) => unknown) & (infer C) ? C : never;
|
|
41
41
|
/**
|
|
42
42
|
* Extracts the instance type from a constructor function
|
|
43
43
|
* @typeParam T - The constructor function type
|
|
@@ -119,10 +119,7 @@ type ExtractTag<T> = T extends Typeable<infer Tag, unknown> ? Tag : never;
|
|
|
119
119
|
* @typeParam Tag - The string literal type used as the discriminator
|
|
120
120
|
* @typeParam T - The base type to extend with the tag
|
|
121
121
|
*/
|
|
122
|
-
declare function Typeable<Tag extends string, T>({
|
|
123
|
-
_tag,
|
|
124
|
-
impl
|
|
125
|
-
}: TypeableParams<Tag, T>): Typeable<Tag, T>;
|
|
122
|
+
declare function Typeable<Tag extends string, T>({ _tag, impl }: TypeableParams<Tag, T>): Typeable<Tag, T>;
|
|
126
123
|
/**
|
|
127
124
|
* Type guard with automatic type inference using the full type
|
|
128
125
|
* @param value - The value to check
|
package/dist/cli/exports.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"../full-interfaces-
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"../full-interfaces-npeBihi2.js";export{n as CATEGORIES,i as FULL_INTERFACES,r as INTERFACES,t as TYPES,e as VERSION};
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
package/dist/cli/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)},l=(
|
|
4
|
-
`).trimEnd()},u=()=>{let e=
|
|
5
|
-
`).trimEnd()},d=e=>JSON.stringify(e,null,2),f=()=>({version:r,categories:a,types:i}),p=
|
|
2
|
+
import{$ as e,Ct as t,jt as n}from"../src-dCt7rWSB.js";import{a as r,i,n as a,r as o,t as s}from"../full-interfaces-npeBihi2.js";const c=()=>{let e=t([`functype ${r} - Scala-inspired FP for TypeScript`,``]);return t(Object.entries(a)).foldLeft(e)((e,[r,a])=>{let o=e.add(r.toUpperCase());return t(a).foldLeft(o)((e,t)=>n(i[t]).fold(()=>e,n=>{let r=n.interfaces.length>0?` [${n.interfaces.join(`, `)}]`:``;return e.add(` ${t}${r}`).add(` ${n.description}`)})).add(``)}).concat(t([`Use: npx functype <Type> for details`,`Use: npx functype interfaces for interface reference`])).toArray().join(`
|
|
3
|
+
`)},l=(e,r)=>{let i=r.interfaces.length>0?` [${r.interfaces.join(`, `)}]`:``,a=t([`create`,`transform`,`extract`,`check`,`other`]),o=t([`${e}<T>${i}`,``,r.description,``]);return a.foldLeft(o)((e,i)=>n(r.methods[i]).filter(e=>e.length>0).fold(()=>e,n=>{let r=e.add(i.toUpperCase());return t(n).foldLeft(r)((e,t)=>e.add(` ${t}`)).add(``)})).toArray().join(`
|
|
4
|
+
`).trimEnd()},u=()=>{let e=t([`INTERFACES`,``]);return t(Object.entries(o)).foldLeft(e)((e,[n,r])=>{let i=r.extends?` extends ${r.extends}`:``,a=e.add(`${n}<A>${i}`).add(` ${r.description}`);return t(r.methods).foldLeft(a)((e,t)=>e.add(` ${t}`)).add(``)}).toArray().join(`
|
|
5
|
+
`).trimEnd()},d=e=>JSON.stringify(e,null,2),f=()=>({version:r,categories:a,types:i}),p=e=>n(i[e]).map(t=>({name:e,data:t})).or(t(Object.entries(i)).find(([t])=>t.toLowerCase()===e.toLowerCase()).map(([e,t])=>({name:e,data:t}))).orUndefined(),m=()=>Object.keys(i),h=()=>o,g=e=>{let n=t(e.slice(2));return{flags:{json:n.contains(`--json`),full:n.contains(`--full`),help:n.exists(e=>e===`--help`||e===`-h`)},args:n.filter(e=>!e.startsWith(`--`)&&e!==`-h`)}},_=e=>n(s[e]).or(t(Object.entries(s)).find(([t])=>t.toLowerCase()===e.toLowerCase()).map(([,e])=>e)),v=()=>{let e=t([`FULL INTERFACE DEFINITIONS`,`=`.repeat(60),``]);return t(Object.entries(s)).foldLeft(e)((e,[n,r])=>e.concat(t([`// ${n}`,r,``,`-`.repeat(60),``]))).toArray().join(`
|
|
6
6
|
`).trimEnd()},y=()=>{console.log(`functype - API documentation for LLMs
|
|
7
7
|
|
|
8
8
|
USAGE
|
|
@@ -24,4 +24,4 @@ EXAMPLES
|
|
|
24
24
|
npx functype Option --json # Option as JSON
|
|
25
25
|
npx functype Option --full # Full TypeScript interface
|
|
26
26
|
npx functype --full # All full interfaces (large output!)
|
|
27
|
-
`)},b=e=>{console.error(`Unknown type: ${e}`),console.error(``),console.error(`Available types: ${m().join(`, `)}`),console.error(``),console.error(`Use: npx functype interfaces - for interface reference`),process.exit(1)},x=e=>console.log(e),S=(t
|
|
27
|
+
`)},b=e=>{console.error(`Unknown type: ${e}`),console.error(``),console.error(`Available types: ${m().join(`, `)}`),console.error(``),console.error(`Use: npx functype interfaces - for interface reference`),process.exit(1)},x=e=>console.log(e),S=(e,t)=>n(p(e)).fold(()=>b(e),e=>{t.full?_(e.name).fold(()=>x(t.json?d({[e.name]:e.data}):l(e.name,e.data)),n=>x(t.json?d({[e.name]:{...e.data,fullInterface:n}}):n)):x(t.json?d({[e.name]:e.data}):l(e.name,e.data))});(()=>{let{flags:t,args:n}=g(process.argv);e(!0).when(()=>t.help,()=>y()).when(()=>n.isEmpty,()=>t.full?x(t.json?d(s):v()):x(t.json?d(f()):c())).when(()=>n.headOption.contains(`interfaces`),()=>x(t.json?d(h()):u())).default(()=>n.headOption.fold(()=>x(t.json?d(f()):c()),e=>S(e,t)))})();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as Companion, n as InstanceType, r as isCompanion, t as CompanionMethods } from "../CompanionTypes-
|
|
1
|
+
import { i as Companion, n as InstanceType, r as isCompanion, t as CompanionMethods } from "../CompanionTypes-Cc90cQ4P.js";
|
|
2
2
|
export { Companion, CompanionMethods, InstanceType, isCompanion };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Dr as Cond, n as UntypedMatch, t as Match } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Cond, Match, UntypedMatch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,
|
|
1
|
+
import{$ as e,et as t}from"../src-dCt7rWSB.js";export{t as Cond,e as Match};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as
|
|
1
|
+
import { $t as TaskOutcome, Gt as CancellationTokenSource, Jt as Sync, Kt as Err, Qt as TaskMetadata, Ut as Async, Wt as CancellationToken, Xt as Task, Yt as TaggedThrowable, Zt as TaskFailure, en as TaskParams, in as isTaggedThrowable, nn as TaskSuccess, qt as Ok, rn as createCancellationTokenSource, tn as TaskResult } from "../../index-j0hrJjoo.js";
|
|
2
2
|
export { Async, CancellationToken, CancellationTokenSource, Err, Ok, Sync, TaggedThrowable, Task, TaskFailure, TaskMetadata, TaskOutcome, TaskParams, TaskResult, TaskSuccess, createCancellationTokenSource, isTaggedThrowable };
|
package/dist/core/task/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as e,J as t,K as n,
|
|
1
|
+
import{G as e,J as t,K as n,Y as r,q as i}from"../../src-dCt7rWSB.js";export{e as Err,n as Ok,i as Task,t as createCancellationTokenSource,r as isTaggedThrowable};
|
package/dist/decoder/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Bt as
|
|
1
|
+
import { Bt as DecoderError, Ht as DecoderErrorLeaf, Vt as DecoderErrorComposite, zt as Decoder } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Decoder, DecoderError, type DecoderErrorComposite, type DecoderErrorLeaf };
|
package/dist/decoder/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{H as e,V as t}from"../src-dCt7rWSB.js";export{t as Decoder,e as DecoderError};
|
package/dist/do/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { At as
|
|
1
|
+
import { At as DoGenerator, Dt as $, Er as Doable, Ft as LeftErrorType, It as NoneError, Lt as isDoCapable, Mt as FailureError, Nt as FailureErrorType, Ot as Do, Pt as LeftError, Rt as unwrap, Tr as DoResult, jt as EmptyListError, kt as DoAsync } from "../index-j0hrJjoo.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{
|
|
1
|
+
import{B as e,F as t,I as n,L as r,M as i,N as a,P as o,R as s,z as c}from"../src-dCt7rWSB.js";export{i as $,a as Do,o as DoAsync,t as EmptyListError,n as FailureError,r as LeftError,s as NoneError,c as isDoCapable,e as unwrap};
|
package/dist/either/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $n as
|
|
1
|
+
import { $n as Either, ar as TestEither, cr as isLeft, dr as tryCatchAsync, er as EitherBase, ir as RightOf, lr as isRight, nr as LeftOf, or as TypeCheckLeft, rr as Right, sr as TypeCheckRight, tr as Left, ur as tryCatch } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Either, EitherBase, Left, LeftOf, Right, RightOf, TestEither, TypeCheckLeft, TypeCheckRight, isLeft, isRight, tryCatch, tryCatchAsync };
|
package/dist/either/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{St as e,_t as t,bt as n,gt as r,ht as i,mt as a,vt as o,xt as s,yt as c}from"../src-dCt7rWSB.js";export{a as Either,i as Left,r as Right,t as TypeCheckLeft,o as TypeCheckRight,c as isLeft,n as isRight,s as tryCatch,e as tryCatchAsync};
|
package/dist/fetch/index.d.ts
CHANGED
|
@@ -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-
|
|
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-j0hrJjoo.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 };
|
package/dist/fetch/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as e,f as t,u as n}from"../src-
|
|
1
|
+
import{d as e,f as t,u as n}from"../src-dCt7rWSB.js";export{n as Http,t as HttpClient,e as HttpErrors};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=`1.6.2`;const t={Option:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Matchable`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`,`Traversable`],Either:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],Try:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],List:[`Collection`,`Doable`,`Iterable`,`Reshapeable`],Set:[`Collection`,`Iterable`],Map:[`Collection`,`Foldable`,`Iterable`,`KVTraversable`,`Serializable`],Obj:[`Doable`,`Promisable`,`Reshapeable`],Lazy:[`Applicative`,`AsyncMonad`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Serializable`,`Traversable`],LazyList:[`Foldable`,`Serializable`],Tuple:[`Foldable`,`Serializable`],Task:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Serializable`,`Traversable`]},n=e,r=(e,...n)=>Array.from(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`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.orElse(d: T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toYAML(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Task`,`TaskOutcome`,`TaskResult`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Brand`,`ValidatedBrand`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`]},s={Option:`export interface Option<out T extends Type>
|
|
1
|
+
var e=`1.7.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? })`,`.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`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.orElse(d: T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toYAML(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Task`,`TaskOutcome`,`TaskResult`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Brand`,`ValidatedBrand`],Validation:[`TypedError`,`Validation`],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
|
package/dist/functype/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Cn as
|
|
1
|
+
import { Cn as FunctypeSum, En as FunctypeCollection, Tn as FunctypeBase, wn as Functype } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Functype, FunctypeBase, FunctypeCollection, FunctypeSum };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { t as Brand } from "./Brand-bfnGXuum.js";
|
|
2
|
-
import { d as Type, l as Pipe, o as Serializable, r as Typeable, t as Tuple, u as Foldable } from "./Tuple-
|
|
3
|
-
|
|
2
|
+
import { d as Type, l as Pipe, o as Serializable, r as Typeable, t as Tuple, u as Foldable } from "./Tuple-B8KM-H8Y.js";
|
|
4
3
|
//#region src/conditional/Cond.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Conditional expression that enforces exhaustive returns without early returns.
|
|
@@ -2022,8 +2021,11 @@ type TaskResult<T> = Promise<TaskOutcome<T>>;
|
|
|
2022
2021
|
* Cancellation is cooperative, meaning the task must check the token and respond to cancellation requests
|
|
2023
2022
|
*/
|
|
2024
2023
|
type CancellationToken = {
|
|
2025
|
-
/** Whether the token has been cancelled */
|
|
2026
|
-
readonly
|
|
2024
|
+
/** Whether the token has been cancelled */
|
|
2025
|
+
readonly isCancelled: boolean;
|
|
2026
|
+
/** Signal that can be used with fetch and other abortable APIs */
|
|
2027
|
+
readonly signal: AbortSignal;
|
|
2028
|
+
/** Register a callback to be called when cancellation occurs */
|
|
2027
2029
|
onCancel(callback: () => void): void;
|
|
2028
2030
|
};
|
|
2029
2031
|
/**
|
|
@@ -2031,7 +2033,9 @@ type CancellationToken = {
|
|
|
2031
2033
|
* The controller can be used to cancel operations that use the token
|
|
2032
2034
|
*/
|
|
2033
2035
|
type CancellationTokenSource = {
|
|
2034
|
-
/** The token to be passed to cancellable operations */
|
|
2036
|
+
/** The token to be passed to cancellable operations */
|
|
2037
|
+
readonly token: CancellationToken;
|
|
2038
|
+
/** Cancel all operations using this token */
|
|
2035
2039
|
cancel(): void;
|
|
2036
2040
|
};
|
|
2037
2041
|
/**
|
|
@@ -2295,7 +2299,7 @@ declare const Decoder: {
|
|
|
2295
2299
|
try: <A>(inner: Decoder$1<A>) => Decoder$1<Try<A>>;
|
|
2296
2300
|
list: <A>(inner: Decoder$1<A>) => Decoder$1<List<A>>;
|
|
2297
2301
|
map: <V>(inner: Decoder$1<V>) => Decoder$1<Map$1<string, V>>;
|
|
2298
|
-
obj: <T extends Record<string, unknown>>(shape: { [K in keyof T]: Decoder$1<T[K]
|
|
2302
|
+
obj: <T extends Record<string, unknown>>(shape: { [K in keyof T]: Decoder$1<T[K]>; }) => Decoder$1<T>;
|
|
2299
2303
|
};
|
|
2300
2304
|
string: Decoder$1<string>;
|
|
2301
2305
|
number: Decoder$1<number>;
|
|
@@ -2317,7 +2321,7 @@ declare const Decoder: {
|
|
|
2317
2321
|
list: <A>(inner: Decoder$1<A>) => Decoder$1<List<A>>;
|
|
2318
2322
|
array: <A>(inner: Decoder$1<A>) => Decoder$1<A[]>;
|
|
2319
2323
|
map: <V>(inner: Decoder$1<V>) => Decoder$1<Map$1<string, V>>;
|
|
2320
|
-
object: <T extends Record<string, unknown>>(shape: { [K in keyof T]: Decoder$1<T[K]
|
|
2324
|
+
object: <T extends Record<string, unknown>>(shape: { [K in keyof T]: Decoder$1<T[K]>; }) => Decoder$1<T>;
|
|
2321
2325
|
};
|
|
2322
2326
|
//#endregion
|
|
2323
2327
|
//#region src/do/index.d.ts
|
|
@@ -2527,12 +2531,19 @@ type ErrorChainElement = {
|
|
|
2527
2531
|
* Options for formatting error chains
|
|
2528
2532
|
*/
|
|
2529
2533
|
type ErrorFormatterOptions = {
|
|
2530
|
-
/** Include task names in the formatted output */
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2534
|
+
/** Include task names in the formatted output */
|
|
2535
|
+
includeTasks?: boolean;
|
|
2536
|
+
/** Include stack traces in the formatted output */
|
|
2537
|
+
includeStackTrace?: boolean;
|
|
2538
|
+
/** Separator between error lines (default: newline) */
|
|
2539
|
+
separator?: string;
|
|
2540
|
+
/** Include detailed error data in the output */
|
|
2541
|
+
includeData?: boolean;
|
|
2542
|
+
/** Maximum number of stack frames to include if stack trace is enabled */
|
|
2543
|
+
maxStackFrames?: number;
|
|
2544
|
+
/** Title to display at the start of the formatted error */
|
|
2545
|
+
title?: string;
|
|
2546
|
+
/** Format the output with colors for console display */
|
|
2536
2547
|
colors?: boolean;
|
|
2537
2548
|
};
|
|
2538
2549
|
/**
|
|
@@ -2777,7 +2788,7 @@ declare const Validation: (<T extends Type>(rule: ValidationRule) => Validator<T
|
|
|
2777
2788
|
* }
|
|
2778
2789
|
* const result = Validation.form(schema, { name: "John", email: "john@example.com", age: 25 })
|
|
2779
2790
|
*/
|
|
2780
|
-
form: <T extends Record<string, Type>>(schema: { [K in keyof T]: Validator<T[K]
|
|
2791
|
+
form: <T extends Record<string, Type>>(schema: { [K in keyof T]: Validator<T[K]>; }, data: Record<string, unknown>) => FormValidation<T>;
|
|
2781
2792
|
};
|
|
2782
2793
|
//#endregion
|
|
2783
2794
|
//#region src/io/Tag.d.ts
|
|
@@ -3293,6 +3304,23 @@ declare class InterruptedError extends Error {
|
|
|
3293
3304
|
readonly _tag: "InterruptedError";
|
|
3294
3305
|
constructor(message?: string);
|
|
3295
3306
|
}
|
|
3307
|
+
/**
|
|
3308
|
+
* Error thrown when a combinator that cannot run on the synchronous interpreter is
|
|
3309
|
+
* reached by `runSync`. `timeout` and `race` are inherently asynchronous — there is no
|
|
3310
|
+
* sync semantics for "wait `ms` then give up", or for racing concurrent effects.
|
|
3311
|
+
*
|
|
3312
|
+
* This is a **programmer error, not a domain failure**: it says the effect was built
|
|
3313
|
+
* wrong for the terminal it was run with, so recovery combinators deliberately do not
|
|
3314
|
+
* catch it (see {@link rethrowIfNonRecoverable}). Before it had its own type it was a
|
|
3315
|
+
* plain `Error`, indistinguishable from a failed effect, so any downstream `.recover()`
|
|
3316
|
+
* absorbed it and silently produced the fallback — `IO.succeed(1).timeoutTo(50, 99)`
|
|
3317
|
+
* returned `Right(99)` under `runSync()`. See #246.
|
|
3318
|
+
*/
|
|
3319
|
+
declare class UnsupportedSyncOperationError extends Error {
|
|
3320
|
+
readonly operation: "timeout" | "race";
|
|
3321
|
+
readonly _tag: "UnsupportedSyncOperationError";
|
|
3322
|
+
constructor(operation: "timeout" | "race");
|
|
3323
|
+
}
|
|
3296
3324
|
/**
|
|
3297
3325
|
* Error surfaced by value-driven repeat combinators when the iteration bound is
|
|
3298
3326
|
* reached without the predicate being satisfied. Carries the last observed
|
|
@@ -4056,7 +4084,7 @@ declare const IO: (<A extends Type>(f: () => A | Promise<A>) => IO<never, unknow
|
|
|
4056
4084
|
* )
|
|
4057
4085
|
* ```
|
|
4058
4086
|
*/
|
|
4059
|
-
withServices: <Services extends Record<string, Tag<Type>>, A extends Type>(services: Services, f: (ctx: { [K in keyof Services]: TagService<Services[K]
|
|
4087
|
+
withServices: <Services extends Record<string, Tag<Type>>, A extends Type>(services: Services, f: (ctx: { [K in keyof Services]: TagService<Services[K]>; }) => A | Promise<A>) => IO<TagService<Services[keyof Services]>, unknown, A>;
|
|
4060
4088
|
/**
|
|
4061
4089
|
* Runs all IOs in parallel and collects results.
|
|
4062
4090
|
*/
|
|
@@ -5840,7 +5868,7 @@ type RequireExhaustive<T, Cases> = IsUnion<T> extends true ? (keyof Cases extend
|
|
|
5840
5868
|
* Pattern types for nested matching
|
|
5841
5869
|
* @internal
|
|
5842
5870
|
*/
|
|
5843
|
-
type Pattern<T> = T | { [K in keyof T]?: Pattern<T[K]
|
|
5871
|
+
type Pattern<T> = T | { [K in keyof T]?: Pattern<T[K]>; } | ((value: T) => boolean) | {
|
|
5844
5872
|
_: (value: T) => boolean;
|
|
5845
5873
|
};
|
|
5846
5874
|
/**
|
|
@@ -6078,7 +6106,7 @@ declare const Match: (<T extends Type>(value: T) => UntypedMatch<T>) & {
|
|
|
6078
6106
|
* .build()
|
|
6079
6107
|
*/
|
|
6080
6108
|
struct: <T extends Type, R extends Type>() => {
|
|
6081
|
-
case: (pattern: Pattern<T>, handler: (value: T) => R) => /*elided*/any;
|
|
6109
|
+
case: (pattern: Pattern<T>, handler: (value: T) => R) => /*elided*/ any;
|
|
6082
6110
|
build: () => (value: T) => R;
|
|
6083
6111
|
};
|
|
6084
6112
|
/**
|
|
@@ -6097,12 +6125,12 @@ declare const Match: (<T extends Type>(value: T) => UntypedMatch<T>) & {
|
|
|
6097
6125
|
* .build()
|
|
6098
6126
|
*/
|
|
6099
6127
|
builder: <T extends Type, R extends Type>() => {
|
|
6100
|
-
case: (pattern: Pattern<T>, result: PatternResult<T, R>) => /*elided*/any;
|
|
6101
|
-
when: (guard: (value: T) => boolean, result: PatternResult<T, R>) => /*elided*/any;
|
|
6128
|
+
case: (pattern: Pattern<T>, result: PatternResult<T, R>) => /*elided*/ any;
|
|
6129
|
+
when: (guard: (value: T) => boolean, result: PatternResult<T, R>) => /*elided*/ any;
|
|
6102
6130
|
default: (result: PatternResult<T, R>) => {
|
|
6103
6131
|
build: () => (value: T) => R;
|
|
6104
6132
|
};
|
|
6105
6133
|
};
|
|
6106
6134
|
};
|
|
6107
6135
|
//#endregion
|
|
6108
|
-
export {
|
|
6136
|
+
export { LayerError as $, Either as $n, TaskOutcome as $t, HttpQueryParams as A, Collection as An, DoGenerator as At, ResponseDecodeError as B, createCustomSerializer as Bn, DecoderError as Bt, TryKind as C, FunctypeSum as Cn, isExtractable as Cr, createErrorSerializer as Ct, HttpClient as D, Traversable as Dn, Cond as Dr, $ as Dt, Http as E, FunctypeCollection as En, Doable as Er, safeStringify as Et, DecodeError as F, JSONValue as Fn, LeftErrorType as Ft, InterruptedError as G, fromBinary as Gn, CancellationTokenSource as Gt, TestClockTag as H, createSerializer as Hn, DecoderErrorLeaf as Ht, HttpError as I, Serialization_d_exports as In, NoneError as It, Task as J, taggedEnvelope as Jn, Sync as Jt, RIO as K, fromJSON as Kn, Err as Kt, HttpMethod as L, FUNCTYPE_MARKER as Ln, isDoCapable as Lt, HttpRequestView as M, List as Mn, FailureError as Mt, HttpResponse as N, Try as Nn, FailureErrorType as Nt, HttpClientConfig as O, Matchable as On, Do as Ot, ParseMode as P, TypeNames as Pn, LeftError as Pt, Layer as Q, LazyList as Qn, TaskMetadata as Qt, HttpStatusError as R, FunctypeEnvelope as Rn, unwrap as Rt, OptionKind as S, ValidatedBrandCompanion as Sn, Extractable as Sr, TaskErrorInfo as St, FoldableUtils as T, FunctypeBase as Tn, DoResult as Tr, formatStackTrace as Tt, TestContext as U, createTaggedSerializer as Un, Async as Ut, TestClock as V, createSerializationCompanion as Vn, DecoderErrorComposite as Vt, IO as W, envelope as Wn, CancellationToken as Wt, UIO as X, deserializeError as Xn, Task$1 as Xt, TimeoutError as Y, SerializedError as Yn, TaggedThrowable as Yt, UnsupportedSyncOperationError as Z, serializeError as Zn, TaskFailure as Zt, Identity as _, PositiveInteger as _n, AsyncMonad as _r, TypedError as _t, OptionConstructor as a, NAME as an, TestEither as ar, ContextServices as at, Kind as b, UrlString as bn, CollectionOps as br, ErrorFormatterOptions as bt, Valuable as c, Base as cn, isLeft as cr, TagService as ct, Obj as d, EmailAddress as dn, tryCatchAsync as dr, Validation as dt, TaskParams as en, EitherBase as er, LayerInput as et, ESMap as f, ISO8601Date as fn, Widen as fr, ValidationRule as ft, Lazy as g, PatternString as gn, Applicative as gr, ErrorStatus as gt, KVTraversable as h, NonNegativeNumber as hn, Promisable as hr, ErrorMessage as ht, Option as i, isTaggedThrowable as in, RightOf as ir, Context as it, HttpRequestOptions as j, Set as jn, EmptyListError as jt, HttpMethodOptions as k, MatchableUtils as kn, DoAsync as kt, ValuableParams as l, BoundedNumber as ln, isRight as lr, FieldValidation as lt, Map$1 as m, NonEmptyString as mn, reduceWiden as mr, ErrorCode as mt, UntypedMatch as n, TaskSuccess as nn, LeftOf as nr, Exit as nt, Some as o, Throwable as on, TypeCheckLeft as or, HasService as ot, ESMapType as p, IntegerNumber as pn, reduceRightWiden as pr, Validator as pt, RepeatExhausted as q, fromYAML as qn, Ok as qt, None as r, createCancellationTokenSource as rn, Right as rr, ExitTag as rt, Stack as s, ThrowableType as sn, TypeCheckRight as sr, Tag as st, Match as t, TaskResult as tn, Left as tr, LayerOutput as tt, Ref as u, BoundedString as un, tryCatch as ur, FormValidation as ut, EitherKind as v, PositiveNumber as vn, Functor as vr, TypedErrorContext as vt, UniversalContainer as w, Functype as wn, ParseError as wr, formatError as wt, ListKind as x, ValidatedBrand as xn, ContainerOps as xr, ErrorWithTaskInfo as xt, HKT as y, UUID as yn, Monad as yr, ErrorChainElement as yt, NetworkError as z, SerializationResult as zn, Decoder 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
|
-
import { i as Companion, n as InstanceType, r as isCompanion, t as CompanionMethods } from "./CompanionTypes-
|
|
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-
|
|
4
|
-
import { $ as
|
|
2
|
+
import { i as Companion, n as InstanceType, r as isCompanion, t as CompanionMethods } from "./CompanionTypes-Cc90cQ4P.js";
|
|
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-B8KM-H8Y.js";
|
|
4
|
+
import { $ as LayerError, $n as Either, $t as TaskOutcome, A as HttpQueryParams, An as Collection, At as DoGenerator, B as ResponseDecodeError, Bn as createCustomSerializer, Bt as DecoderError, C as TryKind, Cn as FunctypeSum, Cr as isExtractable, Ct as createErrorSerializer, D as HttpClient, Dn as Traversable, Dr as Cond, Dt as $, E as Http, En as FunctypeCollection, Er as Doable, Et as safeStringify, F as DecodeError, Fn as JSONValue, Ft as LeftErrorType, G as InterruptedError, Gn as fromBinary, Gt as CancellationTokenSource, H as TestClockTag, Hn as createSerializer, Ht as DecoderErrorLeaf, I as HttpError, In as Serialization_d_exports, It as NoneError, J as Task, Jn as taggedEnvelope, Jt as Sync, K as RIO, Kn as fromJSON, Kt as Err, L as HttpMethod, Ln as FUNCTYPE_MARKER, Lt as isDoCapable, M as HttpRequestView, Mn as List, Mt as FailureError, N as HttpResponse, Nn as Try, Nt as FailureErrorType, O as HttpClientConfig, On as Matchable, Ot as Do, P as ParseMode, Pn as TypeNames, Pt as LeftError, Q as Layer, Qn as LazyList, Qt as TaskMetadata, R as HttpStatusError, Rn as FunctypeEnvelope, Rt as unwrap, S as OptionKind, Sn as ValidatedBrandCompanion, Sr as Extractable, St as TaskErrorInfo, T as FoldableUtils, Tn as FunctypeBase, Tr as DoResult, Tt as formatStackTrace, U as TestContext, Un as createTaggedSerializer, Ut as Async, V as TestClock, Vn as createSerializationCompanion, Vt as DecoderErrorComposite, W as IO, Wn as envelope, Wt as CancellationToken, X as UIO, Xn as deserializeError, Xt as Task$1, Y as TimeoutError, Yn as SerializedError, Yt as TaggedThrowable, Z as UnsupportedSyncOperationError, Zn as serializeError, Zt as TaskFailure, _ as Identity, _n as PositiveInteger, _r as AsyncMonad, _t as TypedError, a as OptionConstructor, an as NAME, ar as TestEither, at as ContextServices, b as Kind, bn as UrlString, br as CollectionOps, bt as ErrorFormatterOptions, c as Valuable, cn as Base, cr as isLeft, ct as TagService, d as Obj, dn as EmailAddress, dr as tryCatchAsync, dt as Validation, en as TaskParams, er as EitherBase, et as LayerInput, f as ESMap, fn as ISO8601Date, fr as Widen, ft as ValidationRule, g as Lazy, gn as PatternString, gr as Applicative, gt as ErrorStatus, h as KVTraversable, hn as NonNegativeNumber, hr as Promisable, ht as ErrorMessage, i as Option, in as isTaggedThrowable, ir as RightOf, it as Context, j as HttpRequestOptions, jn as Set, jt as EmptyListError, k as HttpMethodOptions, kn as MatchableUtils, kt as DoAsync, l as ValuableParams, ln as BoundedNumber, lr as isRight, lt as FieldValidation, m as Map, mn as NonEmptyString, mr as reduceWiden, mt as ErrorCode, n as UntypedMatch, nn as TaskSuccess, nr as LeftOf, nt as Exit, o as Some, on as Throwable, or as TypeCheckLeft, ot as HasService, p as ESMapType, pn as IntegerNumber, pr as reduceRightWiden, pt as Validator, q as RepeatExhausted, qn as fromYAML, qt as Ok, r as None, rn as createCancellationTokenSource, rr as Right, rt as ExitTag, s as Stack, sn as ThrowableType, sr as TypeCheckRight, st as Tag, t as Match, tn as TaskResult, tr as Left, tt as LayerOutput, u as Ref, un as BoundedString, ur as tryCatch, ut as FormValidation, v as EitherKind, vn as PositiveNumber, vr as Functor, vt as TypedErrorContext, w as UniversalContainer, wn as Functype, wr as ParseError, wt as formatError, x as ListKind, xn as ValidatedBrand, xr as ContainerOps, xt as ErrorWithTaskInfo, y as HKT, yn as UUID, yr as Monad, yt as ErrorChainElement, z as NetworkError, zn as SerializationResult, zt as Decoder } from "./index-j0hrJjoo.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, 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 };
|
|
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, UnsupportedSyncOperationError, 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{$ 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,
|
|
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,Pt as j,Q as M,R as N,S as P,St as F,T as I,Tt as L,U as R,V as z,W as B,X as V,Y as H,Z as U,_ as W,_t as G,a as K,at as q,b as J,bt as Y,c as X,ct as Z,d as Q,dt as $,et as ee,f as te,ft as ne,g as re,gt as ie,h as ae,ht as oe,i as se,it as ce,j as le,jt as ue,k as de,kt as fe,l as pe,lt as me,m as he,mt as ge,n as _e,nt as ve,o as ye,ot as be,p as xe,pt as Se,q as Ce,r as we,rt as Te,s as Ee,st as De,t as Oe,tt as ke,u as Ae,ut as je,v as Me,vt as Ne,w as Pe,wt as Fe,x as Ie,xt as Le,y as Re,yt as ze,z as Be}from"./src-dCt7rWSB.js";import{t as Ve}from"./Companion-DiOMBHDG.js";import{a as He,c as Ue,d as We,f as Ge,i as Ke,l as qe,n as Je,o as Ye,r as Xe,s as Ze,t as Qe,u as $e}from"./serialization-my_TLROv.js";import{n as et,t as tt}from"./typeclass-C61yDVYd.js";import{t as nt}from"./CompanionTypes-BVqO7Kc2.js";import{Tuple as rt}from"./tuple/index.js";export{w as $,M as Base,ke as BoundedNumber,ve as BoundedString,e as Brand,t as BrandedBoolean,n as BrandedNumber,r as BrandedString,Ve as Companion,ee as Cond,Pe as Context,z as Decoder,y as DecoderError,E as Do,A as DoAsync,B as ESMap,ge as Either,Te as EmailAddress,_ as EmptyListError,v as Err,d as Exit,Qe as FUNCTYPE_MARKER,b as FailureError,pe as FoldableUtils,X as HKT,Ae as Http,te as HttpClient,Q as HttpErrors,Me as IO,ce as ISO8601Date,Ee as Identity,q as IntegerNumber,Re as InterruptedError,W as Layer,ye as Lazy,m as LazyList,oe as Left,C as LeftError,f as List,R as Map,s as Match,K as MatchableUtils,V as NAME,be as NonEmptyString,De as NonNegativeNumber,l as None,N as NoneError,se as Obj,S as Ok,ue as Option,T as OptionConstructor,j as ParseError,Z as PatternString,me as PositiveInteger,je as PositiveNumber,k as Ref,J as RepeatExhausted,ie as Right,_e as Serialization,fe as Set,D as Some,we as Stack,re as Tag,Ce as Task,xe as TestClock,he as TestClockTag,ae as TestContext,U as Throwable,Ie as TimeoutError,g as Try,rt as Tuple,G as TypeCheckLeft,Ne as TypeCheckRight,Fe as Typeable,p as TypedError,$ as UUID,P as UnsupportedSyncOperationError,ne as UrlString,Se as ValidatedBrand,h as Validation,Oe as Valuable,i as createBrander,x as createCancellationTokenSource,Je as createCustomSerializer,O as createErrorSerializer,Xe as createSerializationCompanion,Ke as createSerializer,He as createTaggedSerializer,We as deserializeError,Ye as envelope,de as formatError,c as formatStackTrace,Ze as fromBinary,Ue as fromJSON,qe as fromYAML,a as hasBrand,nt as isCompanion,Be as isDoCapable,I as isExtractable,ze as isLeft,Y as isRight,H as isTaggedThrowable,L as isTypeable,tt as reduceRightWiden,et as reduceWiden,le as safeStringify,Ge as serializeError,$e as taggedEnvelope,Le as tryCatch,F as tryCatchAsync,u as unwrap,o as unwrapBrand};
|
package/dist/io/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
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 };
|
|
1
|
+
import { $ as LayerError, G as InterruptedError, H as TestClockTag, J as Task, K as RIO, Q as Layer, U as TestContext, V as TestClock, W as IO, X as UIO, Y as TimeoutError, Z as UnsupportedSyncOperationError, at as ContextServices, ct as TagService, et as LayerInput, it as Context, nt as Exit, ot as HasService, q as RepeatExhausted, rt as ExitTag, st as Tag, tt as LayerOutput } from "../index-j0hrJjoo.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, UnsupportedSyncOperationError };
|
package/dist/io/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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,
|
|
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,w as l,x as u,y as d}from"../src-dCt7rWSB.js";export{l as Context,e as Exit,c as IO,d as InterruptedError,n as Layer,r as RepeatExhausted,i as Tag,s as TestClock,o as TestClockTag,a as TestContext,u as TimeoutError,t as UnsupportedSyncOperationError};
|
package/dist/lazy/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { g as Lazy } from "../index-
|
|
1
|
+
import { g as Lazy } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Lazy, type Lazy as LazyType };
|
package/dist/lazy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"../src-
|
|
1
|
+
import{o as e}from"../src-dCt7rWSB.js";export{e as Lazy};
|
package/dist/list/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Mn as List } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { List };
|
package/dist/list/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ct as e}from"../src-dCt7rWSB.js";export{e as List};
|
package/dist/map/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { m as Map } from "../index-
|
|
1
|
+
import { m as Map } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Map };
|
package/dist/map/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{U as e}from"../src-dCt7rWSB.js";export{e as Map};
|
package/dist/obj/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { d as Obj } from "../index-
|
|
1
|
+
import { d as Obj } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Obj };
|
package/dist/obj/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"../src-
|
|
1
|
+
import{i as e}from"../src-dCt7rWSB.js";export{e as Obj};
|
package/dist/option/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as OptionConstructor, i as Option, o as Some, r as None } from "../index-
|
|
1
|
+
import { a as OptionConstructor, i as Option, o as Some, r as None } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { None, Option, OptionConstructor, Some };
|
package/dist/option/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{At as e,Mt as t,
|
|
1
|
+
import{At as e,Mt as t,Nt as n,jt as r}from"../src-dCt7rWSB.js";export{e as None,r as Option,t as OptionConstructor,n as Some};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Bn as
|
|
1
|
+
import { Bn as createCustomSerializer, Fn as JSONValue, Gn as fromBinary, Hn as createSerializer, Jn as taggedEnvelope, Kn as fromJSON, Ln as FUNCTYPE_MARKER, Rn as FunctypeEnvelope, Un as createTaggedSerializer, Vn as createSerializationCompanion, Wn as envelope, Xn as deserializeError, Yn as SerializedError, Zn as serializeError, qn as fromYAML, zn as SerializationResult } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { FUNCTYPE_MARKER, FunctypeEnvelope, type JSONValue, SerializationResult, SerializedError, createCustomSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, fromBinary, fromJSON, fromYAML, serializeError, taggedEnvelope };
|
package/dist/set/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { jn as Set } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Set };
|
package/dist/set/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{kt as e}from"../src-dCt7rWSB.js";export{e as Set};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
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
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
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
|
|
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}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)))),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
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
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
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(`
|
|
@@ -13,5 +13,5 @@ import{t as e}from"./rolldown-runtime-DK3Fl9T5.js";import{Brand as t}from"./bran
|
|
|
13
13
|
`);return[t[0],...t.slice(1).map(e=>e.trim())].join(`
|
|
14
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
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
|
|
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){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},ln=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 un=Symbol.for(`functype/IO/effect`),B=e=>e[un],V=e=>{let t={[Symbol.toStringTag]:`IO`,[un]: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 ln(n.max)));let r=i=>t.flatMap(t=>{if(e(t))return z(W.succeed(t));if(i<=1)return z(W.fail(new ln(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},dn=e=>{if(e instanceof sn||e instanceof cn)throw e},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 dn(t),e.f(t)}case`Recover`:try{return H(B(e.effect),t)}catch(t){return dn(t),e.fallback}case`RecoverWith`:try{return z(H(B(e.effect),t))}catch(n){dn(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 dn(t),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=e instanceof sn?z(R.interrupted()):z(R.fail(e)),e}finally{H(B(e.release(n,r)),t)}}case`Race`:throw new cn(`race`);case`Timeout`:throw new cn(`timeout`)}},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.isFailure()?R.succeed(e.fallback):z(n)}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 ln(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 fn(W.succeed({}))}},fn=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return fn(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return fn(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return fn(e.tap(t))},tapEffect(t){return fn(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`})`}}),pn={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()))},mn=e=>({id:e,_tag:`Tag`,toString(){return`Tag(${e})`}}),hn=()=>{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})})}}},gn=mn(`TestClock`),_n={make:hn,tag:gn,test:async e=>e(hn()),get:G.service(gn),advance:e=>G.serviceWithIO(gn,t=>G.async(()=>t.advance(e))),setTime:e=>G.serviceWithIO(gn,t=>G.async(()=>t.setTime(e))),runAll:G.serviceWithIO(gn,e=>G.async(()=>e.runAll())),context:()=>{let e=hn();return{clock:e,context:I.make(gn,e)}}},vn={make:()=>{let e=hn(),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=hn();return vn.make().withService(gn,e)}},yn=mn(`HttpClient`),bn={},xn=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)}}}),Sn=(e,t)=>!e||t.startsWith(`http://`)||t.startsWith(`https://`)?t:`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`,Cn=(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},wn=(e,t,n)=>{let r=Sn(e,t);return n?Cn(r,n):r},Tn=(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(Tn(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(Tn(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(Tn(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(Tn(e,`List`)){let n=e.toArray().map(e=>q(e,t));return t===`tagged`?{_tag:`List`,value:n}:n}if(Tn(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},En=(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}},Dn=e=>{let t=e.get(`content-type`)??``;return t.includes(`application/json`)?`json`:t.startsWith(`text/`)?`text`:`raw`},On=async(e,t,n,r,i,a)=>{let o=t??Dn(e.headers),s,c={};switch(o){case`json`:{let t=await e.text();c.value=t;try{s=JSON.parse(t)}catch(e){throw xn.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 xn.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 xn.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:wn(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:En(n.body,r)}}catch(e){return{ok:!1,cause:e}}})();if(!i.ok)return G.fail(xn.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 xn.httpStatusError(n.url,n.method,e.status,e.statusText,t)}return On(e,n.parseAs,n.url,n.method,t.decode,t.validate)}),e=>typeof e==`object`&&e&&`_tag`in e?e:xn.networkError(n.url,n.method,e));return e.afterResponse?c.flatMap(t=>e.afterResponse(t).map(e=>e)):c})},kn=e=>J(bn,e),An=r({},{request:kn,get:(e,t)=>kn({...t,url:e,method:`GET`}),post:(e,t)=>kn({...t,url:e,method:`POST`}),put:(e,t)=>kn({...t,url:e,method:`PUT`}),patch:(e,t)=>kn({...t,url:e,method:`PATCH`}),delete:(e,t)=>kn({...t,url:e,method:`DELETE`}),head:(e,t)=>kn({...t,url:e,method:`HEAD`,parseAs:`raw`}),options:(e,t)=>kn({...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`})})}),jn={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)},Mn=e=>typeof e==`object`&&!!e&&(e._tag===`Some`||e._tag===`None`),Y=e=>typeof e==`object`&&!!e&&e._tag===`List`,Nn=e=>typeof e==`object`&&!!e&&(e._tag===`Left`||e._tag===`Right`),Pn=e=>typeof e==`object`&&!!e&&(e._tag===`Success`||e._tag===`Failure`),X=()=>{let e=(e,t)=>{if(Mn(e)||Y(e)||Nn(e)||Pn(e))return e.map(e=>t(e));throw Error(`Unsupported functor type: ${JSON.stringify(e)}`)},t=e=>{if(Mn(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(Nn(e))return e.isRight()?e.fold(()=>null,e=>e):e;if(Pn(e))return e.isSuccess()?e.orThrow():e;throw Error(`Unsupported functor type for flatten: ${JSON.stringify(e)}`)},n=(e,t)=>{if(Mn(e)||Y(e)||Nn(e)||Pn(e))return e.flatMap(e=>t(e));throw Error(`Unsupported functor type for flatMap: ${JSON.stringify(e)}`)},r=(e,t)=>{if(Mn(e)&&Mn(t)||Y(e)&&Y(t)||Nn(e)&&Nn(t)||Pn(e)&&Pn(t))return e.flatMap(e=>t.map(t=>e(t)));throw Error(`Unsupported functor type for ap: ${JSON.stringify(e)}`)},i=e=>{if(Mn(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(Mn(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`}},Fn=X();X.map=(e,t)=>Fn.map(e,t),X.flatten=e=>Fn.flatten(e),X.flatMap=(e,t)=>Fn.flatMap(e,t),X.ap=(e,t)=>Fn.ap(e,t),X.sequence=e=>Fn.sequence(e),X.traverse=(e,t)=>Fn.traverse(e,t),X.isOption=Mn,X.isList=Y,X.isEither=Nn,X.isTry=Pn;const In=e=>({id:e,isSame:t=>t.id===e}),Ln=r(In,{of:e=>In(e),pure:e=>In(e)}),Rn=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`}},zn={of:e=>Rn(e),fromValue:e=>Rn(()=>e),fromOption:(e,t)=>Rn(()=>e._tag===`Some`?e.value:t()),fromTry:e=>Rn(()=>e.orThrow()),fromEither:e=>Rn(()=>e.fold(e=>{throw e},e=>e)),fromPromise:e=>Rn(()=>{throw Error(`Promise not yet resolved. Use await on the promise before creating Lazy.`)}),fail:e=>Rn(()=>{throw e}),evaluated:e=>Rn(()=>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 zn.fail(e)}return zn.evaluated(t.value)}},Z=r(Rn,zn),Bn={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}}}),Vn=e=>Q(e),Hn={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 Hn.fromJSON(t)}},Un=r(Vn,Hn),$=(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)}},Wn=(e=[])=>$(e),Gn={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 Kn(t.value)},fromYAML:e=>{let t=e.split(`
|
|
17
|
+
`)[1]?.split(`: `)[1];if(!t)return Kn([]);let n=JSON.parse(t);return Kn(n)},fromBinary:e=>{let t=Buffer.from(e,`base64`).toString();return Gn.fromJSON(t)}},Kn=r(Wn,Gn);var qn=e({deserialize:()=>$n,deserializeStrict:()=>er,fromEnvelope:()=>rr,isFunctypeValue:()=>ir,serialize:()=>tr,toEnvelope:()=>nr});let Jn;const Yn=()=>(Jn===void 0&&(Jn={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=>Un(e.value),Stack:e=>Kn(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)}}),Jn),Xn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zn=e=>Xn(e)&&typeof e[`@functype`]==`string`,Qn=e=>{if(Array.isArray(e))return e.map(Qn);if(Zn(e)){let t=e[l],n=Yn()[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]=Qn(e[t]);return n(r)}if(Xn(e)){let t={};for(let n of Object.keys(e))t[n]=Qn(e[n]);return t}return e},$n=e=>x(()=>Qn(JSON.parse(e))),er=e=>x(()=>{let t=JSON.parse(e);if(!Zn(t))throw Error(`Serialization.deserializeStrict: input is not a functype envelope (no @functype marker at the top level)`);return Qn(t)}),tr=e=>JSON.stringify(e??null),nr=e=>JSON.parse(JSON.stringify(e??null)),rr=e=>x(()=>Qn(e)),ir=e=>typeof e==`object`&&!!e&&typeof e.serialize==`function`&&typeof e._tag==`string`;function ar(e){let t=he({_tag:e._tag,impl:e.impl});return{...t,toValue:()=>({_tag:t._tag,value:e.value})}}export{Je as $,Jt as A,p as At,Bt as B,R as C,C as Ct,P as D,fe as Dt,$t as E,x as Et,Wt as F,O as G,M as H,Gt as I,et as J,k as K,Ut as L,Vt as M,re as Mt,It as N,d as Nt,Xt as O,_ as Ot,Rt as P,ne as Pt,Ye as Q,Ht as R,cn as S,De as St,tn as T,ge as Tt,st as U,Nt as V,rt as W,Xe as X,Qe as Y,Ze as Z,pn as _,Ee as _t,Bn as a,Ne as at,ln as b,Se as bt,X as c,He as ct,xn as d,Re as dt,Ge as et,yn as f,Le as ft,mn as g,w as gt,vn as h,T as ht,Un as i,ze as it,qt as j,m as jt,Yt as k,ce as kt,jn as l,Pe as lt,gn as m,Ae as mt,qn as n,Ve as nt,Z as o,Fe as ot,_n as p,E as pt,A as q,Kn as r,Ie as rt,Ln as s,Me as st,ar as t,Be as tt,An as u,je as ut,G as v,Te as vt,I as w,he as wt,on as x,we as xt,sn as y,Ce as yt,zt as z};
|
package/dist/try/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Nn as Try, Pn as TypeNames } from "../index-j0hrJjoo.js";
|
|
2
2
|
export { Try, TypeNames };
|
package/dist/try/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Et as e}from"../src-dCt7rWSB.js";export{e as Try};
|
package/dist/tuple/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as Tuple } from "../Tuple-
|
|
1
|
+
import { t as Tuple } from "../Tuple-B8KM-H8Y.js";
|
|
2
2
|
export { Tuple };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _r as
|
|
1
|
+
import { _r as AsyncMonad, br as CollectionOps, fr as Widen, gr as Applicative, hr as Promisable, mr as reduceWiden, pr as reduceRightWiden, vr as Functor, xr as ContainerOps, yr as Monad } from "../index-j0hrJjoo.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.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A functional programming library for TypeScript, using immutable data structures and type classes",
|
|
6
6
|
"keywords": [
|
|
@@ -35,13 +35,13 @@
|
|
|
35
35
|
"@eslint/compat": "^2.1.0",
|
|
36
36
|
"@types/node": "~24.10.15",
|
|
37
37
|
"eslint-plugin-functional": "^9.0.5",
|
|
38
|
-
"fast-check": "^4.
|
|
39
|
-
"globals": "^17.
|
|
40
|
-
"ts-builds": "^3.2.
|
|
41
|
-
"tsdown": "^0.22.
|
|
42
|
-
"tsx": "^4.23.
|
|
38
|
+
"fast-check": "^4.9.0",
|
|
39
|
+
"globals": "^17.8.0",
|
|
40
|
+
"ts-builds": "^3.2.3",
|
|
41
|
+
"tsdown": "^0.22.14",
|
|
42
|
+
"tsx": "^4.23.1",
|
|
43
43
|
"typedoc": "^0.28.20",
|
|
44
|
-
"eslint-config-functype": "2.
|
|
44
|
+
"eslint-config-functype": "2.107.0"
|
|
45
45
|
},
|
|
46
46
|
"types": "./dist/index.d.ts",
|
|
47
47
|
"module": "./dist/index.js",
|