functype 2.2.1 → 2.3.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/cli/data.js CHANGED
@@ -1 +1 @@
1
- import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.mapTry(f, onError)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.mapTry(f, onError) // a throw in f becomes a typed error, not a defect`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},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; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse })`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`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 and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},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:[`.getOrElse(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().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
1
+ import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.mapTry(f, onError)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.mapTry(f, onError) // a throw in f becomes a typed error, not a defect`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},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; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. 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 }): HttpMethods`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`,`DecoderError.formatPath(path): string — one path as format renders it (endpoints[1].name; (root) when empty)`]}},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 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`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 and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},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:[`.getOrElse(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().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
@@ -278,6 +278,15 @@ declare const MatchStatics: {
278
278
  * .default("Unknown")
279
279
  *
280
280
  * @example
281
+ * // A string-literal result widens to string, so mark each result `as const`
282
+ * // to match into a literal union
283
+ * type Grade = "healthy" | "degraded" | "unknown"
284
+ * const grade: Grade = Match(status)
285
+ * .caseValue("ok", "healthy" as const)
286
+ * .caseValue("degraded", () => "degraded" as const)
287
+ * .default("unknown" as const)
288
+ *
289
+ * @example
281
290
  * // Using exhaustive() method
282
291
  * type Status = "idle" | "loading" | "success" | "error"
283
292
  * const result = Match<Status, string>("success")
@@ -46,6 +46,7 @@ declare const DecoderErrorStatics: {
46
46
  readonly message: string;
47
47
  }>;
48
48
  format: (e: DecoderError) => string;
49
+ formatPath: (path: ReadonlyArray<string>) => string;
49
50
  };
50
51
  export declare const DecoderError: DecoderErrorCompanion;
51
52
  /** The type of `DecoderError`: its tag and its statics, named so that errors and hovers print `DecoderErrorCompanion`. */
