functype 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/cli/data.js +1 -1
- package/dist/cli/full-interfaces.js +11 -0
- package/dist/either/index.d.ts +11 -0
- package/dist/either/index.js +1 -1
- package/dist/io/IO.d.ts +20 -0
- package/dist/io/IO.js +1 -1
- package/dist/package.json.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://functype.org/logo-dark.svg">
|
|
4
|
+
<img src="https://functype.org/logo.svg" alt="functype" height="72">
|
|
5
|
+
</picture>
|
|
6
|
+
</p>
|
|
7
|
+
|
|
1
8
|
# Functype
|
|
2
9
|
|
|
3
10
|
[](https://www.npmjs.com/package/functype)
|
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)`,`.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)`,`.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 })`],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};
|
|
@@ -222,6 +222,17 @@ export interface EitherBase<out L extends Type, out R extends Type>
|
|
|
222
222
|
orNull(): R | null
|
|
223
223
|
orUndefined(): R | undefined
|
|
224
224
|
map<U extends Type>(f: (value: R) => U): Either<L, U>
|
|
225
|
+
/**
|
|
226
|
+
* Maps the Right value with a function that may throw, catching the throw into a Left built by
|
|
227
|
+
* \`onError\`. \`map\` lets a throw escape. Use \`mapTry\` for a callback you don't own.
|
|
228
|
+
*
|
|
229
|
+
* - A Left passes through unchanged, and \`f\` doesn't run.
|
|
230
|
+
* - A throw from \`onError\` itself escapes.
|
|
231
|
+
* - Only a synchronous throw is caught. For an async callback, use \`tryCatchAsync\`.
|
|
232
|
+
*
|
|
233
|
+
* Same as \`either.flatMap((value) => tryCatch(() => f(value), onError))\`, with functype's \`tryCatch\`.
|
|
234
|
+
*/
|
|
235
|
+
mapTry<U extends Type, L2 extends Type>(f: (value: R) => U, onError: (error: unknown) => L2): Either<L | L2, U>
|
|
225
236
|
ap<L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>): Either<L | L2, U>
|
|
226
237
|
merge<L1 extends Type, R1 extends Type>(other: Either<L1, R1>): Either<L | L1, [R, R1]>
|
|
227
238
|
/**
|
package/dist/either/index.d.ts
CHANGED
|
@@ -50,6 +50,17 @@ export interface EitherBase<out L extends Type, out R extends Type> extends Func
|
|
|
50
50
|
orNull(): R | null;
|
|
51
51
|
orUndefined(): R | undefined;
|
|
52
52
|
map<U extends Type>(f: (value: R) => U): Either<L, U>;
|
|
53
|
+
/**
|
|
54
|
+
* Maps the Right value with a function that may throw, catching the throw into a Left built by
|
|
55
|
+
* `onError`. `map` lets a throw escape. Use `mapTry` for a callback you don't own.
|
|
56
|
+
*
|
|
57
|
+
* - A Left passes through unchanged, and `f` doesn't run.
|
|
58
|
+
* - A throw from `onError` itself escapes.
|
|
59
|
+
* - Only a synchronous throw is caught. For an async callback, use `tryCatchAsync`.
|
|
60
|
+
*
|
|
61
|
+
* Same as `either.flatMap((value) => tryCatch(() => f(value), onError))`, with functype's `tryCatch`.
|
|
62
|
+
*/
|
|
63
|
+
mapTry<U extends Type, L2 extends Type>(f: (value: R) => U, onError: (error: unknown) => L2): Either<L | L2, U>;
|
|
53
64
|
ap<L2 extends Type, U extends Type>(ff: Either<L2, (value: R) => U>): Either<L | L2, U>;
|
|
54
65
|
merge<L1 extends Type, R1 extends Type>(other: Either<L1, R1>): Either<L | L1, [R, R1]>;
|
|
55
66
|
/**
|
package/dist/either/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Companion as e}from"../companion/Companion.js";import{base64ToUtf8 as t}from"../internal/base64.js";import{traverseWithConcurrency as n}from"../internal/concurrency.js";import{define as r}from"../internal/define.js";import{showValue as i}from"../internal/stringify.js";import{List as a}from"../list/index.js";import{None as o,Some as s}from"../option/index.js";import{createSerializer as c,expectMarker as l}from"../serialization/SerializationCompanion.js";import{Try as u}from"../try/index.js";const d=(e,t)=>[e,t],f=r()(`Right`,{[Symbol.toStringTag]:`Either`,isLeft(){return!1},isRight(){return!0},getOrElse(){return this.value},orThrow(){return this.value},expect(){return this.value},orElse(){return this},orNull(){return this.value},orUndefined(){return this.value},map(e){return m(e(this.value))},ap(e){return e._tag===`Right`?m(e.value(this.value)):_(e.value)},async mapAsync(e){return m(await e(this.value))},merge(e){return e.isLeft()?_(e.value):m(d(this.value,e.value))},flatMap(e){return e(this.value)},async flatMapAsync(e){return e(this.value)},toOption(){return s(this.value)},toList(){return a([this.value])},toEither(){return m(this.value)},toTry(){return u(()=>this.value)},toJSON(){return{"@functype":`Either`,_tag:`Right`,value:this.value}},toString(){return`Right(${i(this.value)})`},*[Symbol.iterator](){yield this.value},*yield(){yield this.value},traverse(e){let t=e(this.value);return t.isLeft()?_(t.value):m([t.value])},tap(e){return e(this.value),this},tapLeft(){return this},mapLeft(){return m(this.value)},filterOrElse(e,t){return e(this.value)?this:_(t(this.value))},bimap(e,t){return m(t(this.value))},fold(e,t){return t(this.value)},async foldAsync(e,t){return t(this.value)},foldLeft(e){return t=>t(e,this.value)},foldRight(e){return t=>t(this.value,e)},match(e){return e.Right(this.value)},swap(){return _(this.value)},toPromise(){return Promise.resolve(this.value)},toValue(){return{_tag:`Right`,value:this.value}},pipeEither(e,t){return t(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Right`,this.value)},contains(e){return this.value===e},exists(e){return e(this.value)},every(e){return e(this.value)},forEach(e){e(this.value)},doUnwrap(){return{ok:!0,value:this.value}}}),p=r()(`Left`,{[Symbol.toStringTag]:`Either`,isLeft(){return!0},isRight(){return!1},getOrElse(e){return e()},orThrow(e){throw e===void 0?this.value:typeof e==`function`?e(this.value):e},expect(e){return e(this.value)},orElse(e){return e()},orNull(){return null},orUndefined(){},map(){return h(this.value)},ap(){return h(this.value)},mapAsync(){return Promise.resolve(h(this.value))},merge(){return h(this.value)},flatMap(){return h(this.value)},flatMapAsync(){return Promise.resolve(h(this.value))},toOption(){return o()},toList(){return a()},toEither(e){return h(e)},toTry(){return u(()=>{throw Error(String(this.value))})},toJSON(){return{"@functype":`Either`,_tag:`Left`,value:this.value}},toString(){return`Left(${i(this.value)})`},*[Symbol.iterator](){},*yield(){},traverse(){return h(this.value)},tap(){return this},tapLeft(e){return e(this.value),this},mapLeft(e){return h(e(this.value))},filterOrElse(){return this},bimap(e){return h(e(this.value))},fold(e){return e(this.value)},async foldAsync(e){return e(this.value)},foldLeft(e){return()=>e},foldRight(e){return()=>e},match(e){return e.Left(this.value)},swap(){return m(this.value)},toPromise(){return Promise.reject(this.value)},toValue(){return{_tag:`Left`,value:this.value}},pipeEither(e){return e(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Left`,this.value)},contains(){return!1},exists(){return!1},every(){return!0},forEach(){},doUnwrap(){return{ok:!1,empty:!1,error:this.value}}}),m=e=>{let t=Object.create(f);return t._tag=`Right`,t.value=e,t},h=e=>{let t=Object.create(p);return t._tag=`Left`,t.value=e,t},g=e=>m(e),_=e=>h(e),v=e=>e.isRight(),y=e=>e.isLeft(),b=(e,t)=>{try{return g(e())}catch(e){return _(t(e))}},x=e=>m(e);console.assert(x);const S=e=>h(e);console.assert(S);const C=async(e,t)=>{try{let t=await e();return g(t)}catch(e){return _(t(e))}},w=(e,t)=>t?g(e):_(e),T=(e,t)=>(l(e,`Either`,t),e._tag===`Right`?g(e.value):_(e.value)),E={left:e=>_(e),right:e=>g(e),void:()=>g(void 0),isRight:e=>e.isRight(),isLeft:e=>e.isLeft(),sequence:e=>e.reduce((e,t)=>e.isLeft()?e:t.isLeft()?_(t.value):e.map(e=>[...e,t.value]),g([])),traverse:(e,t)=>e.reduce((e,n,r)=>e.flatMap(e=>t(n,r).map(t=>[...e,t])),g([])),traverseAsync:async(e,t,r)=>{let i=await n(e,t,r?.concurrency??1,e=>e.isLeft());return E.sequence(i)},fromNullable:(e,t)=>e==null?_(t):g(e),fromPredicate:(e,t,n)=>t(e)?g(e):_(n),ap:(e,t)=>e.flatMap(e=>t.map(e)),fromPromise:async(e,t)=>{try{let t=await e;return g(t)}catch(e){return _(t(e))}},fromJSON:e=>T(JSON.parse(e),`fromJSON`),fromBinary:e=>{let n=t(e);return E.fromJSON(n)}},D=e(w,E);export{D as Either,_ as Left,g as Right,S as TypeCheckLeft,x as TypeCheckRight,y as isLeft,v as isRight,b as tryCatch,C as tryCatchAsync};
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{base64ToUtf8 as t}from"../internal/base64.js";import{traverseWithConcurrency as n}from"../internal/concurrency.js";import{define as r}from"../internal/define.js";import{showValue as i}from"../internal/stringify.js";import{List as a}from"../list/index.js";import{None as o,Some as s}from"../option/index.js";import{createSerializer as c,expectMarker as l}from"../serialization/SerializationCompanion.js";import{Try as u}from"../try/index.js";const d=(e,t)=>[e,t],f=r()(`Right`,{[Symbol.toStringTag]:`Either`,isLeft(){return!1},isRight(){return!0},getOrElse(){return this.value},orThrow(){return this.value},expect(){return this.value},orElse(){return this},orNull(){return this.value},orUndefined(){return this.value},map(e){return m(e(this.value))},mapTry(e,t){return b(()=>e(this.value),t)},ap(e){return e._tag===`Right`?m(e.value(this.value)):_(e.value)},async mapAsync(e){return m(await e(this.value))},merge(e){return e.isLeft()?_(e.value):m(d(this.value,e.value))},flatMap(e){return e(this.value)},async flatMapAsync(e){return e(this.value)},toOption(){return s(this.value)},toList(){return a([this.value])},toEither(){return m(this.value)},toTry(){return u(()=>this.value)},toJSON(){return{"@functype":`Either`,_tag:`Right`,value:this.value}},toString(){return`Right(${i(this.value)})`},*[Symbol.iterator](){yield this.value},*yield(){yield this.value},traverse(e){let t=e(this.value);return t.isLeft()?_(t.value):m([t.value])},tap(e){return e(this.value),this},tapLeft(){return this},mapLeft(){return m(this.value)},filterOrElse(e,t){return e(this.value)?this:_(t(this.value))},bimap(e,t){return m(t(this.value))},fold(e,t){return t(this.value)},async foldAsync(e,t){return t(this.value)},foldLeft(e){return t=>t(e,this.value)},foldRight(e){return t=>t(this.value,e)},match(e){return e.Right(this.value)},swap(){return _(this.value)},toPromise(){return Promise.resolve(this.value)},toValue(){return{_tag:`Right`,value:this.value}},pipeEither(e,t){return t(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Right`,this.value)},contains(e){return this.value===e},exists(e){return e(this.value)},every(e){return e(this.value)},forEach(e){e(this.value)},doUnwrap(){return{ok:!0,value:this.value}}}),p=r()(`Left`,{[Symbol.toStringTag]:`Either`,isLeft(){return!0},isRight(){return!1},getOrElse(e){return e()},orThrow(e){throw e===void 0?this.value:typeof e==`function`?e(this.value):e},expect(e){return e(this.value)},orElse(e){return e()},orNull(){return null},orUndefined(){},map(){return h(this.value)},mapTry(){return h(this.value)},ap(){return h(this.value)},mapAsync(){return Promise.resolve(h(this.value))},merge(){return h(this.value)},flatMap(){return h(this.value)},flatMapAsync(){return Promise.resolve(h(this.value))},toOption(){return o()},toList(){return a()},toEither(e){return h(e)},toTry(){return u(()=>{throw Error(String(this.value))})},toJSON(){return{"@functype":`Either`,_tag:`Left`,value:this.value}},toString(){return`Left(${i(this.value)})`},*[Symbol.iterator](){},*yield(){},traverse(){return h(this.value)},tap(){return this},tapLeft(e){return e(this.value),this},mapLeft(e){return h(e(this.value))},filterOrElse(){return this},bimap(e){return h(e(this.value))},fold(e){return e(this.value)},async foldAsync(e){return e(this.value)},foldLeft(e){return()=>e},foldRight(e){return()=>e},match(e){return e.Left(this.value)},swap(){return m(this.value)},toPromise(){return Promise.reject(this.value)},toValue(){return{_tag:`Left`,value:this.value}},pipeEither(e){return e(this.value)},pipe(e){return e(this.value)},serialize(){return c(`Either`,`Left`,this.value)},contains(){return!1},exists(){return!1},every(){return!0},forEach(){},doUnwrap(){return{ok:!1,empty:!1,error:this.value}}}),m=e=>{let t=Object.create(f);return t._tag=`Right`,t.value=e,t},h=e=>{let t=Object.create(p);return t._tag=`Left`,t.value=e,t},g=e=>m(e),_=e=>h(e),v=e=>e.isRight(),y=e=>e.isLeft(),b=(e,t)=>{try{return g(e())}catch(e){return _(t(e))}},x=e=>m(e);console.assert(x);const S=e=>h(e);console.assert(S);const C=async(e,t)=>{try{let t=await e();return g(t)}catch(e){return _(t(e))}},w=(e,t)=>t?g(e):_(e),T=(e,t)=>(l(e,`Either`,t),e._tag===`Right`?g(e.value):_(e.value)),E={left:e=>_(e),right:e=>g(e),void:()=>g(void 0),isRight:e=>e.isRight(),isLeft:e=>e.isLeft(),sequence:e=>e.reduce((e,t)=>e.isLeft()?e:t.isLeft()?_(t.value):e.map(e=>[...e,t.value]),g([])),traverse:(e,t)=>e.reduce((e,n,r)=>e.flatMap(e=>t(n,r).map(t=>[...e,t])),g([])),traverseAsync:async(e,t,r)=>{let i=await n(e,t,r?.concurrency??1,e=>e.isLeft());return E.sequence(i)},fromNullable:(e,t)=>e==null?_(t):g(e),fromPredicate:(e,t,n)=>t(e)?g(e):_(n),ap:(e,t)=>e.flatMap(e=>t.map(e)),fromPromise:async(e,t)=>{try{let t=await e;return g(t)}catch(e){return _(t(e))}},fromJSON:e=>T(JSON.parse(e),`fromJSON`),fromBinary:e=>{let n=t(e);return E.fromJSON(n)}},D=e(w,E);export{D as Either,_ as Left,g as Right,S as TypeCheckLeft,x as TypeCheckRight,y as isLeft,v as isRight,b as tryCatch,C as tryCatchAsync};
|
package/dist/io/IO.d.ts
CHANGED
|
@@ -294,6 +294,26 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
294
294
|
* @returns New IO with transformed value
|
|
295
295
|
*/
|
|
296
296
|
map<B extends Type>(f: (a: A) => B): IO<R, E, B>;
|
|
297
|
+
/**
|
|
298
|
+
* Transforms the success value with a function that may throw, catching the throw into the error
|
|
299
|
+
* channel. In `map` a throw is a defect, so `run()` rejects; `mapTry` turns it into a typed error
|
|
300
|
+
* built by `onError`. Use it for a callback you don't own, such as a caller's mapper inside a library.
|
|
301
|
+
*
|
|
302
|
+
* - A failure passes through unchanged, and `f` doesn't run.
|
|
303
|
+
* - A throw from `onError` itself is still a defect.
|
|
304
|
+
* - Only a synchronous throw is caught. For an async callback, use `flatMap` with `IO.tryPromise`.
|
|
305
|
+
* - The failure is typed, so `retry` re-runs a step whose `f` threw. A `map` throw is a defect and is
|
|
306
|
+
* never retried.
|
|
307
|
+
* - If `f` runs another IO itself (`inner.runSync()`), that run's interruption or defect reaches `f`
|
|
308
|
+
* as an ordinary throw, so `onError` turns it into a typed error. The outer run's own interruption
|
|
309
|
+
* never does: `f` doesn't run.
|
|
310
|
+
*
|
|
311
|
+
* Same as `io.flatMap((a) => IO.tryCatch(() => f(a), onError))`.
|
|
312
|
+
* @param f - Function to apply to the success value; it may throw
|
|
313
|
+
* @param onError - Turns what `f` threw into a typed error
|
|
314
|
+
* @returns New IO whose error channel also carries `onError`'s result
|
|
315
|
+
*/
|
|
316
|
+
mapTry<B extends Type, E2 extends Type>(f: (a: A) => B, onError: (error: unknown) => E2): IO<R, E | E2, B>;
|
|
297
317
|
/**
|
|
298
318
|
* Chains another IO effect based on the success value.
|
|
299
319
|
* @param f - Function returning next IO effect
|
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}))},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 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};
|
package/dist/package.json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`2.
|
|
1
|
+
var e=`2.1.0`;export{e as version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.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,12 +34,12 @@
|
|
|
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.
|
|
37
|
+
"eslint-config-functype": "2.201.0",
|
|
38
38
|
"esbuild": "^0.28.2",
|
|
39
39
|
"eslint-plugin-functional": "^10.0.1",
|
|
40
40
|
"fast-check": "^4.10.2",
|
|
41
41
|
"globals": "^17.14.0",
|
|
42
|
-
"ts-builds": "^
|
|
42
|
+
"ts-builds": "^5.0.0",
|
|
43
43
|
"tsdown": "^0.23.7",
|
|
44
44
|
"tsx": "^4.23.15",
|
|
45
45
|
"typedoc": "^0.28.20",
|