[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"F1ZOM0IaXg":3},"\u003Cp align=\"center\">\n  \u003Cpicture>\n    \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"logo-dark.svg\">\n    \u003Cimg src=\"logo.svg\" alt=\"LINEN\" width=\"460\">\n  \u003C/picture>\n\u003C/p>\n\n\u003Cp align=\"center\">\n  A curated standard-library companion for Lean 4 — external concepts ported in,\n  with everything Lean already provides stripped out.\n\u003C/p>\n\n\u003Cp align=\"center\">\n  \u003Ca href=\"https://github.com/typednotes/linen/actions/workflows/lean_action_ci.yml\">\u003Cimg src=\"https://github.com/typednotes/linen/actions/workflows/lean_action_ci.yml/badge.svg\" alt=\"CI\">\u003C/a>\n  \u003Ca href=\"https://github.com/typednotes/linen/stargazers\">\u003Cimg src=\"https://img.shields.io/github/stars/typednotes/linen?style=flat\" alt=\"GitHub Stars\">\u003C/a>\n  \u003Ca href=\"https://github.com/typednotes/linen/blob/main/LICENSE\">\u003Cimg src=\"https://img.shields.io/github/license/typednotes/linen\" alt=\"License\">\u003C/a>\n  \u003Ca href=\"https://github.com/typednotes/linen\">\u003Cimg src=\"https://img.shields.io/github/last-commit/typednotes/linen\" alt=\"Last Commit\">\u003C/a>\n  \u003Ca href=\"https://lean-lang.org/\">\u003Cimg src=\"https://img.shields.io/badge/Lean-4.33.1-blue\" alt=\"Lean 4\">\u003C/a>\n\u003C/p>\n\n\u003Cp align=\"center\">\n  \u003C!-- Counts are produced by, and should be refreshed with:\n         modules:  find Linen -name '*.lean' | wc -l\n         theorems: grep -rhE '^theorem ' Linen Tests --include='*.lean' | wc -l\n         guards:   grep -rhE '^#guard'    Linen Tests --include='*.lean' | wc -l -->\n  \u003Cstrong>770 modules\u003C/strong> · \u003Cstrong>468 compile-time theorems\u003C/strong> · \u003Cstrong>10882 \u003Ccode>#guard\u003C/code> checks\u003C/strong>\n\u003C/p>\n\n## Overview\n\n`linen` is a small, opinionated extension of the Lean 4 standard library. When a\nuseful concept exists in another ecosystem (a Haskell package, another Lean\nproject, a single module), it is ported in — but **every concept that already\nhas a Lean standard-library equivalent is replaced with that equivalent**, and\nthe result is reshaped to follow Lean's own module hierarchy and naming. What\nships is only what core genuinely lacks, written as idiomatic Lean on top of the\nstandard library.\n\nThree rules hold across the whole library:\n\n- **Stdlib-first** — no bespoke re-implementation of anything core provides\n  (e.g. `Id` over a hand-rolled identity functor, `· >=> ·` over a custom\n  Kleisli combinator, `List.foldlM` over `foldM`).\n- **No `partial`, no `sorry`** — all recursion is structural or has a proven\n  termination argument, and proofs are complete.\n- **Everything is tested** — each module has a `Tests/` counterpart whose\n  `#guard` examples run on every build.\n\n## Features\n\n`linen` covers the following areas — see **[docs/modules.md](docs/modules.md)**\nfor the full per-module feature list and module table.\n\n- **`Data.Functor` / `Control`** — functor, applicative & monad constructions\n  missing from core (`Compose`/`Product`/`FunctorSum`, `Bifunctor`,\n  `Foldable`/`Traversable`, `mtl`-style `Reader`/`State`/`Except`, STM,\n  green-thread concurrency, …).\n- **`Control.Monad.Effect`** — extensible effects ported from `freer-simple`:\n  an open union over an effect row (`Data.OpenUnion`), the `Eff` monad with\n  `send`/`interpret`/`interpose`/`reinterpret`/`run`, and the\n  `Reader`/`State`/`Error`/`Writer`/`NonDet`/`Coroutine`/`Fresh`/`Trace`\n  effects — so a signature *is* an effect whitelist. Its `FileSystem`, `HTTP`\n  and `PostgreSQL` effects go past what Haskell's rows can say, indexing the\n  effect on a `Capability` **value** and so constraining an effect's\n  *arguments*, not just which effects are named:\n  - `FileSystem` — a read-only capability makes `writeFile` fail to elaborate,\n    read/write/delete are separately grantable within one effect, and each\n    path `Scope` carries its own operation list, so one capability says \"read,\n    write and delete under `/srv/app/releases`, read only under `/etc/app`,\n    nothing anywhere else\". Roots are matched component-wise, so\n    `/tmp/sandbox-evil` is rejected where a string prefix would wrongly admit\n    it. Scopes union — no deny rules, no precedence — so `Capability.union`\n    provably takes nothing away (`permits_union_left`/`_right`).\n  - `HTTP` — methods are separately grantable, and each URL scope carries its\n    own method list, so one capability says \"GET anywhere under\n    `u!\"https://api.example.com/v1\"`, POST only to `/v1/events`\". Hosts are\n    compared as DNS labels and paths component-wise, so\n    `api.example.com.evil.com`, a scheme downgrade, a changed port and\n    `/v1-admin` are all rejected.\n  - `PostgreSQL` — the database, instance and role are capability fields the\n    handler builds its connection from, so no computation can reach another;\n    statement kinds and tables are separately grantable. Queries are a\n    parameterised AST rather than strings, because a `String` of SQL cannot be\n    checked by `decide` — and so the SQL sent cannot disagree with the SQL\n    authorised.\n- **`Control.Lens`** — a `lens`-style profunctor-optics library (plus its\n  `profunctors`/`indexed-traversable` prerequisites): `Lens`/`Prism`/`Iso`/\n  `Traversal`/`Fold`/`Getter`/`Setter`/`Review` and indexed variants, with\n  `Ixed`/`At`/`Each`/`Cons`/`Snoc`/`Wrapped` instances over most existing\n  containers; `makeLenses`-generated accessors are hand-written per field\n  instead, since Lean has no Template Haskell.\n- **`Data.ByteString*` / `Data.String` / `Data.Word8`** — byte strings (strict,\n  lazy, short, builder), Base64, Base16 (`Data.Hex`), case-insensitive text,\n  and ASCII byte classification.\n- **`Data.Json`** — a tiny JSON library with `ToJSON`/`FromJSON` and proven\n  encode→decode round trips.\n- **`Data.Float`** — `parseFloat?` from text, shared by the JSON decoder, the\n  YAML reader and the SQL decoders; Lean core has no `String.toFloat?`.\n- **`Data.Ini` / `Data.Yaml`** — configuration formats: INI sections and pairs,\n  and YAML 1.2's core schema (block and flow collections, block scalars,\n  multi-document streams). Anchors, aliases, merge keys and custom tags are\n  rejected outright rather than silently mis-parsed.\n- **`Data.Map` / `Data.Set` / `Data.IntMap` / `Data.List'` / `Data.List.NonEmpty`\n  / …** — Haskell-style container and list APIs over core `Std`/`List` types.\n- **`Time`** — a `time`-style calendar/clock layer over Lean's own `Std.Time`:\n  Julian-calendar conversion, Gregorian/Orthodox Easter dates, absolute\n  `Month`/`Quarter` counters, `(months, days)`/`(months, Duration)` calendar\n  periods, UT1 mean-solar-time conversion, and TAI↔UTC leap-second\n  conversion — the pieces `Std.Time` itself doesn't cover; `Data.Time.*`'s\n  day/UTC-instant/time-of-day types are `Std.Time.Date.PlainDate`/\n  `Std.Time.Duration`/`Std.Time.Zoned` underneath.\n- **`Network.HTTP` / `HTTP2` / `HTTP3` / `Socket` / `TLS` / `QUIC` /\n  `WebSockets`** — a full network stack: HTTP/1.1 client & wire types,\n  HTTP/2 framing + HPACK, HTTP/3 over QUIC + QPACK, POSIX sockets with a\n  green-thread event dispatcher, TLS 1.2/1.3 over OpenSSL, and WebSockets.\n- **`Network.WebApp` / `Network.WebApp.Server`** — a WAI-style application\n  interface plus an HTTP server implementing it.\n- **`Web.Html` / `Web.Css`** — typed HTML5/CSS construction where illegal\n  nesting and property/value mismatches are compile-time errors, with `elem!`\n  and `rule!` macro sugar.\n- **`DataFrame`** — typed tabular data with a proven rectangular invariant,\n  CSV I/O, joins, sorting, grouping/aggregation, and statistics.\n- **`Database.PostgreSQL` / `Database.SQL`** — libpq FFI bindings and a\n  hasql-style typed client (encoders/decoders, sessions, pooling).\n- **`Database.SQLite3`** — `direct-sqlite`-style FFI bindings to a vendored\n  SQLite amalgamation (no pkg-config), with an `Except Error`-returning\n  `Direct` layer and a public `IO`-throwing API.\n- **`Database.SQLite.Simple`** — a `sqlite-simple`-style mid-level client:\n  `Query`/`Only`/row-cons types, the error-accumulating `Ok` applicative,\n  SQLite date/time text parsing & rendering, `Connection`/`Statement`/`Field`\n  connection plumbing, and the `ToField`/`FromField`/`ToRow`/`FromRow`\n  parameter/row conversion classes (tuple instances up to arity 7); a public\n  facade (`withConnection`, `query`/`query_`/`execute`/`execute_`,\n  streaming `fold`/`fold_`, `withTransaction`/`withSavepoint`,\n  `lastInsertRowId`/`changes`); the `sql \"…\"` `syntax`/`macro_rules`\n  quasiquoter substitute; and user-defined scalar SQL function registration\n  (`createFunction0`–`createFunction3`/`deleteFunction`) via a new\n  Lean-closure-called-from-C `sqlite3_create_function_v2` bridge.\n- **`Database.DuckDB.FFI`** — low-level `duckdb-ffi`-style FFI bindings to\n  `libduckdb`: connection/query lifecycle, prepared statements & the\n  appender, `DataChunk`/`Vector`/validity-mask access to result data, the\n  logical-type system (primitive/`LIST`/`ARRAY`/`MAP`/`STRUCT`/`UNION`/\n  `ENUM`/`DECIMAL`), catalog/config/error/logging helpers, and user-defined\n  scalar SQL function registration via a Lean-closure-called-from-C\n  trampoline (mirroring the one built for `Database.SQLite.Simple`).\n- **`Database.DuckDB.Simple`** — a `duckdb-simple`-style mid-level client atop\n  `Database.DuckDB.FFI`: the error-accumulating `Ok` applicative, `Query`/\n  `Only`/row-cons types, the `ToField`/`FromField`/`ToRow`/`FromRow`\n  parameter/row conversion classes (tuple instances up to arity 7) including\n  DuckDB's `STRUCT`/`UNION`/`LIST`/`MAP`/`ENUM`/`DECIMAL` logical-type decode\n  support and hand-written `STRUCT`/`UNION` decode combinators standing in for\n  GHC-generics-derived instances; catalog/config/file-system/logging helpers\n  and user-defined scalar SQL function registration; and a public facade\n  (`withConnection`, `query`/`query_`/`execute`/`execute_`, streaming\n  `fold`/`fold_`, `withTransaction`) built on the appender-free\n  prepared-statement/`DataChunk` fetch pipeline. Completes the\n  `sqlite-simple` → `duckdb-ffi` → `duckdb-simple` import chain.\n- **`Database.Redis`** — a `hedis`-style Redis client: the RESP2 wire\n  protocol (`Reply` encoder/parser over `Std.Internal.Parsec.ByteArray`) and\n  request/response pipelining over `Network.Socket`/`Network.TLS`; the\n  `Redis` monad with `RedisCtx`/`MonadRedis`; the full command surface\n  (simple + irregular `ManualCommands`); `ConnectInfo`/`redis://`-URL parsing\n  and an `IO.Ref`-guarded connection pool; `MULTI`/`EXEC`/`WATCH`\n  transactions; Pub/Sub (`publish`, `pubSub`, `pubSubForever`); Redis Cluster\n  (CRC16 hash slots, topology, `MOVED`/`ASK` redirects); and Sentinel-based\n  master discovery with failover — no separate prerequisite Hackage package\n  needed, every dependency resolving onto the Lean stdlib, an existing\n  `linen` port, or a small inlined slice.\n- **`Data.Stream`** — a `streamly-core`-style stream-fusion library: the\n  fused, direct-style `Stream` (a `Yield`/`Skip`/`Stop` `Step`-machine stepper)\n  and the CPS-encoded `StreamK`, bridged both ways; `Fold`/`Scanl` terminating\n  left folds and scans, `Unfold`/`Producer` generators, and a backtracking\n  streaming `Parser`; plus an unboxed-array subsystem (`MutByteArray`/`Unbox`,\n  `MutArray`, `Array.Unboxed`). A distinct streaming paradigm from the existing\n  `Conduit` port — the fused data encoding is reproduced faithfully, without\n  GHC's `fusion-plugin` optimizer that eager Lean has no analogue for; bounded\n  to `streamly-core`, deferring the concurrent `SVar` scheduler.\n- **`Text.DocLayout`** — a Wadler/Leijen-style pretty-printer: the `Doc`\n  document algebra (`literal`, `\u003C+>`, `$$`, `vcat`, `nest`, `hang`, `flush`,\n  side-by-side blocks, ANSI/OSC-8 styling) and its `render`/`renderANSI` line-\n  wrapping engine, plus the `HasChars`/`Attributed`/`ANSIFont` layers beneath\n  it. `linen`'s first document-layout algebra, and a blocking prerequisite of\n  `pandoc` — every pandoc writer renders through it.\n- **`Text.Pandoc`** — a `pandoc`-style universal document converter: the\n  shared AST (`Pandoc`/`Block`/`Inline`, folded in from `pandoc-types`) with\n  its `Walk`/`Generic` traversals and `Builder` combinator API; the shared\n  reader/writer infrastructure (`Extensions`, `Options`, `Parsing`,\n  `Shared`, `Templates`, `Writers.Shared`'s `gridTable`) and the pure\n  `PandocMonad`/`PandocPure`; and a working Markdown↔AST↔HTML round-trip\n  (`Readers`/`Writers.{Markdown,HTML}`) plus the AST-native `Native`/`JSON`\n  formats, dispatched through a top-level `getReader`/`getWriter`/`convert`\n  facade. `tagsoup` (the HTML tokenizer) and a YAML front-matter parser had\n  no other consumer, so each is folded in as a bounded slice directly inside\n  its one reader module rather than imported as its own package; `blaze-html`\n  substitutes onto the existing `Web.Html`. Scoped to the AST plus Markdown\n  and HTML (both directions) — the long tail of exotic formats, binary/zip\n  formats, the Lua-filter system, syntax highlighting, math typesetting,\n  citations, and templating are all deferred.\n- **`Crypto.JOSE`** — JOSE/JWT signing and verification (HMAC/RSA/EC) over OpenSSL.\n- **`Crypto.SigV4`** — AWS Signature Version 4 request signing, over the\n  existing SHA-256/HMAC FFI and RFC 3986 escaping; checked against AWS's\n  published test vectors, so it also serves S3-compatible clouds.\n- **`Text.XML`** — an XML reader (the counterpart to `Text.Pandoc.XML`'s\n  escaping): a character-at-a-time state machine feeding a stack-based tree\n  builder, so nesting needs no `partial` and no fuel.\n- **`Network.HTTP.Client.Retry`** — capped exponential backoff with equal\n  jitter over connection errors and 408/429/5xx, honouring `Retry-After`.\n  Alongside it, socket read/write deadlines (`SO_RCVTIMEO`/`SO_SNDTIMEO` plus\n  `poll`-based waiting) now bound every request: the blocking wrappers used to\n  retry `EAGAIN` in a hot loop, so a stalled peer meant an indefinite hang at\n  100% CPU.\n- **`Network.OAuth2`** — a `hoauth2`-style OAuth2 client: authorization-code,\n  client-credentials, device-authorization, JWT-bearer, resource-owner-password\n  and refresh-token grants; PKCE (`S256`) via two new OpenSSL-backed\n  `Crypto.SHA256`/`Crypto.SecureRandom` FFI primitives; typed request-builder\n  application config; and token/user-info/device-authorization HTTP flows over\n  `Network.HTTP.Client.Conduit`.\n- **`Crypto.Zlib` / `Crypto.MD5` / `Crypto.RC4` / `Crypto.AES`** — zlib\n  inflate, RFC 1321 MD5, the RC4 stream cipher, and AES-128 CBC decryption\n  + PKCS5 unpadding — the primitives behind the PDF Standard Security\n  Handler.\n- **`System.Keychain`** — OS credential-store access (macOS Keychain,\n  Linux Secret Service, Windows Credential Manager).\n- **`Data.PDF.Stream` / `Data.PDF.Core` / `Data.PDF.Content` /\n  `Data.PDF.Document`** — PDF parsing, rendering, and text extraction: a\n  buffer-resident `io-streams` port, the low-level object model/parser/\n  xref/encryption layer, content-stream operators and font/text-encoding\n  handling, and a document/page-tree API with text extraction.\n- **`Options.Applicative`** — `optparse-applicative`-style command-line\n  argument parsing.\n- **`PostgREST`** — a Lean port of PostgREST's request/response pipeline:\n  API request parsing, config, schema cache introspection, query planning,\n  auth, and OpenAPI generation.\n- **`CDP`** — a Chrome DevTools Protocol client: typed commands/events/types\n  for every protocol domain, plus a WebSocket-based runtime to connect to a\n  browser, send commands, and subscribe to events.\n- **`Data.Colour`** — a `colour`-style colour library: `Colour`/`AlphaColour`\n  blending, CIE chromaticity/illuminants, RGB colour spaces (HSL/HSV, sRGB),\n  and named SVG colours.\n- **`Data.Array.Shaped`** — a `repa`-style rank-polymorphic, shape-indexed\n  array library: `Delayed`/`Manifest`/`Cursored`/`Partitioned`/`Undefined`\n  representations, index-space operators, and stencil-based convolution.\n- **`System.Console.Ansi` / `System.Exit` / `System.Log.FastLogger`** —\n  terminal styling, process exit codes, and buffered logging.\n- **`Graphics.Netpbm`** — a `netpbm`-style parser for the PBM/PGM/PPM\n  \"portable anymap\" image formats (ASCII and binary variants, magic numbers\n  `P1`–`P6`) over `ByteArray`.\n- **`Codec.Picture`** — a `JuicyPixels`-style image codec suite: pixel/image\n  types and colorspace conversions, plus PNG, JPEG (baseline + progressive),\n  GIF (including animation), BMP, TGA, TIFF, and Radiance HDR encoders/\n  decoders, Exif/TIFF/JFIF metadata, and median-cut colour quantization.\n- **`Graphics.Image`** — a `hip`-style image-processing library: `Y`/`RGB`/\n  `HSI`/`CMYK`/`YCbCr`/complex/binary colour spaces over a shape-indexed\n  pixel array; geometric transforms (rotate/scale/translate/crop) with\n  nearest-neighbour/bilinear interpolation; kernel convolution and named\n  filters (Sobel, Gaussian, Laplacian, …); binary morphology (erode/dilate/\n  open/close); FFT-based complex-image processing; adaptive histogram\n  equalization; Hough-transform line detection; salt-and-pepper noise\n  generation; and PNG/JPEG/GIF/BMP/TGA/TIFF/HDR and PNM/PGM/PPM file I/O via\n  `Codec.Picture`/`Graphics.Netpbm`.\n\n- **`Cloud`** — one way to use cloud services across **AWS, GCP and\n  Scaleway**: object stores, message queues and secret managers behind three\n  portable interfaces, each a record of closures with one implementation per\n  cloud. Scaleway's Object Storage and Queues speak the S3 and SQS APIs, so a\n  single client serves two clouds and differs only in the endpoint; Cloud\n  Storage gets its own JSON client, and Pub/Sub — a topic-and-subscription\n  system rather than a queue — splits into a `Producer` and a `Consumer` so\n  nothing has to pretend otherwise. Underneath: the three-source credential\n  chain (CLI config files, OS keychain, environment), RFC 7523 token minting\n  for GCP, locality-to-region tables, request signing over `Crypto.SigV4`, the\n  four wire dialects, a classified error taxonomy, and pagination that reports\n  whether it finished. Every interface has an **in-memory backend** and the\n  transport is swappable, so all of it is tested with no credentials and no\n  network.\n- **`Control.Monad.Effect.{ObjectStore,Queue,SecretStore}`** — the same three\n  services as capability-restricted effects, on the `Effect.FileSystem`\n  pattern. A capability is a value indexing the effect, so it can confine a\n  program to one bucket's key prefix, let a worker read one queue and write\n  another without draining either, or grant a health check the right to see\n  that a secret *exists* while making `getValue` **fail to elaborate**. The\n  handler takes the backend as a parameter, so one program runs against S3,\n  against Cloud Storage, or against an in-memory double.\n\n## Quick Start\n\nAdd to your `lakefile.toml`:\n\n```toml\n[[require]]\nname = \"linen\"\ngit = \"https://github.com/typednotes/linen\"\nrev = \"main\"\n```\n\nThen import what you need:\n\n```lean\nimport Linen.Data.Functor\nimport Linen.Control.Monad\n\nopen Data.Functor Control.Monad\n\n#eval join (some (some 3))            -- some 3\n#eval replicateM 3 (some 7)           -- some [7, 7, 7]\n```\n\n### Using the FFI-backed modules\n\nPure modules need nothing beyond the `require` above. The modules backed by\nnative code — `System.Keychain`, `Crypto.*`, `Network.TLS`, `Network.HTTP`\n(over HTTPS), `Database.*` — need link flags in **your** lakefile.\n\nLake does not propagate a dependency's `moreLinkArgs` to a dependent's\nexecutable: `liblinenffi.a` lands on your link line, but the flags its members\nneed do not, so you get `undefined symbol: SecItemCopyMatching` or similar.\nBecause the flags are platform-conditional, this needs `lakefile.lean` rather\nthan `lakefile.toml`. Take only the lines for the features you use:\n\n```lean\nimport Lake\nopen System Lake DSL\n\ndef pkgConfigFlags (args : Array String) : IO (Array String) := do\n  try\n    let out ← IO.Process.output { cmd := \"pkg-config\", args }\n    if out.exitCode != 0 then return #[]\n    return (out.stdout.trimAscii.copy.splitOn \" \").toArray.map (·.trimAscii.copy)\n      |>.filter (· != \"\")\n  catch _ => return #[]\n\ndef pkgLinkFlags (pkg : String) : IO (Array String) := do\n  let libs ← pkgConfigFlags #[\"--libs\", pkg]\n  let libdir ← pkgConfigFlags #[\"--variable=libdir\", pkg]\n  return (libdir.filter (· != \"\")).map (\"-L\" ++ ·) ++ libs\n\n/-- Lean ships its own `lld`, which has no default framework search path. -/\ndef macSdkArgs : IO (Array String) := do\n  try\n    let out ← IO.Process.output { cmd := \"xcrun\", args := #[\"--show-sdk-path\"] }\n    if out.exitCode != 0 then return #[]\n    let sdk := out.stdout.trimAscii.copy\n    if sdk.isEmpty then return #[]\n    return #[\"-F\", sdk ++ \"/System/Library/Frameworks\", \"-L\", sdk ++ \"/usr/lib\"]\n  catch _ => return #[]\n\nopen Lean Elab Command in\nrun_cmd do\n  let mkDef (n : Name) (flags : Array String) : CommandElabM Unit := do\n    let lits : Array (TSyntax `term) := flags.map (fun s => quote s)\n    elabCommand (← `(def $(mkIdent n) : Array String := #[$lits,*]))\n  -- `System.Keychain`\n  let keychain : Array String ←\n    if System.Platform.isOSX then\n      (macSdkArgs).map (· ++ #[\"-framework\", \"Security\", \"-framework\", \"CoreFoundation\"])\n    else if System.Platform.isWindows then pure #[\"-ladvapi32\", \"-lcredui\"]\n    else pkgLinkFlags \"libsecret-1\"\n  -- `Crypto.*` and `Network.TLS`. The explicit `-L` matters on macOS: without\n  -- it these can bind to the system's incompatible `libboringssl`, which links\n  -- cleanly and then crashes on the first TLS call.\n  let ssl ← pkgLinkFlags \"openssl\"\n  mkDef `nativeLinkArgs (keychain ++ ssl)\n\npackage myapp where\n  moreLinkArgs := nativeLinkArgs\n```\n\nAdd `pkgLinkFlags \"libpq\"` for `Database.PostgreSQL`, `pkgLinkFlags \"zlib\"` for\n`Crypto.Zlib`, and DuckDB's `lib` directory for `Database.DuckDB`.\n\nSetting `precompileModules := true` on this package *would* make all of the\nabove automatic, since Lake then links the extern library's shared form, which\ncarries these flags. It is deliberately not the default: the shared form links\nthe whole archive, so every dependent would need libpq, SQLite and DuckDB\ninstalled even to use, say, `Crypto.SigV4`.\n\n## Modules\n\nSee **[docs/modules.md](docs/modules.md)** for the full module table (all 770 modules).\n\n## Build & Test\n\n```bash\nlake build          # build the library\nlake build Tests    # run every #guard / #eval check\n```\n\n## Examples\n\nExample programs live under [`Examples/`](Examples) and share one entrypoint,\n`lake exe examples \u003Cname> [args...]` (run with no name to list them):\n\n```bash\nlake exe examples                  # list the available examples\nlake exe examples echo             # green-threaded echo server — self-checking demo (exits 0)\nlake exe examples echo serve 9099  # run the echo server forever; then:  nc 127.0.0.1 9099\nlake exe examples bench            # network round-trips w/ a few-ms server delay: Green vs blocking pool (same #cores threads)\nlake exe examples postgrest        # in-memory PostgREST request handling + OpenAPI spec generation — self-checking demo\nlake exe examples quic             # QUIC types/config + HTTP/3 QPACK/frame wire round trip — self-checking demo\nlake exe examples recv             # Network.Socket.Blocking accept/connect/send/recv round trip — self-checking demo\nlake exe examples resourcet        # Control.Monad.Trans.Resource LIFO cleanup over real scratch files — self-checking demo\nlake exe examples conduit          # Data.Conduit / Data.Conduit.Combinators pipelines, incl. bracketP/runConduitRes — self-checking demo\nlake exe examples stm              # Control.Monad.STM + Concurrent.STM.{TVar,TMVar,TQueue} — self-checking demo\nlake exe examples streaming-commons        # Data.Streaming.Network bindPortTCP/getSocketTCP/acceptSafe/AppData round trip — self-checking demo\nlake exe examples streaming-commons serve 9098  # run it forever; then:  nc 127.0.0.1 9098\nlake exe examples tls              # Network.TLS.Context handshake over loopback against a self-signed cert — self-checking demo\nlake exe examples httpclient       # Network.HTTP.Client connect/request/response + redirect-following, over loopback — self-checking demo\nlake exe examples httpconduit      # Network.HTTP.Client.Conduit / Network.HTTP.Simple streaming HTTP, over loopback — self-checking demo\nlake exe examples req              # Network.HTTP.Req type-safe req/runReq (HttpBodyAllowed-checked GET/POST), over loopback — self-checking demo\nlake exe examples webapp           # Network.WebApp: Application/Middleware/AppM (composeMiddleware/ifRequest/modifyResponse), over loopback — self-checking demo\nlake exe examples webappstatic     # Network.WebApp.Static: staticApp/static + defaultFileServerSettings over a real scratch directory — self-checking demo\nlake exe examples vault            # Data.Vault type-safe heterogeneous map: typed keys, adjust/delete/union — self-checking demo\nlake exe examples vector           # Data.Vector-derived Array combinators: generate/ifilter/folds/reductions/backpermute/slice — self-checking demo\nlake exe examples effects          # Control.Monad.Effect.{FileSystem,HTTP,PostgreSQL,Trace} capabilities over real files/socket/Postgres — self-checking demo\nlake exe examples effects no-db    # same, minus the Podman-started PostgreSQL section\nlake exe examples todo             # Web.Html/Web.Css typed TODO list over Network.WebApp.Server — self-checks, then keeps serving; try:  curl localhost:\u003Cport>\nlake exe examples todo check       # same self-check round trip, but exits instead of staying up (for scripting)\n```\n\nThe `echo` example exercises the whole socket stack end-to-end — a green accept\nloop forks a green handler per connection, each suspending on\n`recvGreen`/`sendAllGreen` (via the kqueue/epoll `EventDispatcher`) instead of\nholding an OS thread, so one small worker pool serves many connections. Adding\nan example is a new module under `Examples/` plus one line in the registry in\n`Examples/Main.lean`.\n\nThe `quic` example demonstrates the HTTP/3-over-QUIC wire format end-to-end —\n`Network.HTTP3.QPACK.Encode`/`Frame.encode` producing bytes that\n`Frame.decode`/`Network.HTTP3.QPACK.Decode` reproduce exactly — without\nneeding a live connection, since `Network.QUIC.Client`/`Server` are stubbed\npending TLS 1.3 FFI. It also calls `Client.connect`/`Server.run`/`Server.accept`\ndirectly and checks that each fails with exactly its documented\n\"not yet implemented\" error, so the demo stays honest about what is and isn't\nwired up yet.\n\nThe `stm` example puts ten green tasks through a thousand `atomically`\nincrements each of a shared `TVar`, hands values between a producer and\nconsumer through an empty `TMVar`, checks `TQueue`'s FIFO order survives its\ntwo-list representation, and shows `orElse` falling through to its alternative\non `retry`.\n\nThe `streaming-commons` example drives `Data.Streaming.Network`'s `AppData`\nabstraction over a real loopback connection; `streaming-commons serve \u003Cport>`\nruns `runTCPServer` forever for manual testing with `nc`.\n\nThe `tls` example runs a full TLS 1.2/1.3 handshake over loopback against a\nself-signed `CN=localhost` certificate, trusting it directly as its own CA via\n`createClientContextWithCA` so the demo stays fully offline. It also documents\na real API limitation: `getAlpn` always reports `none`, because `setAlpn` only\nregisters the server's selection callback — nothing in the current client API\ncalls `SSL_set_alpn_protos` to advertise a protocol list for it to select from.\n\nThe `httpclient` and `httpconduit` examples each stand up a tiny hand-rolled\nHTTP/1.1 server over a real loopback socket and drive it with a different\nlayer of the client stack: `httpclient` uses `Client.connectPlain` +\n`Client.performRequest` directly, then `Client.execute` to show a `302 Found`\n→ `/final` redirect followed automatically; `httpconduit` uses\n`Simple.parseUrl!`/`httpBS`, the callback-scoped `Client.Conduit.withResponse`,\nand `Client.Conduit.httpSource` streamed through a `.| sinkList` conduit\npipeline.\n\nThe `req` example exercises `Network.HTTP.Req`'s type-safe client — a `GET`\nwith `NoReqBody` and a `POST` with a `ReqBodyBs` payload, both against a\nloopback server, both admitted by the `HttpBodyAllowed` typeclass at compile\ntime (swapping a body onto the `GET` would instead fail to compile, since\nthere is no `HttpBodyAllowed .NoBody .YesBody` instance).\n\nThe `webapp` example drives a `Network.WebApp.Application` through the same\nkind of hand-rolled loopback HTTP/1.1 server as `httpclient`/`req`, but this\ntime the request handler itself is the thing under test: raw bytes are parsed\ninto a `Request`, run through the application via `Green.block`, and the\nresulting `Response` serialized back. The demo application composes an echo\nhandler with a `/health` route and a `Server` header, entirely from\n`Middleware` combinators — `composeMiddleware`, `ifRequest`,\n`modifyResponse`, `addHeader` — the same combinators the algebraic-law\ntheorems in `Network.WebApp` (`idMiddleware_comp_left`/`_right`,\n`modifyResponse_id`, `ifRequest_false`) prove associative/identity laws for.\n\nThe `webappstatic` example serves a real scratch directory through\n`Network.WebApp.Static.static` (`defaultFileServerSettings` + `staticApp`),\nreusing `webapp`'s loopback harness — including its `Sendfile.sendFile` path\nfor `.responseFile`, since `defaultFileServerSettings` serves files that way\nrather than buffering them into a `.responseBuilder`. It checks a direct file\nhit (with its `Cache-Control: max-age=3600` default), a directory request\nredirected to `index.html`, a 404 for a missing path, and a 403 for a\ndotfile-shaped path segment (rejected by `Piece`'s `no_dot` invariant before\nany filesystem lookup runs).\n\nThe `vault` example mints distinctly-typed keys with `Key.new` and stores\nunrelated payloads under each in the same `Vault`, showing that a key only\never yields back the type it was minted for, plus `adjust`/`delete`/`union`.\n\nThe `vector` example runs through every combinator `Linen.Data.Vector` adds to\n`Array` (`generate`, `ifilter`, `foldl1'`/`foldr1`, `ifoldl'`/`ifoldr`,\n`and`/`or`/`product`, `notElem`, `backpermute`, `slice`) — everything else\nHaskell's `Data.Vector` offers already exists verbatim on `Array`.\n\nThe `todo` example is a small in-memory TODO list whose every page is built\nfrom `Web.Html`/`Web.Css` typed constructors — the `\u003Cul>`/`\u003Cli>` nesting, each\nitem's `\u003Cform>`s, and its inline `style` all go through the same\nillegal-construct-is-a-compile-error discipline as `Tests.Linen.Web.HtmlTest`/\n`CssTest` (e.g. a `\u003Cdiv>` inside a `\u003Cp>`, or a `color` declaration given a\n`Display` value, simply fails to compile). Routing and state reuse\n`Network.WebApp`'s `Application`/`AppM`, driven by the real\n`Network.WebApp.Server` engine via `withApplication`, exactly as the `server`\nexample drives `webapp`'s `demoApplication`. Unlike the other examples, `todo`\ndoesn't exit after checking itself — it self-checks against its own live\nserver and then keeps that same server (with its accumulated state) running\non the printed OS-assigned port, so you can immediately `curl` it by hand;\n`todo check` runs the identical round trip but exits instead, for scripting.\n\nThe `effects` example is the capability-restricted effect modules\n(`Control.Monad.Effect.{FileSystem,HTTP,PostgreSQL,Trace}`) run against real\nresources, so that \"authorised\" and \"actually happened\" can be checked against\neach other: a capability rooted at a scratch directory reads and writes real\nfiles through `IO.FS` (and a second capability, same root plus the delete bit,\nremoves them); a capability that may `GET` anything under `/v1` but `POST` only\nto `/v1/events` drives a hand-rolled loopback HTTP/1.1 server; and a capability\nscoped to one table of one database, as one role, runs real\n`INSERT`/`UPDATE`/`SELECT` statements against a disposable `postgres` container\nthe example starts with Podman itself. A second table exists in that same\ndatabase and is provably unreachable through the capability, and `CREATE TABLE`\nis done with `psql` because the query AST has no DDL constructor and no\n`rawSql` escape hatch — so schema changes are outside the effect by\nconstruction. Every rejection the demo mentions is stated in the module as a\ntheorem (`webCap.permits .POST healthUrl ≠ true := by decide`) rather than a\ncomment, since a program that fails to compile cannot be run. The last two\nsections cover the runtime side: `ScopedPath`/`ScopedUrl`/`ScopedQuery.check?`\nfor arguments only known at run time, and one `Eff` computation over a\nfour-effect row — no `IO` in it — run by a single handler that dispatches each\nrequest to that effect's own interpreter. `effects no-db` skips the container\nsections; without a reachable `podman` they are reported as skipped rather than\nfailed.\n\n### Running `postgrest` against a real database\n\n`lake exe examples postgrest` (no args) and `... postgrest spec` are fully\nself-contained — they run against a hand-built, in-memory `SchemaCache` and\nneed no external services. `postgrest live` instead connects to a real\nPostgreSQL instance, introspects its `public` schema with the same catalog\nqueries (`SchemaCache.tablesSql`/`columnsSql`) PostgREST itself runs at\nstartup, and serves a couple of requests against the real tables.\n\nStart a disposable local Postgres with Docker:\n\n```bash\ndocker run --rm -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres\n```\n\nThen, in another terminal:\n\n```bash\nlake exe examples postgrest live\n```\n\nThis connects with `host=localhost port=5432 user=postgres password=postgres\ndbname=postgres` — matching the container above — prints every table found in\n`public`, serves `GET /` and `GET /\u003Cfirst table>` through the same\n`App.handleRequest` code path as the in-memory demo, and prints the live\nschema's OpenAPI spec. Pass a different libpq connection string as the next\nargument to point at another instance or database, e.g.:\n\n```bash\nlake exe examples postgrest live \"host=localhost port=5432 user=postgres password=postgres dbname=mydb\"\n```\n\nIf nothing is listening, the example prints a short \"could not connect\" hint\n(with this same `docker run` command) and exits 1, rather than crashing.\n\n## Documentation\n\n- [docs/modules.md](docs/modules.md) — the full module feature list and module table.\n- [docs/imports/index.md](docs/imports/index.md) — Hackage-package import order, with a\n  per-package module dependency list under `docs/imports/\u003CPackage>/dependencies.md`.\n- [docs/linking.md](docs/linking.md) — how native libraries are linked: static vs\n  dynamic, PIC, and the C++ exception/unwinder hazard on Linux. Read before\n  adding an FFI dependency.\n- [docs/rfcs.md](docs/rfcs.md) — the specifications `linen` implements, mapped to\n  their modules; the foundational ones it rests on; and a few worth reading for\n  their own sake.\n- [CHANGELOG.md](CHANGELOG.md) — notable changes per released version.\n- [AGENTS.md](AGENTS.md) — conventions for contributing to the library.\n\n## License\n\nSee [LICENSE](LICENSE) for details.\n",1789154844680]