@@ -1,2 +1,2 @@
1
1
  import{Companion as e}from"../companion/Companion.js";import{List as t}from"../list/index.js";const n=(e,t,n)=>({_tag:`Leaf`,path:e,message:t,cause:n}),r=(e,t)=>({_tag:`Composite`,path:e,children:t}),i=e=>e._tag===`Leaf`,a=e=>e._tag===`Composite`,o=(e,t)=>e._tag===`Leaf`?t.Leaf(e):t.Composite(e),s=(e,n)=>n._tag===`Leaf`?{...n,path:[e,...n.path]}:{...n,children:t(n.children.toArray().map(t=>s(e,t)))},c=e=>e._tag===`Leaf`?t([{path:e.path,message:e.message}]):t(e.children.toArray().flatMap(e=>c(e).toArray())),l=e=>c(e).toArray().map(({path:e,message:t})=>`${u(e)}: ${t}`).join(`
2
- `),u=e=>e.length===0?`(root)`:e.reduce((e,t)=>t.startsWith(`[`)&&t.endsWith(`]`)?`${e}${t}`:e===``?t:`${e}.${t}`,``),d=e({_tag:`DecoderError`},{leaf:n,composite:r,isLeaf:i,isComposite:a,match:o,prepend:s,flatten:c,format:l});export{d as DecoderError};
2
+ `),u=e=>e.length===0?`(root)`:e.reduce((e,t)=>t.startsWith(`[`)&&t.endsWith(`]`)?`${e}${t}`:e===``?t:`${e}.${t}`,``),d=e({_tag:`DecoderError`},{leaf:n,composite:r,isLeaf:i,isComposite:a,match:o,prepend:s,flatten:c,format:l,formatPath:u});export{d as DecoderError};
@@ -2,7 +2,12 @@ import { IO } from "../io/IO.js";
2
2
  import { HttpClientConfig } from "./HttpClient.js";
3
3
  import { HttpError } from "./HttpError.js";
4
4
  import { HttpMethodOptions, HttpRequestOptions, HttpResponse } from "./HttpRequest.js";
5
- type HttpMethods = {
5
+ /**
6
+ * The client `Http.client(config)` returns: `request` and one method per HTTP verb, each bound to the client's config.
7
+ * Name it to pass a client around, such as `(http: HttpMethods) => http.get("/health")`.
8
+ * Not to be confused with `HttpMethod`, the verb union `"GET" | "POST" | …`.
9
+ */
10
+ export type HttpMethods = {
6
11
  readonly request: <T = unknown, TReq = unknown>(options: HttpRequestOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
7
12
  readonly get: <T = unknown>(url: string, options?: HttpMethodOptions<T>) => IO<never, HttpError, HttpResponse<T>>;
8
13
  readonly post: <T = unknown, TReq = unknown>(url: string, options?: HttpMethodOptions<T, TReq>) => IO<never, HttpError, HttpResponse<T>>;
@@ -1,5 +1,5 @@
1
- import { Http, HttpCompanion } from "./Http.js";
1
+ import { Http, HttpCompanion, HttpMethods } from "./Http.js";
2
2
  import { HttpClient, HttpClientConfig } from "./HttpClient.js";
3
3
  import { DecodeError, HttpError, HttpErrorCompanion, HttpMethod, HttpStatusError, NetworkError, ResponseDecodeError } from "./HttpError.js";
4
4
  import { HttpMethodOptions, HttpQueryParams, HttpRequestOptions, HttpRequestView, HttpResponse, ParseMode } from "./HttpRequest.js";
5
- export { type DecodeError, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, type NetworkError, type ParseMode, type ResponseDecodeError };
5
+ export { type DecodeError, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpMethods, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, type NetworkError, type ParseMode, type ResponseDecodeError };
package/dist/index.d.ts CHANGED
@@ -50,7 +50,7 @@ import { TestClock, TestClockTag, TestContext } from "./io/TestClock.js";
50
50
  import { DecodeError, HttpError, HttpErrorCompanion, HttpMethod, HttpStatusError, NetworkError, ResponseDecodeError } from "./fetch/HttpError.js";
51
51
  import { HttpMethodOptions, HttpQueryParams, HttpRequestOptions, HttpRequestView, HttpResponse, ParseMode } from "./fetch/HttpRequest.js";
52
52
  import { HttpClient, HttpClientConfig } from "./fetch/HttpClient.js";
53
- import { Http, HttpCompanion } from "./fetch/Http.js";
53
+ import { Http, HttpCompanion, HttpMethods } from "./fetch/Http.js";
54
54
  import { Reshapeable } from "./reshapeable/Reshapeable.js";
55
55
  import { Serializable, SerializableEnvelope, SerializationMethods } from "./serializable/Serializable.js";
56
56
  import { JSONValue, Serialization_d_exports } from "./serialization/Serialization.js";
@@ -71,4 +71,4 @@ import { TracedOption } from "./traced/TracedOption.js";
71
71
  import { Valuable, ValuableParams } from "./valuable/Valuable.js";
72
72
  import { Wire, WireMark } from "./wire/index.js";
73
73
  import { Match, MatchCompanion, UntypedMatch } from "./conditional/Match.js";
74
- export { $, type Applicative, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, Collection, type CollectionOps, Companion, CompanionMethods, type Concurrency, type ConcurrencyOptions, Cond, CondCompanion, type ContainerOps, Context, type ContextServices, type Context as ContextType, type DecodeError, Decoder, DecoderCompanion, DecoderError, type DecoderErrorCompanion, type DecoderErrorComposite, type DecoderErrorLeaf, type DieExitOf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherCompanion, EitherKind, EmailAddress, EmptyListError, type Encoder, ErrorChainElement, ErrorChainFormatOptions, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type ExitBase, type ExitCompanion, type ExitTag, type Exit as ExitType, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, type FailureExitOf, FailureOf, FieldValidation, type Flattened, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeCore, FunctypeEnvelope, FunctypeSum, FunctypeValue, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IOCompanion, type Task as IOTask, type IO as IOType, ISO8601Date, Identity, IdentityCompanion, InstanceType, IntegerNumber, InterruptedError, type InterruptedExitOf, InvariantViolation, type JSONValue, KVTraversable, Kind, Layer, type LayerError, type LayerInput, type LayerOutput, type Layer as LayerType, Lazy, type LazyCompanion, LazyList, LazyListCompanion, type Lazy as LazyType, Left, LeftError, LeftErrorType, LeftOf, List, ListCompanion, ListKind, type Logger, Map, MapCompanion, Match, MatchCompanion, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, NoneOf, Obj, ObjCompanion, Option, OptionBase, OptionCompanion, OptionConstructor, OptionKind, ParseError, type ParseMode, ParsedEnvelope, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Reducible, Ref, type RefCompanion, type Ref as RefType, RepeatExhausted, type Reshapeable, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, SetCompanion, Some, SomeOf, type SpanAttributes, SpanTracer, Stack, StackCompanion, type SuccessExitOf, SuccessOf, Tag, type TagService, type Tag as TagType, TaggedThrowable, TaskErrorInfo, TestClock, TestClockTag, type TestClock as TestClockType, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, type TraceEvent, type TraceOp, TracedOption, type Tracer, Traversable, Try, TryBase, TryCompanion, TryKind, Tuple, TupleCompanion, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UnsupportedSyncOperationError, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrandCompanion, type ValidatedBrand as ValidatedBrandType, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, type Wire, type WireMark, createBrander, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, formatError, formatErrorChain, formatStackTrace, fromBinary, fromJSON, getErrorChain, hasBrand, invariant, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
74
+ export { $, type Applicative, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, Collection, type CollectionOps, Companion, CompanionMethods, type Concurrency, type ConcurrencyOptions, Cond, CondCompanion, type ContainerOps, Context, type ContextServices, type Context as ContextType, type DecodeError, Decoder, DecoderCompanion, DecoderError, type DecoderErrorCompanion, type DecoderErrorComposite, type DecoderErrorLeaf, type DieExitOf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherCompanion, EitherKind, EmailAddress, EmptyListError, type Encoder, ErrorChainElement, ErrorChainFormatOptions, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type ExitBase, type ExitCompanion, type ExitTag, type Exit as ExitType, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, type FailureExitOf, FailureOf, FieldValidation, type Flattened, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeCore, FunctypeEnvelope, FunctypeSum, FunctypeValue, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpMethods, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IOCompanion, type Task as IOTask, type IO as IOType, ISO8601Date, Identity, IdentityCompanion, InstanceType, IntegerNumber, InterruptedError, type InterruptedExitOf, InvariantViolation, type JSONValue, KVTraversable, Kind, Layer, type LayerError, type LayerInput, type LayerOutput, type Layer as LayerType, Lazy, type LazyCompanion, LazyList, LazyListCompanion, type Lazy as LazyType, Left, LeftError, LeftErrorType, LeftOf, List, ListCompanion, ListKind, type Logger, Map, MapCompanion, Match, MatchCompanion, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, NoneOf, Obj, ObjCompanion, Option, OptionBase, OptionCompanion, OptionConstructor, OptionKind, ParseError, type ParseMode, ParsedEnvelope, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Reducible, Ref, type RefCompanion, type Ref as RefType, RepeatExhausted, type Reshapeable, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, SetCompanion, Some, SomeOf, type SpanAttributes, SpanTracer, Stack, StackCompanion, type SuccessExitOf, SuccessOf, Tag, type TagService, type Tag as TagType, TaggedThrowable, TaskErrorInfo, TestClock, TestClockTag, type TestClock as TestClockType, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, type TraceEvent, type TraceOp, TracedOption, type Tracer, Traversable, Try, TryBase, TryCompanion, TryKind, Tuple, TupleCompanion, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UnsupportedSyncOperationError, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrandCompanion, type ValidatedBrand as ValidatedBrandType, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, type Wire, type WireMark, createBrander, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, formatError, formatErrorChain, formatStackTrace, fromBinary, fromJSON, getErrorChain, hasBrand, invariant, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
package/dist/io/IO.d.ts CHANGED
@@ -205,6 +205,10 @@ type IOEffect<R, E, A> = {
205
205
  readonly _tag: "Timeout";
206
206
  readonly effect: IO<R, E, A>;
207
207
  readonly duration: number;
208
+ /** `timeoutTo`'s value: what the deadline produces instead of a `TimeoutError`. */
209
+ readonly fallback?: {
210
+ readonly value: A;
211
+ };
208
212
  } | {
209
213
  readonly _tag: "InterruptWhen";
210
214
  readonly effect: IO<R, E, A>;
@@ -635,6 +639,10 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
635
639
  timeout(ms: number): IO<R, E | TimeoutError, A>;
636
640
  /**
637
641
  * Returns a fallback value if the effect doesn't complete within the specified duration.
642
+ *
643
+ * Only this deadline produces the fallback. The effect's own failures, including a
644
+ * `TimeoutError` from a timeout inside it, its defects and its interruption pass through
645
+ * unchanged, as the type `IO<R, E, A | B>` says.
638
646
  * @param ms - Maximum time in milliseconds
639
647
  * @param fallback - Value to return on timeout
640
648
  */
package/dist/io/IO.js CHANGED
@@ -1 +1 @@
1
- import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{workerCount as r}from"../internal/concurrency.js";import{define as i}from"../internal/define.js";import{anySignal as a}from"../internal/signal.js";import{safeStringify as o}from"../internal/stringify.js";import{None as s,Option as c,Some as l}from"../option/index.js";import{Try as u}from"../try/index.js";import{Context as d}from"./Context.js";import{Exit as f}from"./Exit.js";import{SpanTracer as p}from"./SpanTracer.js";const m=e=>e,h=e=>e(),g=(e,t)=>e(t),_=(e,t,n)=>e(t,n);var v=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},y=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`InterruptedError`}},b=class extends Error{constructor(e){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},x=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 S=`effect`,C=e=>e[S],w=e=>{let t=!1;return{next:n=>t?{done:!0,value:n}:(t=!0,{done:!1,value:e})}},T=e=>m(e),E=i()(`IO`,{[Symbol.toStringTag]:`IO`,map(e){return D(m({_tag:`Map`,effect:this,f:e}))},flatMap(e){return D(m({_tag:`FlatMap`,effect:this,f:e}))},mapTry(e,t){return this.flatMap(n=>Q.tryCatch(()=>e(n),t))},tap(e){return this.map(t=>(e(t),t))},tapEffect(e){return this.flatMap(t=>e(t).map(()=>t))},mapError(e){return D(m({_tag:`MapError`,effect:this,f:e}))},tapError(e){return this.mapError(t=>(e(t),t))},recover(e){return D(m({_tag:`Recover`,effect:this,fallback:e}))},recoverWith(e){return D(m({_tag:`RecoverWith`,effect:this,f:e}))},fold(e,t){return D(m({_tag:`Fold`,effect:this,onFailure:e,onSuccess:t}))},match(e){return this.fold(e.failure,e.success)},catchTag(e,t){return D(m({_tag:`RecoverWith`,effect:this,f:n=>typeof n==`object`&&n&&`_tag`in n&&n._tag===e?m(t(m(n))):m(Q.fail(n))}))},catchAll(e){return this.recoverWith(e)},retry(e){return e<=0?this:this.recoverWith(()=>this.retry(e-1))},retryWithDelay(e,t){return e<=0?this:this.recoverWith(()=>Q.sleep(t).flatMap(()=>this.retryWithDelay(e-1,t)))},retryWhile(e){let t=(n,r)=>this.recoverWith(i=>{if(n<=0||!e.while(i,r))return m(Q.fail(i));let a=t(n-1,r+1);return e.delayMs===void 0?a:m(Q.sleep(e.delayMs).flatMap(()=>a))});return t(e.n,1)},retryWithBackoff(e){let t=e.factor??2,n=e.maxMs??3e4,r=e.jitter??!0,i=e.while??(()=>!0),a=(o,s)=>this.recoverWith(c=>{if(o<=0||!i(c,s))return m(Q.fail(c));let l=Math.min(n,e.baseMs*t**(s-1)),u=r?l*(.5+Math.random()*.5):l,d=a(o-1,s+1);return m(Q.sleep(u).flatMap(()=>d))});return a(e.n,1)},repeatUntil(e,t){if(t.max<=0)return m(Q.fail(new x(t.max)));let n=r=>this.flatMap(i=>{if(e(i))return m(Q.succeed(i));if(r<=1)return m(Q.fail(new x(t.max,i)));let a=n(r-1);return t.delayMs===void 0?a:m(Q.sleep(t.delayMs).flatMap(()=>a))});return n(t.max)},repeatWhile(e,t){return this.repeatUntil(t=>!e(t),t)},zipRight(e){return this.flatMap(()=>e)},zipLeft(e){return this.flatMap(t=>e.map(()=>t))},zip(e){return this.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return D(m({_tag:`ProvideContext`,effect:this,context:e}))},provideService(e,t){let n=d.make(e,t);return D(m({_tag:`ProvideContext`,effect:this,context:n}))},provideLayer(e){let t=m(Q.async(async()=>{let t=d.empty();return await e.build(m(t))}));return m(t.flatMap(e=>D(m({_tag:`ProvideContext`,effect:this,context:e}))))},async run(){return F(await q(C(T(this)),A,void 0,void 0))},async runOrThrow(){return I(await q(C(T(this)),A,void 0,void 0))},runSync(){return F(B(C(T(this)),A,void 0))},runSyncOrThrow(){return I(B(C(T(this)),A,void 0))},async runExit(e){let t=e?.signal;if(!t)return q(C(T(this)),A,void 0,void 0);let n=await q(C(T(this)),A,t,void 0);return t.aborted&&n.isFailure()?f.interrupted():n},async runOption(){let e=await q(C(T(this)),A,void 0,void 0);return e.isSuccess()?l(e.value):s()},async runTry(){let e=await q(C(T(this)),A,void 0,void 0);if(e.isSuccess())return m(u(()=>e.value));let t=O(e),n=t?t.value:/* @__PURE__ */ Error(`Effect was interrupted`);return m(u(()=>{throw n}))},runCancellable(){let e=new AbortController;return{result:T(this).interruptOn(e.signal).run(),cancel:()=>e.abort()}},pipe(e){return e(this)},delay(e){return Q.sleep(e).flatMap(()=>this)},timeout(e){return D(m({_tag:`Timeout`,effect:this,duration:e}))},timeoutTo(e,t){return m(this.timeout(e).recover(m(t)))},interruptOn(e){return D(m({_tag:`InterruptWhen`,effect:this,signal:e}))},withSpan(e,t=j){return D(m({_tag:`WithSpan`,effect:this,name:e,attributes:t}))},toString(){return`IO(${o(this[S]._tag)})`},toJSON(){return{_tag:`IO`,effect:this[S]._tag}},[Symbol.iterator](){return w(this)}}),D=e=>{let t=Object.create(E);return t[S]=e,t},O=e=>{if(e._tag===`Failure`)return{value:e.error};if(e._tag===`Die`)return{value:e.defect}},k=e=>e._tag===`Die`&&e.defect instanceof b?void 0:O(e),A=d.empty(),j=Object.freeze({}),M=e=>{let t=e.get(p);return t.isNone()?void 0:t.orThrow()},N=()=>/* @__PURE__ */ Error(`Cannot run async effect synchronously`),P=e=>/* @__PURE__ */ Error(`Service not found: ${e.id}`),F=e=>{if(e._tag===`Success`)return n(e.value);if(e._tag===`Failure`)return t(e.error);throw e._tag===`Die`?e.defect:new y},I=e=>{if(e._tag===`Success`)return e.value;throw e._tag===`Failure`?e.error:e._tag===`Die`?e.defect:new y},L=e=>{try{return e()}catch(e){return f.die(e)}},R=e=>{let t=typeof e==`object`&&e?e[S]:void 0;if(typeof t==`object`&&t&&typeof t._tag==`string`)return m(t);throw TypeError("IO.gen was yielded a value that isn't an IO. Use `yield*` on an IO; convert an Option, Either or Try first with IO.fromOption, IO.fromEither or IO.fromTry, and wrap a plain value with IO.succeed.")},z=()=>f.die(/* @__PURE__ */ TypeError(`A step produced no outcome: a SpanTracer's run must return what its fn returns`)),B=(e,t,n)=>{let r=[],i=m(e),a=m(t),o;for(;;){if(o===void 0)try{switch(i._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:r.push(i,a),i=C(i.effect);continue;case`ProvideContext`:a=a.merge(i.context),i=C(i.effect);continue;case`Gen`:{let e=h(i.start),t=e.next(void 0);if(t.done===!0){o=f.succeed(t.value);continue}r.push({_tag:`GenNext`,iterator:e},a),i=R(t.value);continue}default:o=V(i,a,n)??z();continue}}catch(e){o=f.die(e);continue}if(r.length===0)return m(o);let e=r.pop(),t=r.pop();try{switch(t._tag){case`Map`:o._tag===`Success`&&(o=f.succeed(g(t.f,o.value)));break;case`FlatMap`:o._tag===`Success`&&(i=C(g(t.f,o.value)),a=e,o=void 0);break;case`MapError`:{let e=k(o);e&&(o=f.fail(g(t.f,e.value)));break}case`Recover`:k(o)&&(o=f.succeed(t.fallback));break;case`RecoverWith`:{let n=k(o);n&&(i=C(g(t.f,n.value)),a=e,o=void 0);break}case`Fold`:{let e=k(o);e?o=f.succeed(g(t.onFailure,e.value)):o._tag===`Success`&&(o=f.succeed(g(t.onSuccess,o.value)));break}case`GenNext`:if(o._tag===`Success`){let n=t.iterator.next(o.value);n.done===!0?o=f.succeed(n.value):(r.push(t,e),i=R(n.value),a=e,o=void 0)}}}catch(e){o=f.die(e)}}},V=(e,t,n)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return f.die(N());case`Auto`:return H(e.thunk);case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Bracket`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(g(e.release,i)),t,n);return o.isSuccess()?a:o}case`BracketExit`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(_(e.release,i,a)),t,n);return o.isSuccess()?a:o}case`All`:return W(e.effects,t,n);case`Race`:return f.die(new b(`race`));case`Timeout`:return f.die(new b(`timeout`));case`Sleep`:return f.die(new b(`sleep`));case`WithSpan`:return U(e,t,n);case`InterruptWhen`:{if(e.signal.aborted)return f.fail(new y);let r=B(C(e.effect),t,n);return r.isInterrupted()?f.fail(new y):r}default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},H=e=>{try{let t=e();return t instanceof Promise?f.die(N()):f.succeed(t)}catch(e){return f.fail(e)}},U=(e,t,n)=>{let r=M(t);if(!r)return B(C(e.effect),t,n);let i=r.start(e.name,e.attributes,n),a=L(()=>r.run(i,()=>B(C(e.effect),t,i)));return r.end(i,a),a},W=(e,t,n)=>{let r=[];for(let i of e){let e=B(C(i),t,n);if(!e.isSuccess())return m(e);r.push(e.value)}return f.succeed(r)},G=(e,t)=>{if(t)return e.isDie()?m(e):f.interrupted()},K=(e,t,n)=>e.isSuccess()||e.isDie()?e:n?f.interrupted():e.isInterrupted()||t.aborted?f.fail(new y):e,q=async(e,t,n,r)=>{let i=[],a=m(e),o=m(t),s,c=()=>n?.aborted??!1;for(;;){if(s===void 0){if(c()){s=f.interrupted();continue}try{switch(a._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:i.push(a,o),a=C(a.effect);continue;case`ProvideContext`:o=o.merge(a.context),a=C(a.effect);continue;case`Gen`:{let e=h(a.start),t=e.next(void 0);if(t.done===!0){s=c()?f.interrupted():f.succeed(t.value);continue}i.push({_tag:`GenNext`,iterator:e},o),a=R(t.value);continue}default:{let e=X(a,o,n,r);s=(e instanceof Promise?await e:e)??z();continue}}}catch(e){s=f.die(e);continue}}if(i.length===0)return m(s);let e=i.pop(),t=i.pop();try{switch(t._tag){case`Map`:s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.f,s.value)));break;case`FlatMap`:s._tag===`Success`&&(c()?s=f.interrupted():(a=C(g(t.f,s.value)),o=e,s=void 0));break;case`MapError`:{let e=O(s);e&&(s=G(s,c())??f.fail(g(t.f,e.value)));break}case`Recover`:O(s)&&(s=G(s,c())??f.succeed(t.fallback));break;case`RecoverWith`:{let n=O(s);if(n){let r=G(s,c());r?s=r:(a=C(g(t.f,n.value)),o=e,s=void 0)}break}case`Fold`:{let e=O(s);e?s=G(s,c())??f.succeed(g(t.onFailure,e.value)):s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.onSuccess,s.value)));break}case`GenNext`:if(s._tag===`Success`){if(c())s=f.interrupted();else{let n=t.iterator.next(s.value);n.done===!0?s=c()?f.interrupted():f.succeed(n.value):(i.push(t,e),a=R(n.value),o=e,s=void 0)}}}}catch(e){s=f.die(e)}}},J=e=>e.catch(e=>f.die(e)),Y=(e,t)=>J(Promise.resolve().then(()=>t?.aborted?f.interrupted():e())),X=(e,t,n,r)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return ee(e.thunk,n);case`Auto`:try{let t=h(e.thunk);return t instanceof Promise?t.then(e=>f.succeed(e),e=>f.fail(e)):f.succeed(t)}catch(e){return f.fail(e)}case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Sleep`:return se(e.duration,n);case`Bracket`:return Y(()=>te(e,t,n,r),n);case`BracketExit`:return Y(()=>ne(e,t,n,r),n);case`Race`:return e.effects.length===0?f.die(/* @__PURE__ */ Error(`No effects to race`)):Y(()=>ce(e.effects,t,n,r),n);case`Timeout`:return Y(()=>le(e.effect,e.duration,t,n,r),n);case`InterruptWhen`:return Y(()=>re(e,t,n,r),n);case`WithSpan`:return Y(()=>ie(e,t,n,r),n);case`All`:return Y(()=>ue(e.effects,e.concurrency,t,n,r),n);default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},ee=async(e,t)=>{try{return f.succeed(await e(t))}catch(e){return f.fail(e)}},Z=async(e,t,n,r)=>{if(n?.aborted)return f.interrupted();try{return await q(C(e()),t,n,r)}catch(e){return f.die(e)}},te=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(g(e.release,a)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},ne=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(_(e.release,a,o)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},re=async(e,t,n,r)=>{let{signal:i}=e,o=a([n,i]);try{let a=await q(C(e.effect),t,o.signal,r);return K(a,i,n?.aborted??!1)}catch(e){return f.die(e)}finally{o.dispose()}},ie=async(e,t,n,r)=>{let i=M(t);if(!i)return q(C(e.effect),t,n,r);let a=i.start(e.name,e.attributes,r),o=await ae(()=>i.run(a,()=>q(C(e.effect),t,n,a)));return i.end(a,oe(o,n)),o},ae=async e=>{try{return await e()}catch(e){return f.die(e)}},oe=(e,t)=>e.isFailure()&&t?.aborted===!0?f.interrupted():e,se=(e,t)=>new Promise(n=>{let r=e===1/0?void 0:setTimeout(()=>{t?.removeEventListener(`abort`,i),n(f.succeed(void 0))},e);function i(){clearTimeout(r),n(f.interrupted())}t?.addEventListener(`abort`,i,{once:!0})}),ce=(e,t,n,r)=>{let i=e.map(()=>{let e=new AbortController;return{own:e,scope:a([n,e.signal])}}),o={settled:!1};return new Promise(n=>{e.forEach((e,a)=>{q(C(e),t,i[a].scope.signal,r).then(e=>{o.settled||(o.settled=!0,i.forEach(({own:e,scope:t},n)=>{n!==a&&e.abort(),t.dispose()}),n(e))})})})},le=(e,t,n,r,i)=>{let o=new AbortController,s=a([r,o.signal]);return new Promise(r=>{let a=setTimeout(()=>{o.abort(),s.dispose(),r(f.fail(new v(t)))},t);q(C(e),n,s.signal,i).then(e=>{clearTimeout(a),s.dispose(),r(e)})})},ue=(e,t,n,i,o)=>{if(e.length===0)return Promise.resolve(f.succeed([]));let s=new AbortController,c=a([i,s.signal]),l=Array(e.length),u={next:0,succeeded:0,settled:!1};return new Promise(i=>{let a=e=>{u.settled=!0,e.isSuccess()||s.abort(),c.dispose(),i(e)},d=()=>{if(u.settled||u.next>=e.length)return;let t=u.next;u.next=t+1,q(C(e[t]),n,c.signal,o).then(n=>{u.settled||(n.isSuccess()?(l[t]=n.value,u.succeeded+=1,u.succeeded===e.length?a(f.succeed(l)):d()):a(m(n)))})};Array.from({length:r(t,e.length)}).forEach(d)})},Q={sync:e=>D({_tag:`Sync`,thunk:e}),succeed:e=>D({_tag:`Succeed`,value:e}),fail:e=>D({_tag:`Fail`,error:e}),die:e=>D({_tag:`Die`,defect:e}),async:e=>D(m({_tag:`Async`,thunk:e})),tryPromise:e=>D({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,r)=>Q.sync(()=>{try{return n(e())}catch(e){return t(r(e))}}).flatMap(e=>Q.fromEither(e)),liftSync:e=>(...t)=>Q.sync(()=>e(...t)),liftPromise:e=>(...t)=>Q.async(()=>e(...t)),fromEither:e=>m(e.isRight()?Q.succeed(e.value):Q.fail(e.value)),fromPromiseEither:(e,t)=>{let n=Q.async(async()=>e());return(t?n.mapError(t):n.recoverWith(e=>Q.die(e))).flatMap(e=>Q.fromEither(e))},fromOption:e=>m(e.isSome()?Q.succeed(e.value):Q.fail(void 0)),fromOptionOrFail:(e,t)=>m(e.isSome()?Q.succeed(e.value):Q.fail(t())),fromTry:e=>m(e.isSuccess()?Q.succeed(e.orThrow()):Q.fail(e.error)),fromResult:e=>m(e.error?Q.fail(e.error):Q.succeed(c(e.data))),tryAsync:(e,t,n)=>n?.aborted?m(Q.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):Q.async(t=>{if(!n)return e(t);if(!t)return e(n);let r=a([n,t]);try{return e(r.signal).finally(r.dispose)}catch(e){throw r.dispose(),e}}).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return Q.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>Q.fromResult({data:e[r],error:e[i]}))},service:e=>D({_tag:`Service`,tag:e}),serviceWith:(e,t)=>Q.service(e).map(t),serviceWithIO:(e,t)=>Q.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return m(D({_tag:`Auto`,thunk:()=>t({})}));let r=m(Q.succeed({})),i=n.reduce((e,[t,n])=>m(e.flatMap(e=>Q.service(n).map(n=>({...e,[t]:n})))),r);return m(i.flatMap(e=>D({_tag:`Auto`,thunk:()=>t(e)})))},all:(e,t)=>{let n=t?.concurrency??`unbounded`;if(r(n,1),n!==1&&e.length>1)return D(m({_tag:`All`,effects:e,concurrency:n}));if(e.length===0)return m(Q.succeed([]));let i=m(Q.succeed([]));return m(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),i))},firstSuccessOf:e=>e.length===0?m(Q.die(/* @__PURE__ */ Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>D(m({_tag:`Sleep`,duration:e})),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?m(Q.succeed(e)):r<=0?m(Q.fail(new x(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>D(m({_tag:`Sleep`,duration:1/0})),get unit(){return m(D({_tag:`Succeed`,value:void 0}))},fromNullable:e=>m(e==null?Q.fail(void 0):Q.succeed(e)),interrupt:()=>D({_tag:`Interrupt`}),bracket:(e,t,n)=>D({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>Q.bracket(e,t,n),bracketExit:(e,t,n)=>D({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>D({_tag:`Race`,effects:e}),forEach:(e,t,n)=>{let i=n?.concurrency??1;if(r(i,1),i!==1)return Q.unit.flatMap(()=>Q.all(e.map(t),{concurrency:i}));if(e.length===0)return m(Q.succeed([]));let a=m(Q.succeed([]));return m(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),a))},timeout:(e,t)=>D(m({_tag:`Timeout`,effect:e,duration:t})),gen:e=>D(m({_tag:`Gen`,start:e})),get Do(){return $(Q.succeed({}))}},$=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return $(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return $(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return $(e.tap(t))},tapEffect(t){return $(e.tapEffect(t))},done(){return e}}),de=e(e=>D(m({_tag:`Auto`,thunk:e})),Q);export{de as IO,S as IOEffectKey,y as InterruptedError,x as RepeatExhausted,v as TimeoutError,b as UnsupportedSyncOperationError};
1
+ import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{workerCount as r}from"../internal/concurrency.js";import{define as i}from"../internal/define.js";import{anySignal as a}from"../internal/signal.js";import{safeStringify as o}from"../internal/stringify.js";import{None as s,Option as c,Some as l}from"../option/index.js";import{Try as u}from"../try/index.js";import{Context as d}from"./Context.js";import{Exit as f}from"./Exit.js";import{SpanTracer as p}from"./SpanTracer.js";const m=e=>e,h=e=>e(),g=(e,t)=>e(t),_=(e,t,n)=>e(t,n);var v=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},y=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`InterruptedError`}},b=class extends Error{constructor(e){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},x=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 S=`effect`,C=e=>e[S],w=e=>{let t=!1;return{next:n=>t?{done:!0,value:n}:(t=!0,{done:!1,value:e})}},T=e=>m(e),E=i()(`IO`,{[Symbol.toStringTag]:`IO`,map(e){return D(m({_tag:`Map`,effect:this,f:e}))},flatMap(e){return D(m({_tag:`FlatMap`,effect:this,f:e}))},mapTry(e,t){return this.flatMap(n=>Q.tryCatch(()=>e(n),t))},tap(e){return this.map(t=>(e(t),t))},tapEffect(e){return this.flatMap(t=>e(t).map(()=>t))},mapError(e){return D(m({_tag:`MapError`,effect:this,f:e}))},tapError(e){return this.mapError(t=>(e(t),t))},recover(e){return D(m({_tag:`Recover`,effect:this,fallback:e}))},recoverWith(e){return D(m({_tag:`RecoverWith`,effect:this,f:e}))},fold(e,t){return D(m({_tag:`Fold`,effect:this,onFailure:e,onSuccess:t}))},match(e){return this.fold(e.failure,e.success)},catchTag(e,t){return D(m({_tag:`RecoverWith`,effect:this,f:n=>typeof n==`object`&&n&&`_tag`in n&&n._tag===e?m(t(m(n))):m(Q.fail(n))}))},catchAll(e){return this.recoverWith(e)},retry(e){return e<=0?this:this.recoverWith(()=>this.retry(e-1))},retryWithDelay(e,t){return e<=0?this:this.recoverWith(()=>Q.sleep(t).flatMap(()=>this.retryWithDelay(e-1,t)))},retryWhile(e){let t=(n,r)=>this.recoverWith(i=>{if(n<=0||!e.while(i,r))return m(Q.fail(i));let a=t(n-1,r+1);return e.delayMs===void 0?a:m(Q.sleep(e.delayMs).flatMap(()=>a))});return t(e.n,1)},retryWithBackoff(e){let t=e.factor??2,n=e.maxMs??3e4,r=e.jitter??!0,i=e.while??(()=>!0),a=(o,s)=>this.recoverWith(c=>{if(o<=0||!i(c,s))return m(Q.fail(c));let l=Math.min(n,e.baseMs*t**(s-1)),u=r?l*(.5+Math.random()*.5):l,d=a(o-1,s+1);return m(Q.sleep(u).flatMap(()=>d))});return a(e.n,1)},repeatUntil(e,t){if(t.max<=0)return m(Q.fail(new x(t.max)));let n=r=>this.flatMap(i=>{if(e(i))return m(Q.succeed(i));if(r<=1)return m(Q.fail(new x(t.max,i)));let a=n(r-1);return t.delayMs===void 0?a:m(Q.sleep(t.delayMs).flatMap(()=>a))});return n(t.max)},repeatWhile(e,t){return this.repeatUntil(t=>!e(t),t)},zipRight(e){return this.flatMap(()=>e)},zipLeft(e){return this.flatMap(t=>e.map(()=>t))},zip(e){return this.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return D(m({_tag:`ProvideContext`,effect:this,context:e}))},provideService(e,t){let n=d.make(e,t);return D(m({_tag:`ProvideContext`,effect:this,context:n}))},provideLayer(e){let t=m(Q.async(async()=>{let t=d.empty();return await e.build(m(t))}));return m(t.flatMap(e=>D(m({_tag:`ProvideContext`,effect:this,context:e}))))},async run(){return F(await q(C(T(this)),A,void 0,void 0))},async runOrThrow(){return I(await q(C(T(this)),A,void 0,void 0))},runSync(){return F(B(C(T(this)),A,void 0))},runSyncOrThrow(){return I(B(C(T(this)),A,void 0))},async runExit(e){let t=e?.signal;if(!t)return q(C(T(this)),A,void 0,void 0);let n=await q(C(T(this)),A,t,void 0);return t.aborted&&n.isFailure()?f.interrupted():n},async runOption(){let e=await q(C(T(this)),A,void 0,void 0);return e.isSuccess()?l(e.value):s()},async runTry(){let e=await q(C(T(this)),A,void 0,void 0);if(e.isSuccess())return m(u(()=>e.value));let t=O(e),n=t?t.value:/* @__PURE__ */ Error(`Effect was interrupted`);return m(u(()=>{throw n}))},runCancellable(){let e=new AbortController;return{result:T(this).interruptOn(e.signal).run(),cancel:()=>e.abort()}},pipe(e){return e(this)},delay(e){return Q.sleep(e).flatMap(()=>this)},timeout(e){return D(m({_tag:`Timeout`,effect:this,duration:e}))},timeoutTo(e,t){return D(m({_tag:`Timeout`,effect:this,duration:e,fallback:{value:t}}))},interruptOn(e){return D(m({_tag:`InterruptWhen`,effect:this,signal:e}))},withSpan(e,t=j){return D(m({_tag:`WithSpan`,effect:this,name:e,attributes:t}))},toString(){return`IO(${o(this[S]._tag)})`},toJSON(){return{_tag:`IO`,effect:this[S]._tag}},[Symbol.iterator](){return w(this)}}),D=e=>{let t=Object.create(E);return t[S]=e,t},O=e=>{if(e._tag===`Failure`)return{value:e.error};if(e._tag===`Die`)return{value:e.defect}},k=e=>e._tag===`Die`&&e.defect instanceof b?void 0:O(e),A=d.empty(),j=Object.freeze({}),M=e=>{let t=e.get(p);return t.isNone()?void 0:t.orThrow()},N=()=>/* @__PURE__ */ Error(`Cannot run async effect synchronously`),P=e=>/* @__PURE__ */ Error(`Service not found: ${e.id}`),F=e=>{if(e._tag===`Success`)return n(e.value);if(e._tag===`Failure`)return t(e.error);throw e._tag===`Die`?e.defect:new y},I=e=>{if(e._tag===`Success`)return e.value;throw e._tag===`Failure`?e.error:e._tag===`Die`?e.defect:new y},L=e=>{try{return e()}catch(e){return f.die(e)}},R=e=>{let t=typeof e==`object`&&e?e[S]:void 0;if(typeof t==`object`&&t&&typeof t._tag==`string`)return m(t);throw TypeError("IO.gen was yielded a value that isn't an IO. Use `yield*` on an IO; convert an Option, Either or Try first with IO.fromOption, IO.fromEither or IO.fromTry, and wrap a plain value with IO.succeed.")},z=()=>f.die(/* @__PURE__ */ TypeError(`A step produced no outcome: a SpanTracer's run must return what its fn returns`)),B=(e,t,n)=>{let r=[],i=m(e),a=m(t),o;for(;;){if(o===void 0)try{switch(i._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:r.push(i,a),i=C(i.effect);continue;case`ProvideContext`:a=a.merge(i.context),i=C(i.effect);continue;case`Gen`:{let e=h(i.start),t=e.next(void 0);if(t.done===!0){o=f.succeed(t.value);continue}r.push({_tag:`GenNext`,iterator:e},a),i=R(t.value);continue}default:o=V(i,a,n)??z();continue}}catch(e){o=f.die(e);continue}if(r.length===0)return m(o);let e=r.pop(),t=r.pop();try{switch(t._tag){case`Map`:o._tag===`Success`&&(o=f.succeed(g(t.f,o.value)));break;case`FlatMap`:o._tag===`Success`&&(i=C(g(t.f,o.value)),a=e,o=void 0);break;case`MapError`:{let e=k(o);e&&(o=f.fail(g(t.f,e.value)));break}case`Recover`:k(o)&&(o=f.succeed(t.fallback));break;case`RecoverWith`:{let n=k(o);n&&(i=C(g(t.f,n.value)),a=e,o=void 0);break}case`Fold`:{let e=k(o);e?o=f.succeed(g(t.onFailure,e.value)):o._tag===`Success`&&(o=f.succeed(g(t.onSuccess,o.value)));break}case`GenNext`:if(o._tag===`Success`){let n=t.iterator.next(o.value);n.done===!0?o=f.succeed(n.value):(r.push(t,e),i=R(n.value),a=e,o=void 0)}}}catch(e){o=f.die(e)}}},V=(e,t,n)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return f.die(N());case`Auto`:return H(e.thunk);case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Bracket`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(g(e.release,i)),t,n);return o.isSuccess()?a:o}case`BracketExit`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(_(e.release,i,a)),t,n);return o.isSuccess()?a:o}case`All`:return W(e.effects,t,n);case`Race`:return f.die(new b(`race`));case`Timeout`:return f.die(new b(`timeout`));case`Sleep`:return f.die(new b(`sleep`));case`WithSpan`:return U(e,t,n);case`InterruptWhen`:{if(e.signal.aborted)return f.fail(new y);let r=B(C(e.effect),t,n);return r.isInterrupted()?f.fail(new y):r}default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},H=e=>{try{let t=e();return t instanceof Promise?f.die(N()):f.succeed(t)}catch(e){return f.fail(e)}},U=(e,t,n)=>{let r=M(t);if(!r)return B(C(e.effect),t,n);let i=r.start(e.name,e.attributes,n),a=L(()=>r.run(i,()=>B(C(e.effect),t,i)));return r.end(i,a),a},W=(e,t,n)=>{let r=[];for(let i of e){let e=B(C(i),t,n);if(!e.isSuccess())return m(e);r.push(e.value)}return f.succeed(r)},G=(e,t)=>{if(t)return e.isDie()?m(e):f.interrupted()},K=(e,t,n)=>e.isSuccess()||e.isDie()?e:n?f.interrupted():e.isInterrupted()||t.aborted?f.fail(new y):e,q=async(e,t,n,r)=>{let i=[],a=m(e),o=m(t),s,c=()=>n?.aborted??!1;for(;;){if(s===void 0){if(c()){s=f.interrupted();continue}try{switch(a._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:i.push(a,o),a=C(a.effect);continue;case`ProvideContext`:o=o.merge(a.context),a=C(a.effect);continue;case`Gen`:{let e=h(a.start),t=e.next(void 0);if(t.done===!0){s=c()?f.interrupted():f.succeed(t.value);continue}i.push({_tag:`GenNext`,iterator:e},o),a=R(t.value);continue}default:{let e=X(a,o,n,r);s=(e instanceof Promise?await e:e)??z();continue}}}catch(e){s=f.die(e);continue}}if(i.length===0)return m(s);let e=i.pop(),t=i.pop();try{switch(t._tag){case`Map`:s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.f,s.value)));break;case`FlatMap`:s._tag===`Success`&&(c()?s=f.interrupted():(a=C(g(t.f,s.value)),o=e,s=void 0));break;case`MapError`:{let e=O(s);e&&(s=G(s,c())??f.fail(g(t.f,e.value)));break}case`Recover`:O(s)&&(s=G(s,c())??f.succeed(t.fallback));break;case`RecoverWith`:{let n=O(s);if(n){let r=G(s,c());r?s=r:(a=C(g(t.f,n.value)),o=e,s=void 0)}break}case`Fold`:{let e=O(s);e?s=G(s,c())??f.succeed(g(t.onFailure,e.value)):s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.onSuccess,s.value)));break}case`GenNext`:if(s._tag===`Success`){if(c())s=f.interrupted();else{let n=t.iterator.next(s.value);n.done===!0?s=c()?f.interrupted():f.succeed(n.value):(i.push(t,e),a=R(n.value),o=e,s=void 0)}}}}catch(e){s=f.die(e)}}},J=e=>e.catch(e=>f.die(e)),Y=(e,t)=>J(Promise.resolve().then(()=>t?.aborted?f.interrupted():e())),X=(e,t,n,r)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return ee(e.thunk,n);case`Auto`:try{let t=h(e.thunk);return t instanceof Promise?t.then(e=>f.succeed(e),e=>f.fail(e)):f.succeed(t)}catch(e){return f.fail(e)}case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Sleep`:return se(e.duration,n);case`Bracket`:return Y(()=>te(e,t,n,r),n);case`BracketExit`:return Y(()=>ne(e,t,n,r),n);case`Race`:return e.effects.length===0?f.die(/* @__PURE__ */ Error(`No effects to race`)):Y(()=>ce(e.effects,t,n,r),n);case`Timeout`:return Y(()=>le(e.effect,e.duration,e.fallback,t,n,r),n);case`InterruptWhen`:return Y(()=>re(e,t,n,r),n);case`WithSpan`:return Y(()=>ie(e,t,n,r),n);case`All`:return Y(()=>ue(e.effects,e.concurrency,t,n,r),n);default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},ee=async(e,t)=>{try{return f.succeed(await e(t))}catch(e){return f.fail(e)}},Z=async(e,t,n,r)=>{if(n?.aborted)return f.interrupted();try{return await q(C(e()),t,n,r)}catch(e){return f.die(e)}},te=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(g(e.release,a)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},ne=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(_(e.release,a,o)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},re=async(e,t,n,r)=>{let{signal:i}=e,o=a([n,i]);try{let a=await q(C(e.effect),t,o.signal,r);return K(a,i,n?.aborted??!1)}catch(e){return f.die(e)}finally{o.dispose()}},ie=async(e,t,n,r)=>{let i=M(t);if(!i)return q(C(e.effect),t,n,r);let a=i.start(e.name,e.attributes,r),o=await ae(()=>i.run(a,()=>q(C(e.effect),t,n,a)));return i.end(a,oe(o,n)),o},ae=async e=>{try{return await e()}catch(e){return f.die(e)}},oe=(e,t)=>e.isFailure()&&t?.aborted===!0?f.interrupted():e,se=(e,t)=>new Promise(n=>{let r=e===1/0?void 0:setTimeout(()=>{t?.removeEventListener(`abort`,i),n(f.succeed(void 0))},e);function i(){clearTimeout(r),n(f.interrupted())}t?.addEventListener(`abort`,i,{once:!0})}),ce=(e,t,n,r)=>{let i=e.map(()=>{let e=new AbortController;return{own:e,scope:a([n,e.signal])}}),o={settled:!1};return new Promise(n=>{e.forEach((e,a)=>{q(C(e),t,i[a].scope.signal,r).then(e=>{o.settled||(o.settled=!0,i.forEach(({own:e,scope:t},n)=>{n!==a&&e.abort(),t.dispose()}),n(e))})})})},le=(e,t,n,r,i,o)=>{let s=new AbortController,c=a([i,s.signal]);return new Promise(a=>{let l=setTimeout(()=>{s.abort(),c.dispose(),a(n===void 0?f.fail(new v(t)):i?.aborted===!0?f.interrupted():f.succeed(n.value))},t);q(C(e),r,c.signal,o).then(e=>{clearTimeout(l),c.dispose(),a(e)})})},ue=(e,t,n,i,o)=>{if(e.length===0)return Promise.resolve(f.succeed([]));let s=new AbortController,c=a([i,s.signal]),l=Array(e.length),u={next:0,succeeded:0,settled:!1};return new Promise(i=>{let a=e=>{u.settled=!0,e.isSuccess()||s.abort(),c.dispose(),i(e)},d=()=>{if(u.settled||u.next>=e.length)return;let t=u.next;u.next=t+1,q(C(e[t]),n,c.signal,o).then(n=>{u.settled||(n.isSuccess()?(l[t]=n.value,u.succeeded+=1,u.succeeded===e.length?a(f.succeed(l)):d()):a(m(n)))})};Array.from({length:r(t,e.length)}).forEach(d)})},Q={sync:e=>D({_tag:`Sync`,thunk:e}),succeed:e=>D({_tag:`Succeed`,value:e}),fail:e=>D({_tag:`Fail`,error:e}),die:e=>D({_tag:`Die`,defect:e}),async:e=>D(m({_tag:`Async`,thunk:e})),tryPromise:e=>D({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,r)=>Q.sync(()=>{try{return n(e())}catch(e){return t(r(e))}}).flatMap(e=>Q.fromEither(e)),liftSync:e=>(...t)=>Q.sync(()=>e(...t)),liftPromise:e=>(...t)=>Q.async(()=>e(...t)),fromEither:e=>m(e.isRight()?Q.succeed(e.value):Q.fail(e.value)),fromPromiseEither:(e,t)=>{let n=Q.async(async()=>e());return(t?n.mapError(t):n.recoverWith(e=>Q.die(e))).flatMap(e=>Q.fromEither(e))},fromOption:e=>m(e.isSome()?Q.succeed(e.value):Q.fail(void 0)),fromOptionOrFail:(e,t)=>m(e.isSome()?Q.succeed(e.value):Q.fail(t())),fromTry:e=>m(e.isSuccess()?Q.succeed(e.orThrow()):Q.fail(e.error)),fromResult:e=>m(e.error?Q.fail(e.error):Q.succeed(c(e.data))),tryAsync:(e,t,n)=>n?.aborted?m(Q.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):Q.async(t=>{if(!n)return e(t);if(!t)return e(n);let r=a([n,t]);try{return e(r.signal).finally(r.dispose)}catch(e){throw r.dispose(),e}}).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return Q.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>Q.fromResult({data:e[r],error:e[i]}))},service:e=>D({_tag:`Service`,tag:e}),serviceWith:(e,t)=>Q.service(e).map(t),serviceWithIO:(e,t)=>Q.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return m(D({_tag:`Auto`,thunk:()=>t({})}));let r=m(Q.succeed({})),i=n.reduce((e,[t,n])=>m(e.flatMap(e=>Q.service(n).map(n=>({...e,[t]:n})))),r);return m(i.flatMap(e=>D({_tag:`Auto`,thunk:()=>t(e)})))},all:(e,t)=>{let n=t?.concurrency??`unbounded`;if(r(n,1),n!==1&&e.length>1)return D(m({_tag:`All`,effects:e,concurrency:n}));if(e.length===0)return m(Q.succeed([]));let i=m(Q.succeed([]));return m(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),i))},firstSuccessOf:e=>e.length===0?m(Q.die(/* @__PURE__ */ Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>D(m({_tag:`Sleep`,duration:e})),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?m(Q.succeed(e)):r<=0?m(Q.fail(new x(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>D(m({_tag:`Sleep`,duration:1/0})),get unit(){return m(D({_tag:`Succeed`,value:void 0}))},fromNullable:e=>m(e==null?Q.fail(void 0):Q.succeed(e)),interrupt:()=>D({_tag:`Interrupt`}),bracket:(e,t,n)=>D({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>Q.bracket(e,t,n),bracketExit:(e,t,n)=>D({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>D({_tag:`Race`,effects:e}),forEach:(e,t,n)=>{let i=n?.concurrency??1;if(r(i,1),i!==1)return Q.unit.flatMap(()=>Q.all(e.map(t),{concurrency:i}));if(e.length===0)return m(Q.succeed([]));let a=m(Q.succeed([]));return m(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),a))},timeout:(e,t)=>D(m({_tag:`Timeout`,effect:e,duration:t})),gen:e=>D(m({_tag:`Gen`,start:e})),get Do(){return $(Q.succeed({}))}},$=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return $(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return $(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return $(e.tap(t))},tapEffect(t){return $(e.tapEffect(t))},done(){return e}}),de=e(e=>D(m({_tag:`Auto`,thunk:e})),Q);export{de as IO,S as IOEffectKey,y as InterruptedError,x as RepeatExhausted,v as TimeoutError,b as UnsupportedSyncOperationError};
@@ -1 +1 @@
1
- var e=`2.2.1`;export{e as version};
1
+ var e=`2.3.0`;export{e as version};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "functype",
3
- "version": "2.2.1",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "A functional programming library for TypeScript, using immutable data structures and type classes",
6
6
  "keywords": [
@@ -34,7 +34,7 @@
34
34
  "@eslint/compat": "^2.1.1",
35
35
  "@eslint/eslintrc": "^3.3.7",
36
36
  "@types/node": "~24.19.2",
37
- "eslint-config-functype": "2.202.1",
37
+ "eslint-config-functype": "2.203.0",
38
38
  "esbuild": "^0.28.2",
39
39
  "eslint-plugin-functional": "^10.0.1",
40
40
  "fast-check": "^4.10.3",