# Functype v2.0.0 > A functional programming library for TypeScript, using immutable data structures and type classes, with Scala-inspired patterns. - Install: npm install functype - Homepage: https://functype.org/ - Repository: https://github.com/jordanburke/functype This file contains the complete functype documentation concatenated into a single file for LLM consumption. ──────────────────────────────────────────────────────────────────────────────── ## AI Guide ──────────────────────────────────────────────────────────────────────────────── # AI Guide to Functype This document provides a concise reference for AI models to understand the patterns and usage of the Functype library. ## Core Types ### Option ```typescript // Create: Option(value) returns Some(value) or None const some = Option(42) // Some(42) const none = Option(null) // None // Access: .get() or .getOrElse(() => default) some.get() // 42 none.getOrElse(() => "default") // "default" // Transform: .map(), .flatMap(), .filter() some.map((x) => x * 2) // Some(84) some.flatMap((x) => Option(x.toString())) // Some("42") some.filter((x) => x > 50) // None // Pattern match: .fold() or .match() some.fold( () => "empty", (val) => `value: ${val}`, ) // "value: 42" ``` ### Either ```typescript // Create: Right(value) or Left(error) const right = Right(42) const left = Left("error") // From functions: Either.tryCatch() const result = Either.tryCatch( () => JSON.parse('{"key":"value"}'), (err) => `Parse error: ${err}`, ) // Right({key: "value"}) // Transform: .map(), .mapLeft(), .flatMap() right.map((x) => x * 2) // Right(84) left.mapLeft((e) => e.toUpperCase()) // Left("ERROR") right.flatMap((x) => Right(x.toString())) // Right("42") // Pattern match: .fold() or .match() right.fold( (err) => `Error: ${err}`, (val) => `Success: ${val}`, ) // "Success: 42" ``` ### Try ```typescript // Create: Try(() => potentially_throwing_function()) const success = Try(() => 42) const failure = Try(() => { throw new Error("Failed") }) // Transform: .map(), .flatMap(), .recover() success.map((x) => x * 2) // Success(84) failure.recover("default") // Success("default") success.flatMap((x) => Try(() => x.toString())) // Success("42") // Pattern match: .fold() or .match() success.fold( (err) => `Error: ${err.message}`, (val) => `Success: ${val}`, ) // "Success: 42" ``` ### List ```typescript // Create: List([...elements]) const list = List([1, 2, 3, 4, 5]) // Access: .head(), .tail(), .at(index) list.head() // Some(1) list.tail() // List([2, 3, 4, 5]) // Transform: .map(), .flatMap(), .filter() list.map((x) => x * 2) // List([2, 4, 6, 8, 10]) list.filter((x) => x % 2 === 0) // List([2, 4]) list.flatMap((x) => List([x, x])) // List([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) // Reduce: .foldLeft(), .foldRight() list.foldLeft(0)((acc, x) => acc + x) // 15 ``` ### Map ```typescript // Create: Map({key: value}) const map = Map({ a: 1, b: 2, c: 3 }) // Access: .get(key), .getOrElse(key, () => default) map.get("a") // Some(1) map.getOrElse("d", () => 0) // 0 // Transform: .map(), .filter() map.map((v) => v * 2) // Map({a: 2, b: 4, c: 6}) map.filter((v) => v > 1) // Map({b: 2, c: 3}) ``` ### Set ```typescript // Create: Set([...elements]) const set = Set([1, 2, 3, 4, 5]) // Operations: .add(), .remove(), .has() set.add(6) // Set([1, 2, 3, 4, 5, 6]) set.remove(3) // Set([1, 2, 4, 5]) set.has(2) // true // Set operations: .union(), .intersect(), .difference() const set2 = Set([4, 5, 6, 7]) set.union(set2) // Set([1, 2, 3, 4, 5, 6, 7]) set.intersect(set2) // Set([4, 5]) ``` ### IO ```typescript // Create: nothing runs until a run method const parsed = IO.tryCatch( () => JSON.parse(raw) as unknown, (err) => new Error(`Failed: ${err}`), ) const fetched = IO.tryPromise({ try: (signal) => fetchData(signal), catch: (err) => new Error(`Fetch failed: ${err}`), }) // Run: Either, or Exit for all four outcomes const result = await fetched.run() result.fold( (error) => console.error(error), (value) => console.log(value), ) // Cancel: a handle, or your own AbortSignal const { cancel } = fetched.runCancellable() ``` ### Tuple ```typescript // Create: Tuple(...values) const pair = Tuple(42, "hello") // Access: .first(), .second(), etc. pair.first() // 42 pair.second() // "hello" // Transform: .map(), .mapFirst(), .mapSecond() pair.mapFirst((x) => x * 2) // Tuple(84, "hello") ``` ## Common Patterns ### Type Safety ```typescript // Branded types type UserId = Brand const UserId = (id: string): UserId => { if (!/^U\d{6}$/.test(id)) throw new Error("Invalid ID format") return id as UserId } // Type-safe functions function getUserById(id: UserId): User { /* ... */ } getUserById(UserId("U123456")) // Works getUserById("U123456") // Type error ``` ### Error Handling ```typescript // Option for nullable values const maybeUser = Option(findUser(id)) maybeUser.fold( () => console.log("User not found"), (user) => console.log("User:", user.name), ) // Either for errors with context const validationResult = validateForm(formData) validationResult.fold( (errors) => handleErrors(errors), (data) => processForm(data), ) // Try for exception safety const parseResult = Try(() => JSON.parse(input)) parseResult.fold( (err) => console.error("Parse error:", err.message), (data) => console.log("Data:", data), ) ``` ### Chaining Operations ```typescript // Option chain const userCity = Option(user) .flatMap((u) => Option(u.address)) .flatMap((a) => Option(a.city)) .getOrElse(() => "Unknown") // Either chain parseInput(input) .flatMap(validateData) .flatMap(transformData) .fold( (err) => handleError(err), (result) => displayResult(result), ) // List processing List([1, 2, 3, 4, 5]) .filter((n) => n % 2 === 0) .map((n) => n * n) .foldLeft(0)((acc, n) => acc + n) // 20 (4 + 16) ``` ### Pattern Matching ```typescript // Using match method result.match({ Some: (value) => `Found: ${value}`, None: () => "Not found", }) // Using fold method either.fold( (left) => `Error: ${left}`, (right) => `Success: ${right}`, ) // Using MatchableUtils const isPositive = MatchableUtils.when( (n: number) => n > 0, (n) => `Positive: ${n}`, ) const isNegative = MatchableUtils.when( (n: number) => n < 0, (n) => `Negative: ${n}`, ) const defaultCase = MatchableUtils.default((n: number) => `Zero: ${n}`) // Usage isPositive(42) ?? isNegative(42) ?? defaultCase(42) // "Positive: 42" ``` ### Functional Composition ```typescript // Using pipe for sequential operations import { pipe } from "functype" const result = pipe( Option(input), (opt) => opt.map((s) => s.trim()), (opt) => opt.filter((s) => s.length > 0), (opt) => opt.map((s) => parseInt(s, 10)), (opt) => opt.filter((n) => !isNaN(n)), (opt) => opt.getOrElse(() => 0), ) // Converting between types import { FoldableUtils } from "functype" const optionAsList = FoldableUtils.toList(option) const listAsOption = FoldableUtils.toOption(list) const tryAsEither = FoldableUtils.toEither(tryVal, "Default error") ``` ## Key Principles 1. **Immutability**: All data structures return new instances when modified 2. **Type Safety**: Strong TypeScript typing throughout the library 3. **Null Safety**: No null/undefined values within containers (Option, Either, etc.) 4. **Error Handling**: Explicit error handling using functional patterns 5. **Pattern Matching**: Consistent APIs for inspecting and handling variants 6. **Composability**: Methods designed for chaining and composition 7. **Consistency**: Similar patterns across different data structures ## Common Imports ```typescript // Full package import (not recommended for production) import { Option, Either, Try, List } from "functype" // Subpath imports work too, and bundle the same as the root import import { Option } from "functype/option" import { Either } from "functype/either" import { List } from "functype/list" ``` ## Type Class Hierarchy - **Functor**: `map` - Transform values while preserving structure - **Applicative**: Apply functions inside containers - **Monad**: `flatMap` - Chain operations that return containerized values - **Foldable**: `fold`, `foldLeft`, `foldRight` - Collapse structure - **Traversable**: Convert/sequence containers ## Anti-Patterns to Avoid 1. ❌ **Unnecessary Unwrapping**: ```typescript // Bad if (option.isDefined()) { doSomething(option.get()) } else { doSomethingElse() } // Good option.fold( () => doSomethingElse(), (value) => doSomething(value), ) ``` 2. ❌ **Throwing from Inside Containers**: ```typescript // Bad option.map((value) => { if (!isValid(value)) throw new Error("Invalid") return transform(value) }) // Good option.flatMap((value) => (isValid(value) ? Option(transform(value)) : Option(null))) ``` 3. ❌ **Not Using Composition**: ```typescript // Bad const a = option.map((x) => x + 1) const b = a.filter((x) => x > 10) const c = b.getOrElse(() => 0) // Good const result = option .map((x) => x + 1) .filter((x) => x > 10) .getOrElse(() => 0) ``` 4. ❌ **Mixing Imperative and Functional Styles**: ```typescript // Bad let result = 0 option.fold( () => { result = 42 }, (value) => { result = value }, ) // Good const result = option.getOrElse(() => 42) ``` ──────────────────────────────────────────────────────────────────────────────── ## Quick Reference ──────────────────────────────────────────────────────────────────────────────── # Functype Quick Reference ## Option ```typescript import { Option, Some, None } from "functype/option" // Creation Option(42) // Some(42) Option(null) // None Option(undefined) // None Some(42) // Some(42) None() // None Option.from(42) // Some(42) Option.none() // None // Checking option.isSome() // true if Some, false if None option.isNone() // true if None, false if Some option.isEmpty // same as isNone(), as a property // Accessing option.orThrow() // Gets value or throws if None option.getOrElse(() => defaultValue) // Gets value or returns default option.orThrow(new Error("No value")) // Gets value or throws custom error // Transforming option.map((x) => x * 2) // Transforms inner value option.flatMap((x) => Option(x.toString())) // Chains with operations returning Option option.filter((x) => x > 10) // None if predicate fails, unchanged if passes // Pattern matching option.fold( () => "empty", // Called for None (value) => `value: ${value}`, // Called for Some ) option.match({ Some: (value) => `value: ${value}`, None: () => "empty", }) ``` ## Either ```typescript import { Either, Left, Right } from "functype/either" // Creation Right(42) // Right(42) Left("error") // Left("error") Either.right(42) // Right(42) Either.left("error") // Left("error") Either.fromNullable(value, "was null") // Left if null/undefined // Checking either.isRight() // true if Right, false if Left either.isLeft() // true if Left, false if Right // Accessing either.orThrow() // Gets Right value or throws if Left either.getOrElse(() => defaultValue) // Gets Right value or returns default either.swap().orThrow() // Gets Left value or throws if Right // Transforming either.map((x) => x * 2) // Transforms Right value either.mapLeft((e) => `Error: ${e}`) // Transforms Left value either.flatMap((x) => Right(x.toString())) // Chains with operations returning Either either.filterOrElse( (x) => x > 10, (x) => `${x} is too small`, ) // Left if predicate fails // Operations either.swap() // Converts Left to Right and vice versa // Pattern matching either.fold( (left) => `Error: ${left}`, (right) => `Success: ${right}`, ) either.match({ Right: (value) => `Success: ${value}`, Left: (error) => `Error: ${error}`, }) ``` ## Try ```typescript import { Try } from "functype/try" // Creation Try(() => 42) // Success(42) Try(() => { throw new Error("Failed") }) // Failure(Error) Try.success(42) // Success(42) Try.failure(new Error("Failed")) // Failure(Error) // Checking tryVal.isSuccess() // true if Success, false if Failure tryVal.isFailure() // true if Failure, false if Success // Accessing tryVal.orThrow() // Gets value or throws original error tryVal.getOrElse(() => defaultValue) // Gets value or returns default tryVal.error // Gets error for Failure // Error handling tryVal.recover(() => defaultValue) // Success with original value or default tryVal.recoverWith(() => Try(() => backup())) // Tries alternative computation on failure // Transforming tryVal.map((x) => x * 2) // Maps success value tryVal.flatMap((x) => Try(() => operation(x))) // Chains with operations returning Try // Conversions tryVal.toOption() // Option.Some for Success, Option.None for Failure tryVal.toEither((error) => error.message) // Either.Right for Success, Either.Left for Failure // Pattern matching tryVal.fold( (error) => `Error: ${error.message}`, (value) => `Success: ${value}`, ) tryVal.match({ Success: (value) => `Success: ${value}`, Failure: (error) => `Error: ${error.message}`, }) ``` ## List ```typescript import { List } from "functype/list" // Creation List([1, 2, 3]) // List([1, 2, 3]) List.empty() // List([]) // Properties list.isEmpty // true if empty, false otherwise list.size // Number of elements // Accessing list.headOption() // Option.Some with first element or None if empty list.head() // First element, or undefined if empty list.tail() // List with all elements except the first (a copy) list.get(2) // Option.Some with element at index or None // Adding/removing list.add(4) // New list with element added list.concat(List([4, 5, 6])) // New list with elements added list.remove(2) // New list with the value 2 removed list.removeAt(1) // New list with element at index removed // Transforming list.map((x) => x * 2) // List with transformed elements list.flatMap((x) => List([x, x * 2])) // Transform + flatten list.filter((x) => x % 2 === 0) // List with elements matching predicate // Slicing list.take(2) // First n elements list.drop(2) // All elements after first n list.slice(1, 3) // Elements from start to end (exclusive) // Finding list.find((x) => x > 10) // Option.Some with first match or None list.exists((x) => x > 10) // true if any element matches predicate list.every((x) => x > 0) // true if all elements match predicate (true when empty) list.partition((x) => x > 0) // [matching, rest] list.count((x) => x % 2 === 0) // Count of elements matching predicate // Aggregating list.foldLeft(0)((acc, x) => acc + x) // Reduce from left to right list.foldRight(0)((x, acc) => x + acc) // Reduce from right to left list.reduce((a, b) => a + b) // Reduce (without initial value) // Operations list.reverse() // Reversed list list.sorted((a, b) => a - b) // Sorted list list.sortBy((x) => -x) // Sorted by a key list.distinct() // List with duplicates removed list.concat(List([4, 5, 6])) // Lists combined list.groupBy((x) => (x % 2 === 0 ? "even" : "odd")) // native Map of key to List ``` ## Map ```typescript import { Map } from "functype/map" import { Option } from "functype/option" import { Tuple } from "functype/tuple" // Creation Map([ ["a", 1], ["b", 2], ]) // From [key, value] pairs Map.of(["a", 1], ["b", 2]) // Variadic Map.empty() // Empty map // Properties, not calls map.isEmpty // true if empty map.size // Number of entries // Accessing map.has("a") // true if the key is present, even when its value is undefined map.get("a") // Some(value) or None map.getOrElse("a", () => 0) // Value or default map.orElse("a", () => Option(0)) // Option of the value, or the alternative Option map.keys() // List, insertion order map.values() // List, insertion order map.contains(Tuple(["a", 1])) // true if that exact entry is present (value compared with ===) map.toList() // List of Tuple<[K, V]> entries for (const [k, v] of map) { } // Iterates [key, value] pairs // Modifying (each returns a new Map) map.add(Tuple(["d", 4])) // Entry added or replaced; add takes one Tuple map.remove("a") // Key removed // Transforming map.map((v) => v * 2) // Values transformed, keys kept map.flatMap((entry) => [[`key_${entry.get(0)}`, entry.get(1)]]) // Entries to new [key, value] pairs map.fold(0, (acc, entry) => acc + entry.get(1)) // Fold over Tuple entries // Conversions map.toValue() // { _tag: "Map", value: [K, V][] } map.toSet() // Set of Tuple<[K, V]> entries ``` ## Set ```typescript import { Set } from "functype/set" // Creation Set([1, 2, 3]) // Set([1, 2, 3]) Set.empty() // Empty set // Properties set.isEmpty // true if empty set.size // Number of elements set.has(2) // true if element exists // Modifying set.add(4) // New set with element added set.remove(2) // New set with element removed // Transforming set.map((x) => x * 2) // Set with transformed elements set.flatMap((x) => Set([x, x + 1])) // Transform + flatten set.filter((x) => x % 2 === 0) // Set with elements matching predicate // Set operations: same names as native Set; `other` can be any iterable; results keep this set's order set.union(Set([3, 4, 5])) // Union set.intersection(Set([2, 3, 4])) // Intersection set.difference([3, 4]) // Elements in this set but not in other set.symmetricDifference([3, 4]) // Elements in either set but not both set.isSubsetOf(Set([1, 2, 3, 4])) // true if all elements are in other set.isSupersetOf([1, 2]) // true if all of other's elements are in this set set.isDisjointFrom([7, 8]) // true if no element is shared set.every((x) => x > 0) // true if all elements match predicate ``` ## IO IO is a lazy effect: nothing runs until a `run` method. ```typescript import { Right } from "functype/either" import { IO } from "functype/io" // Sync work that may throw const parsed = IO.tryCatch( () => JSON.parse("{}") as unknown, (err) => new Error(`Failed: ${String(err)}`), ) const parsedNow = parsed.runSync() // Either // Async work const fetched = IO.tryPromise({ try: (signal) => fetch("/api", { signal }).then((r) => r.json() as Promise), catch: (err) => new Error(`Fetch failed: ${String(err)}`), }) const result = await fetched.run() // Either // Ready-made outcomes IO.succeed(42) IO.fail(new Error("Failed")) IO.fromEither(Right(42)) // Adapting a promise-returning function const fetchAPI = (id: string): Promise => fetch(`/api/users/${id}`).then((r) => r.json() as Promise) const getUser = (id: string) => IO.tryPromise({ try: () => fetchAPI(id), catch: (err) => new Error(String(err)) }) // Cancelling const { result: pending, cancel } = getUser("1").runCancellable() const controller = new AbortController() const exit = await getUser("1").runExit({ signal: controller.signal }) // Success | Failure | Die | Interrupted // Racing and timing out const first = await IO.race([getUser("1"), getUser("2")]) .timeout(5000) .run() // Back to a Promise const user = await getUser("1").runOrThrow() ``` ## Tuple ```typescript import { Tuple } from "functype/tuple" // Creation: Tuple takes an array const pair = Tuple([42, "hello"] as [number, string]) const triple = Tuple.triple(true, 42, "hello") Tuple.pair("key", 42) // Tuple<[string, number]> Tuple.of(1, "a", true) // Tuple<[number, string, boolean]> // Accessing pair.get(0) // 42 pair.get(1) // "hello" triple.get(2) // "hello" pair.length // 2 pair.toArray() // [42, "hello"] const [n, s] = pair // destructures like an array (elements typed as the union) pair.get(0) + pair.get(1).length // 47: use the parts directly (there is no apply) // Transforming: map and flatMap receive the whole array pair.map(([a, b]) => [a * 2, b.toUpperCase()] as [number, string]) // Tuple([84, "HELLO"]) pair.map(([a, b]) => [b, a] as [string, number]) // swap: Tuple(["hello", 42]) pair.flatMap(([a, b]) => Tuple([a, b, true] as [number, string, boolean])) // Tuple([42, "hello", true]) // Folding over the elements pair.fold("", (acc, x) => acc + String(x)) // "42hello" ``` ## Branded Types ```typescript import { Brand } from "functype/branded" // Type definitions type UserId = Brand<"UserId", string> type Email = Brand<"Email", string> type PositiveInt = Brand<"PositiveInt", number> // Factory functions with validation const UserId = (id: string): UserId => { if (!/^U\d{6}$/.test(id)) throw new Error("Invalid ID format") return id as UserId } const PositiveInt = (n: number): PositiveInt => { if (!Number.isInteger(n) || n <= 0) throw new Error("Not a positive integer") return n as PositiveInt } // Usage declare function getUserById(id: UserId): User // Type-safe calls getUserById(UserId("U123456")) // Works // getUserById("U123456") // Type error: string is not UserId ``` ## Pattern Matching ```typescript import { Option, Either, Try, List, MatchableUtils } from "functype" // Built-in pattern matching option.match({ Some: (value) => `Found: ${value}`, None: () => "Not found", }) either.match({ Right: (value) => `Success: ${value}`, Left: (error) => `Error: ${error}`, }) list.match({ NonEmpty: (values) => `Values: ${values.join(", ")}`, Empty: () => "No values", }) // Custom pattern matching const isPositive = MatchableUtils.when( (n: number) => n > 0, (n) => `Positive: ${n}`, ) const isZero = MatchableUtils.when( (n: number) => n === 0, () => "Zero", ) const isNegative = MatchableUtils.when( (n: number) => n < 0, (n) => `Negative: ${n}`, ) const defaultCase = MatchableUtils.default((x: number) => `Default: ${x}`) // Chain patterns with fallbacks isPositive(42) ?? isZero(42) ?? isNegative(42) ?? defaultCase(42) // "Positive: 42" ``` ## Http ```typescript import { Decoder } from "functype/decoder" import { Http, HttpError } from "functype/fetch" import { IO } from "functype/io" // Without a decoder — data is unknown const effect = Http.get("/api/users") // IO> // With a decoder — T inferred from it. Decoder.fromThrowing adapts a throwing parser (Zod's .parse) const users = Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }) // IO> const created = Http.post("/api/users", { body: { name: "Alice" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }) // IO> // Or compose one without a schema library; failures accumulate into a DecoderError tree const point = Http.get("/api/point", { decode: Decoder.object({ x: Decoder.number, y: Decoder.number }) }) // Configured client const http = Http.client({ baseUrl: "https://api.example.com", defaultHeaders: { Authorization: "Bearer token" }, }) const user = http.get("/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)) }) // Configured client with effectful request transformer (auth refresh, request IDs, logging) const api = Http.client({ baseUrl: "https://api.example.com", beforeRequest: (r) => IO.succeed(r) .map((req) => ({ ...req, headers: { ...req.headers, "x-request-id": crypto.randomUUID() } })) .flatMap((req) => IO.tryPromise({ try: () => getToken(), catch: (e) => HttpError.networkError(req.url, req.method, e), }).map((token) => ({ ...req, headers: { ...req.headers, Authorization: `Bearer ${token}` } })), ) .tap((req) => logger.info(req.method, req.url)), }) // Compose with IO Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)) }) .map((res) => res.data.filter((u) => u.active)) .retry(3) .timeout(5000) // Error handling Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)) }) .catchTag("HttpStatusError", (e) => (e.status === 404 ? IO.succeed(defaultResponse) : IO.fail(e))) .catchTag("NetworkError", () => IO.succeed(cachedResponse)) // Run await Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)) }).runOrThrow() // HttpResponse await Http.get("/api/users/1").run() // Either> ``` ## Common Conversions ```typescript import { Option, Either, Try, List, FoldableUtils } from "functype" // Convert between types FoldableUtils.toList(Option(42)) // List([42]) FoldableUtils.toList(Either.right(42)) // List([42]) FoldableUtils.toList(Try(() => 42)) // List([42]) List([1, 2, 3]).headOption() // Some(1): a List is not a sum type, so take its head FoldableUtils.toOption(Either.right(42)) // Some(42) FoldableUtils.toOption(Try(() => 42)) // Some(42) FoldableUtils.toEither(Option(42), "Empty") // Right(42) FoldableUtils.toEither( Try(() => 42), "Failed", ) // Right(42) // Built-in conversions option.toEither("No value") // Either.Right or Either.Left either.toOption() // Option.Some or Option.None tryVal.toEither((error) => error) // Either.Right, or Either.Left with the error tryVal.toOption() // Option.Some or Option.None ``` ## Functional Composition ```typescript import { Option } from "functype/option" // Method chaining is the pipeline: each step returns a new container const result = Option("42") .map((s) => s.trim()) .map((s) => parseInt(s, 10)) .filter((n) => !isNaN(n)) .map((n) => n * 2) .getOrElse(() => 0) // 84 // Cross-type transformations const mixed = Option("42") .map((s) => parseInt(s, 10)) .toEither("Invalid number") .map((n) => n * 2) .fold( (err) => `Error: ${err}`, (val) => `Result: ${val}`, ) // "Result: 84" ``` ## Companion Pattern All major types in functype use the Companion pattern for consistent API design: ```typescript import { Option, Either, List, Try } from "functype" // Constructor function usage const opt = Option(42) // Constructor const list = List([1, 2, 3]) // Constructor const right = Either.right(42) // Companion method // Companion methods (static methods) Option.from(value) // Alias for constructor Option.none() // Create empty instance Either.left(err) // Create Left Either.right(42) // Create Right List.fromJSON(jsonString) // Deserialize from JSON Try.fromJSON(jsonString) // Deserialize from JSON // Type guards as companion methods if (Option.isSome(option)) { // TypeScript knows option.value is defined console.log(option.value) } if (Either.isRight(either)) { // TypeScript knows either has Right value console.log(either.value) } if (Try.isSuccess(tryValue)) { // TypeScript knows tryValue succeeded console.log(tryValue.orThrow()) } ``` ## Type Guards Use static type guards for better type narrowing: ```typescript import { Option, Either, Try } from "functype" // Option type guards const option: Option = Option(42) if (Option.isSome(option)) { option.value // TypeScript knows: number (not number | undefined) } if (Option.isNone(option)) { // option.value is undefined here } // Either type guards const either: Either = Either.right(42) if (Either.isRight(either)) { either.value // TypeScript knows: number } if (Either.isLeft(either)) { either.value // TypeScript knows: Error } // Try type guards const tryValue: Try = Try(() => 42) if (Try.isSuccess(tryValue)) { tryValue.error // TypeScript knows: undefined } if (Try.isFailure(tryValue)) { tryValue.error // TypeScript knows: Error } ``` ## Serialization All major types support JSON and binary serialization: ```typescript import { Option, Either, List, Try } from "functype" // Serialize to different formats const option = Option(42) const serialized = option.serialize() const json = serialized.toJSON() // '{"@functype":"Option","_tag":"Some","value":42}' const binary = serialized.toBinary() // Base64 encoded // Deserialize from JSON const opt1 = Option.fromJSON('{"_tag":"Some","value":42}') const opt2 = Option.fromBinary(binary) // Works with all types const list = List([1, 2, 3]) const listJson = list.serialize().toJSON() const restored = List.fromJSON(listJson) const either = Either.right(42) const eitherJson = either.serialize().toJSON() const restoredEither = Either.fromJSON(eitherJson) ``` ## Custom Companion Types Create your own types using the Companion pattern: ```typescript import { Companion } from "functype/companion" // 1. Define interface interface Box { value: T map: (f: (v: T) => U) => Box get: () => T } // 2. Constructor function const BoxConstructor = (value: T): Box => ({ value, map: (f: (v: T) => U) => BoxConstructor(f(value)), get: () => value, }) // 3. Companion object with static methods const BoxCompanion = { of: (value: T) => BoxConstructor(value), empty: () => BoxConstructor(undefined as T), } // 4. Combine using Companion export const Box = Companion(BoxConstructor, BoxCompanion) // Usage const box1 = Box(10) // Constructor const box2 = Box.of(20) // Companion method const box3 = Box.empty() box1.map((x) => x * 2).get() // 20 ``` ## Companion Helper Types Work with Companion objects using helper types: ```typescript import { Companion, type CompanionMethods, type InstanceType, isCompanion } from "functype/companion" import { Option } from "functype/option" // Companion type of a constructor (today this includes the call signature, not only the static methods) type OptionMethods = CompanionMethods // Extract instance type type OptionInstance = InstanceType // Option // Runtime type guard if (isCompanion(Option)) { console.log("Option is a Companion object") } // Use with custom types const Point = Companion((x: number, y: number) => ({ x, y }), { origin: () => ({ x: 0, y: 0 }) }) Point.origin() // { x: 0, y: 0 } type PointInst = InstanceType const instance: PointInst = Point(1, 2) ``` ──────────────────────────────────────────────────────────────────────────────── ## Feature Matrix ──────────────────────────────────────────────────────────────────────────────── # Functype Feature Matrix This matrix shows which interfaces are supported by each data structure in the functype library. ## Legend - ✓ Full support - ◐ Partial support (custom implementation) - ✗ Not supported - ← Inherited from parent interface ## Core Interfaces | Data Structure | Functor | Applicative | Monad | AsyncMonad | Foldable | Matchable | Serializable | Traversable | Extractable | Unsafe | Pipe | Collection | ContainerOps | CollectionOps | | --------------- | :-----: | :---------: | :---: | :--------: | :------: | :-------: | :----------: | :---------: | :---------: | :----: | :--: | :--------: | :----------: | :-----------: | | **Option** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ← | ✓ | ✗ | ✓ | ✗ | | **Either** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✓ | ← | ✗ | ✗ | ◐ | ✗ | | **Try** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✓ | ← | ✓ | ✗ | ◐ | ✗ | | **IO** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | | **Http** | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **List** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | | **Set** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | | **Obj** | ◐ | ◐ | ◐ | ◐ | ✓ | ✓ | ✓ | ◐ | ✓ | ← | ✓ | ✗ | ✓ | ✗ | | **Map** | ◐ | ✗ | ✗ | ✗ | ✓ | ✗ | ✓ | ◐ | ✗ | ✗ | ✓ | ✓ | ✗ | ✗ | | **Lazy** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✓ | ✓ | ← | ✓ | ✗ | ✓ | ✗ | | **Stack** | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | | **LazyList** | ◐ | ✗ | ◐ | ✗ | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | | **Tuple** | ◐ | ✗ | ◐ | ✗ | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ## Variance (0.6.0+) | Data Structure | Variance | Notes | | --------------- | :------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | **Option** | `` | covariant | | **Either** | `` | covariant in both | | **Try** | `` | covariant | | **List** | `` | covariant. `contains`/`remove`/`indexOf` accept `unknown`; `add`/`prepend`/`concat` widen to `A \| B`; `reduce` guarded by `Widen` | | **Set** | `` | covariant. Same patterns as List | | **LazyList** | `` | covariant. `concat` widens | | **Lazy** | `` | covariant | | **Identity** | `` | covariant. `isSame` accepts `Identity` | | **Tuple** | `` | covariant | | **Map** | `` | V covariant; K invariant (Scala Map[K, +V] precedent — equality-sensitive keys) | | **Stack** | structural covariant | intersection type alias can't carry ``; subtyping works structurally | | **Obj** | invariant (by design) | T is a record type; `keyof T` is contravariant, so widening loses key fidelity | | **Ref** | invariant (by design) | mutable cell; `set(A)` writes A, widening would be unsound | | **IO** | `` | E and A covariant; R invariant. `IO` widens to `IO` without a cast. ZIO-style `` still deferred. | All base typeclasses (`Traversable`, `Extractable`, `Functor`, `Applicative`, `Monad`, `AsyncMonad`, `ContainerOps`, `CollectionOps`, `Foldable`, `Serializable`, `Pipe`, `Matchable`, `Promisable`, `Doable`, `Reshapeable`) declared `` / ``. `Traversable.reduce` / `reduceRight` are guarded by `Widen` (`src/typeclass/variance.ts`), TypeScript's equivalent of Scala's `[B >: A]` lower-bound constraint. See [`variance-guide.md`](./variance-guide.md) for the full contributor reference. Collections (`List`, `Set`, `LazyList`, `Stack`, `Map`, `Obj`) keep `Traversable`. Sum types (`Either`, `Try`) extend the lighter `FunctypeSum` base with no collection-style methods. ## Additional Properties | Data Structure | Typeable | Valuable | Iterable | PromiseLike | Do-notation | Reshapeable | Promisable | | --------------- | :------: | :------: | :------: | :---------: | :---------: | :---------: | :--------: | | **Option** | ✓ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | | **Either** | ✓ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | | **Try** | ✓ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | | **IO** | ✗ | ✗ | ✓ | ✗ | ✓ | ✗ | ✗ | | **Http** | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **List** | ✓ | ✗ | ✓ | ✗ | ✓ | ✓ | ✗ | | **Set** | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | | **Obj** | ✓ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | | **Map** | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | | **Lazy** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Stack** | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **LazyList** | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | | **Tuple** | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ## Companion Methods All types follow the **Companion pattern** (inspired by Scala), combining constructor functions with static utility methods. Each type provides: ### Common Creation Methods | Data Structure | of | from | pure | empty | none | left | right | success | failure | | --------------- | :-: | :--: | :--: | :---: | :--: | :--: | :---: | :-----: | :-----: | | **Option** | ✓ | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | | **Either** | ✗ | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | ✗ | ✗ | | **Try** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | | **IO** | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | | **Http** | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **List** | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Set** | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Obj** | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Map** | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Lazy** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Stack** | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **LazyList** | ✓ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Tuple** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Identity** | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **Ref** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | **Collection creation** - multiple options available: ```typescript // List creation List([1, 2, 3]) // from array List.of(1, 2, 3) // variadic factory List.empty() // typed empty list // Set creation Set([1, 2, 3]) // from array Set.of(1, 2, 3) // variadic factory Set.empty() // typed empty set // Map creation Map([ ["a", 1], ["b", 2], ]) // from key-value pairs Map.of(["a", 1], ["b", 2]) // variadic factory Map.empty() // typed empty map ``` ### Http Methods ```typescript ignore // Http — fetch wrapper returning IO> by default // Provide a decoder to get typed responses (BYOV: bring your own validator) Http.get(url, opts?) // GET → HttpResponse Http.get(url, { decode }) // GET → HttpResponse (T inferred from the Decoder) Http.post(url, opts?) // POST with auto JSON body serialization Http.put(url, opts?) // PUT Http.patch(url, opts?) // PATCH Http.delete(url, opts?) // DELETE Http.request(fullOpts) // Full control Http.client(config) // Create configured client with baseUrl, defaultHeaders, custom fetch, beforeRequest (effectful request transformer) // Decoder.fromThrowing adapts any throwing parser (Zod, TypeBox, Valibot, or manual validators) Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)) }) Http.post("/api/users", { body: { name: "Alice" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)) }) // HttpError — three-variant ADT HttpError.networkError(url, method, cause) HttpError.httpStatusError(url, method, status, statusText, body) HttpError.decodeError(url, method, body, cause) HttpError.match(error, { NetworkError, HttpStatusError, DecodeError }) HttpError.isNetworkError(e) / .isHttpStatusError(e) / .isDecodeError(e) ``` ### Validation & Typed Errors Error-accumulating validation — functype's "Validated" applicative role. `Validation` collects **all** field errors rather than short-circuiting on the first (unlike `Either.sequence`, which fails fast). Not a typeclass-grid container, so it lives here rather than in the interface matrix above (same as `HttpError` / `DecoderError`). ```typescript ignore // FormValidation — the accumulating result type type FormValidation = Either>, T> // TypedError — code-tagged structured error (extends Throwable) TypedError.validation(field, value, rule) // → TypedError<"VALIDATION_FAILED">, context { field, value, rule } TypedError.isTypedError(v) / TypedError.hasCode(e, code) // Validation — rule DSL + form validator Validation.rule("min:18" | "email" | "required" | "pattern:..." | "in:a,b" | ...) Validation.combine(...validators) // all must pass (fail-fast per field) Validation.custom(predicate, message) // custom per-field rule Validation.validators.email / .url / .required / .positiveNumber / .nonEmptyString Validation.form(schema, data) // → FormValidation, accumulates every field error // Validator = (value: unknown) => Either, T> // form() is flat/per-field. For cross-field (lo < hi) or dynamic-key (weights.*) checks, // hand-accumulate TypedError.validation(...) into a List and return the same FormValidation shape. ``` ### Type Guards Static type guards for narrowing types: | Data Structure | Type Guard Methods | | --------------- | -------------------------------------------- | | **Option** | `isSome(option)`, `isNone(option)` | | **Either** | `isLeft(either)`, `isRight(either)` | | **Try** | `isSuccess(tryValue)`, `isFailure(tryValue)` | ### Serialization Methods All Serializable types provide static deserialization methods: - `fromJSON(json: string): T` - Deserialize from JSON - `fromBinary(binary: string): T` - Deserialize from base64-encoded binary **Note**: See `docs/companion-pattern.md` for complete guide on the Companion pattern. ## Key Methods by Interface ### Functor - `map(f: (value: A) => B): Functor` ### Applicative (extends Functor) - `ap(ff: Applicative<(value: A) => B>): Applicative` ### Monad (extends Applicative) - `flatMap(f: (value: A) => Monad): Monad` ### AsyncMonad (extends Monad) - `flatMapAsync(f: (value: A) => PromiseLike>): PromiseLike>` ### Foldable - `foldLeft(z: B): (op: (b: B, a: A) => B) => B` - `foldRight(z: B): (op: (a: A, b: B) => B) => B` Note: `fold` has different semantics per type category: - **Sum types** (Option, Either, Try, IO): `fold(onEmpty: () => B, onValue: (value: A) => B): B` — pattern match - **Collections** (List, Set, Map, Stack, Tuple, LazyList): `fold(initial: B, fn: (acc: B, a: A) => B): B` — left-reduce accumulator `foldAsync` (Option, Either, Try) — same shape as `fold` but accepts sync or async handlers and always returns `Promise`. Use when at least one branch performs async work to avoid `T | Promise` unions. ### Matchable - `match(patterns: Record R>): R` ### Serializable - `serialize(): SerializationMethods` - `toJSON(): string` - `toBinary(): Uint8Array` ### Traversable (extends AsyncMonad) - `size: number` - `isEmpty: boolean` - `contains(value: A): boolean` - `reduce(f: (acc: B, value: A) => B, initial: B): B` - `reduceRight(f: (value: A, acc: B) => B, initial: B): B` ### Unsafe - `orThrow(error?: Error): T` ### Extractable (extends Unsafe) - `getOrElse(defaultValue: () => T): T` - `orElse(alternative: () => Extractable): Extractable` - `orNull(): T | null` - `orUndefined(): T | undefined` ### Pipe - `pipe(f: (value: T) => U): U` ### Collection - `toList(): List` - `toSet(): Set` - `toString(): string` ### ContainerOps - `count(p: (value: A) => boolean): number` - `find(p: (value: A) => boolean): A | undefined` - `exists(p: (value: A) => boolean): boolean` - `forEach(f: (value: A) => void): void` `every(p)`, the dual of `exists`, is on `Option`, on `FunctypeSum` (so `Either` and `Try`) and on `CollectionOps` (`List`, `Set`). It gives `true` when there's no value: `None`, `Left`, `Failure` or an empty collection. `Lazy` and `Obj` don't have it. ### CollectionOps - `every(p: (value: A) => boolean): boolean` - `drop(n: number): Self` - `dropRight(n: number): Self` - `dropWhile(p: (value: A) => boolean): Self` - `flatten()`: the element type flattened, so `List` gives `List`. Strings stay whole - `head(): A | undefined` - `headOption(): Option` - `take(n: number): Self` - `takeWhile(p: (value: A) => boolean): Self` - `takeRight(n: number): Self` - `last(): A | undefined` - `lastOption(): Option` - `tail(): Self` - `init(): Self` - `toArray(): A[]` `List` and `Set` return `List` and `Set` from every method above that returns `Self`, and a type test fails if a new one isn't overridden. A count `n` of 0 or less means 0: `drop(-1)` drops nothing and `take(-1)` takes nothing. ### List-specific Methods - `reverse(): List` - `indexOf(value: A): number` - `prepend(item: A): List` - `distinct(): List` - `sorted(compareFn?): List` - `sortBy(f, compareFn?): List` - `zip(other: List): List<[A, B]>` - `zipWithIndex(): List<[A, number]>` - `groupBy(f: (a: A) => K): Map>` - `partition(p): [List, List]` - `span(p): [List, List]` - `slice(start, end): List` ### Do-notation Support Enables Scala-like for-comprehensions using JavaScript generators: - `Do(function* () { ... })`: Synchronous monadic comprehensions - `DoAsync(async function* () { ... })`: Async monadic comprehensions - `$(monad)`: Helper for type inference with `yield*` ### Reshapeable Provides type conversion between monadic types: - `toOption(): Option` - `toEither(leftValue: E): Either` - `toList(): List` - `toTry(): Try` ### Promisable Provides conversion to Promise for async interop: - `toPromise(): Promise` ## Notes 1. **Functype**: Implemented by single-value containers (Option, Try, Lazy). Provides full functional programming support. 2. **FunctypeCollection**: Implemented by collection containers (List, Set). Extends FunctypeBase with collection-specific operations. 3. **Special Cases**: - **Either**: Implements FunctypeBase but not full Functype (no Extractable/Matchable) - **Map**: Uses KVTraversable (omits map/flatMap/ap from Traversable — key-value containers can't freely transform their type parameter) - **Obj**: Immutable object wrapper using KVTraversable. Record-constrained map/flatMap (B must be a Record). Provides fluent ops: get, set, assign, merge, when, omit, pick - **Stack**: Implements individual interfaces without FunctypeBase - **LazyList**: Lazy evaluation with support for Foldable, Serializable, Pipe, and Typeable interfaces - **Tuple**: Enhanced container with Foldable, Serializable, Pipe, Typeable, and Valuable support 4. **Do-notation**: Provides generator-based monadic comprehensions similar to Scala's for-comprehensions. Supports Option, Either, Try, and List with automatic short-circuiting and cartesian products. 5. **Reshapeable**: Enables conversion between different monad types, allowing flexible composition in Do-notation when mixing types. 6. **Promisable**: Provides conversion to Promise for async interoperability. Supported by Option, Either and Try. 7. **Utility Types** (not in matrix): - **Cond**: Conditional expression builder - **Match**: Pattern matching utility - **ValidatedBrand**: Branded types with validation - **Throwable**: Enhanced error type 8. **IO**: Lazy, composable effect type with typed errors and dependency injection. - **R** = Requirements (environment/dependencies needed to run) - **E** = Error type (typed failures) - **A** = Success type (value produced on success) - Key features: - Lazy execution (nothing runs until explicitly executed) - Unified sync/async API (auto-detects Promise returns) - Typed errors at compile time - Composable via map/flatMap - Dependency injection via Tag/Layer/Context - Structured concurrency: bracket, race, timeout - Cancellation: `interruptOn(signal)` stops a running effect at its next step once the `AbortSignal` fires (cleanup still runs); `runCancellable()` returns `{ result, cancel }` - Tracing: `withSpan(name, attributes?)` runs an effect in a span, and an inner `withSpan` nests under it without a parent. Core ships only the type-only `SpanTracer` contract (`start`, `run`, `end`), provided with `provideService(SpanTracer, tracer)`; with none, it's a no-op - Generator do-notation (`IO.gen`) and builder do-notation (`IO.Do`) - Error handling: catchTag, catchAll, retry, retryWithDelay, retryWhile, retryWithBackoff - Value-driven repetition: repeatUntil, repeatWhile, IO.iterate (bounded by RepeatExhausted) - Execution methods: run(), runOrThrow(), runSync(), runSyncOrThrow(), runExit(), runOption(), runTry(), runCancellable() - Outcomes: `Exit` = Success | Failure | Die | Interrupted, returned by runExit(). `Failure` carries a value from the declared `E` channel; `Die` carries a **defect** — a value that is not an `E` (a throwing `IO.sync` thunk, a throwing map/flatMap/mapError callback, or `IO.die`). `run()` returns `Either`, which has no branch for either a defect or an interruption, so both arrive in the `Left`; `runExit()` is what keeps them apart. Defects stay recoverable — recover/recoverWith/fold/mapError treat `Die` as `Failure`. `fold`'s `onDie` and `match`'s `Die` are optional and fall back to the failure handler. - Testing utilities: - **TestClock**: Controlled time for testing timeouts/delays - **TestContext**: Test environment with mocked services ──────────────────────────────────────────────────────────────────────────────── ## option ──────────────────────────────────────────────────────────────────────────────── # Option Safe handling of nullable values. ## Overview Option is a container that either holds a value (`Some`) or represents the absence of a value (`None`). It eliminates null pointer exceptions by making nullable values explicit in the type system. ## Basic Usage ```typescript import { Option } from "functype/option"; // Creating Options const some = Option(42); // Some(42) const none = Option(null); // None const explicit = Option.none(); // None // Checking state some.isSome(); // true none.isNone(); // true // Extracting values some.getOrElse(() => 0); // 42 none.getOrElse(() => 0); // 0 some.orThrow(); // 42 none.orThrow(); // throws Error some.orNull(); // 42 none.orNull(); // null ``` ## Constructors | Method | Description | | -------------------- | ------------------------------------- | | `Option(value)` | Some if non-null/undefined, else None | | `Option.from(value)` | Same as constructor | | `Option.none()` | Create None explicitly | ## Transformations ```typescript // Map - transform the value if present Option(5).map((x) => x * 2); // Some(10) Option(null).map((x) => x * 2); // None // FlatMap - chain operations that return Options Option(5).flatMap((x) => (x > 0 ? Option(x) : Option.none())); // Filter - keep value only if predicate passes Option(5).filter((x) => x > 3); // Some(5) Option(5).filter((x) => x > 10); // None // forEach - side effect only, runs when the value is present Option(5).forEach((x) => console.log(x)); // logs 5 // exists / every - test the value. None gives false for exists and true for every Option(5).exists((x) => x > 3); // true Option(null).exists((x) => x > 3); // false Option(null).every((x) => x > 3); // true: "absent, or present and matching" ``` ## Pattern Matching ```typescript // Using fold const result = Option(user).fold( () => "No user found", (u) => `Hello, ${u.name}`, ); // Using match const greeting = Option(name).match({ Some: (n) => `Hello, ${n}`, None: () => "Hello, stranger", }); ``` ## Do-Notation ```typescript import { Do, $ } from "functype/do"; import { Option } from "functype/option"; const result = Do(function* () { const a = yield* $(Option(1)); const b = yield* $(Option(2)); const c = yield* $(Option(3)); return a + b + c; }); // Some(6) // Short-circuits on None const failed = Do(function* () { const a = yield* $(Option(1)); const b = yield* $(Option.none()); // stops here const c = yield* $(Option(3)); return a + b + c; }); // None ``` ## Key Features - **Type Safety**: TypeScript enforces explicit handling of empty cases - **Chainable Operations**: map, flatMap, filter without null checks - **Pattern Matching**: Explicit Some/None handling with fold() and match() - **Composable**: Works with Do-notation for complex workflows ## When to Use Option - Function return values that might not exist (database queries, array searches) - Optional configuration or parameters - Chaining operations where any step might fail - Replacing nullable types with explicit presence/absence ## Type Conversions ```typescript option.toEither("Error message"); // Left("Error message") or Right(value) option.toList(); // List([]) or List([value]) option.toTry(); // Failure or Success(value) option.toPromise(); // Rejected or Resolved Promise ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/types/Option.html) ──────────────────────────────────────────────────────────────────────────────── ## either ──────────────────────────────────────────────────────────────────────────────── # Either Express success/failure with values. ## Overview Either represents a value that can be one of two types: `Left` (typically for errors) or `Right` (for success values). It's perfect for operations that can fail with meaningful error information. ## Basic Usage ```typescript import { Either, Left, Right } from "functype/either"; // Creating Either values const success = Right(42); // Right(42) const failure = Left("error"); // Left("error") // Checking state success.isRight(); // true failure.isLeft(); // true // Extracting values success.getOrElse(() => 0); // 42 failure.getOrElse(() => 0); // 0 success.orThrow(); // 42 failure.orThrow(); // throws Error ``` ## Constructors | Method | Description | | --------------------- | ------------------------------ | | `Right(value)` | Create a Right (success) value | | `Left(error)` | Create a Left (error) value | | `Either.right(value)` | Same as Right() | | `Either.left(error)` | Same as Left() | ## Transformations ```typescript // Map - transform the Right value Right(5).map((x) => x * 2); // Right(10) Left("err").map((x) => x * 2); // Left("err") - unchanged // MapLeft - transform the Left value Left("err").mapLeft((e) => e.toUpperCase()); // Left("ERR") Right(5).mapLeft((e) => e.toUpperCase()); // Right(5) - unchanged // FlatMap - chain operations Right(5).flatMap((x) => (x > 0 ? Right(x * 2) : Left("negative"))); // Bimap - transform both sides either.bimap( (left) => `Error: ${left}`, (right) => right * 2, ); // Exists / Every - test the Right value. A Left gives false for exists and true for every Right(5).every((x) => x > 3); // true Left("err").every((x) => x > 3); // true: no Right value to fail // FilterOrElse - turn a value-level guard into a typed Left without breaking the chain Right(5).filterOrElse( (n) => n > 10, (n) => `too small: ${n}`, ); // Left("too small: 5") // Traverse - run an Either-returning function over an array; stops calling it at the first Left const parseNumber = (s: string): Either => Number.isNaN(Number(s)) ? Left(`not a number: ${s}`) : Right(Number(s)); Either.traverse(["1", "2", "3"], parseNumber); // Right([1, 2, 3]) Either.traverse(["1", "x", "3"], parseNumber); // Left("not a number: x"); "3" is never parsed Either.sequence([Right(1), Right(2)]); // Right([1, 2]) // TraverseAsync - run an async Either-returning function over many items await Either.traverseAsync(rows, saveRow); // one at a time, stops at the first Left await Either.traverseAsync(ids, fetchUser, { concurrency: 4 }); // up to 4 at once ``` ## Pattern Matching ```typescript // Using fold const result = either.fold( (error) => `Failed: ${error}`, (value) => `Success: ${value}`, ); // Using match pattern const message = validateUser(input).fold( (errors) => `Validation failed: ${errors.join(", ")}`, (user) => `Welcome, ${user.name}!`, ); ``` ## Validation Pipeline ```typescript const validateAge = (age: number): Either => age >= 0 && age <= 120 ? Right(age) : Left("Invalid age"); const validateName = (name: string): Either => name.length > 0 ? Right(name) : Left("Name required"); // Chain validations const validateUser = (data: UserInput) => validateName(data.name).flatMap((name) => validateAge(data.age).map((age) => ({ name, age })), ); ``` ## Do-Notation ```typescript import { Do, $ } from "functype/do"; const result = Do(function* () { const name = yield* $(validateName(input.name)); const age = yield* $(validateAge(input.age)); const email = yield* $(validateEmail(input.email)); return { name, age, email }; }); // Short-circuits on first Left ``` ## Key Features - **Error Information**: Preserve detailed error context instead of losing it with try-catch - **Railway Oriented**: Operations automatically short-circuit on Left - **Composable Errors**: Chain operations with mapLeft to transform errors - **Type-Safe**: Both success and error types are known at compile time ## When to Use Either - Operations that can fail with detailed error info (validation, parsing, API calls) - Multiple validation steps in a pipeline - Railway-oriented programming (happy path and error path handled separately) - When you need typed errors at compile time ## Type Conversions ```typescript either.toOption(); // None for Left, Some(value) for Right either.toTry(); // Failure for Left, Success for Right either.toPromise(); // Rejected for Left, Resolved for Right ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/interfaces/EitherBase.html) ──────────────────────────────────────────────────────────────────────────────── ## try ──────────────────────────────────────────────────────────────────────────────── # Try Safely execute operations that might throw exceptions. ## Overview Try wraps operations that might throw exceptions, converting them to `Success` or `Failure` values. It bridges exception-based code with functional error handling. ## Basic Usage ```typescript import { Try } from "functype/try"; // Wrap potentially throwing code const result = Try(() => JSON.parse(jsonString)); // Check state result.isSuccess(); // true if no exception result.isFailure(); // true if exception thrown // Extract values result.getOrElse(() => ({})); // value or default result.orThrow(); // value or re-throw result.toEither((error) => error); // Either; pass a value or a builder for the Left ``` ## Constructors | Method | Description | | -------------------- | ------------------------------------------- | | `Try(() => value)` | Wrap a potentially throwing function | | `Try.success(value)` | Create a Success directly | | `Try.failure(error)` | Create a Failure directly (Error or string) | | `Try.fromPromise(p)` | Create Try from a Promise (async) | ## Transformations ```typescript // Map - transform success value Try(() => "hello").map((s) => s.toUpperCase()); // Success("HELLO") Try(() => { throw new Error("boom"); }).map((s) => s.toUpperCase()); // Failure, map is skipped // FlatMap - chain Try operations Try(() => readFile(path)) .flatMap((content) => Try(() => JSON.parse(content))) .flatMap((data) => Try(() => validate(data))); // Recover - handle failures by mapping over the error Try(() => riskyOperation()).recover((error) => fallbackValue); // RecoverWith - handle with another Try Try(() => primarySource()).recoverWith((error) => Try(() => backupSource())); // Exists / Every - test the success value. A Failure gives false for exists and true for every Try(() => 5).every((x) => x > 3); // true Try(() => { throw new Error("boom"); }).every((x) => x > 3); // true: no success value to fail // FilterOrElse - turn a value-level guard into a typed Failure (no manual throw) Try.success(parse(raw)) .filterOrElse( (j) => j.data.children.length > 0, () => new Error("Post not found"), ) .map((j) => j.data.children[0]?.data); // ?. because noUncheckedIndexedAccess can't see the guard ``` ## Pattern Matching ```typescript // Using fold const message = Try(() => fetchData()).fold( (error) => `Failed: ${error.message}`, (data) => `Got ${data.length} items`, ); // Using match result.match({ Success: (value) => console.log("Got:", value), Failure: (error) => console.error("Error:", error), }); ``` ## Error Handling Patterns ```typescript // Chain multiple operations const result = Try(() => readConfig()) .flatMap((config) => Try(() => connectDB(config))) .flatMap((db) => Try(() => db.query("SELECT * FROM users"))) .recover(() => []); // Return empty array on any failure // Transform errors: Try has no mapFailure, so recover into a new Failure Try(() => riskyCall()).recoverWith((err) => Try.failure(new CustomError(err.message)), ); // Filter with predicate Try(() => parseInt(input)).filterOrElse( (n) => n > 0, () => new Error("Must be positive"), ); ``` ## Do-Notation ```typescript import { Do, $ } from "functype/do"; import { Try } from "functype/try"; const result = Do(function* () { const config = yield* $(Try(() => readConfig())); const db = yield* $(Try(() => connectDB(config))); const users = yield* $(Try(() => db.query("SELECT * FROM users"))); return users; }); // Try ``` ## Key Features - **Exception Bridge**: Convert throwing code to functional style - **Composable**: Chain operations without try-catch blocks - **Recovery**: Elegant fallback patterns - **Type-Safe**: Success type tracked at compile time ## When to Use Try - Wrapping external code that throws exceptions - JSON parsing, file operations, network calls - When you want to chain operations that might fail - Converting exception-based APIs to functional style ## Type Conversions ```typescript tryValue.toOption(); // None for Failure, Some for Success tryValue.toEither((error) => error); // Left(error) or Right(value) tryValue.toPromise(); // Rejected or Resolved Promise ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/types/Try.html) ──────────────────────────────────────────────────────────────────────────────── ## list ──────────────────────────────────────────────────────────────────────────────── # List Immutable arrays with functional operations. ## Overview List is an immutable collection that wraps arrays and provides functional operations. Every transformation creates a new List, preserving the original data. ## Basic Usage ```typescript import { List } from "functype/list"; // Creating Lists const nums = List([1, 2, 3, 4, 5]); const empty = List.empty(); const single = List.of(42); // Basic operations nums.head(); // 1 nums.tail(); // List([2, 3, 4, 5]) nums.size; // 5 nums.isEmpty; // false ``` ## Constructors | Method | Description | | -------------------- | ----------------------- | | `List(array)` | Create from array | | `List.of(...values)` | Create from values | | `List.empty()` | Create empty typed list | ## Transformations ```typescript // Map - transform each element List([1, 2, 3]).map((x) => x * 2); // List([2, 4, 6]) // Filter - keep matching elements List([1, 2, 3, 4]).filter((x) => x % 2 === 0); // List([2, 4]) // FlatMap - flatten nested results List([1, 2]).flatMap((x) => List([x, x * 10])); // List([1, 10, 2, 20]) // Fold - reduce to single value List([1, 2, 3]).foldLeft(0)((acc, x) => acc + x); // 6 // MapAsync - await each element; one at a time unless you raise the cap await List(ids).mapAsync(fetchUser); // in order await List(ids).mapAsync(fetchUser, { concurrency: 4 }); // up to 4 at once ``` ## Collection Operations ```typescript // Take and drop List([1, 2, 3, 4, 5]).take(3); // List([1, 2, 3]) List([1, 2, 3, 4, 5]).takeRight(2); // List([4, 5]) List([1, 2, 3, 4, 5]).drop(2); // List([3, 4, 5]) List([1, 2, 3, 4, 5]).dropRight(2); // List([1, 2, 3]) List([1, 2, 3]).drop(-1); // List([1, 2, 3]): n of 0 or less drops nothing List([1, 2, 3, 4, 5]).takeWhile((x) => x < 4); // List([1, 2, 3]) List([1, 2, 3]).dropWhile((x) => x < 10); // List([]): every element matched List([1, 2, 3, 4, 5]).slice(1, 4); // List([2, 3, 4]) // Flatten - spread arrays, Lists and Sets into one List List([[1, 2], [3]]).flatten(); // List([1, 2, 3]) List([List([1]), Set([2])]).flatten(); // List([1, 2]) // Strings stay whole. For characters, use flatMap((s) => [...s]) // Element access. These are methods (2.0); tail() and init() copy the rest of the List List([1, 2, 3]).head(); // 1 List([1, 2, 3]).headOption(); // Option(1) List([1, 2, 3]).last(); // 3 List([1, 2, 3]).lastOption(); // Option(3) List([1, 2, 3]).tail(); // List([2, 3]) List([1, 2, 3]).init(); // List([1, 2]) // Find and contains List([1, 2, 3]).find((x) => x > 1); // Some(2), or None when nothing matches List([1, 2, 3]).contains(2); // true List([1, 2, 3]).exists((x) => x > 2); // true List([1, 2, 3]).every((x) => x > 0); // true (also true for an empty List) // Combine and reorder List([1, 2]).concat(List([3, 4])); // List([1, 2, 3, 4]) List([1, 2]).add(3); // List([1, 2, 3]) List([1, 2]).prepend(0); // List([0, 1, 2]) List([1, 2, 3]).reverse(); // List([3, 2, 1]) ``` ## Grouping and Sorting ```typescript // Group by key List([1, 2, 3, 4]).groupBy((x) => (x % 2 === 0 ? "even" : "odd")); // Map { "odd" => List([1, 3]), "even" => List([2, 4]) } // Partition - split by predicate [matching, non-matching] List([1, 2, 3, 4, 5]).partition((x) => x % 2 === 0); // [List([2, 4]), List([1, 3, 5])] // Span - split at first non-matching [prefix, rest] List([1, 2, 3, 4, 1]).span((x) => x < 3); // [List([1, 2]), List([3, 4, 1])] // Sort List([3, 1, 2]).sorted(); // List([1, 2, 3]) List(["b", "a"]).sortBy((s) => s); // List(["a", "b"]) // Distinct List([1, 2, 2, 3, 3, 3]).distinct(); // List([1, 2, 3]) // Zip List([1, 2, 3]).zip(List(["a", "b", "c"])); // List([[1, "a"], [2, "b"], [3, "c"]]) List(["a", "b", "c"]).zipWithIndex(); // List([["a", 0], ["b", 1], ["c", 2]]) ``` ## Do-Notation (Cartesian Products) ```typescript import { Do, $ } from "functype/do"; import { List } from "functype/list"; // Generate all combinations const result = Do(function* () { const x = yield* $(List([1, 2])); const y = yield* $(List(["a", "b"])); return `${x}${y}`; }); // List(["1a", "1b", "2a", "2b"]) // Performance: 175x faster than nested flatMaps ``` ## Key Features - **Immutable**: All operations return new Lists - **Optimized Performance**: 12x faster than nested flatMaps for complex operations - **Functional Methods**: map, filter, fold, groupBy, and 40+ more - **Type-Safe**: Full TypeScript inference for all transformations ## When to Use List - Data transformations that need to preserve originals (UI state, historical data) - Functional pipelines with map/filter/fold - Cartesian products with Do-notation (generating combinations, test data) - When immutability is important ## Type Conversions ```typescript list.toArray(); // Convert to native array list.toSet(); // Convert to Set list.headOption(); // Option for first element ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/interfaces/List.html) ──────────────────────────────────────────────────────────────────────────────── ## set ──────────────────────────────────────────────────────────────────────────────── # Set Immutable sets of unique values. ## Overview Set holds each value once, in insertion order, and never changes in place: every operation returns a new Set. Values compare the way a native `Set` compares them, so objects match by identity and `NaN` equals `NaN`. Import it under its own name; the built-in stays reachable as `globalThis.Set`. ## Basic Usage ```typescript import { Set } from "functype/set"; const tags = Set(["a", "b", "a"]); // Set(a, b): duplicates collapse const empty = Set.empty(); tags.size; // 2 tags.isEmpty; // false tags.has("a"); // true tags.add("c"); // Set(a, b, c) tags.add("a"); // Set(a, b): already there tags.remove("a"); // Set(b) ``` ## Constructors | Method | Description | | ------------------- | ------------------------------------ | | `Set(iterable)` | Create from an array or any iterable | | `Set.of(...values)` | Create from values | | `Set.empty()` | Create an empty typed set | ## Set Operations These have the same names as native `Set` (ES2025) and give the same elements. `other` can be any iterable: an array, a native `Set`, a functype `Set` or a `List`. Results keep this set's order, then `other`'s. ```typescript const a = Set([1, 2, 3]); a.union([3, 4, 5]); // Set(1, 2, 3, 4, 5) a.intersection([2, 3, 4]); // Set(2, 3) a.difference([3]); // Set(1, 2) a.symmetricDifference([3, 4]); // Set(1, 2, 4) a.isSubsetOf([1, 2, 3, 4]); // true a.isSupersetOf([1, 2]); // true a.isDisjointFrom([7, 8]); // true ``` `union` and `symmetricDifference` widen the element type, so `Set.union(["a"])` is a `Set`. ## Transformations ```typescript const nums = Set([1, 2, 3]); nums.map((x) => x % 2); // Set(1, 0): equal results collapse nums.filter((x) => x > 1); // Set(2, 3) nums.flatMap((x) => [x, x + 10]); // Set(1, 11, 2, 12, 3, 13) nums.fold(0, (sum, x) => sum + x); // 6 // Async map: one call at a time by default await nums.mapAsync(async (x) => x * 2); // Set(2, 4, 6) await nums.mapAsync(async (x) => x * 2, { concurrency: 4 }); // up to 4 at once ``` ## Checking Elements ```typescript nums.has(2); // true nums.exists((x) => x > 2); // true: at least one matches nums.every((x) => x > 0); // true: all match, and true for an empty Set ``` ## Type Conversions ```typescript nums.toList(); // List([1, 2, 3]) nums.toArray(); // [1, 2, 3] List([1, 1, 2]).toSet(); // Set(1, 2) ``` ## When to Use Set - Membership checks and de-duplication - Combining groups of ids, tags or permissions with union, intersection and difference - Anywhere a value should appear once, and the collection should not change in place ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/interfaces/Set.html) ──────────────────────────────────────────────────────────────────────────────── ## obj ──────────────────────────────────────────────────────────────────────────────── # Obj Immutable object wrapper with fluent operations. ## Overview Obj wraps plain JavaScript objects and provides chainable, immutable operations for building and transforming them. It replaces imperative object mutation patterns (like `headers["key"] = value`) with a fluent functional API. Obj uses `KVTraversable` — the same pattern as Map — because key-value containers can't freely transform their type parameter like Option or Either can. Map/flatMap are available but constrained to return Record types. ## Basic Usage ```typescript import { Obj } from "functype/obj"; // Creating Obj instances const user = Obj({ name: "John", age: 30 }); const empty = Obj.empty<{ name: string }>(); const fromOf = Obj.of({ x: 1, y: 2 }); // Accessing values user.get("name"); // Some("John") user.value(); // { name: "John", age: 30 } user.has("name"); // true user.isEmpty; // false user.size; // 2 ``` ## Object Operations ```typescript const user = Obj({ name: "John", age: 30, role: "admin" }); // Set a single key (existing keys only) user.set("age", 31); // → Obj({ name: "John", age: 31, role: "admin" }) // Assign partial (same shape, no new keys) user.assign({ name: "Jane", age: 25 }); // → Obj({ name: "Jane", age: 25, role: "admin" }) // Merge (can add new keys, widens type) user.merge({ city: "NYC" }); // → Obj({ name: "John", age: 30, role: "admin", city: "NYC" }) // Conditional assign (existing keys only, like assign) user.when(isAdmin, { role: "superadmin" }); // → assigns only if isAdmin is true // Pick specific keys user.pick("name", "role"); // → Obj({ name: "John", role: "admin" }) // Omit specific keys user.omit("role"); // → Obj({ name: "John", age: 30 }) ``` ## Conditional Building with `when` The primary motivator for Obj — replacing imperative if/assign patterns: Before, mutable: ```typescript const headers: Record = { "User-Agent": userAgent }; if (requiresAuth && accessToken) { headers["Authorization"] = `Bearer ${accessToken}`; } ``` After, immutable and fluent: ```typescript const headers = Obj({ "User-Agent": userAgent } as Record) .assign({ "Content-Type": "application/json" }) .when(requiresAuth, { Authorization: `Bearer ${accessToken}` }) .value(); ``` ## Accessors ```typescript const obj = Obj({ a: 1, b: 2, c: 3 }); obj.keys(); // List(["a", "b", "c"]) obj.values(); // List([1, 2, 3]) obj.entries(); // List([Tuple(["a", 1]), Tuple(["b", 2]), Tuple(["c", 3])]) ``` ## Functype Interface ```typescript // Fold Obj({ x: 1 }).fold( () => "empty", (v) => `value: ${v.x}`, ); // "value: 1" // Match Obj({ x: 1 }).match({ Obj: (v) => v.x }); // 1 // Pipe Obj({ x: 5 }).pipe((v) => v.x * 2); // 10 // Reshapeable Obj({ x: 1 }).toOption(); // Some({ x: 1 }) Obj({ x: 1 }).toEither("err"); // Right({ x: 1 }) // Serialization const json = Obj({ x: 1 }).serialize().toJSON(); Obj.fromJSON<{ x: number }>(json); ``` ## Method Chaining All operations return new Obj instances, enabling fluent chains: ```typescript const result = Obj({ a: 1, b: 2, c: 3 }) .set("a", 10) .assign({ b: 20 }) .omit("c") .value(); // { a: 10, b: 20 } ``` ## Companion Methods | Method | Description | | ------------------------ | -------------------------------- | | `Obj(data)` | Create from plain object | | `Obj.of(data)` | Create from plain object (alias) | | `Obj.empty()` | Create empty Obj | | `Obj.fromJSON(json)` | Deserialize from JSON | | `Obj.fromBinary(binary)` | Deserialize from base64 | ──────────────────────────────────────────────────────────────────────────────── ## io ──────────────────────────────────────────────────────────────────────────────── # IO Lazy, composable effects with typed errors and dependency injection. ## Overview IO represents a lazy effect that: - Requires environment `R` (dependencies) - May fail with error `E` (typed errors) - Produces value `A` on success Nothing runs until explicitly executed. ## Basic Usage ```typescript import { IO } from "functype/io"; // Synchronous effect const sync = IO.sync(() => 42); // Async effect const async = IO.async(async () => fetchData()); // Effect that may fail const safe = IO.tryCatch( () => JSON.parse(input) as unknown, (e) => new Error(`Invalid JSON: ${String(e)}`), ); // Running effects const either = await sync.run(); // Either - Left is a typed error; a defect or interruption rejects const value = await sync.runOrThrow(); // A - throws on error const exit = await sync.runExit(); // Exit - full outcome (see below) // Synchronous execution const syncEither = sync.runSync(); // Either - throws a defect or interruption const syncValue = sync.runSyncOrThrow(); // A - throws on error ``` ## Constructors | Method | Description | | ------------------------------------- | ----------------------------------------------------- | | `IO.succeed(value)` | Effect that succeeds with value | | `IO.fail(error)` | Effect that fails with error | | `IO.sync(() => A)` | Wrap synchronous computation | | `IO.async(async () => A)` | Wrap async computation | | `IO.tryCatch(fn, onError)` | Catch exceptions as typed errors | | `IO.tryPromise({ try, catch })` | Convert a Promise to IO, mapping the rejection | | `IO.fromPromiseEither(fn, onReject?)` | Lift `() => Promise>`, keeping `E` typed | | `IO.unit` | Effect that succeeds with void | | `IO.never()` | Effect that never completes until it is interrupted | | `IO.sleep(ms)` | Wait `ms`; an interruption ends the wait at once | ## Transformations ```typescript // Map over success value io.map((x) => x * 2); // Chain effects io.flatMap((x) => IO.succeed(x + 1)); // Handle errors io.mapError((e) => new WrappedError(e)); io.catchAll((e) => IO.succeed(fallback)); io.recover(defaultValue); // Provide fallback io.catchAll(() => fallbackIO); ``` ## Combining Effects ```typescript // All at once by default; all must succeed, and the first failure interrupts the rest IO.all([io1, io2, io3]); IO.all([io1, io2, io3], { concurrency: 2 }); // Up to 2 at once IO.all([io1, io2, io3], { concurrency: 1 }); // One after another; stops at the first failure IO.forEach(items, (item) => save(item)); // One effect per item, in order IO.forEach(items, (item) => save(item), { concurrency: "unbounded" }); IO.race([io1, io2]); // First to settle wins, success or failure; the others are interrupted IO.firstSuccessOf([io1, io2, io3]); // First success wins, trying them in order // Zip effects io1.zip(io2); // [A, B] io1.zip(io2).map(([a, b]) => a + b); // combine both results // Sequential io1.zipRight(io2); // Run io2 after io1, keep io2's result ``` ## Dependency Injection IO has built-in dependency injection using Tags, Contexts, and Layers. ```typescript import { IO, Tag, Context } from "functype/io"; // Define service interface interface Logger { log(message: string): void; } // Create a Tag for the service const Logger = Tag("Logger"); // Use the service const program = IO.service(Logger).flatMap((logger) => IO.sync(() => logger.log("Hello!")), ); // Provide implementation const result = await program .provideService(Logger, { log: console.log }) .runOrThrow(); ``` ### Context and Layer ```typescript // Build context with multiple services const context = Context.empty() .add(Logger, consoleLogger) .add(Config, appConfig); // Provide full context program.provideContext(context); // Use Layer for complex dependency graphs const AppLayer = Layer.succeed(Logger, consoleLogger).merge( Layer.succeed(Config, appConfig), ); program.provideLayer(AppLayer); ``` ## Do-Notation ### Generator Syntax (IO.gen) ```typescript const program = IO.gen(function* () { const a = yield* IO.succeed(1); const b = yield* IO.succeed(2); const c = yield* IO.succeed(3); return a + b + c; }); await program.runOrThrow(); // 6 ``` ### Builder Syntax (IO.Do) ```typescript const program = IO.Do.bind("user", () => getUser("123")) .bind("posts", ({ user }) => getPosts(user.id)) .let("count", ({ posts }) => posts.length) .map(({ user, posts, count }) => ({ user, posts, count })); ``` ## Resource Management ```typescript // Bracket pattern: acquire, use, release IO.bracket( IO.sync(() => openFile(path)), // acquire (file) => IO.sync(() => file.read()), // use (file) => IO.sync(() => file.close()), // release ); // Acquire/Release: same arguments, more descriptive name IO.acquireRelease( IO.sync(() => openConnection()), (conn) => IO.sync(() => conn.query(sql)), (conn) => IO.sync(() => conn.close()), ); ``` ## Cancellation `interruptOn(signal)` stops a running effect when an `AbortSignal` fires, such as the one React Query or a request handler provides. No further step starts, so a cancelled poll stops polling. The result is `Left(InterruptedError)`. ```typescript const poll = checkStatus.repeatUntil((s) => s.done, { max: 60, delayMs: 500 }); const outcome = await poll.interruptOn(signal).run(); // Left(InterruptedError) if aborted // Handle it outside the cancelled section poll .interruptOn(signal) .catchTag("InterruptedError", () => IO.succeed(lastKnown)); // Or start it with a handle const { result, cancel } = loadReport.runCancellable(); // An async thunk receives the run's signal, so a request stops too const load = IO.async((signal) => fetch(url, { signal }).then((r) => r.json())); ``` - Inside the cancelled section, `retry`, `recover` and `catchAll` can't swallow the cancellation. - `bracket` / `acquireRelease` cleanup still runs, to completion. - `IO.sleep`, `IO.never`, `.delay` and the waits in `retryWithDelay` / `repeatUntil` wake at once. - A promise already in flight can't be stopped. The cancellation is seen at the next step, so if that promise was the last step, the effect succeeds with its result. Pass the same signal to `Http` or `IO.tryAsync` so the request itself aborts. - `race`, `timeout` and a parallel `IO.all` interrupt the effects they no longer need, in the same way. They return at once; an effect that ignores its signal may still be running, and its `bracket` release runs when it settles. `race` returns the first effect to settle, even a failure; in ZIO and Effect it is the first to succeed. - When `E` is `unknown` (effects from `IO.async`), use `InterruptedError.is(e)`. ## Tracing `withSpan(name, attributes?)` runs an effect in a span. A `withSpan` inside it nests under it, without being passed a parent. functype ships only the contract, `SpanTracer`, and no tracer. With none provided, `withSpan` does nothing: same result, nothing recorded. ```typescript import { IO, SpanTracer } from "functype"; const loadUser = (id: string) => IO.succeed({ id }).withSpan("loadUser", { "user.id": id }); const checkout = IO.all([loadUser("a"), loadUser("b")]).withSpan("checkout"); // A tracer that only times its spans. Provide it outside the spans. const timing: SpanTracer<{ readonly name: string; readonly started: number }> = { start: (name) => ({ name, started: Date.now() }), run: (_span, fn) => fn(), end: (span, exit) => console.log( `${span.name}: ${exit._tag} in ${Date.now() - span.started} ms`, ), }; await checkout.provideService(SpanTracer, timing).run(); ``` For each `withSpan`, the interpreter calls the tracer's three methods: - `start(name, attributes, parent)` opens a span. `parent` is the enclosing span in this run, or `undefined` at the top. - `run(span, fn)` runs `fn` with the span active. The whole body runs inside it, so a log sink there can read the trace IDs, even after an `await`. - `end(span, exit)` closes the span once, with the body's `Exit`: `Success`, `Failure`, `Die` or `Interrupted`. ### An OpenTelemetry bridge functype has no OpenTelemetry dependency and ships no bridge. This sketch, with `@opentelemetry/api`, is the whole of one: ```ts ignore import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api"; import { SpanTracer } from "functype"; const otel = trace.getTracer("my-app"); export const otelTracer: SpanTracer = { // With no parent, nest under whatever span is active already, such as an HTTP server's start: (name, attributes, parent) => otel.startSpan( name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active(), ), // context.with makes the span active, so trace.getActiveSpan() finds it inside withSpan run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn), end: (span, exit) => { if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR }); span.end(); }, }; await program.provideService(SpanTracer, otelTracer).run(); ``` - Every outcome closes the span once. A `race` loser or a timed-out effect closes when it settles, which may be after `race` or `timeout` has returned. A failure that arrives after the run was cancelled, such as an aborted `fetch`, closes as `Interrupted`. A loser that ignores the signal closes with its own outcome, such as `Success`, and one that never settles never closes its span. - A span outside `interruptOn(signal)` sees its `InterruptedError` as a typed `Failure`, as the code after it does. - Parallel children of `IO.all` and `race` each nest under the enclosing span and see only their own. Two runs at once never share a span: the current span travels with the run, not in the shared services. - Provide the tracer outside the spans. In `io.withSpan("a").provideService(SpanTracer, t).withSpan("b")`, only `a` is recorded. - It works under `runSync` too, because `run` is synchronous. - Provide it with `provideService(SpanTracer, t)` or `provideLayer(Layer.succeed(SpanTracer, t))`. `withSpan` reads the tracer without adding `SpanTracer` to the effect's requirements. - A separate run, such as a `.run()` inside a request handler, starts with no parent. The bridge above falls back to the active OpenTelemetry context then, so its spans still nest under the handler's. - A throw from the tracer itself becomes a `Die`. ## Outcomes: `Exit` `.run()` returns `Either`, which has exactly two branches: a success or an `E`. Anything else rejects the promise. `.runExit()` returns `Exit`, which names all four outcomes and never rejects: ```typescript const exit = await effect.runExit(); exit.isSuccess(); // completed with a value exit.isFailure(); // failed with a value from the declared E channel exit.isDie(); // produced a *defect* — a value that is not an E exit.isInterrupted(); // was cancelled // Each guard narrows to the field it names: if (exit.isSuccess()) exit.value; if (exit.isFailure()) exit.error; // an E if (exit.isDie()) exit.defect; // unknown if (exit.isInterrupted()) exit.fiberId; ``` A **defect** is what happens when something lands in the error channel that the declared type says cannot be there. `IO.sync` and `IO.die` are `IO` — `E` is `never` — so a throwing thunk, a throwing `map` / `flatMap` / `mapError` callback, and `IO.die` all produce values that are not `E`s: ```typescript await IO.fail(new AuthError()).runExit(); // Failure — an E await IO.sync(() => JSON.parse(bad)).runExit(); // Die — a SyntaxError, not an E await IO.die(new Error("bug")).runExit(); // Die ``` The line is the _declared_ channel, not whether something threw. `IO.async` and the `IO(...)` constructor are `IO`, so their rejections are legitimate errors and stay `Failure`. Defects remain **recoverable** — `recover`, `recoverWith`, `fold`, and `mapError` treat a `Die` exactly as they treat a `Failure`, and `mapError` over a defect produces a `Failure` because your mapper returns a real `E`. `Exit.Die` records what the outcome was when nothing recovered it; it does not change what recovery catches. ```typescript // Both handlers are optional and fall back to the failure branch exit.fold( (error) => `failed: ${error}`, (value) => `ok: ${value}`, (fiberId) => `cancelled: ${fiberId}`, (defect) => `bug: ${defect}`, ); exit.match({ Success: (value) => value, Failure: (error) => report(error), Interrupted: () => null, Die: (defect) => crash(defect), // omit to route defects to Failure }); ``` **Reach for `.runExit()` when the difference matters** — telling a real failure from a bug in your own code, or a cancellation from either, without a `try`. `.run()` is the right default when the `Left` is all you handle: its `Left` is always an `E`. A defect rejects the promise with the raw thrown value, and an interruption rejects it with an `InterruptedError`. `runSync()` follows the same rule: a typed failure is a `Left`, and a defect or an interruption is thrown. An effect it can't run synchronously (`IO.async`, `timeout`, `race`, `sleep`) is a defect, so it throws too. ## Error Handling Patterns ```typescript // Catch specific errors by their _tag taggedIO.catchTag("NotFound", () => IO.succeed(null)); // Fold over success/failure io.fold( (error) => `Failed: ${error}`, (value) => `Success: ${value}`, ); // Retry on failure io.retry(3); // any error, no delay io.retryWithDelay(3, 1000); // any error, fixed delay // Retry only when a predicate matches (1.3.0+) io.retryWhile({ n: 3, while: (e) => e._tag === "HttpStatusError" && e.status >= 500, delayMs: 250, }); // Exponential backoff with optional full jitter (1.3.0+) // Defaults: factor=2, maxMs=30_000, jitter=true, while=()=>true io.retryWithBackoff({ n: 5, baseMs: 250, while: (e) => e._tag === "NetworkError", }); // Value-driven repetition (1.6.0+): re-run until a predicate over the // *success value* is satisfied. Bounded by `max`; on exhaustion, fails // with RepeatExhausted (carrying the last observed value). Composes // with retry* — errors and values are independent axes. pollJob .retry(3) // error axis .repeatUntil((job) => job.done, { max: 20, delayMs: 500 }); // value axis // Symmetric sibling — continue while cont is true, stop when it flips. pollUntilReady.repeatWhile((r) => r.status === "pending", { max: 20 }); // Stateful effectful loop: thread state S through an effectful step // until done(state). done(seed) is checked *before* the first step. IO.iterate( 0, (n) => IO.sync(() => n + 1), (n) => n >= 10, ); // → IO, number> settling on 10 ``` ## Moving from Task functype 2.0 deleted `Task`. IO does what it did, except progress reporting and task names, which nothing used. | Task (1.x) | IO | | ------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | `Task(params).Sync(f, onError)` | `IO.tryCatch(f, onError).runSync()` → `Either` | | `await Task(params).Async(f, onError)` | `await IO.tryPromise({ try: f, catch: onError }).run()` → `Either` | | `Task.ok` / `Task.err`, `Task.success` / `Task.fail`, `Ok` / `Err` | `IO.succeed(v)` / `IO.fail(e)`, or `Right` / `Left` | | `TaskOutcome` | `Either` from `run()`, or `Exit` from `runExit()` | | `Task.fromEither` / `Task.fromTry` | `IO.fromEither` / `IO.fromTry` | | `Task.fromPromise(fn)` | `(...args) => IO.tryPromise({ try: () => fn(...args), catch })` | | `Task.toPromise(outcome)` | `effect.runOrThrow()` | | `Task.fromNodeCallback(fn)` | `IO.tryPromise` around `util.promisify(fn)` | | `Task.race(tasks, ms)` | `IO.race(effects).timeout(ms)` | | `Task.cancellable(fn)`, `CancellationToken` | `effect.runCancellable()`, `runExit({ signal })` or `interruptOn(signal)` | | `Task.getErrorChain` / `Task.formatErrorChain` | `getErrorChain` / `formatErrorChain`, exported from `functype` | | `Task.withProgress`, `AsyncWithProgress` | none: call your own callback inside the effect | | Task JSON (`"@functype": "Task"`), `Task.fromJSON` | none: `Serialization.deserialize` returns a `Failure` for the unknown marker | ```typescript const loadUser = (id: string) => IO.tryPromise({ // pass the run's signal to fetch, so cancelling stops the request itself try: (signal) => fetch(`/api/users/${id}`, { signal }).then( (r) => r.json() as Promise<{ name: string }>, ), catch: (error) => new Error(`Failed to load ${id}: ${String(error)}`), }); // Nothing runs until here const user = await loadUser("42").run(); // Either // Cancellable: a handle, or your own AbortController const { result, cancel } = loadUser("42").runCancellable(); const controller = new AbortController(); const exit = loadUser("42").runExit({ signal: controller.signal }); controller.abort(); // the Exit is Interrupted ``` ## When to Use IO - Applications with complex dependencies (web servers, CLI tools) - When you want errors tracked in the type system - Resource management with guaranteed cleanup - Building composable, testable programs - When you need dependency injection without mocking frameworks ## API Reference See full API documentation at functype API docs: [IO's methods](https://functype.org/api-docs/interfaces/IO.html) and [its constructors](https://functype.org/api-docs/variables/IO.html) (`IO.sync`, `IO.succeed`, `IO.tryPromise` and the rest) ──────────────────────────────────────────────────────────────────────────────── ## http ──────────────────────────────────────────────────────────────────────────────── # Http HTTP fetch wrapper returning `IO>` effects by default. Provide a `decode` decoder to get typed responses. ## Overview `Http` wraps the global `fetch` API with full IO integration: - Returns `IO>` by default — every request is a lazy, composable effect - **BYOV (Bring Your Own Validator)**: Pass `decode: Decoder` to get `HttpResponse`. `Decoder.fromThrowing` adapts any parser that throws, such as Zod's `parse` - Works with any validation library: Zod, TypeBox, Valibot, or manual validators - Three typed error variants: `NetworkError`, `HttpStatusError`, `DecodeError` - Zero dependencies — uses `globalThis.fetch` (browsers, Node 18+, Bun, Deno) - Auto content-type detection from response headers (JSON, text, raw) - Body serialization — objects are automatically JSON-serialized with `Content-Type: application/json`. Pass `encode: Encoder` to control the wire shape yourself - Configurable clients with base URLs and default headers Nothing runs until you call `.run()` or `.runOrThrow()`. ## Basic Usage ```typescript import { Decoder } from "functype/decoder"; import { Http } from "functype/fetch"; // Without validator — data is unknown const effect = Http.get("/api/users/1"); const result = await effect.run(); // Either> // With a decoder — T inferred from the parser's return type const typedEffect = Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); const typedResult = await typedEffect.run(); // Either> // POST with body — auto-serialized as JSON const create = Http.post("/api/users", { body: { name: "Alice", email: "alice@example.com" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); // PUT, PATCH, DELETE Http.put("/api/users/1", { body: { name: "Alice Updated" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); Http.patch("/api/users/1", { body: { name: "Alice" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); Http.delete("/api/users/1"); // HEAD and OPTIONS (return HttpResponse) Http.head("/api/users"); Http.options("/api/users"); // Low-level request with full control Http.request({ url: "/api/users/1", method: "GET", headers: { "X-Request-Id": "abc123" }, decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); ``` ## Validation Without `decode`, response data is `unknown`. This is intentional — it prevents unsafe type casts and encourages runtime validation. ```typescript // Without decode — data is unknown, you must narrow it yourself const effect = Http.get("/api/users"); // effect: IO> // With decode — T is inferred from the decoder's type const typedEffect = Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }); // typedEffect: IO> ``` ### Using Different Validators ```typescript // Zod Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }); // TypeBox Http.get("/api/users", { decode: Decoder.fromThrowing((data) => Value.Decode(UserSchema, data)), }); // Valibot Http.get("/api/users", { decode: Decoder.fromThrowing((data) => parse(UserSchema, data)), }); // functype's own decoders, no library Http.get("/api/users", { decode: Decoder.array(UserDecoder) }); // Manual validation Http.get("/api/users", { decode: Decoder.fromThrowing((data) => { if (!Array.isArray(data)) throw new Error("Expected array"); return data as User[]; }), }); ``` ## Request bodies Object bodies are JSON-serialized. By default (`flatten: true`) functype containers are stripped to plain JSON first: `Option` becomes the value or `null`, `List` an array, `Map` a record. `flatten: false` sends each container's tagged `{_tag, value}` form instead, for a functype service that decodes it with `Decoder.tagged.*`. ### Custom wire shape with `encode` When neither fits, such as snake_case keys or a date-only string, pass an `Encoder`. It is the request-side counterpart of `Decoder`: any `(value: A) => JSONValue` function. When `encode` is set, its output goes on the wire as is and `flatten` is ignored. ```typescript import { type Encoder, Http } from "functype"; type NewUser = { name: string; createdAt: Date }; const encodeNewUser: Encoder = (u) => ({ user_name: u.name, created_at: u.createdAt.toISOString().slice(0, 10), }); Http.post("/api/users", { body: newUser, encode: encodeNewUser }); ``` `TReq` is inferred from `encode`. If you pass the response type explicitly, pass the request type too: `Http.post(…)`. TypeScript defaults any type argument you leave out to `unknown`, and an `Encoder` doesn't fit `Encoder`. If `encode` throws, the request fails with `HttpError.NetworkError` and `fetch` is never called. ## HttpResponse\ Every successful request resolves to `HttpResponse` (where `T` is `unknown` without a validator): ```typescript type HttpResponse = { readonly data: T; // Parsed response body (unknown without decode) readonly status: number; // HTTP status code (e.g. 200) readonly statusText: string; // HTTP status text (e.g. "OK") readonly headers: Headers; // Response headers (standard Web API) }; // Accessing response fields with a validator const effect = Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }); const either = await effect.run(); if (either._tag === "Right") { const { data, status, headers } = either.value; console.log(status); // 200 console.log(data[0]?.name); // "Alice" — data is User[], not unknown console.log(headers.get("x-total-count")); } ``` ## Error Handling All HTTP errors are typed as `HttpError`, a union of three variants: ```typescript import type { HttpMethod } from "functype/fetch"; type NetworkError = { _tag: "NetworkError"; url: string; method: HttpMethod; cause: unknown; // The underlying fetch error }; type HttpStatusError = { _tag: "HttpStatusError"; url: string; method: HttpMethod; status: number; // e.g. 404, 500 statusText: string; body: string; // Raw response body text }; type DecodeError = { _tag: "DecodeError"; url: string; method: HttpMethod; body: string; // The text that failed to parse cause: unknown; }; ``` ### Pattern Matching with HttpError.match ```typescript import { Decoder } from "functype/decoder"; import { Http, HttpError } from "functype/fetch"; const effect = Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); const result = await effect .mapError((err) => HttpError.match(err, { NetworkError: (e) => `Network failure: ${String(e.cause)}`, HttpStatusError: (e) => `HTTP ${e.status}: ${e.statusText}`, DecodeError: (e) => `Parse failed: ${e.body}`, }), ) .run(); ``` ### Catching Specific Error Tags ```typescript // Recover from 404 with a default value const user = Http.get("/api/users/99", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }).catchTag("HttpStatusError", (e) => e.status === 404 ? IO.succeed({ data: null, status: 404, statusText: "Not Found", headers: new Headers(), }) : IO.fail(e), ); // Handle network errors separately const resilient = Http.get("/api/data").catchTag("NetworkError", () => Http.get("/api/data/fallback"), ); ``` ### Type Guards ```typescript import { Decoder } from "functype/decoder"; import { Http, HttpError } from "functype/fetch"; const either = await Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }).run(); if (either._tag === "Left") { const err = either.value; if (HttpError.isHttpStatusError(err)) { console.log(err.status, err.body); // typed as HttpStatusError } else if (HttpError.isNetworkError(err)) { console.log(err.cause); // typed as NetworkError } else if (HttpError.isDecodeError(err)) { console.log(err.body); // typed as DecodeError } } ``` ## Http.client() Create a configured client with a base URL, default headers, or a custom fetch implementation: ```typescript import { Decoder } from "functype/decoder"; import { Http } from "functype/fetch"; const api = Http.client({ baseUrl: "https://api.example.com/v1", defaultHeaders: { Authorization: `Bearer ${token}`, "X-App-Version": "2.0.0", }, }); // Paths are resolved relative to baseUrl const users = api.get("/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }); // → https://api.example.com/v1/users const user = api.get("/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }); // → https://api.example.com/v1/users/1 // Absolute URLs bypass baseUrl const ext = api.get("https://other.com/data"); // → https://other.com/data (data is unknown) // Custom fetch for testing or proxying const testApi = Http.client({ baseUrl: "http://localhost:3000", fetch: myMockFetch, }); ``` ### HttpClientConfig ```typescript import type { IO } from "functype"; import type { HttpError, HttpRequestView, HttpResponse } from "functype/fetch"; interface HttpClientConfig { readonly baseUrl?: string; // Base URL prepended to relative paths readonly defaultHeaders?: Record; // Merged with per-request headers readonly fetch?: typeof globalThis.fetch; // Override the fetch implementation readonly beforeRequest?: ( request: HttpRequestView, ) => IO; // Effectful request transformer readonly afterResponse?: ( response: HttpResponse, ) => IO>; // Success-path response transformer } ``` Per-request headers always override `defaultHeaders` when keys conflict. ## Request-side composition with `beforeRequest` The response side of an `Http` call composes on the returned `IO` — `.tap`, `.map`, `.flatMap`, `.catchTag`, `.mapError`, `.retry`, `.timeout`. The request side gets the same treatment via `beforeRequest`: an effectful transformer that runs after `defaultHeaders` and per-call headers are merged, but before the request is sent. It receives the assembled `HttpRequestView` and returns an `IO`, so concerns stack via standard IO operators. ```typescript import { Decoder } from "functype/decoder"; import { Http, HttpError, type HttpRequestView } from "functype/fetch"; import { IO } from "functype"; // Each concern is a small function; sync ones use plain returns, // effectful ones return an IO. const addRequestId = (r: HttpRequestView): HttpRequestView => ({ ...r, headers: { ...r.headers, "x-request-id": crypto.randomUUID() }, }); const addBearer = (getToken: () => Promise) => (r: HttpRequestView): IO => IO.tryPromise({ try: () => getToken(), catch: (e) => HttpError.networkError(r.url, r.method, e), }).map((token) => ({ ...r, headers: { ...r.headers, Authorization: `Bearer ${token}` }, })); const api = Http.client({ baseUrl: "https://api.example.com", defaultHeaders: { "x-app": "my-app" }, beforeRequest: (r) => IO.succeed(r) .map(addRequestId) // sync header injection .flatMap(addBearer(getToken)) // async, can fail with HttpError .tap((req) => logger.info(req.method, req.url)), // side-effect }); // Every call through `api` runs the full transformer stack. const user = await api .get("/users/me", { decode: Decoder.fromThrowing((d) => UserSchema.parse(d)), }) .runOrThrow(); ``` Notes on the contract: - **Failure short-circuits.** Returning `IO.fail(httpError)` from `beforeRequest` aborts the call — `fetch` is never invoked and the error surfaces through the normal `.catchTag` / `.run*` paths. - **Headers passed in are already merged.** `r.headers` reflects `defaultHeaders` + per-call `headers` — `beforeRequest` is the final word. - **Body is raw at hook time.** `r.body` is the pre-serialization value. Content-Type is derived after the hook runs, so swapping `body` for a different shape produces the correct content-type header. - **`decode` lives on the response side.** `HttpRequestView` deliberately omits it; the hook can't change response decoding. - **Compose vs. replace.** This is additive to `fetch` override — they can coexist if you have a reason. For request-decoration use cases (auth, request IDs, logging), `beforeRequest` is the lighter touch and gives you typed `HttpRequestOptions` instead of raw `(input, init)`. ## Response-side composition with `afterResponse` Symmetric with `beforeRequest`, the `afterResponse` hook runs after the response is parsed (and the decoder, if any, succeeds) and before the IO resolves to the caller. Use it for ETag capture, response logging, metrics, or header transformations. ```typescript const api = Http.client({ baseUrl: "https://api.example.com", afterResponse: (response) => IO.succeed(response) .tap((r) => logger.info("response", { status: r.status })) .map((r) => ({ ...r, headers: redactSensitiveHeaders(r.headers) })), }); ``` The contract differs from `beforeRequest` in one important way: **`afterResponse` only runs on the success path.** Errors — `HttpStatusError` (non-2xx), `DecodeError` (validation failure), `NetworkError` (fetch / abort) — skip the hook entirely. This keeps observability and recovery separate: response transforms live in `afterResponse`; error logging and recovery live in `.catchTag(...)` / `.tapError(...)` chains at the call site. ### Production retry policy Pair `retryWithBackoff` with the `HttpError` tagged ADT for a sane production retry policy — retry network blips and server errors, never retry validation errors or 4xx: ```typescript import { Http, type HttpError } from "functype/fetch"; const isRetryable = (e: HttpError): boolean => e._tag === "NetworkError" || (e._tag === "HttpStatusError" && (e.status >= 500 || e.status === 429)); const result = await Http.get("/api/users", { decode: usersDecoder }) .retryWithBackoff({ n: 3, baseMs: 250, while: isRetryable }) .timeout(10_000) .runOrThrow(); ``` `retryWithBackoff` schedules `min(maxMs, baseMs * factor^(attempt-1))` and applies full jitter (50–100% of the computed delay) by default — prevents thundering herd. `retryWhile` is the simpler sibling for fixed-delay (or no-delay) selective retry. ### Refresh-on-401 pattern Refresh-on-401 is **not** an `afterResponse` pattern — it's a `.catchTag` pattern, because a 401 is an error, not a successful response: ```typescript const api = Http.client({ baseUrl: "https://api.example.com", beforeRequest: addBearer, }); const me = await api .get("/me", { decode: userDecoder }) .catchTag("HttpStatusError", (e) => e.status === 401 ? refreshToken().flatMap(() => api.get("/me", { decode: userDecoder })) : IO.fail(e), ) .runOrThrow(); ``` ### Query parameters Pass `params` to any method (or to `Http.request`) — values are properly percent-encoded, arrays repeat the key, and `undefined` / `null` are dropped: ```typescript await api .get("/search", { params: { q: "a b&c", // → q=a+b%26c tag: ["x", "y"], // → tag=x&tag=y page: 2, // → page=2 cursor: maybeCursor.orNull(), // null is dropped if None }, }) .runOrThrow(); ``` If the URL already has a query string, params are merged (existing keys preserved; new keys appended). ## Content-Type Detection Response bodies are parsed based on the `Content-Type` response header: | Content-Type | Parse Mode | Result type | | ------------------------ | ---------- | ----------------- | | `application/json` | `json` | Parsed JS object | | `text/*` (any text type) | `text` | `string` | | Anything else | `raw` | `Response` object | Override auto-detection with the `parseAs` option: ```typescript type ParseMode = "json" | "text" | "blob" | "arrayBuffer" | "raw"; // Force JSON parsing regardless of Content-Type header Http.get("/api/config", { parseAs: "json", decode: Decoder.fromThrowing((data) => ConfigSchema.parse(data)), }); // Get raw Blob for file downloads Http.get("/api/export/report.pdf", { parseAs: "blob" }); // Get ArrayBuffer for binary data Http.get("/api/binary", { parseAs: "arrayBuffer" }); // Get the raw Response object Http.get("/api/stream", { parseAs: "raw" }); ``` ## IO Composition Because `Http` returns `IO` effects, the full IO operator set is available: ```typescript import { Decoder } from "functype/decoder"; import { Http } from "functype/fetch"; // Retry on failure Http.get("/api/data").retry(3); // Retry with delay between attempts (ms) Http.get("/api/data").retryWithDelay(3, 1000); // Timeout after N milliseconds Http.get("/api/data").timeout(5000); // Transform the response data (with validator for typed access) Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }).map((res) => res.data.name); // Chain requests — use result of first to drive second Http.get("/api/users/1", { decode: Decoder.fromThrowing((data) => UserSchema.parse(data)), }).flatMap((res) => Http.get(`/api/users/${res.data.id}/posts`, { decode: Decoder.fromThrowing((data) => z.array(PostSchema).parse(data)), }), ); // Both requests, one after the other; each result keeps its own type const [users, posts] = await Http.get("/api/users", { decode: Decoder.fromThrowing((data) => z.array(UserSchema).parse(data)), }) .zip( Http.get("/api/posts", { decode: Decoder.fromThrowing((data) => z.array(PostSchema).parse(data)), }), ) .runOrThrow(); // [HttpResponse, HttpResponse] // IO.all([...], { concurrency }) runs a list of same-typed requests, up to n at once // Map over errors Http.get("/api/data").mapError((err) => new AppError(err)); ``` ## Body Serialization Request bodies are serialized based on their JavaScript type: | Body value | Serialized as | Content-Type header added | | -------------------- | -------------------- | ----------------------------- | | `undefined` / `null` | No body sent | None | | `string` | Passed through as-is | None (set manually if needed) | | Object or Array | `JSON.stringify()` | `application/json` | | Other primitives | `String(value)` | None | ```typescript // Object body → JSON serialized automatically Http.post("/api/orders", { body: { productId: 42, quantity: 3 }, decode: Decoder.fromThrowing((data) => OrderSchema.parse(data)), // Content-Type: application/json is added automatically }); // String body → sent as-is, no Content-Type added Http.post("/api/graphql", { body: '{"query":"{ users { id name } }"}', headers: { "Content-Type": "application/json" }, decode: Decoder.fromThrowing((data) => GraphQLResultSchema.parse(data)), }); // FormData or URLSearchParams — pass as string or handle manually Http.post("/api/form", { body: new URLSearchParams({ key: "value" }).toString(), headers: { "Content-Type": "application/x-www-form-urlencoded" }, }); ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/variables/Http.html) ──────────────────────────────────────────────────────────────────────────────── ## logger ──────────────────────────────────────────────────────────────────────────────── # Logger A minimal, ecosystem-wide logging interface. Type-only — zero runtime, no `console` dependency, no opinion on output format. Every present and future `functype-*` package targets this shape, so a consumer writes ONE logger adapter and it works everywhere. ## Overview ```typescript export interface Logger { debug(message: string, metadata?: Record): void; info(message: string, metadata?: Record): void; warn(message: string, metadata?: Record): void; error(message: string, metadata?: Record): void; } ``` Four methods, all mandatory. No `trace`/`fatal`/`child`/`withContext` in the core shape — richer loggers (like `DirectLogger` from `functype-log`) add those on top and remain structurally assignable. ## Import `Logger` is reachable from both the top barrel and the `functype/logger` subpath: ```typescript import type { Logger } from "functype"; ``` or ```typescript import type { Logger } from "functype/logger"; ``` If your application already has its own `Logger` type, rename on import: ```typescript import type { Logger as FunctypeLogger } from "functype"; ``` ## Why it lives in core Logger was the first service-style interface in `functype` core — and only because every production TypeScript app already has one. The proposal explicitly **rejected** adding `Clock` or `Random` (framework abstractions Effect ships) on the same grounds: those aren't universally needed the way logging is. `Tracer` was later added on exactly the same terms: type-only, one method, no Tag and no default implementation in core, consumed by `TracedOption`. The test is not "is this a service?" but "does this name a concept the caller already has, without shipping a runtime?" The proposal also rejected baking in a default implementation. Concrete loggers live in consumer packages (`consoleBootLogger` in `functype-os/config`, `DirectLogger` in `functype-log`). Core stays pure types — Bun/Deno/edge-runtime portability comes for free. ## Implementing it Any 4-method object with the right signatures satisfies `Logger`: ```typescript import type { Logger } from "functype"; const myLogger: Logger = { debug: (msg, meta) => console.debug(msg, meta ?? ""), info: (msg, meta) => console.log(msg, meta ?? ""), warn: (msg, meta) => console.warn(msg, meta ?? ""), error: (msg, meta) => console.error(msg, meta ?? ""), }; ``` ## Interop with `functype-log` `functype-log/direct` exposes `DirectLogger` — a sync/imperative logger with `debug`/`info`/`warn`/`error(msg, meta?): void` methods plus extras (`trace`, `fatal`, `withError`, `withContext`, `child`). Its surface is a structural **superset** of core `Logger`, so it assigns directly with no adapter: ```typescript import type { Logger } from "functype"; import { createDirectConsoleLogger } from "functype-log/direct"; const logger: Logger = createDirectConsoleLogger(); // no cast required ``` This lets you wire `functype-log` into any hook expecting a core `Logger` — including `bootDiagnostics` from `functype-os/config`: ```typescript import { bootDiagnostics, Layered, ProcessEnvSource } from "functype-os/config"; import { createDirectConsoleLogger } from "functype-log/direct"; bootDiagnostics({ source: Layered([ProcessEnvSource()]), required: ["DATABASE_URL"], logger: createDirectConsoleLogger(), }); ``` > Note: the IO-shaped `Logger` (the primary export of `functype-log`) does NOT structurally satisfy core `Logger` — its methods return `IO` instead of `void`. Use `toDirectLogger(ioLogger)` to bridge from one to the other when you need to mix IO-aware code with imperative consumers. ## When to use - Authoring a `functype-*` ecosystem package or any library that wants to log without picking a logging stack. - Wiring `bootDiagnostics` for application startup with a custom logger. - Library authors targeting "drop-in any logger" composition without a logging-library peer dependency. ## When NOT to use - If your app already uses `functype-log` directly and you want full `IO` composition with `.tap`/`.flatMap` — use `functype-log`'s `Logger` (IO-shaped) directly, not the core type. - If you need structured `child(context)` propagation or per-call context binding — those are richer-logger concerns; pick `functype-log` or wrap your own. ──────────────────────────────────────────────────────────────────────────────── ## wire ──────────────────────────────────────────────────────────────────────────────── # Wire A serialization-boundary marker for values crossing DB rows, HTTP bodies, JSONB payloads and workflow inputs. It wraps any boundary shape: a collection, a nullable field, or a whole row type. Zero runtime cost, assignable both ways with the plain type, no casts at call sites. ## Overview ```typescript declare const WIRE: unique symbol; export interface WireMark { readonly [WIRE]?: never; } export type Wire = T | (T & WireMark); ``` Wire is a **flavored** type, not a branded one. The plain `T` member means `Wire` and `T` accept each other without ceremony, including `null`, `undefined` and `unknown`, so generic helpers like `findOne(): Promise>` compile. `null` is exactly the shape that survives `JSON.stringify`. The `T & WireMark` member is there for naming, not safety. It keeps TypeScript from resolving the alias away, so inferred exports emit `Wire` in `.d.ts` files and hovers. The value doesn't come from type-level enforcement. It comes from three places: - **Grep-ability.** `rg 'Wire<'` is a complete, countable inventory of every serialization boundary in the codebase. - **Intent at the declaration site.** `type UserRow = Wire<{ … }>` states the boundary in exactly one place. - **ESLint pairing.** `functype/prefer-list` and `functype/prefer-option` skip everything inside a `Wire<…>` type argument. A `ReadonlyArray` or a `T | null` there is the declared wire shape, not a missed `List` or `Option`. ## Import ```typescript import type { Wire } from "functype"; ``` or ```typescript import type { Wire } from "functype/wire"; ``` ## The three shapes ```typescript import type { Wire } from "functype"; // A whole row or DTO: every field inside is covered. type UserRow = Wire<{ readonly id: string; readonly email: string | null; readonly tags: ReadonlyArray; }>; // A collection. type UserRows = Wire>; // A single field on an otherwise domain-shaped type. type Invite = { readonly id: InviteId; readonly acceptedAt: Wire; }; ``` ## The boundary recipe ```jsonc // eslint.config.mjs — hold the enforcement, mark the boundaries { "functype/prefer-list": ["error", { "allowReadonlyArrays": false }], "functype/prefer-option": "warn", // "error" once your boundary types are wired } ``` ```typescript // Declare the boundary once. async function fetchUsers(): Promise { return db.query("SELECT * FROM users").rows; } // Inside the pipeline, convert to List and Option for transformation. const reachable = List(await fetchUsers()) .filter((u) => Option(u.email).isSome()) .map(enrich); ``` ## Rule options Both rules take `wireTypes` (default `["Wire"]`). Add your own boundary alias name if you have one, or pass `[]` to turn the exemption off. Qualified references (`functype.Wire<…>`) are recognized. ## Migrating from 1.9 In 1.9, `Wire` meant `ReadonlyArray`. In 1.10 it wraps any shape, so: ```typescript import type { Wire } from "functype"; // 1.9 wrote this as Wire, which meant an array of Row type ClaimedDocs = Wire>; // 1.10+ ``` The break is loud, not silent: a `Wire` that meant an array fails to compile at the first `.map` or array assignment. The two exceptions are `Wire` and `Wire`, which accept an array under either meaning; search for them when upgrading. ## When to use - Types for DB rows, HTTP request and response bodies, JSONB payloads, queue and workflow inputs. - Function signatures that return or accept those shapes at the edge of the system. ## When NOT to use - Values you're about to transform. Convert to `List` / `Option` first. - Function-local variables that never cross a boundary. ## Wire or Option? Ask who reads the absence. - **Use `Option` when your own code reads it.** You branch on it, map it, or return it to code that does. - **Use `Wire` when something outside your code reads it, or when the absence is part of the format.** That reader is a serializer, a driver, a schema library or a host API. - **Convert once, at the edge.** The first function that receives a `Wire` value turns it into `Option` if later code decides anything from it. ### Where Wire is the answer **Serialized shapes.** `Option` doesn't survive `JSON.stringify`, and drivers return `null`. ```typescript import type { Wire } from "functype"; type ChainRow = Wire<{ readonly id: string; readonly entity_id: string | null; readonly literal: string | null; }>; ``` **Three states: left out, cleared, set.** This is the case where `Option` is wrong, not just awkward. A patch body's field can be left out (keep the old value), sent as `null` (remove it) or sent with a value (replace it). `Option` has two states, so converting loses the difference. `prefer-option` says so when one union, as a type alias's body or a type-literal or interface member, holds both `null` and `undefined`, and when an optional member can also be `null` (`a?: T | null`). The message names both fixes, because a domain type written that way often only meant "may be absent". ```typescript import type { Wire } from "functype"; type Clearable = Wire; // undefined: keep, null: remove, T: replace const keep = (next: Wire, old: T): T => next === undefined ? old : next; ``` **Types inferred from a schema.** A type from `z.infer`, valibot or a decoder is the wire shape by definition. Wrap the alias, and convert a field to `Option` when code first decides something from it. ```typescript import type { Wire } from "functype"; type Given = Wire; // a tool input field that may be left out ``` **Helpers that pass a wire value through.** A row mapper that reads a nullable column and writes a nullable field decides nothing about the absence. An `Option` there only adds a conversion you undo. ```typescript import type { Wire } from "functype"; type Quantity = { readonly value: number; readonly unit: string }; const quantity = ( value: Wire, unit: Wire, ): Wire => value === null || unit === null ? null : { value, unit }; ``` **Props and options objects.** The caller writes ``, so these are host shapes. `prefer-option` skips `a?: T` and `a: T | undefined` on a member or parameter by default. ### Where Option stays the answer A function result that code goes on to read is an `Option`. The driver returns a row or `undefined`, the function converts it once, and callers `fold`. ```typescript import { Option } from "functype"; type Entity = { readonly name: string }; const findByName = ( entities: ReadonlyArray, name: string, ): Option => Option(entities.find((entity) => entity.name === name)); ``` ### Misuses - **`Wire` on a domain type just to quiet the rule.** Ask whether the value really crosses a boundary in this exact shape. - **`Option` inside a row or body type.** It serializes as an object and doesn't round-trip. - **A `Wire` value that keeps flowing** past the first function that decides something from it. ──────────────────────────────────────────────────────────────────────────────── ## do-notation ──────────────────────────────────────────────────────────────────────────────── # Do-Notation Scala-like for-comprehensions for composing monadic operations. ## Overview Do-notation provides generator-based monadic comprehensions inspired by Scala's for-comprehensions. It makes complex monadic chains readable and maintainable by eliminating nested flatMap calls. ## Basic Usage ```typescript import { Do, $ } from "functype/do"; import { Option } from "functype/option"; // Instead of nested flatMaps const nested = Option(1).flatMap((a) => Option(2).flatMap((b) => Option(3).map((c) => a + b + c)), ); // Use Do-notation const clean = Do(function* () { const a = yield* $(Option(1)); const b = yield* $(Option(2)); const c = yield* $(Option(3)); return a + b + c; }); // Some(6) ``` ## The $ Helper The `$` function enables TypeScript type inference with generators: ```typescript import { Do, $ } from "functype/do"; import { Option } from "functype/option"; const result = Do(function* () { const x = yield* $(Option(42)); // x is number, not unknown return x * 2; }); ``` ## Short-Circuiting Do-notation automatically propagates None/Left/Failure: ```typescript // Option - stops on None const result = Do(function* () { const a = yield* $(Option(1)); const b = yield* $(Option.none()); // stops here const c = yield* $(Option(3)); return a + b + c; }); // None // Either - stops on Left const validated = Do(function* () { const name = yield* $(validateName(input)); // Left stops chain const email = yield* $(validateEmail(input)); return { name, email }; }); ``` ## Supported Types Do-notation works with any monad in functype: ### Option ```typescript const result = Do(function* () { const user = yield* $(findUser(id)); const profile = yield* $(user.profile); const email = yield* $(profile.email); return email; }); // Option ``` ### Either ```typescript const result = Do(function* () { const name = yield* $(validateName(input.name)); const age = yield* $(validateAge(input.age)); const email = yield* $(validateEmail(input.email)); return { name, age, email }; }); // Either ``` ### Try ```typescript const result = Do(function* () { const config = yield* $(Try(() => readConfig())); const db = yield* $(Try(() => connectDB(config))); const users = yield* $(Try(() => db.query("SELECT * FROM users"))); return users; }); // Try ``` ### List (Cartesian Products) ```typescript const combinations = Do(function* () { const x = yield* $(List([1, 2, 3])); const y = yield* $(List(["a", "b"])); return `${x}${y}`; }); // List(["1a", "1b", "2a", "2b", "3a", "3b"]) ``` ## Async Do-Notation For async operations, use `DoAsync` and `await` each step's promise: ```typescript import { DoAsync, $ } from "functype/do"; // fetchUser and fetchPosts return Promise> const result = await DoAsync(async function* () { const user = yield* $(await fetchUser(id)); const posts = yield* $(await fetchPosts(user.id)); return { user, posts }; }); // Either: Right({ user, posts }), or the first Left ``` ## Performance Do-notation is highly optimized: - **Option/Either/Try**: Near-zero overhead - **List comprehensions**: 175x faster than nested flatMaps - Uses direct iteration instead of creating intermediate structures ## Key Features - **Scala-Inspired**: Similar syntax to Scala's for-comprehensions - **Type-Safe**: Full TypeScript inference with the $ helper - **Short-Circuiting**: None/Left/Failure automatically propagates - **High Performance**: Optimized for List comprehensions ## When to Use Do-Notation - Chaining 3+ monadic operations - List comprehensions (cartesian products) - Complex validation pipelines - When readability matters more than micro-optimization ## Comparison Without Do-notation: ```typescript const result = getUser(id).flatMap((user) => getProfile(user.profileId).flatMap((profile) => getSettings(profile.settingsId).map((settings) => ({ user, profile, settings, })), ), ); ``` With Do-notation: ```typescript const result = Do(function* () { const user = yield* $(getUser(id)); const profile = yield* $(getProfile(user.profileId)); const settings = yield* $(getSettings(profile.settingsId)); return { user, profile, settings }; }); ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/functions/Do.html) ──────────────────────────────────────────────────────────────────────────────── ## match ──────────────────────────────────────────────────────────────────────────────── # Match & Cond Powerful pattern matching and conditional expressions. ## Overview Match provides exhaustive pattern matching for Scala-style case expressions, while Cond offers functional conditional evaluation without early returns or if-else chains. ## Match ### Basic Usage ```typescript import { Match } from "functype/conditional"; const result = Match(statusCode) .case(200, () => "OK") .case(404, () => "Not Found") .case(500, () => "Server Error") .default(() => "Unknown"); ``` ### Pattern Matching on Types ```typescript const describe = Match(value) .case( (v): v is string => typeof v === "string", (s) => `String: ${s}`, ) .case( (v): v is number => typeof v === "number", (n) => `Number: ${n}`, ) .case( (v): v is boolean => typeof v === "boolean", (b) => `Boolean: ${b}`, ) .default(() => "Unknown type"); ``` ### With Functype Types Option, Either, Try, and other types have built-in match methods: ```typescript // Option match const greeting = Option(name).match({ Some: (n) => `Hello, ${n}!`, None: () => "Hello, stranger!", }); // Either match const message = result.match({ Left: (error) => `Error: ${error}`, Right: (value) => `Success: ${value}`, }); // Try match const output = tryValue.match({ Success: (v) => `Got: ${v}`, Failure: (e) => `Failed: ${e.message}`, }); ``` ## Cond Cond provides conditional expressions without early returns: ### Basic Usage ```typescript import { Cond } from "functype/conditional"; const grade = Cond() .when(score >= 90, () => "A") .when(score >= 80, () => "B") .when(score >= 70, () => "C") .when(score >= 60, () => "D") .else(() => "F"); ``` ### With Predicates ```typescript const category = Cond() .when(age < 13, () => "child") .when(age < 20, () => "teenager") .when(age < 65, () => "adult") .else(() => "senior"); ``` ### Lazy Evaluation Cond evaluates lazily - only the matching branch runs: ```typescript const result = Cond() .when(true, () => 1) // This runs .when(true, () => expensiveCompute()) // This doesn't run .else(() => 0); ``` ## Match vs Cond | Feature | Match | Cond | | -------- | ----------------------------- | --------------------------- | | Input | Single value to match against | No input, checks conditions | | Use Case | Value-based branching | Predicate-based branching | | Pattern | `Match(value).case(...)` | `Cond().when(...)` | ### When to Use Match ```typescript // Matching on specific values Match(httpMethod) .case("GET", () => handleGet()) .case("POST", () => handlePost()) .case("PUT", () => handlePut()) .default(() => handleOther()); // Matching on discriminated unions Match(action.type) .case("INCREMENT", () => state + 1) .case("DECREMENT", () => state - 1) .case("RESET", () => 0) .default(() => state); ``` ### When to Use Cond ```typescript // Complex conditional logic const shipping = Cond() .when(order.total > 100, () => 0) .when(order.isPrime, () => 0) .when(order.isLocal, () => 5) .else(() => 10); // Replacing if-else chains const message = Cond() .when(errors.length > 0, () => `${errors.length} errors found`) .when(warnings.length > 0, () => `${warnings.length} warnings`) .else(() => "All good!"); ``` ## Key Features - **Exhaustive Matching**: Type-safe pattern matching with default case enforcement - **No Early Returns**: Functional style without breaking out of expressions - **Type Inference**: Full TypeScript type inference for all branches - **Composable**: Chain multiple conditions and patterns together ## When to Use Match & Cond - Complex conditional logic with multiple cases (status codes, state machines) - Avoiding if-else chains and early returns - Pattern matching on monadic types (Option, Either, Try) - Expression-based code where you need a value back ## Comparison with if-else Traditional if-else (imperative): ```typescript let result: string; if (status === 200) { result = "OK"; } else if (status === 404) { result = "Not Found"; } else { result = "Unknown"; } ``` Match (functional expression): ```typescript const result = Match(status) .case(200, () => "OK") .case(404, () => "Not Found") .default(() => "Unknown"); ``` ## API Reference See full API documentation at [functype API docs](https://functype.org/api-docs/types/Match.html) ──────────────────────────────────────────────────────────────────────────────── ## mcp-server ──────────────────────────────────────────────────────────────────────────────── # MCP Server Live documentation and code validation for any AI agent. ## Overview The functype MCP server gives AI coding assistants direct access to functype's documentation, type APIs, and a compile-time code validator. Instead of relying on training data that may be outdated, your AI tools get live, accurate information from the library itself. It works with any tool that supports the [Model Context Protocol](https://modelcontextprotocol.io/) — Claude Code, Cursor, Windsurf, and more. ## Setup Add the MCP server to your project's `.mcp.json`: ```json { "mcpServers": { "functype": { "command": "npx", "args": ["-y", "functype-mcp-server"] } } } ``` The server is installed automatically via npx — no global installation needed. ## Tools The MCP server provides 5 tools: ### search_docs Browse all functype types or search by keyword. Call with no arguments for a full overview of every type and its implemented interfaces. **Example output:** ``` Option [Functor, Monad, Foldable, Extractable, Matchable, Serializable, Traversable] Safe nullable handling - Some or None Either [Functor, Monad, Foldable, Traversable, PromiseLike] Error handling with Left (error) or Right (success) List [Functor, Monad, Foldable, Collection, Serializable, Traversable] Immutable array with functional operations ``` ### get_type_api Get detailed API reference for any type, organized by category: Create, Transform, Extract, Check. **Example** — `get_type_api("Option")`: ``` Option [Functor, Monad, Foldable, Extractable, Matchable, Serializable, Traversable] Create: Option(v), Option.none(), Some(v), None() Transform: .map(f), .flatMap(f), .filter(p), .ap(ff) Extract: .fold(n, s), .getOrElse(() => d), .orThrow(), .orNull(), .match({Some, None}) Check: .isSome(), .isNone(), .isEmpty ``` ### get_interfaces Get the full interface hierarchy — Functor, Monad, Foldable, Extractable, Matchable, and more — with their method signatures and inheritance relationships. **Example output:** ``` Functor .map(f: A => B): Functor Monad .flatMap(f: A => Monad): Monad Foldable .fold(empty: () => B, f: A => B): B Extractable .getOrElse(d: () => T): T Matchable .match(patterns): R ``` ### validate_code Type-check functype code snippets against the TypeScript compiler. Catches type errors before code is presented or committed. Supports auto-importing all functype types. **Example** — valid code: ```typescript const result = Option(42) .map((x) => x * 2) .flatMap((x) => (x > 50 ? Option(x) : Option.none())) .fold( () => "nothing", (x) => `got ${x}`, ); // Validation PASSED ``` **Example** — invalid code: ```typescript ignore const result = Option(42) .map((x) => x * 2) .getOrElse(0); // Validation FAILED — Line 3, Col 14: Argument of type 'number' is not assignable // to parameter of type '() => unknown'. (TS2345) ``` ### set_functype_version Switch the functype version at runtime. Installs the specified version and reloads all documentation and type definitions. Useful for working with projects pinned to older versions. **Example:** `set_functype_version("0.46.0")` ## Compatibility The functype MCP server works with any tool that supports the Model Context Protocol: | Tool | Status | | -------------- | --------- | | Claude Code | Supported | | Cursor | Supported | | Windsurf | Supported | | Any MCP client | Supported | ──────────────────────────────────────────────────────────────────────────────── ## ESLint Plugin ──────────────────────────────────────────────────────────────────────────────── # eslint-plugin-functype Custom ESLint rules for functional TypeScript with [functype](https://github.com/jordanburke/functype). Encourages idiomatic functype patterns like `Option`, `Either`, `List`, `Do` notation, and safe data access. ## Install ```bash npm install -D eslint-plugin-functype eslint ``` ## Usage ```js // eslint.config.mjs import functype from "eslint-plugin-functype" export default [functype.configs.recommended, functype.configs.tests] ``` There is one preset. The code it checks is written by coding agents, and an agent acts on what fails its build and passes over a warning, so every rule is `error` or `off`. `tests` relaxes it for test files. - **`error`:** every rule whose precision is measured on real code. A forgotten `.run()`, a dropped `Either` or a throw in render is the kind of mistake an agent makes and a reviewer misses. - **`off`:** `prefer-flatmap` and `prefer-do-notation`, whose precision is unmeasured. At `error` they would teach an agent to write `eslint-disable`. Each moves to `error` once it's measured. - **At a real boundary, mark it** rather than disable the rule: `@interop ` or `invariant()` for a throw (see below), `Wire` for a data shape. - **Type-aware rules:** `no-array-mutation`, `no-floating-io`, `no-floating-result` and `no-serialize-container` need typescript-eslint's parser with `parserOptions.projectService`. Without it they report nothing. - **Make sure the agent runs lint.** An error it never sees doesn't steer it, so put `eslint` in the check it runs before it's done, such as `pnpm validate`. In 1.x the plugin had three presets: `recommended` and `strict`, which warned on rules still being measured, and `agent`, which didn't. 2.0's `recommended` is 1.x's `agent`, and `strict` and `agent` are gone: a config that names one fails to load (ESLint reports an `Unexpected undefined config`), so update it to `recommended`. ## TypeScript 7 typescript-eslint, which this plugin runs on, doesn't support TypeScript 7 yet: it loads the TypeScript 6 compiler API, and TypeScript 7.0 ships none. With `typescript@7` as a project's only `typescript`, `npm install` fails on typescript-eslint's peer range, and a forced install fails at lint time with "typescript-eslint does not support TS 7.0". Two paths work today. **Run TypeScript 7 side by side with 6.0, which is the setup Microsoft and typescript-eslint point to.** Alias `typescript` to the 6.0 package, so lint loads the 6.0 API, and install TypeScript 7 as `@typescript/native`: ```json { "devDependencies": { "typescript": "npm:@typescript/typescript6@6.0.2", "@typescript/native": "npm:typescript@7.0.2" } } ``` `tsc` is then TypeScript 7 and `tsc6` is 6.0. Keep the name `@typescript/native`: under npm, the name decides which package's `tsc` gets linked, and with another alias name `tsc` ran 6.0. typescript-eslint 8.73.0 also declares an optional peer `@typescript/native` for TypeScript 7.1 builds, so a package manager may warn that 7.0.2 misses its range, or install a 7.1 nightly beside it; lint results are the same either way. ESLint, typescript-eslint and every rule here, the type-aware ones included, run unchanged. Checked on 2026-11-22 with typescript-eslint 8.73.0, ESLint 10.14.0 and this plugin's 2.127.2: `no-floating-result` and `no-array-mutation` reported, and `tsc` 7.0.2 type-checked the same project. **Or run the plugin in Oxlint, without type information.** Oxlint loads it as a JS plugin, unchanged, on a project with only TypeScript 7. In `.oxlintrc.json`: ```json { "jsPlugins": ["eslint-plugin-functype"], "rules": { "functype/no-let": "error", "functype/prefer-option": "error", "functype/prefer-list": "error" } } ``` Every rule that works without type information works there. The four type-aware rules, `no-array-mutation`, `no-floating-io`, `no-floating-result` and `no-serialize-container`, report nothing, because Oxlint doesn't pass type information to JS plugins yet. Checked on 2026-11-22 with Oxlint 1.94.0. When typescript-eslint supports TypeScript 7.1's new compiler API, the 6.0 alias can go and nothing in this plugin changes; its `@typescript/native` peer suggests that name stays. Until then, prefer the side-by-side setup, which keeps the type-aware rules. ## Rules | Rule | `recommended` | `tests` | Description | | ---------------------------------------- | :-----------: | :-----: | -------------------------------------------------------------------------------------------- | | `functype/no-let` | error | | Use `const`; no reassignment | | `functype/no-imperative-loops` | error | | Use `List`/array methods, async traversal or `IO.forEach` instead of loops | | `functype/prefer-functype-map` | error | | Use functype `Map` instead of a native `Map` you only read | | `functype/prefer-functype-set` | error | | Use functype `Set` instead of a native `Set` you only read | | `functype/collection-naming` | error | | Import functype's `Map`/`Set` under their own names; spell the built-in `globalThis.Map` | | `functype/prefer-map` | error | | Use `map` instead of pushing inside `forEach` | | `functype/prefer-fold` | error¹ | | Use `fold` instead of branching on `isSome()`/`isLeft()`/… | | `functype/prefer-option` | error | off | Use `Option` instead of `null`/`undefined` | | `functype/prefer-either` | error | off | Use `Either` for typed domain errors instead of `throw` | | `functype/prefer-try` | error | off | Use `Try` / `Try.fromPromise` instead of try/catch | | `functype/prefer-flatmap` | off | | Use `flatMap` instead of `map().flat()` | | `functype/prefer-do-notation` | off | | Use `Do` notation for chained operations | | `functype/no-get-unsafe` | error² | | Disallow unsafe extraction (`.orThrow()`, `.expect()`) | | `functype/prefer-list` | error | | Use `List` instead of native arrays | | `functype/no-array-mutation` | error | | Don't change an array in place (`push`, `sort`, `xs[i] = v`…); build a new one | | `functype/no-floating-io` | error | | Don't build an `IO` and drop it, or `await` it unrun; run, return or `yield*` it | | `functype/no-floating-result` | error | off | Don't drop an `Either`/`Try` result; a failure in it is silently ignored | | `functype/no-serialize-container` | error | off | Don't send an `Either`/`Option`/`List` to `c.json()` or `JSON.stringify()`; unwrap it first | | `functype/no-getOrThrow-in-render` | error | | React: no bare `.orThrow()` in a component or hook body; a throw in render unmounts the tree | | `functype/must-fold-on-component-return` | error | | React: render an `Option`/`Either`/`Try` with `fold` or ``, not a guard or `&&` | ¹ With `checkGuards: true`: a guard followed by an unwrap is reported too. ² Allowed in test files by its own `allowInTests` option. ### Severity policy A rule is **`error` once it is right on ~95–99% of real code**, meaning its known false-positive classes are closed. Until then it is `off`, never `warn`: a warning is advice an agent passes over, and a rule that is reliably right should fail the build. `prefer-fold` reports only; its rewrite is a suggestion you apply, never an autofix, so `eslint --fix` can't change code on your behalf. ## Throwing on purpose: `invariant()` and `@interop` `prefer-either` reports every `throw`. Two kinds of throw are correct, and each has its own tool: | The throw is… | Use | | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | A bug check: the condition can only fail because of a programmer error | `invariant(cond, msg)` from `functype` | | A host contract: the caller (React `use()`, React Query, a step runner, an MCP tool) needs a throw or rejection | `@interop ` on the declaration, or `orThrow(builder)` | | A router's control flow: `throw redirect(…)` or `throw notFound()` in a loader or route guard | nothing: recognized by its import (below) | | Anything that can fail in normal operation | return an `Either` | ```ts ignore import { invariant } from "functype" function deriveRunId(workflowId: string, step: number): string { invariant(step >= 0, "step must be non-negative") // a call, not a throw: nothing to report return `${workflowId}:${step}` } /** * Runs the effect, or throws a boxed error. * * @interop React Query signals failure only by promise rejection; an Either return reads as success. */ const runBoxed = async (effect: () => IO): Promise => { … } // A host throw built from the failure, with no tag at all: const value = either.orThrow((left) => new StepError(left.message)) ``` `invariant()` covers one statement and narrows the condition for the code after it, so a function can mix bug checks with `Either`-returning failures. `@interop` rules: - **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered. Honored by `prefer-either`, `prefer-option`, `prefer-fold`, `prefer-try`, `no-get-unsafe`, `no-getOrThrow-in-render` and `must-fold-on-component-return`. - **The reason is required**, on the same line as the tag. A bare `@interop` exempts nothing. - **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not. - **Opt out** per rule with `allowInteropMarker: false`. ### Router control-flow throws TanStack Router redirects or shows Not found only when `beforeLoad` or `loader` throws the value `redirect()` or `notFound()` returns, and React Router and Remix loaders work the same way. That throw is the router's API, so `prefer-either` leaves it alone when the helper is imported from one of these modules, under any local name or through a namespace import: | Module | Helpers | | ------------------------------------------------------------------------------- | --------------------------------------------------------- | | `@tanstack/react-router`, `@tanstack/router-core` | `redirect`, `notFound` | | `react-router` | `redirect`, `redirectDocument`, `replace`, `data` | | `react-router-dom` (React Router 6), `@remix-run/node`, `@remix-run/cloudflare` | `redirect`, `redirectDocument`, `replace`, `data`, `json` | ```ts ignore import { redirect } from "@tanstack/react-router" beforeLoad: ({ params }) => { if (params.id === "all") throw redirect({ to: "/queue" }) // fine: the router's redirect if (!isValid(params.id)) throw new Error("bad id") // still reported } ``` Unlike `@interop`, this exempts only the router's own throws, so a real error thrown in the same function is still reported. A local `redirect` helper isn't the router's, and neither is `throw new Response(…)`. Add your own framework with the `hostThrows` option: `{ hostThrows: { "@acme/router": ["bounce"] } }`. It adds to the defaults: naming a default module adds helpers to its list rather than replacing it, and a module set to `[]` turns that module's defaults off. Prefer either tool to `eslint-disable`. A disable covers a whole file or line and says only "be quiet". `rg 'invariant\('` lists every bug check, and `rg '@interop'` lists every place the code touches a throw-based host. ## Rule options ### `functype/prefer-list` | Option | Default | Description | | --------------------- | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `allowArraysInTests` | `true` | Silence the rule inside test files (`.test.ts`, `.spec.ts`, `__tests__/`, `/test/`, `/tests/`). | | `allowReadonlyArrays` | `true` | When `true`, `ReadonlyArray`, `readonly T[]` **and** `Readonly` pass. When `false`, all three are flagged consistently. Use `false` in combination with `Wire` from `functype` to hold the rule at `error` — every unmarked `ReadonlyArray` becomes a lint error, and wrapping a boundary type in `Wire<…>` is the explicit escape hatch. | | `allowArrayLiterals` | `false` | When `true`, `const xs = [1, 2, 3]` is not reported. Useful when you want type-position enforcement but tolerate idiomatic literals like `[...map.entries()]`. Mutable `T[]` in type positions is always reported regardless. | **What it reports.** The defect is a collection that can change under you, so: - **A mutable `T[]` / `Array` type.** The first suggestion is `ReadonlyArray`, which every caller and library accepts; `List` is second, for a collection you transform. With `allowReadonlyArrays: true` (the default) one accepted suggestion silences the report, so in practice the rule asks for read-only types; set it to `false` with `Wire` at boundaries to push towards `List`. - **An array changed in place** (`push`, `sort`, `splice`, `x[i] = …`, on a binding, a literal accumulator or a field). This gets advice instead of a suggestion, because `ReadonlyArray` wouldn't compile there: build it with `map` / `filter` / `flatMap`, a `List`, or a fold. (This only fires where the rule has an annotation or a literal to hook onto; an inferred array that's pushed to isn't seen.) - **A cast of untyped data to an array** (`JSON.parse(raw) as Row[]`, `raw as Row[]` after `Array.isArray`), with type information. Decoded outside data belongs in a `Wire>` shape. - **An array literal that becomes a collection in your own code** (stored, then transformed with `map` / `filter` / `slice` / `reduce`), with type information. **What it leaves alone.** Data handed to a library in the shape the library demands isn't yours to change. With type-aware linting (`projectService`) the rule skips: - a literal passed where an array is expected (drizzle `.values([...])`, an index definition, a prop typed as an array, a parameter typed `Iterable`), or spread into a call (`and(...conds)`); - a literal inside an object passed to an untyped parameter (a `JSON.stringify` request body), or to a generic one that doesn't hand it back (`c.json(data: T)`). A generic that returns the argument (`useState(init)`, including React's `S | (() => S)` signature, `identity(x)`, `Promise`) leaves the shape with you, so it's reported; - a method chain whose result goes to JSX children or an array slot (`{["PDF", "DOCX"].map((f) => )}`); - a mutable type whose value goes to a slot that **requires** a mutable array (pg's `query(text, values: unknown[])`, an SDK option typed `string[]`), including through a function's declared return type; - a `const` whose every use is one of those, or a single-value read. **Single-value reads** are temporaries, with or without type information: `.length`, `[i]`, `join` / `includes` / `indexOf` / `some` / `every` / `find` / `at`, and chains that end in one (`[a, b].filter(Boolean).join(" ")`, `[...xs].sort(byRank)[0]`). A chain that produces another collection is collection work and is reported. **Without type information, array literals aren't reported at all.** The rule can't tell a literal handed to a library from one of your own, so it reports neither rather than guess. Type positions and in-place mutation are still reported. Turn on type-aware linting to get literal checks. Also skipped: `as const` and other tuple assertions, tuple rest elements (`[string, ...string[]]`), rest parameters (`...args: T[]`), literals passed straight into `List(…)` / `Set(…)`, and files marked generated (`@generated`, "auto-generated", "DO NOT EDIT"). Supabase's generated types carry no marker, so a file whose top level exports both `Json` and `Database` is skipped too. Any other generator with no marker needs an `ignores` entry. Anything still reported that is a deliberate host shape gets `Wire<…>`. Measured on five consumers (2026-10-10), with type-aware linting: **2,000 hits under 2.114, 696 after.** By repo, before → after: a private app monorepo 821 → 215, agent-todo 843 → 328, dokploy-mcp-server 170 → 68, ts-builds 111 → 43, supabase-typed-query 55 → 42. Known false positives left: 25 hits in agent-todo's unmarked Supabase types (an `ignores` entry), one nested ReactFlow return type (`Wire`), one AWS SES request built in an untyped object. Linting all of that monorepo with the rule on takes about 18 seconds. **Boundary recipe (recommended for codebases touching serialization boundaries):** ```jsonc { "functype/prefer-list": ["error", { "allowReadonlyArrays": false }], } ``` Then annotate boundaries with `Wire` from `functype`: ```ts import type { Wire } from "functype" type ClaimedDocs = Wire> type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArray }> ``` `Wire` is assignable both ways with the plain type, so no casts. `prefer-list` and `prefer-option` skip everything inside a `Wire<…>` type argument (`wireTypes` option, default `["Wire"]`; `[]` turns it off), and consumer aliases stack cleanly. ### `functype/no-array-mutation` Reports changing an array in place: - the methods `push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse`, `fill` and `copyWithin`; - assigning to an element (`xs[i] = v`, `xs[i] += 1`, `xs[i]++`); - `delete xs[i]`; - setting `length`. It catches the mutation wherever the array came from, including an inferred `const rows = load(); rows.push(x)`, which `prefer-list` can't see because there's no annotation or literal. ```ts ignore rows.push(row) // reported → [...rows, row], or build rows with map / flatMap xs.sort(byRank) // reported → xs.toSorted(byRank) xs[i] = v // reported → xs.with(i, v) const sorted = [...xs].sort(byRank) // fine: sorts a fresh copy ``` **It only runs with type-aware linting** (`parserOptions.projectService`). It checks the receiver's type, so `push` on a queue class, a `Set` or an `any` value is never mistaken for an array. Without type information it reports nothing. **What it skips:** - mutating a value assumed fresh on the spot: a literal or any call result (`[...xs].sort()`, `xs.slice().reverse()`, `(await load()).sort()`). This also misses a call that returns a shared array (`getSharedCache().push(x)`), a recall gap the rule accepts to stay free of false positives; - `ReadonlyArray`, which the compiler already guards. For a host that has to mutate, such as a charting library that takes the array it fills, tag the function `@interop `. | Option | Default | Description | | -------------------- | ------- | ---------------------------------------------------------- | | `allowInTests` | `true` | Silence the rule inside test files. | | `allowInteropMarker` | `true` | Skip code inside a declaration tagged `@interop `. | Measured on five consumers (2026-10-10): 91 hits, every one a real in-place mutation. Most were `push` accumulators building a list or a Markdown body line by line; the rest were `sort` on a named array and element assignment. It's `error` in every preset since 2.0. In 1.x it was `off` in `recommended`, to avoid failing builds on a minor upgrade. A local array that is declared and then changed by a method or an index write (`acc.push(x)`, `acc[i] = x`) is reported once, here at the change: with type information, `prefer-list` leaves its declaration to this rule. Without type information this rule reports nothing, so `prefer-list` reports the declaration instead. A field, a change through an alias, `acc[i]++` and `delete acc[i]` can still be reported by both. The dedupe assumes this rule is on, as it is in `recommended`. ### `functype/no-floating-io` Reports an `IO` that is built and never run, so it does nothing: - an expression statement whose value is an `IO`; - `await` on an `IO`. `IO` is not a Promise, so `await io` hands back the `IO` itself, unrun. `no-floating-promises` and `await-thenable` miss both, because `IO` isn't thenable. ```ts ignore log.info("saved") // reported, when info returns an IO → yield* it, or .run() it save(user).tap(audit) // reported → return it, or run it const user = await loadUser(id) // reported: user is the IO → await loadUser(id).runOrThrow() return save(user) // fine: the caller runs it void save(user) // fine: a deliberate drop ``` **It only runs with type-aware linting** (`parserOptions.projectService`). It recognizes `IO` by its type (it has `runExit` and `provideLayer`), whatever the call is named. Without type information it reports nothing. Measured (2026-10-16) on functype's own source and tests, functype-log, functype-react, agent-todo's agent-gate-api and a private web app's API: 0 false positives across about 1,340 IO-typed calls. The only hits were four deliberate drops in type-only tests. It's `error` in `recommended`. ### `functype/no-floating-result` Reports a statement that computes a result that can carry a failure, such as an `Either` or `Try`, and drops it. A `Left` or `Failure` in it is silently ignored. `no-floating-promises` doesn't help: awaiting the promise satisfies it while the result inside is thrown away. ```ts ignore await userService.updateSubscription(id, plan) // reported: a failed write goes unnoticed parse(input) // reported, when parse returns an Either await save(user).run() // reported: run() returns an Either → check it, or use runOrThrow() const result = await userService.updateSubscription(id, plan) // fine: then check result.isLeft() await audit.write(entry).tapLeft((e) => log.error(e)) // fine: a best-effort write that logs its failure void (await cache.refresh()) // fine: a deliberate drop ``` - **What counts:** a type, or a member of its union, with `fold` and `isLeft` or `isFailure`. That covers `Either`, `Try`, `Exit`, `Validation` and Either-shaped wrappers such as a `ServiceResult`. An ignored `Option` or `List` loses no error, so it isn't reported. An `IO` that is never run is `no-floating-io`'s. - **Handled chains:** a chain that passes through `.tapError(…)` or `.tapLeft(…)` isn't reported, because it handles its failure. A `.flatMap(…)` after the handler can bring in a new failure, so that chain is reported again. `Try` has no failure tap, so mark a deliberate `Try` drop with `void`. - **Tests:** a test that calls something for its side effect and then checks mocks is reported too. Assert on the result, or turn the rule off for test files. - **Not seen yet:** a drop inside a callback, such as `xs.forEach((x) => save(x))`, or in the first part of a comma expression, isn't its own statement, so it isn't reported. `ok && save(x)` and `ok ? a() : b()` are. **It only runs with type-aware linting** (`parserOptions.projectService`). Without type information it reports nothing. Measured (2026-10-30) on agent-todo's agent-gate-api, which kept a hand-written check for this: at the commit that added that check, the rule reports 20 drops in production code. agent-todo fixed every one of them as a real bug, among them 8 in the Stripe webhook handler, where a failed write still answered Stripe 200. On the current code, after those fixes, it reports none in production code and 12 in tests. functype-os, functype-log, functype-react, functype-eval and functype-mcp-server report none. It's `error` in `recommended`, and `off` in `tests`, where a result is often dropped on purpose. ### `functype/no-serialize-container` Reports a functype container handed to a JSON sink, anywhere inside the value. An `Either`, `Option` or `List` serializes as its `{"@functype", _tag, value}` envelope, so a client reading `subscription.plan` gets `undefined`, and a body built around a `Left` answers 200. The compiler can't catch it, because `c.json()` and `JSON.stringify()` accept any value. ```ts ignore return c.json(await svc.getDetails(id)) // reported: sends the Either's envelope return c.json({ user, subscription: details }) // reported, at subscription return JSON.stringify({ success: true, checkout }) // reported, at checkout: an MCP tool reporting success on failure return c.json(result.orThrow()) // fine, after checking result.isLeft() return c.json({ items: list.toArray() }) // fine return c.json(result.toJSON()) // fine: the envelope on purpose ``` - **Sinks:** `JSON.stringify(x)`, and any `.json(x)` call with an argument: Hono's `c.json`, `Response.json`, Express's `res.json`. `new Response(JSON.stringify(x))` is covered by the first. A read such as `await res.json()` has no argument, so it never matches. - **What counts:** a type with `_tag` and `fold`, which every functype container has and its `toJSON()` envelope doesn't. The rule looks through unions and intersections, array and tuple elements, object properties, `Record` values and utility types such as `Partial` and `Omit`, up to 4 levels deep, and names the path in the message. - **The envelope on purpose:** call `.toJSON()` or `.serialize()` first. A test that checks a container's JSON output is reported too, so call `.toJSON()` there as well. **It only runs with type-aware linting** (`parserOptions.projectService`). Without type information it reports nothing. Measured (2026-10-31) on agent-todo's agent-gate-api, which kept a hand-written check for this. Before its fix commit (f002b90), the rule reports 4 calls, and each is a bug agent-todo fixed: `GET /billing`, which showed every paying user "billing account isn't properly linked" for about nine months; `PATCH /user/me` and `PATCH /user/preferences`, which answered 200 with a `Left` in the body; and an MCP tool that reported success on failure. On the current code it reports none, and none in agent-todo's UI or in functype's own packages. It's `error` in `recommended`, and `off` in `tests`, which assert on a container's `JSON.stringify` envelope. ### React rules Two rules are for React code. They fire only inside a **component** (a function named in PascalCase whose body has JSX, including one wrapped in `memo` or `forwardRef`) or a **hook** (a function named `use` + a capital letter), so other code rarely trips them. The one exception is a non-React function whose name starts with `use` + a capital letter, which is read as a hook. Both are `error` in `recommended`. Both work without type information. With it (`parserOptions.projectService`), the receiver must also be a functype container, so an unrelated object that happens to have an `orThrow` or `isSome` method is not reported. Only the component's or hook's own body counts as render. An event handler, an effect, or a callback passed to `.map` is a separate function, so a call there is not reported. That also means a call inside a callback that does run during render (`useMemo(() => …)`, `items.map((o) => o.orThrow())` in JSX) is missed: the rules prefer missing a case to reporting valid code. ### `functype/no-getOrThrow-in-render` Reports a bare `.orThrow()` (or the older `.getOrThrow()`) in a component or hook body. When the value is missing it throws during render, and React unmounts the tree up to the nearest error boundary. ```tsx ignore function Profile({ user }: { user: Option }) { const u = user.orThrow() // reported → user.fold(() => , (u) => ) return } user.isSome() ? : null // fine: guarded, it can't throw if (user.isNone()) return null // …and every later user.orThrow() in this body is guarded too const u = user.orThrow((e) => new NotFound(e)) // fine: a named error, sent to the error boundary on purpose