--- url: https://wvlet.org/uni/book.md --- # The Uni Book *A guided tour of Scala 3 application development with Uni.* This book teaches you to build real applications with [Uni](https://github.com/wvlet/uni) on Scala 3, across the JVM, Scala.js, and Scala Native. It is written for developers who already read Scala comfortably and want to understand not only *how* Uni works but *why* its pieces are shaped the way they are. The Book is narrative. It is meant to be read front to back at first, and used as a jumping-off point afterwards. The short-form API documentation under [Guide](/guide/) and the module references (e.g. [Core](/core/), [HTTP](/http/)) stay where they are, and the Book links into them when you need depth. ## How to read it * Work from Part I to the end of Part II in order. Everything that follows assumes the mental model built in those two parts. * Each part opens with a short intro page; each chapter ends with a *"what you have, what comes next"* recap. If the recap doesn't feel true yet, re-read the chapter before moving on. * Type the examples. Reading them is not the same exercise. ## Table of contents ### [Foreword](./foreword) ### Part I — Getting Started * [Chapter 1: Getting Started](./ch01-00-getting-started) * [1.1 Installation](./ch01-01-installation) * [1.2 Hello, Uni!](./ch01-02-hello-uni) ### Part II — Building a CLI Application * [Chapter 2: A URL Fetcher](./ch02-00-cli-app) ### Part III — Core Concepts * [Chapter 3: Wiring with Design](./ch03-00-design) * [Chapter 4: Testing with UniTest](./ch04-00-testing) * [Chapter 5: Logging That Finds You](./ch05-00-logging) * [Chapter 6: Data In, Data Out — JSON & MessagePack](./ch06-00-data) ### Part IV — Async & Control Flow * [Chapter 7: Rx, the Composable Stream](./ch07-00-rx) * [Chapter 8: Living With Failure — Retry, Circuit Breakers, Resources](./ch08-00-control) ### Part V — HTTP & RPC * [Chapter 9: HTTP Clients and Servers](./ch09-00-http) * [Chapter 10: Typed RPC](./ch10-00-rpc) ### Part VI — Cross-Platform Development * [Chapter 11: One Codebase, Three Runtimes](./ch11-00-cross-platform) ### Part VII — Scala.js in the JavaScript Ecosystem * [Chapter 12: Calling NPM Modules from Scala.js](./ch12-00-npm-facades) * [Chapter 13: Bundling with Vite](./ch13-00-vite) ### Part VIII — Scala Native and the C/Rust World * [Chapter 14: Calling C from Scala Native](./ch14-00-calling-c) * [Chapter 15: Exposing Scala Native to C and Rust](./ch15-00-exposing-native) ### Part IX — Capstone * [Chapter 16: A Bookmarks Service](./ch16-00-capstone) ### Appendices * [Appendix A: Scala 3 Syntax Notes for This Book](./appendix-a-scala3) * [Appendix B: Uni and Airframe — History and Relationship](./appendix-b-airframe) * [Appendix C: Glossary](./appendix-c-glossary) ## Status All parts are drafted, Foreword through the appendices. The book is best read front to back the first time; afterwards, use it as a jumping-off point into the [reference docs](/guide/). --- --- url: https://wvlet.org/uni/book/foreword.md --- # Foreword Scala 3 is a small, sharp language. The standard library is careful, the type system is expressive, and the compiler will happily tell you when your ideas do not fit together. Those are the good parts. The parts the standard library leaves to you are the ones every real application still has to answer: * How do my objects get wired together, and when are they cleaned up? * How do I structure logging so that when a request goes wrong, I find the one line that mattered? * How do I ship an HTTP client that retries the right errors, and no others? * How do I write one piece of business logic that runs in the JVM, in a browser, and in a compiled binary? **Uni** is the collection of small, opinionated libraries that Scala applications reach for to answer those questions. It is a distillation of code from the [Airframe](https://github.com/wvlet/airframe) project, refined for Scala 3 and for a future where Scala.js and Scala Native are first-class targets, not afterthoughts. This book is the long-form counterpart to Uni's reference docs. The reference answers *"what does this API do?"*. This book answers *"how do I build real applications with these pieces, and why are the pieces shaped this way?"*. By the end of it, you should be able to open an empty directory and sketch, in your head, the file layout and the dependency graph of a reasonable Scala 3 service — and have opinions about each choice. You will build two things as you read: 1. A small CLI application (Part II). 2. A single codebase that compiles to the JVM, to JavaScript, and to a native binary (Part VI). Along the way the book will explain, honestly, when Uni is the right tool and when a different tool would serve you better. No library earns trust by hiding its edges. Thank you for spending time with this. Let's start. — *The Uni team* [Next → Chapter 1: Getting Started](./ch01-00-getting-started) --- --- url: https://wvlet.org/uni/book/ch01-00-getting-started.md --- # 1. Getting Started Before you can write Uni code, your machine needs a JDK, an sbt that knows how to fetch Scala 3, and a project wired to pull Uni in. This part of the book gets you there, then writes enough of a program to prove everything is hooked up. Two chapters, in order: * [1.1 Installation](./ch01-01-installation) — prerequisites, a minimal `build.sbt`, and how to pull Uni into JVM-only, Scala.js, and Scala Native projects. * [1.2 Hello, Uni!](./ch01-02-hello-uni) — your first runnable Uni program. It is only a dozen lines, but by the end of it you will have met the two concepts that thread through the rest of the book: **logging** and **Design** (object wiring). By the end of Part I, a fresh clone of your project should compile and run. Part II then turns that starting point into a real command-line application. [← Foreword](./foreword) | [Next → 1.1 Installation](./ch01-01-installation) --- --- url: https://wvlet.org/uni/book/ch01-01-installation.md --- # 1.1 Installation Uni is a library, not a framework. You add it to a Scala 3 project with a single line in `build.sbt` and you are done. This chapter walks you through getting the tools, creating a minimal project, and confirming the setup. If you already have Scala 3 and sbt installed, jump to [Adding Uni to a project](#adding-uni-to-a-project). ## Prerequisites You need three things: | Tool | Minimum version | Why | |------|-----------------|-----| | JDK | 17 | Scala 3 targets modern JVMs. 17 is the LTS floor most of the ecosystem is on. | | sbt | 1.9 | The build tool. Anything older may not know about current Scala.js / Native plugins. | | Scala 3 | 3.9 or newer | Uni is compiled with Scala 3.9 (the current LTS), and an older compiler cannot read its TASTy. | A JDK 17+ and sbt 1.9+ will pull the right Scala 3 compiler on demand. ### Installing the JDK and sbt The single easiest path on any OS is [Coursier](https://get-coursier.io/): ```bash cs setup ``` That command installs a JDK, `sbt`, `scala`, and sets up your `PATH`. If you prefer native package managers: * **macOS:** `brew install sbt openjdk@21` * **Linux (Debian/Ubuntu):** install `sbt` from the [official APT repo](https://www.scala-sbt.org/download.html) and `openjdk-21-jdk` from your distribution. * **Windows:** use [Scoop](https://scoop.sh/) or the [sbt MSI installer](https://www.scala-sbt.org/download.html). Confirm both tools: ```bash $ java --version openjdk 21.0.4 2024-07-16 LTS $ sbt --version sbt script version: 1.9.8 ``` ## Adding Uni to a project Create a directory and drop two files in it. ``` hello-uni/ ├── build.sbt └── src/main/scala/Main.scala ``` `build.sbt`: ```scala val scala3Version = "3.9.0" ThisBuild / scalaVersion := scala3Version lazy val hello = project .in(file(".")) .settings( name := "hello-uni", libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" ) ``` `src/main/scala/Main.scala`: ```scala @main def main(): Unit = println("hello") ``` Run it: ```bash $ sbt run [info] running main hello ``` The first `sbt run` will download Scala 3 and Uni's transitive dependencies. Subsequent runs are fast. > **Why no "framework initialization" step?** Uni is deliberately a > library — a collection of small pieces you pull from. There is no > bootstrap ceremony, no annotation processor to wire up, no agent to > install. The moment sbt resolves the dependency, you can import and > use any of it. ## Cross-platform projects Most Uni code works unchanged on **JVM**, **Scala.js**, and **Scala Native**. On **sbt 2.x**, cross-build with Uni's own [sbt-uni-crossproject](/build/sbt-uni-crossproject) plugin (the portable-scala plugins are not published for sbt 2.x): ```scala // project/plugins.sbt addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.22.0") addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.5.12") addSbtPlugin("org.wvlet.uni" % "sbt-uni-crossproject" % "2026.2.0") ``` ```scala // build.sbt lazy val hello = crossProject(JVMPlatform, JSPlatform, NativePlatform) .crossType(CrossType.Pure) .in(file(".")) .settings( scalaVersion := "3.9.0", libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" ) ``` Two parts of that snippet are worth a moment. `.crossType(CrossType.Pure)` says *"all of this project's sources are shared across platforms"*. With `Pure`, your project looks like this on disk: ``` hello/ ├── build.sbt ├── .jvm/ ← JVM-specific code (rarely needed with Uni) ├── .js/ ← Scala.js-specific code (rarely needed with Uni) ├── .native/ ← Scala Native-specific code (rarely needed with Uni) └── src/ ├── main/scala/ ← shared code, compiled for all three platforms └── test/scala/ ← shared tests ``` The `.jvm`, `.js`, and `.native` directories are per-platform project roots. Each is a distinct sbt subproject with its own `target/`, and each is where **platform-specific** code goes when you need it: `.jvm/src/main/scala` is seen only by the JVM build, `.js/src/main/scala` only by the Scala.js build, and `.native/src/main/scala` only by the Scala Native build. The code everyone shares lives at the module root under `src/main/scala` and `src/test/scala`. > **With Uni, you rarely have to.** Uni's public API — `Design`, > `Logger`, `Http`, `Rx`, `JSON`, `MessagePack` — is the same on every > platform. Where a platform difference exists (filesystem access, > timers, threading), Uni exposes one abstraction that resolves to the > right implementation under the covers. For a typical Uni > application, *all* of your code can live in the shared > `src/main/scala`, and that is usually the whole story. The > `./src/main/scala` folders stay empty unless you reach for > a genuinely platform-only dependency — a JVM-only Java library, a > browser DOM API, a native syscall. You will see examples of that in > Chapter 11. On sbt 2.x the `%%` operator tells sbt: *pick the version of `uni` that was built for whichever platform I am compiling for right now* (it encodes the platform suffix, so the older `%%%` is no longer needed). Your Scala source does not change between platforms; only the build setting does. We will build a real cross-platform codebase in Chapter 11. For now know that it is one cross-plugin, one `CrossType.Pure`, and a `%%` away — and that everything you write goes in `src/main/scala`. ## IDE setup Uni uses only standard Scala 3 features, so any Scala 3-aware IDE works. The common choices: * **IntelliJ IDEA** with the Scala plugin. * **VS Code** with [Metals](https://scalameta.org/metals/). * **Neovim** with Metals. Open the project directory, let the IDE import the build, and you are done. ## What you have, what comes next You now have: * A JDK, sbt, and Scala 3 on your `PATH`. * A `build.sbt` that pulls Uni in as a dependency. * Proof that `sbt run` works on an empty program. The [next chapter](./ch01-02-hello-uni) replaces that `println` with actual Uni code — and in doing so meets the two ideas that thread through the rest of the book: **logging** and **object wiring**. [← 1. Getting Started](./ch01-00-getting-started) | [Next → 1.2 Hello, Uni!](./ch01-02-hello-uni) --- --- url: https://wvlet.org/uni/book/ch01-02-hello-uni.md --- # 1.2 Hello, Uni! With Uni on the classpath, the shortest useful program you can write is one that logs a line. That seems small, but it introduces two of Uni's core ideas — the **LogSupport trait** and **source-location capture** — and sets up the next step, where we let **Design** wire objects together for us. ## The smallest Uni program Replace `src/main/scala/Main.scala` from the previous chapter with: ```scala import wvlet.uni.log.LogSupport object Main extends LogSupport: def main(args: Array[String]): Unit = info("Hello, Uni!") ``` Run it: ```bash $ sbt run 2026-04-18 09:00:00.000-0700 info [Main] Hello, Uni! - (Main.scala:5) ``` Four things are worth pausing on. ### `LogSupport` is a trait, not a wrapper `LogSupport` mixes in two things: a `logger` bound to the enclosing class name, and methods (`info`, `warn`, `error`, `debug`, `trace`) that call it. You do not construct a `Logger`; you declare that this class *has* one. That is the whole of the logging API for day-to-day code. ### The logger name is the class name The output starts with `[Main]`. That is the simple name of the class that mixed in `LogSupport`. When you search logs later, the grep is on a string you can see right here in the source file. ### The source location is captured automatically The `(Main.scala:5)` at the end of the line is free. Uni captures it at compile time using Scala 3's `scala.quoted.Quotes` API, so there is no stack-walking cost at runtime. When a production incident makes you ask *"which line produced this?"*, the answer is already printed. ### Scala 3 syntax is the default No `new`, no `class Main { ... }` braces, no `extends App`. The Scala 3 indentation style is what Uni uses in its own code and what this book will use throughout. If you prefer braces, the compiler still accepts them — but the examples here will stay in the indented style. ## Adding a collaborator: wire it by hand A real program has more than one class. Let's add a `Greeter` and have `Main` use it. ```scala import wvlet.uni.log.LogSupport class Greeter extends LogSupport: def greet(name: String): Unit = info(s"Hello, ${name}!") object Main extends LogSupport: def main(args: Array[String]): Unit = val greeter = Greeter() greeter.greet("Uni") ``` Output: ``` info [Greeter] Hello, Uni! - (Main.scala:5) ``` Two things changed. The logger name shifted to `[Greeter]` (because the `info` call now happens inside the `Greeter` class), and `Main` now constructs the `Greeter` explicitly with `Greeter()`. In a three-line program, manual construction is fine. In a real application it is not: * Every caller needs to know how every callee is built. * When a collaborator grows a dependency ("now `Greeter` needs a `Config`"), every caller changes. * Swapping an implementation in a test means passing a different constructor argument in every call site. Uni offers a better tool. ## Letting Design do the wiring The same program, this time wired by `Design`: ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport class Greeter extends LogSupport: def greet(name: String): Unit = info(s"Hello, ${name}!") @main def main(): Unit = val design = Design.newDesign .bindSingleton[Greeter] design.build[Greeter] { greeter => greeter.greet("Uni") } ``` Run it again — same output, but now something structural has changed. * `Design.newDesign` gives you an empty, immutable wiring configuration. * `.bindSingleton[Greeter]` says *"when someone asks for a `Greeter`, build one and share it."* No instance is created yet. * `design.build[Greeter] { greeter => ... }` opens a **session**, builds the `Greeter` (this is the moment it is actually constructed), hands it to your block, and then shuts the session down when the block returns. Any resources attached to the session are released at that shutdown. You did not have to tell `Main` how `Greeter` is constructed. You did not have to thread a `Greeter` through intermediate functions. You asked for one, and you got one. ### Why this instead of `Greeter()`? Fair question — this is exactly the point. With three lines of code, `Greeter()` is less ceremony. What `Design` buys you shows up when: * `Greeter` gains a dependency (a `Config`, an `HttpClient`). You only update the `Design`, not every call site. * You want a different `Greeter` in tests (say, one that captures messages). You replace one line in a test-specific design. * You want to tie *shutdown behavior* to *construction* (close the HTTP pool when the session ends). Design has a hook for that. We will meet all three of those in Part III. For now, treat `Design.newDesign.bindSingleton[X].build[X] { x => ... }` as the shape your `main` methods will have from here on. ## What you have, what comes next You can now: * Print log lines from a Scala 3 program with source locations. * Construct one object, then three, using `Design` instead of by hand. * Read a Uni-idiomatic `main` method and recognize its shape. The [next chapter](./ch02-00-cli-app) takes these primitives and builds something you would actually run: a small command-line tool that fetches a URL and prints what it gets back. That single program will introduce argument parsing, HTTP, and the first failure modes Uni helps you handle. [← 1.1 Installation](./ch01-01-installation) | [Next → 2. A URL Fetcher](./ch02-00-cli-app) --- --- url: https://wvlet.org/uni/book/ch02-00-cli-app.md --- # 2. A URL Fetcher This chapter builds one complete program — a small command-line tool that fetches a URL, prints the status line, and optionally dumps the body. It is the first real Uni app we write, and the point is to meet four pieces together, in context: * **Launcher** — turn command-line arguments into a typed object. * **HttpClient** — make a request and inspect the response. * **Design** — wire the two together so they can be replaced independently. * **UniTest** — write a fast, dependency-free test. You will not learn everything about any of these in this chapter; Parts III–V take each one apart. What you will get is a working mental shape: *what goes where, and why*. ## What we are building A tool called `fetch` that behaves like this: ```bash $ fetch https://httpbin.org/get 200 OK (https://httpbin.org/get) $ fetch --show-body https://httpbin.org/get 200 OK (https://httpbin.org/get) { "args": {}, "headers": { ... }, ... } $ fetch Missing URL. Usage: fetch [--show-body] ``` Small, but it has the three pieces every real CLI has: it parses args, does I/O, and reports success or failure. ## Step 1: Parse arguments with Launcher Create `src/main/scala/Fetch.scala` and start with the argument shape: ```scala import wvlet.uni.cli.launcher.{Launcher, argument, option} case class FetchArgs( @option(prefix = "--show-body", description = "Print response body") showBody: Boolean = false, @argument(name = "url", description = "URL to fetch") url: String = "" ) @main def fetch(args: String*): Unit = val parsed = Launcher.execute[FetchArgs](args.toArray) if parsed == null then return // user requested --help; Launcher already printed it println(s"url='${parsed.url}', showBody=${parsed.showBody}") ``` Try it: ```bash $ sbt "runMain fetch --show-body https://example.com" url='https://example.com', showBody=true ``` Three things to notice. **`FetchArgs` is a plain case class.** The `@option` and `@argument` annotations are metadata; the class itself is data. This is a recurring Uni shape: configuration and input are ordinary Scala types, and a separate tool (`Launcher`) populates them. **Defaults live with the field.** `showBody = false` is how you say "this flag is optional". `url = ""` is a sentinel we will check below. **`Launcher.execute[FetchArgs](args)` does two things.** It parses, and it constructs — returning a `FetchArgs` ready to use. If you passed malformed flags, it prints help and exits; if the user passed `--help` (or invoked the program with no arguments, which is the default help trigger) `Launcher` prints the annotation-derived usage text and returns `null`. The `if parsed == null then return` line is how you let that help-message path out of your `main`. > **Why annotate the fields instead of calling a builder?** > The annotation form keeps the case class *the* source of truth for > what the CLI accepts. There is no second list to keep in sync, no > place for the "declared flag" and "consumed flag" to drift apart. ## Step 2: Fetch the URL Add a service that does the actual HTTP call. The service takes its `HttpSyncClient` as a constructor parameter instead of creating one inside — so whoever builds `UrlFetcher` decides how long the client lives: ```scala import wvlet.uni.http.{HttpSyncClient, Request} import wvlet.uni.log.LogSupport class UrlFetcher(client: HttpSyncClient) extends LogSupport: def fetch(url: String, showBody: Boolean): Unit = info(s"GET ${url}") val response = client.send(Request.get(url)) println(s"${response.status} (${url})") if showBody then println(response.contentAsString.getOrElse("")) ``` A few things to notice. `Http.client.newSyncClient` (which we will call in the next step) produces a client with sensible defaults: connection pooling, JSON content negotiation, and — importantly — a retry policy. If `httpbin.org` returns a 5xx or the TCP connection flakes, the client retries with exponential backoff before giving up. We lean on that in Chapter 8. `response.status` is a typed `HttpStatus` (not a number), so you can pattern-match on it without digging through strings. `response.contentAsString` returns `Option[String]` — some responses genuinely have no body (a `204 No Content`, for instance), and the type reflects that. We unwrap with `.getOrElse("")` at the print site. Because `UrlFetcher` no longer owns its client, we can tell `Design` to own it instead — and to close it cleanly when the session ends. ## Step 3: Wire it with Design Now connect the pieces in `main`: ```scala import wvlet.uni.cli.launcher.{Launcher, argument, option} import wvlet.uni.design.Design import wvlet.uni.http.{Http, HttpSyncClient, Request} import wvlet.uni.log.LogSupport case class FetchArgs( @option(prefix = "--show-body", description = "Print response body") showBody: Boolean = false, @argument(name = "url", description = "URL to fetch") url: String = "" ) class UrlFetcher(client: HttpSyncClient) extends LogSupport: def fetch(url: String, showBody: Boolean): Unit = info(s"GET ${url}") val response = client.send(Request.get(url)) println(s"${response.status} (${url})") if showBody then println(response.contentAsString.getOrElse("")) @main def fetch(args: String*): Unit = val parsed = Launcher.execute[FetchArgs](args.toArray) if parsed == null then return // --help was handled by Launcher if parsed.url.isEmpty then println("Missing URL. Usage: fetch [--show-body] ") sys.exit(1) val design = Design.newDesign .bindInstance[HttpSyncClient](Http.client.newSyncClient) .onShutdown(_.close()) .bindSingleton[UrlFetcher] design.build[UrlFetcher] { fetcher => fetcher.fetch(parsed.url, parsed.showBody) } ``` Run the real thing: ```bash $ sbt "runMain fetch https://httpbin.org/get" info [UrlFetcher] GET https://httpbin.org/get - (Fetch.scala:15) 200 OK (https://httpbin.org/get) ``` You now have the spine of every Uni application you will write: 1. **Parse** (`Launcher.execute`). 2. **Wire** (`Design.newDesign...`). 3. **Do** (`design.build[EntryPoint] { entry => ... }`). Everything else — more services, more wiring, more complex flows — slots into that spine. ## Why the extra ceremony? Right now you could inline `UrlFetcher` into `main` and save six lines. So what does the indirection buy? **Replaceability.** In the next step we will test this without actually hitting the network. That means swapping the *real* `UrlFetcher` for a stand-in. If `main` constructed `UrlFetcher` directly, the test would have to call `main` with monkey-patched globals. With `Design`, the swap is one line. **Lifecycle.** You saw a small example of this already: `.bindInstance[HttpSyncClient](...).onShutdown(_.close())` attaches the client's cleanup to the session `design.build` opens. When the block returns — whether normally or by throwing — the session shuts down and the client's `close()` runs. A real app might add a database connection, a server, and a scheduler, each with its own hook. One block controls when they all wind down. **Locality of wiring.** The entire dependency graph of your program is visible in one `Design.newDesign...` block. Growing from one service to ten does not scatter construction logic across the codebase. ## Step 4: A test, without the network Add `src/test/scala/FetchTest.scala`: ```scala import wvlet.uni.cli.launcher.Launcher import wvlet.uni.test.UniTest class FetchTest extends UniTest: test("parses --show-body and URL") { val args = Launcher.execute[FetchArgs](Array("--show-body", "https://example.com")) args.showBody shouldBe true args.url shouldBe "https://example.com" } test("defaults showBody to false") { val args = Launcher.execute[FetchArgs](Array("https://example.com")) args.showBody shouldBe false } test("treats missing URL as empty string") { val args = Launcher.execute[FetchArgs](Array.empty) args.url shouldBe "" } ``` Run it: ```bash $ sbt test [info] FetchTest: [info] - parses --show-body and URL [info] - defaults showBody to false [info] - treats missing URL as empty string ``` No network, no mocks, no fixtures. The arg-parsing layer is a pure function from `Array[String]` to `FetchArgs`, and Uni keeps it that way. For testing `UrlFetcher` itself *without* the network, we would replace its HTTP client with a stand-in via a test-only `Design`. We will do exactly that in Chapter 4 once we have met `Design`'s override mechanism. ## What you have, what comes next You have written a Scala 3 CLI tool end to end: * Typed CLI arguments with `@option` and `@argument`. * Real HTTP calls through `Http.client.newSyncClient`. * Object wiring and lifecycle through `Design.build`. * A test suite that runs in milliseconds and has no external dependencies. You have also met the shape every Uni program shares: **parse, wire, do, clean up**. The rest of the book takes each of those layers apart in depth. Next, [Part III](./ch03-00-design) goes back to the beginning and explains **Design** properly — why constructor wiring beats the alternatives, how singletons and sessions interact, and how to override bindings for tests and environments. [← 1.2 Hello, Uni!](./ch01-02-hello-uni) | [Next → 3. Wiring with Design](./ch03-00-design) --- --- url: https://wvlet.org/uni/book/ch03-00-design.md --- # 3. Wiring with Design Your app has a `UserService`, an `OrderService`, and a `ReportService`. All three need the same database connection. How do you get the connection to them — without making it a global, and without threading it by hand through every constructor at every call site? This is the question `Design` answers. You met it in Chapter 2 as the *wire* step; this chapter explains it properly. By the end you should be able to read an unfamiliar `Design.newDesign…` block and know exactly what it says. ## A first wiring Two services, one shared dependency: ```scala import wvlet.uni.design.Design class Database: def query(sql: String): Seq[String] = Seq("alice", "bob") class UserService(db: Database): def listUsers(): Seq[String] = db.query("select name from users") @main def main = val design = Design.newDesign .bindSingleton[Database] .bindSingleton[UserService] design.build[UserService] { users => println(users.listUsers()) } ``` ```bash $ sbt run List(alice, bob) ``` `UserService` takes its `Database` as a constructor parameter. It never constructs one, never looks one up — it just declares that it needs one. The wiring lives somewhere else entirely. ## Walking the code **Each class names its dependencies in its constructor.** `UserService(db: Database)` is a complete, honest statement of what the class needs to do its job. There is no hidden `Database.getInstance()` call buried three methods deep. If you can construct a `UserService`, you have everything it needs; if you can't, the compiler tells you which type is missing. **A `Design` is a plan, not a container.** `Design.newDesign` starts an empty plan. `bindSingleton[Database]` adds a line to it: "when something needs a `Database`, build one and share it." `bindSingleton[UserService]` adds another. A `Design` is an immutable value — every `bind…` call returns a new `Design`, so you can build them up, pass them around, and combine them without anyone mutating yours. **`build` turns the plan into objects.** `design.build[UserService] { … }` reads the plan, constructs the graph from the bottom up (the `Database` first, then the `UserService` that needs it), and hands you the root. When the block returns, the graph is torn down. ### Why not just pass it as a constructor argument yourself? You could. `UserService(Database())` works for two classes. The reason to reach for `Design` shows up at scale and under change: * **No globals.** A `Database` reachable through a global is reachable from anywhere, which means *anything* can depend on it without saying so. Dependencies you can't see are dependencies you can't test or replace. Constructor parameters keep the dependency graph honest. * **No service locator.** A `locator.get[Database]` hides the dependency from the type system — you discover a missing binding when the call runs, not when it compiles. `Design` resolves the graph from constructor *types*, so a missing piece is a wiring error you can find before shipping. * **One place to look.** The entire dependency graph of your program is one `Design.newDesign…` block. Growing from two services to twenty does not scatter `new` calls across the codebase. ## The four ways to bind `bindSingleton` is the common case, but you reach for different bindings depending on how the value is produced. ```scala import wvlet.uni.design.Design // 1. Build it for me, once, and share it. Design.newDesign.bindSingleton[Database] // 2. Use this exact object I already have. Design.newDesign.bindInstance[Database](Database()) // 3. This type is a trait — use this implementation for it. trait UserRepo class InMemoryUserRepo extends UserRepo Design.newDesign.bindImpl[UserRepo, InMemoryUserRepo] // 4. Build it with a function that itself needs dependencies. case class Config(url: String) Design.newDesign .bindInstance[Config](Config("jdbc:db")) .bindProvider[Config, Database] { config => Database() } ``` | Binding | Use it when | |---------|-------------| | `bindSingleton[A]` | `A` is a class Design can construct; you want one shared instance | | `bindInstance[A](v)` | you already hold the value (config, a pre-built client) | | `bindImpl[A, B]` | `A` is an interface and `B` is the implementation to use | | `bindProvider[D, A](d => a)` | building `A` needs other bound values | `bindImpl` is the seam that makes a program configurable: bind `UserRepo` to `InMemoryUserRepo` in development and to `PostgresUserRepo` in production, and nothing that *uses* `UserRepo` changes. See the full [binding reference](/core/design#binding-summary) for the complete set. ## Sessions and lifecycle `design.build[A] { … }` is shorthand for opening a **session**, building the graph inside it, and closing it when the block ends. A session is the lifetime of a set of wired objects. That lifetime is where cleanup hooks attach. Bind a value with an `onStart`/`onShutdown` hook and the session runs them at the edges: ```scala import wvlet.uni.design.Design class Server: def start(): Unit = println("listening") def stop(): Unit = println("stopped") val design = Design.newDesign .bindSingleton[Server] .onStart(_.start()) // when the session starts .onShutdown(_.stop()) // when the session ends — even on exception design.build[Server] { server => // server.start() has already run here println("serving requests") } // server.stop() has run by here ``` ```bash $ sbt run listening serving requests stopped ``` The shutdown hook runs whether the block returns normally or throws, so resources don't leak on the error path. Chapter 2 used the compact form of this — `.onShutdown(_.close())` on the HTTP client — and it is the same mechanism. For a type that is already `AutoCloseable`, Design can call `close()` for you; the [lifecycle reference](/core/design#lifecycle-management) lists every hook and the order they fire in. ```text design.build[App] { app => … } │ ├─ construct the graph (dependencies first) ├─ onStart hooks run │ ├──▶ your block runs (the body of build { }) │ ├─ onShutdown hooks run (even if the block threw) └─ session closed ``` When you need the session itself — to open short-lived **child sessions**, say, one per web request, while singletons live for the whole process — use `design.withSession { session => … }` instead of `build`. [Session management](/core/design#session-management) covers child sessions in depth. ## Overriding a design A `Design` is a value, and two designs combine with `+`. When both bind the same type, the one on the right wins. That single rule is the foundation of testing and per-environment configuration: ```scala // Production wiring, defined once. val appDesign = Design.newDesign .bindSingleton[Database] .bindSingleton[UserService] // A test swaps in a fake Database — everything else is unchanged. val testDesign = appDesign + Design.newDesign.bindInstance[Database](FakeDatabase()) testDesign.build[UserService] { users => // users is the real UserService, wired to FakeDatabase } ``` `UserService` does not know or care that its `Database` was replaced — it asked for a `Database`, and it got one. This is the override mechanism Chapter 4 builds on to test services without their real dependencies. See [Testing with Design](/core/design#testing) for the patterns. ## What you have, what comes next You can now read and write a `Design`: * Classes declare dependencies as **constructor parameters**; `Design` supplies them. * **`bindSingleton` / `bindInstance` / `bindImpl` / `bindProvider`** cover how a value is produced. * **`build`** opens a session, wires the graph, and tears it down; **`onStart` / `onShutdown`** hook the edges of that lifetime. * **`+`** overrides a design, which is how tests swap real dependencies for fakes. Next, [Chapter 4](./ch04-00-testing) puts that override seam to work immediately: now that you can wire a program, you can *test* it — swapping a real dependency for a fake without touching the code under test. [← 2. A URL Fetcher](./ch02-00-cli-app) | [Next → 4. Testing with UniTest](./ch04-00-testing) --- --- url: https://wvlet.org/uni/book/ch04-00-testing.md --- # 4. Testing with UniTest A service under test needs a database, a payment gateway, and the current time. The reflex is to mock all three. Uni pushes you the other way: run the *real* code, and substitute as narrowly as you can. This chapter is about writing tests that way — and why it produces tests you can trust. ## A first test Extend `UniTest`, declare cases with `test`, and assert with `shouldBe`: ```scala import wvlet.uni.test.UniTest class CalculatorTest extends UniTest: test("adds two numbers") { val result = 2 + 3 result shouldBe 5 } test("a list contains a value") { Seq("a", "b", "c") shouldContain "b" } ``` ```bash $ sbt test [info] CalculatorTest: [info] - adds two numbers [info] - a list contains a value ``` `test("name") { … }` is a case; the block is the body. There is no annotation, no separate runner to register. The assertion vocabulary is small and reads as English: `shouldBe`, `shouldNotBe`, `shouldContain`, and `shouldMatch { case … => }` for matching a shape rather than a value. The [UniTest reference](/core/unitest) has the full list. ## Substitute, don't mock The interesting question is the service with dependencies. You met the mechanism already, in [Chapter 3](./ch03-00-design): a `Design` is a value, and `+` overrides it. A test takes the real application wiring and swaps in exactly one piece. ```scala import wvlet.uni.design.Design import wvlet.uni.test.UniTest class UserServiceTest extends UniTest: // appDesign is the real production wiring from Chapter 3. addDesign(_ + appDesign + Design.newDesign.bindInstance[Database](FakeDatabase())) test("looks up a user by id") { (users: UserService) => users.findUser("123") shouldBe Some("Alice") } ``` `addDesign` adds bindings to the suite's Design. The test lists what it needs as the parameters of its body, and UniTest builds `users` from that Design, so the test never opens a session itself. `UserService` is the real class, running its real logic. Only the `Database` underneath it is a fake — an in-process stand-in with no network. Every other binding stays production. The test exercises the code that ships, not a hollowed-out copy of it. ## Why not mock? A mock encodes *your belief* about how a dependency behaves: "when I call `query`, it returns these rows." The test then checks your code against that belief. If your belief is wrong — the real database orders results differently, throws a different exception, paginates — the mock-based test passes anyway, and the bug ships. You tested the mock, not the system. Uni's stance is to keep the real objects and replace only what you must: the genuinely external edge (a network, a clock, a payment processor) with an in-process fake you control. Everything between your entry point and that edge is real, so the test catches the integration mistakes a mock would paper over. A fake `Database` that actually stores and returns rows tells you more than a mock that returns a canned list. This is why Uni ships no mocking framework and the guides steer you away from one. The tool you need is `Design` override, which you already have. ## One suite, three platforms Because `UniTest` is itself cross-platform, a test you write once runs under the JVM, Scala.js, and Scala Native — the same `sbt test` story as [Chapter 11](./ch11-00-cross-platform), now for your tests. A suite over shared logic verifies all three builds at once, so "compiles on Native" becomes "*passes* on Native" without a second test to write. ## Fast on purpose Notice what these tests don't do: spin up a container, open a socket, hit a real clock. A `Design`-substituted suite is in-process and dependency-free, which is why it finishes in well under a second. That speed is not a bonus — it is the point. A suite you can run on every save gets run on every save; a slow one gets run before lunch, if then. Keeping tests fast keeps them used, and the substitution approach is what keeps them fast. ## What you have, what comes next You can now test a Uni application the way it's meant to be tested: * **`extends UniTest`** with `test("…") { … }` and a small assertion vocabulary — `shouldBe`, `shouldContain`, `shouldMatch`. * **`Design` override (`+`)** substitutes one dependency and keeps the rest real — the alternative to mocking. * One suite runs on **all three platforms**, and stays **fast** because it's in-process. Testing comes this early in the book on purpose. With `Design` from [Chapter 3](./ch03-00-design) in one hand and `UniTest` in the other, you can now *prove* a service works — before you've even met logging. Every feature the rest of the book introduces is something you can immediately write a fast, dependency-free test for. Next, [Chapter 5](./ch05-00-logging) adds the other thing every service wants from the start: logging that tells you not just *what* happened but *where*. [← 3. Wiring with Design](./ch03-00-design) | [Next → 5. Logging That Finds You](./ch05-00-logging) --- --- url: https://wvlet.org/uni/book/ch05-00-logging.md --- # 5. Logging That Finds You A log line that reads `save failed` is almost useless if your codebase has twenty `save` methods. The first question you ask is always the same: *where did this come from?* This chapter is about a logger that answers that for you, for free. ## Logging in one line Mix in `LogSupport` and call a level method: ```scala import wvlet.uni.log.LogSupport class OrderService extends LogSupport: def placeOrder(id: String): Unit = info(s"Placing order ${id}") // ... do the work ... ``` ```bash $ sbt run 2024-01-15 10:30:45.123+0900 info [OrderService] Placing order A-100 - (OrderService.scala:5) ``` Look at the end of that line: `(OrderService.scala:5)`. The log tells you the exact file and line that produced it. You did not pass it; you did not configure it. That is the whole idea. ## Walking the code **`LogSupport` is a mixin.** Extending it gives the class `trace`, `debug`, `info`, `warn`, and `error` methods and a logger named after the class (`[OrderService]`). There is no `private val logger = LoggerFactory.getLogger(getClass)` line to copy-paste and get wrong. **The five levels are ordered.** From quietest to loudest: `trace`, `debug`, `info`, `warn`, `error`. You set a threshold and everything at or above it prints. The [levels reference](/core/logging#log-levels) has the full table. **The source location is captured at compile time.** `(file:line)` is not found by walking a stack trace at runtime — that would be slow and would break under inlining. Uni captures it with a Scala 3 macro when your code compiles, so it is exact and free. This is the "finds you" payoff: in a real incident, the location turns "something failed" into "*this line* failed," and you skip the search. ## You don't guard log calls In many logging frameworks you learn to write this, because building the message is expensive and you don't want to pay for it when `debug` is off: ```scala // The defensive pattern you do NOT need here: if logger.isDebugEnabled then logger.debug(s"State dump: ${expensiveSnapshot()}") ``` With Uni you write the obvious thing: ```scala debug(s"State dump: ${expensiveSnapshot()}") ``` The level methods are `inline` macros, so the argument is only evaluated when the level is enabled. If `debug` is off, `expensiveSnapshot()` never runs and there is no allocation — the call compiles down to nothing. The guard is built in, so the readable form is also the fast form. See [zero-overhead logging](/core/logging#zero-overhead-logging-with-scala-macros) for what the macro expands to. ## Errors carry their cause Pass the exception as a second argument and the stack trace rides along: ```scala import wvlet.uni.log.LogSupport class PaymentService extends LogSupport: def charge(amount: Int): Unit = try gateway.charge(amount) catch case e: Exception => error(s"Charge of ${amount} failed", e) // message + full stack trace throw e ``` The log keeps your message *and* the exception's stack trace together, so you see the human-readable context and the machine detail in one record. ## Why the message is a sentence, not a struct Some ecosystems push you toward structured logs — every line a bag of key/value fields, meant to be parsed by a machine. Uni's logger is deliberately *not* that. A log line here is a sentence written for a person reading it during an incident: prose, with the source location and any exception attached. That is a choice, not an omission. Uni's position is that logs are **developer context**, not your metrics or analytics pipeline. When you need machine-readable records — counters, traces, events to aggregate — emit them explicitly to a system built for it, and keep logs for the human who is paging through them at 2 a.m. Mixing the two jobs tends to serve neither well. ## Tuning what prints You usually leave the defaults alone, but two knobs cover most needs: ```scala import wvlet.uni.log.{Logger, LogLevel} Logger.setDefaultLogLevel(LogLevel.DEBUG) // global threshold Logger("OrderService").setLogLevel(LogLevel.TRACE) // one logger, louder ``` A class that mixes in `LogSupport` already has a logger named after it, so you can dial one noisy component up or down without touching the others. Outside a class, `Logger("name")` gives you a named logger directly. To send logs to a rotating file — on the JVM, Node.js, or Native — point a [`FileLogHandler`](/core/logging#writing-logs-to-a-file) at a path. ## What you have, what comes next Logging is now a one-line, zero-ceremony tool: * **`extends LogSupport`** gives any class `trace`/`debug`/`info`/`warn`/`error` and a logger named after it. * Every message carries its **`(file:line)`**, captured at compile time. * Level methods are **macros**, so unguarded `debug(...)` calls cost nothing when disabled. * Logs are **human context** by design; `error(msg, e)` keeps the cause attached. Next, [Chapter 6](./ch06-00-data) turns to data crossing your program's edges — parsing JSON, writing MessagePack, and deriving both from your case classes with one line. [← 4. Testing with UniTest](./ch04-00-testing) | [Next → 6. Data In, Data Out](./ch06-00-data) --- --- url: https://wvlet.org/uni/book/ch06-00-data.md --- # 6. Data In, Data Out — JSON & MessagePack Every service eats and produces data. A request arrives as a JSON body; a cache stores a MessagePack frame; a config file is a blob of text. This chapter is about the boundary where bytes become Scala values and back — and how Uni crosses it without per-type boilerplate. There are two situations, and Uni has a tool for each: * You **don't** know (or control) the shape — a third-party response, a config blob. Parse it into a JSON tree and navigate. * You **do** own the shape — it's your case class. Derive a codec once and round-trip it to JSON *or* MessagePack. ## When you don't own the shape: parse and navigate `JSON.parse` turns text into a navigable tree: ```scala import wvlet.uni.json.* val doc = JSON.parse(""" { "user": { "id": 123, "name": "Alice" }, "posts": [ { "title": "Hello" }, { "title": "World" } ] } """) val name = doc("user")("name").toStringValue // "Alice" val id = doc("user")("id").toLongValue // 123 val first = doc("posts")(0)("title").toStringValue // "Hello" ``` You index into objects with `(key)` and arrays with `(index)`, then read a leaf with a typed accessor like `toStringValue` or `toLongValue`. When a path might be missing, navigate with `/` and pattern-match or use `Option` instead of asserting it exists. The [JSON reference](/core/json) covers the full DSL, including building and mutating trees. This is the right tool for *loosely* structured data. But when the shape is yours, threading `("user")("name")` through your code throws away the types you already have. ## When you own the shape: derive a codec Define the data as case classes and add `derives Weaver`: ```scala import wvlet.uni.weaver.Weaver case class User(id: Long, name: String) derives Weaver val alice = User(123, "Alice") val json = Weaver.toJson(alice) // {"id":123,"name":"Alice"} val back = Weaver.fromJson[User](json) // User(123, Alice) ``` ```bash $ sbt run {"id":123,"name":"Alice"} User(123,Alice) ``` `derives Weaver` asks the compiler to build a serializer for `User` from its structure. No annotations on each field, no hand-written `toJson`/`fromJson`, no companion-object ceremony. Nested case classes, collections, `Option`, enums, and sealed traits all derive the same way — see the [Weaver reference](/core/weaver) for the full type list. ## The same type, as binary Here is the part that pays off: the *same* `Weaver[User]` also speaks MessagePack, a compact binary encoding. You don't define a second codec — you call a different method: ```scala // Continues the User from above. val bytes: Array[Byte] = Weaver.weave(alice) // MessagePack val user = Weaver.unweave[User](bytes) ``` Reach for MessagePack when the bytes matter: a cache entry, a queue message, an internal RPC payload. It is smaller and faster to parse than JSON, and it is binary-safe. Reach for JSON when a human or a browser is on the other end. Either way, your *type* is the same; only the format at the edge changes. ## Why one codec for two formats It would be easy to ship a JSON library and a separate MessagePack library, each with its own derivation. Uni deliberately does not. The insight is that **the wire format is a boundary decision, not a modeling decision.** `User` is `User` whether it travels as text or as bytes — so you describe it once, and choose the encoding where the data actually leaves your program. That keeps the choice cheap. Storing sessions in Redis and decide MessagePack is leaner? Change `toJson` to `weave` at that one boundary; `User` does not move. A reader does not learn two derivation systems, and the two formats cannot drift apart, because they are the same `Weaver`. ::: tip Cross-platform, by construction `derives Weaver` resolves at **compile time** — no runtime reflection. That is what lets the identical codec run on the JVM, in the browser (Scala.js), and as a native binary. A reflection-based serializer would not survive the trip to Scala.js or Native; a derived one does. We return to this theme in [Chapter 11](./ch11-00-cross-platform). ::: ## What you have, what comes next You can now move data across your program's edges: * **`JSON.parse`** for data whose shape you don't own — navigate a tree with `(key)` / `(index)` and typed accessors. * **`derives Weaver`** for data you do own — one derivation, no per-field boilerplate. * **`Weaver.toJson` / `fromJson`** for text, **`Weaver.weave` / `unweave`** for MessagePack — same codec, format chosen at the boundary. * Derivation is compile-time, so the codec is cross-platform. That closes Part III: you can wire a program ([Design](./ch03-00-design)), see what it does ([Logging](./ch05-00-logging)), and move data through it. Next, [Part IV](./ch07-00-rx) makes those services *react* — `Rx`, Uni's composable stream, for values that change over time. [← 5. Logging That Finds You](./ch05-00-logging) | [Next → 7. Rx, the Composable Stream](./ch07-00-rx) --- --- url: https://wvlet.org/uni/book/ch07-00-rx.md --- # 7. Rx, the Composable Stream Two things in your program refuse to sit still. An async HTTP call does not return a `Response` — it returns one *later*. A configuration value or a UI field changes *while the app runs*. Both are "a value that isn't simply here right now," and Uni models both with one type: `Rx`. This chapter is about that type and the handful of operators that make it compose. ## A value that changes The simplest `Rx` is a variable you can watch: ```scala import wvlet.uni.rx.Rx val count = Rx.variable(0) count.subscribe { v => println(s"count is now ${v}") } count := 1 count := 2 ``` ```bash $ sbt run count is now 0 count is now 1 count is now 2 ``` `subscribe` runs your function once with the current value and again on every change. `:=` sets a new value. You are not polling and you are not wiring callbacks by hand — you describe what should happen when the value changes, and `Rx` makes it happen. ## Walking the code **`Rx[A]` is a description, not a result.** An `Rx[A]` says "this will produce zero or more `A` values over time." It does nothing until someone *runs* it — `subscribe` (react to every value) or `run` (run an effect) or `await` (block for the value, JVM only). Nothing fires until then, which means you can build an `Rx` pipeline freely and pay only when you attach a consumer. **`subscribe` hands you a `Cancelable`.** Watching a stream is a resource: it keeps a subscription alive. The return value is a `Cancelable` you call when you're done. This is the one piece of bookkeeping `Rx` asks of you — hold the handle, cancel it when the work that needed it ends. ```scala val sub = count.subscribe(v => println(v)) // ... later, when you no longer care ... sub.cancel ``` ## Composing without unwrapping The point of `Rx` is that you transform the *stream*, not the values one at a time. The operators look exactly like the ones on `Option` and `List`, because they mean the same thing: ```scala import wvlet.uni.rx.Rx val count = Rx.variable(0) val label: Rx[String] = count .filter(_ % 2 == 0) // keep even values .map(n => s"even: ${n}") // turn each into a label label.subscribe(println) count := 1 // filtered out — nothing prints count := 2 // prints: even: 2 ``` `map` transforms each value, `filter` drops the ones you don't want, and `flatMap` lets one stream depend on another (run a second `Rx` for each value of the first). You build a pipeline once; every value that flows through `count` takes the whole path. The [operators reference](/rx/operators) lists the full set, including `zip` to combine streams and `recover` to handle errors. ## Where Rx shows up: async results Back in Chapter 2 the *synchronous* client returned an `HttpResponse` directly. The async client returns the value-over-time version of exactly that: ```scala import wvlet.uni.http.{Http, Request} import wvlet.uni.rx.Rx val client = Http.client.newAsyncClient val title: Rx[String] = client .send(Request.get("https://example.com")) // Rx[HttpResponse] .map(_.status.toString) // Rx[String] title.subscribe(println) ``` The HTTP response is "a value that isn't here yet," so the async client gives you an `Rx[HttpResponse]`. You compose it with the same `map` you used on the counter — there is no separate callback API, no second mental model for "async" versus "reactive." One type covers both, which is why `Rx` is the backbone of async code across Uni: HTTP, WebSockets, and server-sent events all surface as `Rx`. ## Why Rx instead of Future or callbacks A `Future` starts running the moment you create it and can only ever deliver one value. A callback delivers many values but composes badly — nest two and you have a pyramid. `Rx` is chosen to avoid both traps: * **Lazy.** Building an `Rx` runs nothing. You assemble the pipeline, then decide when (and whether) to start it. A `Future` has already left the gate. * **One-shot *and* streaming.** The same type and operators serve a single async result and an endless event stream. You learn one thing. * **Cancellable.** `subscribe`/`run` return a `Cancelable`, so a stream you no longer need stops cleanly — no leaked timer, no listener firing into a dead component. * **Cross-platform.** `Rx` runs the same on the JVM, in the browser, and on Native, so async code moves between platforms unchanged. That cancellation handle is also how `Rx` cooperates with [Design](./ch03-00-design): give a session ownership of a subscription and closing the session cancels it, so streams wind down with the objects that created them. The [concurrency reference](/rx/concurrency) covers the threading and cancellation model in depth. ## What you have, what comes next You can now describe values that change and results that arrive later with one tool: * **`Rx[A]`** is a lazy description of zero or more `A` over time; nothing runs until you `subscribe`/`run`/`await`. * **`Rx.variable` + `:=`** is a value you can watch; **`map` / `filter` / `flatMap`** compose the stream. * **`subscribe` returns a `Cancelable`** — hold it, cancel it when done. * The **async HTTP client** returns `Rx[HttpResponse]`, so async and reactive code share one model. Next, [Chapter 8](./ch08-00-control) is about what happens when those calls *fail* — retries, circuit breakers, and resource lifetimes that clean up after themselves. [← 6. Data In, Data Out](./ch06-00-data) | [Next → 8. Living With Failure](./ch08-00-control) --- --- url: https://wvlet.org/uni/book/ch08-00-control.md --- # 8. Living With Failure — Retry, Circuit Breakers, Resources A call across a network will fail. Not *if* — *when*. The interesting question is what you do about it, and there are three different answers depending on the failure: * It was a blip — the packet dropped, the server hiccuped. **Retry it.** * The backend is genuinely down — every call is failing. **Stop hammering it.** * The call failed and left a connection open. **Clean it up anyway.** Uni gives you one primitive for each: `Retry`, `CircuitBreaker`, and `Control.withResource`. ## Retry a transient failure Wrap the flaky call in a retry policy and `run` it: ```scala import wvlet.uni.control.Retry val result = Retry .withBackOff(maxRetry = 3) .run { callFlakyService() // runs up to 4 times: 1 try + 3 retries } ``` `withBackOff` waits longer between each attempt — a tenth of a second, then more, then more — instead of retrying in a tight loop. That spacing matters: a service that just hiccuped needs a moment, and a hundred clients retrying in lockstep would knock it over again the instant it recovers. For that lockstep problem specifically, `Retry.withJitter()` randomizes the delays so clients don't synchronize. If every attempt fails, the policy gives up by throwing `MaxRetryException`. The [retry reference](/control/retry) covers tuning the intervals and choosing *which* errors to retry. ### Why you can't retry everything Retry has a precondition that is easy to miss: the operation must be **idempotent** — safe to run more than once. Reading a URL is idempotent; running it twice returns the same page. `POST /charge-card` is *not* — run it twice and you've billed the customer twice. Before you wrap a call in `Retry`, ask: if this runs twice, is the world the same as if it ran once? If not, retrying turns a transient failure into a correctness bug. Make the call idempotent first (an idempotency key, an upsert), *then* retry it. ## Stop calling a backend that's down Retry handles a blip. It is exactly the wrong tool when a backend is *actually* down: now every request retries four times before failing, so you've quadrupled the load on a service that's already on the floor, and every caller waits through the full backoff to get an error it could have had instantly. A `CircuitBreaker` watches the failure rate and, once it crosses a threshold, "opens" — failing calls instantly without touching the backend at all: ```scala import wvlet.uni.control.{CircuitBreaker, CircuitBreakerOpenException} val breaker = CircuitBreaker.withConsecutiveFailures(5) try breaker.run { callBackend() } catch case e: CircuitBreakerOpenException => // fail fast — the breaker is open, we didn't even try useFallback() ``` It runs a small state machine: **closed** (calls pass through), **open** (calls fail instantly), and **half-open** (after a cooldown, it lets one trial call through to see if the backend recovered). The point is to *fail fast* while a dependency is down — protecting both the caller, who gets an immediate answer, and the backend, which gets room to recover instead of a retry storm. `withConsecutiveFailures(5)` trips after five failures in a row; `withFailureThreshold` trips on a failure *rate*. See the [circuit breaker reference](/control/circuit-breaker) for the states and recovery policy. ## Clean up no matter what Both tools above can fail the call. When they do, anything the call opened — a file, a socket, a connection — still needs to close. `Control.withResource` guarantees it: ```scala import wvlet.uni.control.Control Control.withResource(openConnection()) { conn => conn.query("select 1") } // conn.close() runs here — even if query threw ``` This is the loan pattern: `withResource` lends you the resource for the duration of the block and closes it when the block exits, on the normal path *and* the exception path. You can't forget the `close()`, because you never wrote it. If that mechanism feels familiar, it should — it is the same guarantee `Design`'s `onShutdown` gives a whole session ([Chapter 3](./ch03-00-design)). `Control.withResource` is the local, block-scoped version; `Design` is the application-scoped version. Reach for `Control.withResource` when a resource lives for one operation, and for a `Design` lifecycle hook when it lives for the program. ## Putting them together A hardened call to a flaky dependency uses all three at once: a `Control.withResource` for the connection, a `CircuitBreaker` to fail fast when the dependency is down, and `Retry` to ride out the blips that get through: ```scala import wvlet.uni.control.{CircuitBreaker, Control, Retry} val breaker = CircuitBreaker.withConsecutiveFailures(5) def fetch(url: String): String = breaker.run { Retry.withBackOff(maxRetry = 3).run { Control.withResource(openConnection()) { conn => conn.get(url) } } } ``` Read it from the inside out: the resource is always cleaned up, retries absorb transient failures, and the breaker stops the whole thing from piling onto a backend that's already down. Each layer does one job, and they compose because each is an ordinary value wrapping an ordinary block. ## What you have, what comes next You can now write code that survives the network: * **`Retry.withBackOff(...).run { }`** absorbs transient failures — *only for idempotent operations*. * **`CircuitBreaker.run { }`** fails fast when a backend is down, so you stop making it worse. * **`Control.withResource(r) { }`** closes resources on every path, the block-scoped cousin of `Design`'s `onShutdown`. That closes Part IV: your services can react ([Rx](./ch07-00-rx)) and recover (this chapter). Next, [Part V](./ch09-00-http) puts them on the network for real — building HTTP clients and servers, then typed RPC on top. [← 7. Rx, the Composable Stream](./ch07-00-rx) | [Next → 9. HTTP Clients and Servers](./ch09-00-http) --- --- url: https://wvlet.org/uni/book/ch09-00-http.md --- # 9. HTTP Clients and Servers Chapter 2 made a single HTTP call to get a CLI tool working. This chapter takes HTTP seriously from both sides: the **client** that calls out, and the **server** that answers. The two share a request/response model, so once you know one, the other reads naturally. ## The client, synchronous first The simplest client blocks until the response arrives: ```scala import wvlet.uni.http.{Http, Request} val client = Http.client.newSyncClient val response = client.send(Request.get("https://httpbin.org/get")) println(response.status) // 200 OK println(response.contentAsString.getOrElse("")) // the body ``` `Request.get(url)` builds a request; `client.send` runs it and returns an `HttpResponse`. `response.status` is a typed `HttpStatus`, and `response.contentAsString` is an `Option[String]` because some responses have no body. You build other verbs the same way — `Request.post(url)`, then `.withJsonContent("""{"name":"Alice"}""")` to attach a body. Start with the sync client. It is the easy thing to reason about: one call, one result, top to bottom. Reach for async only when you need concurrency. ## The client, asynchronously The async client returns the value-over-time version of the response — an `Rx[HttpResponse]`, exactly the shape from [Chapter 7](./ch07-00-rx): ```scala import wvlet.uni.http.{Http, Request} val client = Http.client.newAsyncClient client .send(Request.get("https://httpbin.org/get")) .map(_.contentAsString.getOrElse("")) .subscribe(println) ``` Because the result is an `Rx`, you compose it with `map` and `subscribe` instead of blocking. The same operators you learned for streams work here — async HTTP is not a separate world. Both clients come configured with sensible defaults, including the retry policy from [Chapter 8](./ch08-00-control). Tune them with `withXxx` setters before creating the client: ```scala val client = Http.client .withConnectTimeoutMillis(5000) .withMaxRetry(3) .newSyncClient ``` ## The server A server answers requests. At its simplest, a handler is a function from `Request` to a response — and that form runs on **every** platform: ```scala import wvlet.uni.http.{Request, Response} import wvlet.uni.http.Http import wvlet.uni.rx.Rx Http .server .withPort(8080) .withRxHandler { (request: Request) => Rx.single(Response.ok(s"You asked for ${request.path}")) } .start { server => println(s"listening on ${server.localPort}") } ``` `start { server => … }` runs the server for the duration of the block and shuts it down cleanly when the block ends — the same lifecycle shape as `Design.build`. The same code runs on Scala.js and Native: `Http.server` picks Node.js or the native socket server there. ## Routing without a switch statement A real API has many endpoints, and you don't want one giant `match` on `request.path`. On the JVM, annotate the methods of a controller and let the router dispatch: ```scala import wvlet.uni.http.HttpMethod import wvlet.uni.http.router.{Endpoint, Router} import wvlet.uni.http.Http import wvlet.uni.http.netty.RouterHandler class UserController: @Endpoint(HttpMethod.GET, "/users/:id") def getUser(id: String): String = s"""{"id":"${id}"}""" @Endpoint(HttpMethod.GET, "/users") def listUsers(): Seq[String] = Seq("alice", "bob") val router = Router.of[UserController] Http .server .withPort(8080) .withRxHandler(RouterHandler(router)) .start { _ => /* serve */ } ``` `Router.of[UserController]` reads the annotations at compile time and builds the route table; path parameters like `:id` bind to method parameters by name, and a returned `Seq` or case class is serialized to JSON for you (via the [Weaver](./ch06-00-data) machinery from Chapter 6). The [server reference](/http/server) covers query parameters, filters, and combining controllers. ::: tip JVM-only routing The annotation router (`@Endpoint`, `Router.of`, `RouterHandler`) is a JVM/Netty feature. On Scala.js / Native, route inside a functional `withRxHandler` by matching on `request.path`. The server *itself* runs on all three platforms; only the annotation-based routing is JVM-only. ::: ## One client, three platforms The client code at the top of this chapter compiles and runs unchanged on the JVM, in the browser and Node.js (Scala.js), and as a native binary — because `Http.client` resolves to the right transport for each runtime (`java.net.http`, the Fetch API, or libcurl). You write the request once. The one constraint worth knowing: browsers have no synchronous HTTP, so in browser code use `newAsyncClient`. [Chapter 11](./ch11-00-cross-platform) is about this property in general; the [client reference](/http/client) has the per-platform backend table. For responses too large to hold in memory, or for a server pushing updates to a client, see [streaming and server-sent events](/http/sse). ## What you have, what comes next You can now build both ends of an HTTP exchange: * **`Http.client.newSyncClient`** for blocking calls, **`newAsyncClient`** for `Rx[HttpResponse]`. * A **server** from a functional handler (every platform) or an **annotation router** (`@Endpoint` + `Router.of`, JVM). * The same client source runs on JVM, Scala.js, and Native. Next, [Chapter 10](./ch10-00-rpc) removes the hand-written URLs and JSON entirely: define a trait once and get a typed client and server that speak it. [← 8. Living With Failure](./ch08-00-control) | [Next → 10. Typed RPC](./ch10-00-rpc) --- --- url: https://wvlet.org/uni/book/ch10-00-rpc.md --- # 10. Typed RPC In Chapter 9 both ends of the call wrote out the contract by hand: the server picked the path `/users/:id` and shaped the JSON; the client typed the same path and parsed the same JSON back. Nothing connects those two copies. Rename a field on the server and the client keeps compiling — and breaks at runtime, in production, against the one response you didn't test. RPC closes that gap. You write the contract *once*, as a Scala trait, and both sides are checked against it by the compiler. ## Define the contract once The API is an ordinary trait. The server implements it; the client will call it. ```scala case class User(id: Long, name: String, email: String) derives Weaver trait UserService: def getUser(id: Long): User def createUser(name: String, email: String): User class UserServiceImpl extends UserService: def getUser(id: Long): User = User(id, "Alice", "alice@example.com") def createUser(name: String, email: String): User = User(1L, name, email) ``` There is no annotation on the methods, no per-endpoint glue. `getUser` is a normal method; RPC will turn it into a network call without you describing the wire shape. ## Serve it `RPCRouter.of[UserService]` reads the trait at compile time and builds the routes; `RPCHandler` turns that router into something a server can run: ```scala import wvlet.uni.http.rpc.RPCRouter import wvlet.uni.http.Http import wvlet.uni.http.netty.RPCHandler val router = RPCRouter.of[UserService](UserServiceImpl()) Http .server .withPort(8080) .withRxHandler(RPCHandler(router)) .start { _ => /* serving */ } ``` Each method becomes a `POST /UserService/{methodName}` endpoint. You never chose those paths — they fall out of the trait, which is the point: there is no path for the client and server to disagree about. ```text trait UserService ← the one contract ╱ ╲ RPCRouter.of[T](impl) generated client (server side) (caller side) ╲ ╱ POST /UserService/getUser (MessagePack on the wire) ``` ## Call it like a local method On the client side, the `sbt-uni` plugin generates a typed client from the *same* trait (see [client generation](/http/rpc#generating-a-client) for the build setup). Calling a remote method then looks like calling a local one: ```scala import wvlet.uni.http.Http import com.example.client.UserServiceClient val client = UserServiceClient.SyncClient( Http.client.withBaseUri("http://localhost:8080").newSyncClient ) val user: User = client.getUser(42) // a network round-trip, fully typed ``` `client.getUser(42)` is checked by the compiler against `UserService`. Pass a `String` where the trait wants a `Long`, or rename `getUser` on the server, and the *client* stops compiling — the failure moves from a 2 a.m. production page to your build. That is the entire value proposition: the contract is one artifact, and a violation is a compile error. ## What crosses the wire Arguments and return values are serialized with [Weaver](./ch06-00-data), the same derivation you met in Chapter 6 — which is why `User` has `derives Weaver`. Over the wire RPC uses MessagePack by default: it is compact and fast, and since both ends were generated from one trait, there is no human reading the bytes who would prefer JSON. The encoding is an internal detail you mostly never see. Errors cross the boundary as data too. When the server throws, the client sees a `ServiceException` carrying a structured `ServiceStatus` — a typed code like `NOT_FOUND` or `INVALID_ARGUMENT` — rather than a bare HTTP number you have to interpret. The [RPC reference](/http/rpc#rpc-status-codes) lists the status categories. ## When RPC, when REST RPC is the right tool when **you own both ends** — two of your own services, or your frontend and backend, evolving together. The shared trait is a feature: it keeps them in lockstep. It is the *wrong* tool when the other end is not yours to recompile. A public API consumed by third parties, a webhook, anything that must speak a stable, language-neutral contract — that wants plain [HTTP/REST](./ch09-00-http), where the wire format *is* the interface and no client needs your trait. Use RPC inside your system; use REST at its public edge. ## What you have, what comes next You can now connect two services without hand-written glue: * **A trait is the contract** — implemented on the server, generated into a client, checked by the compiler on both sides. * **`RPCRouter.of[T](impl)` + `RPCHandler`** serves it; **`sbt-uni`** generates the typed client. * Payloads ride **Weaver/MessagePack**; errors arrive as typed **`ServiceStatus`**. * Reach for RPC when you own both ends, REST at the public edge. That closes Part V. Next, [Part VI](./ch11-00-cross-platform) steps back to the property that has been quietly true this whole time: nearly everything you've written runs on three different runtimes from one codebase. [← 9. HTTP Clients and Servers](./ch09-00-http) | [Next → 11. One Codebase, Three Runtimes](./ch11-00-cross-platform) --- --- url: https://wvlet.org/uni/book/ch11-00-cross-platform.md --- # 11. One Codebase, Three Runtimes Here is something that has been quietly true for the whole book: almost every snippet you've written — `Design`, `Rx`, `Weaver`, the HTTP client — already runs on the JVM, in the browser through Scala.js, and as a native binary through Scala Native. You didn't do anything special to make that happen. This chapter explains *how*, and what to do for the handful of things that genuinely can't be shared. ## One build, three targets A cross-platform module is declared once with `crossProject`: ```scala // build.sbt import sbtcrossproject.CrossPlugin.autoImport.{crossProject, CrossType} lazy val app = crossProject(JVMPlatform, JSPlatform, NativePlatform) .crossType(CrossType.Pure) .settings( libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" ) ``` That one declaration produces three projects — `appJVM`, `appJS`, `appNative`. On sbt 2.x the familiar `%%` operator already encodes the platform: it pulls in the build of `uni` that matches each target (`_sjs1` for Scala.js, `_native0.5` for Native). (On sbt 1.x you would write `%%%` instead.) `sbt appJVM/run`, `sbt appJS/fastLinkJS`, and `sbt appNative/run` build the same source three ways. ## Where code lives `CrossType.Pure` gives each module these source roots: ``` app/ src/main/scala/ # shared — compiled for all three platforms .jvm/src/main/scala/ # JVM-only .js/src/main/scala/ # Scala.js-only .native/src/main/scala/ # Native-only ``` The vast majority of your code goes in the shared `src/` and is compiled three times. The `.jvm` / `.js` / `.native` folders hold only the code that *must* differ per platform. If you never need them, you never create them — and most application logic never does. ```text src/main/scala/ ← shared logic, compiled 3× │ ┌────────────────┼────────────────┐ + .jvm/ + .js/ + .native/ ← platform-only code ▼ ▼ ▼ JVM Scala.js Scala Native (Netty, JDK) (browser, Node) (native binary) ``` ## Why most code doesn't care The reason the shared folder stays large is that Uni already wraps the platform-specific pieces behind cross-platform APIs: * File I/O goes through the [FileSystem](/core/filesystem) abstraction (`IOPath`), not `java.nio.file.Path` — so reading a file is the same call everywhere. * The [HTTP client](./ch09-00-http) resolves to `java.net.http`, the Fetch API, or libcurl depending on the runtime, behind one `Http.client`. * `Rx`, `Design`, and `Weaver` are pure Scala with no platform assumptions. Because your business logic talks to these abstractions instead of to JDK classes directly, it lands in the shared folder and compiles everywhere unchanged. That is the whole trick: depend on the abstraction, and the platform detail is someone else's problem. ## Isolating what you truly can't share Sometimes you need a real platform primitive — a JVM library with no JS equivalent, a browser DOM call, a native syscall. The pattern is to declare a small shared interface and put one implementation in each platform folder: ```scala // src/main/scala — shared: the shape everyone agrees on trait Clock: def nowMillis(): Long // .jvm/src/main/scala — the JVM implementation object PlatformClock extends Clock: def nowMillis(): Long = System.currentTimeMillis() ``` Each platform folder supplies its own `PlatformClock`; the shared code only ever sees the `Clock` interface. The seam is exactly the one from [Chapter 3](./ch03-00-design) — program against an interface, bind the implementation elsewhere — applied to platforms instead of test doubles. The payoff is that the gap is caught at **compile time**: if a platform is missing its implementation, that platform's build fails. You don't discover a missing piece when a user in a browser hits it; you discover it when `appJS` won't compile. The type system, not a test matrix, keeps the three builds honest. ::: tip A few things are inherently platform-bound Browsers have no synchronous HTTP and no filesystem; native binaries have no DOM. Uni surfaces these honestly — for example, the sync HTTP client throws in the browser rather than pretending. When a capability only exists on one platform, keep the code that uses it in that platform's folder. ::: ## Reaching into a platform's ecosystem A platform folder isn't only for the JDK or a syscall — it's the door to that runtime's whole *foreign* ecosystem. The `.js` folder is where you call JavaScript packages from npm; the `.native` folder is where you call C, C++, and Rust. Both use the same idea as the `Clock` above — a typed Scala declaration of the foreign code you use, kept in the platform folder that has it — and each gets a dedicated Part later in this book: * **[Part VII](./ch12-00-npm-facades)** — wiring Scala.js to npm modules with hand-written facades, bundled by Vite. * **[Part VIII](./ch14-00-calling-c)** — calling C libraries from Scala Native, and exposing your Scala Native code *as* a library that C, C++, and Rust can call. So the shared folder holds your portable logic, and each platform folder can reach as deep into that platform's native world as you need — without either concern leaking into the other. ## What you have, what comes next You can now ship one codebase to three runtimes: * **`crossProject(JVMPlatform, JSPlatform, NativePlatform)`** with `%%` dependencies builds the same source three ways. * Shared code lives in **`src/`**; only genuinely platform-specific code goes in **`.jvm` / `.js` / `.native`**. * Uni's abstractions (FileSystem, HTTP, Rx, Design, Weaver) keep most code in the shared folder. * Unshareable primitives hide behind a **shared interface with a per-platform implementation**, and missing platforms fail at compile time. * Each platform folder is also the door to that runtime's ecosystem — npm ([Part VII](./ch12-00-npm-facades)) from `.js`, C/Rust ([Part VIII](./ch14-00-calling-c)) from `.native`. Next, [Part VII](./ch12-00-npm-facades) follows the Scala.js side of this story out into the JavaScript ecosystem — calling npm packages from Scala — and [Part VIII](./ch14-00-calling-c) does the same for Scala Native and the C/Rust world. [← 10. Typed RPC](./ch10-00-rpc) | [Next → 12. Calling NPM Modules from Scala.js](./ch12-00-npm-facades) --- --- url: https://wvlet.org/uni/book/ch12-00-npm-facades.md --- # 12. Calling NPM Modules from Scala.js You're building a browser app with Uni ([Chapter 11](./ch11-00-cross-platform)), and you need something the JavaScript world already solved: a Markdown renderer, a charting library, a date picker. It's on npm, written in JavaScript, with no Scala types. How do you call it from Scala 3 without giving up type safety — and without dragging in a code generator? The answer is a **facade**: a few lines of Scala that declare the shape of the JavaScript you actually use. You write it by hand, and it is smaller than you expect. ## A facade is a typed declaration Say you want [`marked`](https://www.npmjs.com/package/marked), which turns Markdown into HTML. In JavaScript you'd write: ```javascript import { marked } from 'marked' marked.parse('# Hello') // "

Hello

" ``` The Scala.js facade for exactly that is: ```scala import scala.scalajs.js import scala.scalajs.js.annotation.JSImport @js.native @JSImport("marked", "marked") object Marked extends js.Object: def parse(markdown: String): String = js.native ``` And you call it like any Scala object: ```scala val html = Marked.parse("# Hello") // "

Hello

" ``` That's the whole thing. Four pieces are doing the work: * **`@JSImport("marked", "marked")`** says where the value comes from: the named export `marked` from the npm package `marked`. Scala.js turns this into a real `import { marked } from "marked"` in its JavaScript output. * **`@js.native`** marks this as a declaration, not an implementation — the code lives on the JavaScript side. * **`extends js.Object`** types it as a JavaScript object. * **`= js.native`** is the method body you don't write, because the real one is in the npm package. You declared *only* `parse`, because that's the only method you call. A facade describes your usage, not the whole library — if you later need `marked.lexer`, you add one line. ## Default exports and other shapes Packages export values in a few shapes, and `@JSImport` has a form for each. A **named** export uses its name (as above). A **default** export uses `JSImport.Default`: ```scala import scala.scalajs.js import scala.scalajs.js.annotation.JSImport // JavaScript: import confetti from 'canvas-confetti'; confetti() @js.native @JSImport("canvas-confetti", JSImport.Default) object Confetti extends js.Object: def apply(): Unit = js.native ``` A method that *returns* a JavaScript object gets its own `@js.native` trait — no `@JSImport`, because you don't import it, you receive it: ```scala @js.native @JSImport("some-db", JSImport.Default) object DB extends js.Object: def open(path: String): Connection = js.native @js.native trait Connection extends js.Object: def query(sql: String): js.Array[js.Any] = js.native ``` JavaScript values map to `js`-prefixed types: `js.Object`, `js.Array[A]`, `js.Function`, `js.Dictionary[A]` for string-keyed maps, and `js.Any` when you genuinely don't care. When even a typed facade is more ceremony than a one-off call deserves, `js.Dynamic` is the escape hatch — fully untyped, method calls resolved at runtime: ```scala import scala.scalajs.js val mod = js.Dynamic.global.someGlobal mod.doThing("arg") // no types, no facade — use sparingly ``` Reach for `js.Dynamic` to prototype; promote to a real facade once you know which three methods you actually call. ## Why not ScalablyTyped? [ScalablyTyped](https://scalablytyped.org/) generates Scala facades automatically from a package's TypeScript definitions. It is impressive, and for this book's purposes it is the wrong default. The cost is out of proportion to the need. A typical npm package ships thousands of lines of `.d.ts`; ScalablyTyped turns that into a large generated Scala library that your build must convert and compile, every clean build, whether or not you call more than three of its functions. That's slower builds, a heavier toolchain, and generated names you didn't choose leaking into your code. What you actually need from `marked` was one method. The hand-written facade for it is four lines you can read, that compile instantly, and that say exactly what your program depends on. The trade is real — you write the declarations yourself instead of having them generated — but for the handful of calls a typical app makes into a JS library, four honest lines beat ten thousand generated ones. Write the facade. ## What you have, what comes next You can now call JavaScript libraries from Scala with types you control: * A **facade** is a `@js.native @JSImport(...)` declaration of just the parts of a package you use. * **`JSImport.Default`** for default exports, **`"name"`** for named ones; returned objects get their own `@js.native` trait. * **`js.Dynamic`** is the untyped escape hatch for prototyping. * Skip **ScalablyTyped** — a few hand-written lines beat a generated library for the calls a real app makes. But there's a missing piece. Your facade says `@JSImport("marked", …)`, and Scala.js faithfully emits `import { marked } from "marked"` — yet nothing has *installed* `marked` or resolved that import for the browser. That is the bundler's job. Next, [Chapter 13](./ch13-00-vite) wires it all together with Vite. [← 11. One Codebase, Three Runtimes](./ch11-00-cross-platform) | [Next → 13. Bundling with Vite](./ch13-00-vite) --- --- url: https://wvlet.org/uni/book/ch13-00-vite.md --- # 13. Bundling with Vite Your facade from [Chapter 12](./ch12-00-npm-facades) says `@JSImport("marked", "marked")`, and Scala.js dutifully emits `import { marked } from "marked"` in its output. But nothing has installed `marked`, and a browser has no idea what the bare name `"marked"` resolves to. Something has to fetch the package, follow its imports, and produce JavaScript a browser can load. That something is a **bundler**, and [Vite](https://vitejs.dev/) is a good one. This chapter wires the two worlds together: Scala.js on one side emitting ES module imports, Vite on the other resolving them against npm. ## Step 1: emit ES modules For `@JSImport` to become a real `import` a bundler can follow, Scala.js must emit ES modules. Set the module kind once in `build.sbt`: ```scala import org.scalajs.linker.interface.ModuleKind lazy val app = project .enablePlugins(ScalaJSPlugin) .settings( scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) } ) ``` This is the one setting that makes the whole chain work. Without it, Scala.js can't emit the `import { marked } from "marked"` that Vite needs to see. (Uni's own JS builds use exactly this setting.) `sbt app/fastLinkJS` then produces a folder of ES modules under `target/scala-3.x/app-fastopt/`, with `main.js` as the entry. The production command is `app/fullLinkJS`, which emits an optimized build under `app-opt/`. ## Step 2: install the npm package Vite resolves `"marked"` the npm way — from `node_modules`. So install it, along with Vite itself: ```bash $ npm install marked $ npm install --save-dev vite ``` This is the half of the contract Scala can't fulfill: the facade *names* the package, and `npm install` *provides* it. ## Step 3: a Vite entry point Vite serves an `index.html` that loads one JavaScript entry module: ```html ``` `main.js` is the seam between the npm world and the Scala.js world. It imports your styles and any npm modules you want to set up, then pulls in the Scala.js output to start your app: ```javascript // main.js import './style.css' // Start the Scala.js application (the fastLinkJS output entry module) import('./target/scala-3.x/app-fastopt/main.js') ``` When Scala.js code runs and hits your `Marked.parse(...)` facade, the emitted `import { marked } from "marked"` resolves through Vite to the installed package. The facade, the linker, and the bundler are now one pipeline: Scala types on top, npm code underneath. ## Step 4: run it Two processes, one for each compiler: ```bash $ sbt "~app/fastLinkJS" # recompile Scala.js on change $ npx vite # dev server with hot reload ``` `vite` serves the app with instant hot-module reload; the `~` keeps Scala.js relinking as you edit. For production, `sbt app/fullLinkJS` followed by `npx vite build` emits a minified bundle to `dist/`. A minimal `vite.config.js` needs almost nothing: ```javascript import { defineConfig } from "vite" export default defineConfig({ base: "./", }) ``` ## When a module won't bundle cleanly Most npm packages bundle without fuss. Two situations need a nudge, and both have a one-line fix. **A library that's easier to load as a global.** Some packages (editors, WASM modules) are simplest to load in `main.js` and hand to Scala.js through the `window` object. Expose it: ```javascript // main.js import { marked } from 'marked' window.marked = marked ``` and facade it with `@JSGlobal` instead of `@JSImport`: ```scala import scala.scalajs.js import scala.scalajs.js.annotation.JSGlobal @js.native @JSGlobal("marked") object Marked extends js.Object: def parse(markdown: String): String = js.native ``` This `window` bridge is how the [Wvlet playground](https://github.com/wvlet/wvlet/tree/main/wvlet-ui-playground) wires its Monaco editor — `main.js` sets `window.MonacoEditor`, and Scala reads it via `@JSGlobal`. **A package with a dependency the browser can't use.** A library may pull in a Node-only module the bundler can't resolve. Point Vite at a browser-safe replacement with `resolve.alias`: ```javascript export default defineConfig({ resolve: { alias: { // swap a Node-only dep for a browser stub "node-only-pkg": "/stubs/browser-stub.js", }, }, }) ``` The playground does this for `koffi` (a native-binding library its DuckDB backend needs on Node but never on the web) — aliasing it to a stub that throws if anything ever calls it. Reach for `alias` only when a transitive dependency fights the browser; you won't need it for ordinary UI packages. ## What you have, what comes next You can now ship a Scala.js app that uses the npm ecosystem: * **`ModuleKind.ESModule`** makes Scala.js emit imports a bundler can follow. * **`npm install`** provides the package your facade named. * A **`main.js` entry** imports the Scala.js output and any npm setup; Vite resolves the bare imports and serves the app. * **`@JSGlobal` + `window`** bridges stubborn modules, and **`resolve.alias`** swaps out browser-hostile dependencies. That completes Part VII — Scala.js is now a full participant in the JavaScript ecosystem, with types on your side of the boundary and npm on the other. Next, [Part VIII](./ch14-00-calling-c) does the mirror image for the other end of the platform spectrum: Scala Native and the C/Rust world — calling C libraries from Scala, and exposing your Scala as a library that C, C++, and Rust can call. [← 12. Calling NPM Modules from Scala.js](./ch12-00-npm-facades) | [Next → 14. Calling C from Scala Native](./ch14-00-calling-c) --- --- url: https://wvlet.org/uni/book/ch14-00-calling-c.md --- # 14. Calling C from Scala Native Compile a Uni app with Scala Native ([Chapter 11](./ch11-00-cross-platform)) and you get a real native binary — and with it, direct access to the entire C ecosystem: `libcurl`, `sqlite`, `openssl`, anything with a C ABI. No JNI, no subprocess, no serialization across a boundary. You call a C function the way you call a Scala one, once you've declared it. This chapter is the Scala-Native counterpart to [Chapter 12](./ch12-00-npm-facades): there you wrote a facade for a JavaScript module; here you write one for a C library. ## An `@extern` binding To call C, you declare the functions you need in an `@extern` object and tell the linker which library provides them. Here is the shape, taken from how Uni's own Native HTTP client binds `libcurl`: ```scala import scala.scalanative.unsafe.* @link("curl") @extern object curl: @name("curl_easy_init") def easyInit(): Ptr[Byte] = extern @name("curl_easy_setopt") def easySetOpt(handle: Ptr[Byte], option: CInt, value: CString): CInt = extern @name("curl_easy_perform") def easyPerform(handle: Ptr[Byte]): CInt = extern @name("curl_easy_strerror") def easyStrError(code: CInt): CString = extern @name("curl_easy_cleanup") def easyCleanup(handle: Ptr[Byte]): Unit = extern // Option codes come from curl.h; 10002 is CURLOPT_URL val CURLOPT_URL: CInt = 10002 ``` Four pieces, mirroring the JavaScript facade from Chapter 12: * **`@link("curl")`** tells the linker to link `libcurl` into the binary — the native equivalent of `npm install`. * **`@extern`** marks the object as a set of declarations whose bodies live in that C library. * **`@name("curl_easy_init")`** maps a Scala method to the actual C symbol, so your Scala name can be idiomatic while the binding still finds `curl_easy_init`. * **`= extern`** is the body you don't write, because C already did. You declare only the handful of functions you call, exactly as with a JS facade. `libcurl` exports hundreds; a working HTTP client needs a dozen. C constants (like `CURLOPT_URL`) don't cross the boundary at all — you copy their values out of the header file into ordinary Scala `val`s. ## C types in Scala C has its own types, and Scala Native gives you a vocabulary for them from `scala.scalanative.unsafe`: | C | Scala Native | |---|--------------| | `int` | `CInt` | | `char*` (string) | `CString` | | `void*` / opaque pointer | `Ptr[Byte]` | | `size_t` | `CSize` | | a `struct` | `CStruct2[A, B]`, `CStruct3[...]`, … | A `CString` is a pointer to bytes, not a Scala `String` — the two are different worlds, and you convert at the boundary. An opaque C handle (like libcurl's `CURL*`) is just a `Ptr[Byte]` you pass back to the library; you never look inside it. ## Crossing the string boundary Two helpers move strings across. `fromCString` reads a C string into a Scala `String`. `toCString` does the reverse — but it has to allocate memory somewhere, and where decides how long the result lives. For a string you pass *into* a C call and don't need afterward, allocate it in a `Zone`: a scoped arena that frees everything in it when the block ends. ```scala import scala.scalanative.unsafe.* Zone.acquire { implicit z => val handle = curl.easyInit() curl.easySetOpt(handle, CURLOPT_URL, toCString("https://example.com")) curl.easyPerform(handle) } // every toCString allocation in this zone is freed here ``` Reading a result back out uses `fromCString`: ```scala val message: String = fromCString(curl.easyStrError(code)) ``` The `Zone` is the key idea for memory safety at the boundary: temporary C allocations get a clear lifetime tied to a block, so they can't leak and can't be used after they're freed. (You'll see the one case where `Zone` is *wrong* — a value handed back to C that must outlive the call — in [Chapter 15](./ch15-00-exposing-native).) ## A Uni service over the binding The binding compiles, but nothing about it feels like the code you've written in the rest of this book: it traffics in pointers and integer return codes, and a failure is a `CInt` you have to remember to check. Don't spread that through your application. Wrap the binding in one ordinary Scala class, and let Uni take over from there. ```scala import scala.scalanative.unsafe.* import wvlet.uni.log.LogSupport class CurlError(code: Int, message: String) extends Exception(s"curl error ${code}: ${message}") class Downloader extends LogSupport with AutoCloseable: private val handle = curl.easyInit() def fetch(url: String): Unit = Zone.acquire { implicit z => curl.easySetOpt(handle, CURLOPT_URL, toCString(url)) val code = curl.easyPerform(handle) if code != 0 then val message = fromCString(curl.easyStrError(code)) error(s"GET ${url} failed: ${message}") throw CurlError(code, message) debug(s"GET ${url} succeeded") } override def close(): Unit = curl.easyCleanup(handle) ``` Notice what this class is: the *only* place where both vocabularies appear. Above it, pure Scala (`fetch(url: String)`, exceptions, `LogSupport`); below it, pure C (`Ptr`, `CString`, return codes). The mixing of the two worlds is the wrapper's entire job, and it happens here and nowhere else — everything C-shaped is translated at this edge: * **Error codes become exceptions.** C reports failure by returning a nonzero `CInt`; the compiler doesn't force anyone to look at it. The wrapper checks once, converts the code to a message with `easyStrError`, and throws — callers can't silently ignore a failed download. * **`LogSupport` works here like everywhere else.** The logging you learned in [Chapter 5](./ch05-00-logging) is pure Scala, so it cross-compiles to Native unchanged — `error` and `debug` at the C boundary behave exactly as they did on the JVM. When a native binary misbehaves in production, the log line with curl's own error message is what you'll want. * **Callers see `fetch(url: String)`.** No `Ptr`, no `CString`, no `Zone`. The rest of the application cannot tell — and should not care — that a C library sits underneath. ## Give the C handle a lifecycle There is one problem left: `handle` is C memory. Scala's garbage collector doesn't know about it, so nothing frees it unless `close()` runs. That is precisely what `Design`'s lifecycle hooks from [Chapter 3](./ch03-00-design) are for: ```scala import wvlet.uni.design.Design val design = Design .newDesign .bindSingleton[Downloader] .onShutdown(_.close()) design.build[Downloader] { downloader => downloader.fetch("https://example.com") } // session ends here: close() runs, curl_easy_cleanup frees the handle ``` The session guarantees `close()` runs exactly once, when the session ends — the same deterministic teardown you'd want for a database connection, applied to a C resource. And because `Downloader` is now just a binding in a design, tests can substitute it the way [Chapter 3](./ch03-00-design) substituted a database: put a trait in front of it, `bindImpl` the C-backed class in the production design, and bind a stub in the test design — no test ever opens a real curl handle. This layering — raw `@extern` facade at the bottom, one safe wrapper class, Uni services on top — is how Uni's own Native HTTP client is built, and it is the shape to copy for any C library you bind. ## Why bind C directly? On the JVM, reaching a C library means JNI: a separate C shim, a build step, and a marshaling layer between the JVM and native code. Scala Native removes the gap — your Scala compiles to native code already, so an `@extern` call is a direct call, with no bridge and no per-call overhead. This is not a toy capability. Uni's Scala Native HTTP client *is* a `libcurl` binding written exactly this way — the same `@link` / `@extern` / `Zone` pattern above, in production, behind the same `Http.client` API you used on the JVM in [Chapter 9](./ch09-00-http). The cross-platform client works on Native because someone wrote this facade once; you can wrap any C library the same way. ## What you have, what comes next You can now call C libraries from Scala Native — and make them feel like Uni code: * An **`@extern` object** with **`@link`** and **`@name`** declares the C functions you use — a facade, like Chapter 12's, but for C. * **C types** (`CInt`, `CString`, `Ptr`, `CStruct…`) describe the values; a `CString` is not a Scala `String`. * **`Zone.acquire`** + **`toCString`** allocate temporary arguments with a scoped lifetime; **`fromCString`** reads results back. * **One wrapper class** turns error codes into exceptions and logs through `LogSupport`; the rest of the app never sees a `Ptr`. * **`Design` + `onShutdown`** give the C handle a deterministic lifecycle, and a trait in front of the wrapper keeps it swappable in tests. Next, [Chapter 15](./ch15-00-exposing-native) turns the arrow around: instead of Scala calling C, you'll expose your Scala Native code *as* a C library that Rust, C, and C++ can call. [← 13. Bundling with Vite](./ch13-00-vite) | [Next → 15. Exposing Scala Native to C and Rust](./ch15-00-exposing-native) --- --- url: https://wvlet.org/uni/book/ch15-00-exposing-native.md --- # 15. Exposing Scala Native to C and Rust You've written something valuable in Scala — a parser, a query compiler, a domain calculation — and now a Rust service and a C++ application both want to call it. Porting it twice is the wrong answer. Instead, compile your Scala Native code into a **C-ABI library** and let any language that speaks C link against it. This is [Chapter 14](./ch14-00-calling-c) in reverse: there Scala called into C; here C, C++, and Rust call into Scala. ## Export a function Mark a method `@exported` with the C symbol name you want, and Scala Native gives it a C calling convention: ```scala import scala.scalanative.unsafe.* object MyLib: @exported("greet") def greet(name: CString): CString = val who = fromCString(name) // C string → Scala String toCStringHeap(s"Hello, ${who}!") // Scala String → C string (see below) ``` `fromCString` reads the incoming `char*` into a Scala `String`, the same helper from Chapter 14. The interesting part is the return value. ## Returning data: not in a Zone In Chapter 14 you allocated temporary C strings in a `Zone`, which frees them when the block ends. For a value you *return to C*, that is exactly wrong: the `Zone` would free the string the instant `greet` returns, and the caller would read freed memory. A returned value has to outlive the call, so you allocate it on the heap with `malloc` and hand ownership across the boundary: ```scala import scala.scalanative.unsafe.* import scala.scalanative.unsigned.* import scala.scalanative.libc.stdlib def toCStringHeap(str: String): CString = val bytes = str.getBytes("UTF-8") val buffer = stdlib.malloc((bytes.length + 1).toCSize) var i = 0 while i < bytes.length do buffer(i) = bytes(i) i += 1 buffer(bytes.length) = 0.toByte buffer.asInstanceOf[CString] ``` This is the one genuinely subtle rule of exporting: **arguments use a `Zone`, return values use the heap.** Wvlet's real C library uses exactly this split — `fromCString` on the way in, a `malloc`-backed `toCString` on the way out. Heap memory raises the question a `Zone` answered for you: who frees it? The answer at a C boundary is a convention — the library that `malloc`s must be the one that `free`s — so a well-behaved library also exports a matching free function. You'll see one in the next section. ## Ship Uni logic, not toy strings `greet` shows the mechanics, but nobody builds a library to concatenate strings. The real question is: your Scala logic works on *rich* values — case classes, collections — and the C ABI only speaks integers and pointers. How do you get a `PriceRequest` across? You don't define C structs for it. You pass **JSON strings** and let [Weaver](./ch06-00-data) do the translating — and you keep the two worlds in two separate files, meeting at a plain Scala `String`. The first file is your actual library. It is pure Uni code: no `CString`, no `Ptr`, no `unsafe` import. Following [Chapter 11](./ch11-00-cross-platform)'s layout it lives in the shared `src/` folder, because nothing in it is native-specific: ```scala // src/ — shared code. Compiles on JVM, JS, and Native alike. import wvlet.uni.log.LogSupport import wvlet.uni.weaver.Weaver case class PriceRequest(product: String, quantity: Int) derives Weaver case class PriceQuote(product: String, quantity: Int, total: Double) derives Weaver object PricingService extends LogSupport: def quote(requestJson: String): String = val request = Weaver.fromJson[PriceRequest](requestJson) debug(s"Quoting ${request.quantity} x ${request.product}") val response = PriceQuote(request.product, request.quantity, request.quantity * 9.99) Weaver.toJson(response) ``` The second file is the C bridge, and it is *only* the bridge. Each exported function is one line: convert, delegate, convert back. It goes in the `.native` folder, because it can compile nowhere else: ```scala // .native/ — the C bridge. Conversions only; no logic lives here. import scala.scalanative.unsafe.* import scala.scalanative.libc.stdlib object PricingLib: @exported("pricing_quote") def quote(requestJson: CString): CString = toCStringHeap(PricingService.quote(fromCString(requestJson))) @exported("pricing_free") def free(str: CString): Unit = stdlib.free(str) ``` The split is the point: * **The two worlds meet in exactly one file.** `PricingService` speaks Scala (`String` in, `String` out); `PricingLib` speaks C (`CString` in, `CString` out); `fromCString` / `toCStringHeap` are the only words they exchange. When something goes wrong at the boundary, there is one short file to look in — the same one-place rule Chapter 14 applied to the `Downloader` wrapper, pointing the other way. * **The service never left the ordinary Uni world.** The logging from [Chapter 5](./ch05-00-logging), the `derives Weaver` codecs from [Chapter 6](./ch06-00-data), `Design`-built services if the logic needs them — all available, because `PricingService` is just Scala. And because it lives in shared `src/`, you can unit-test it with UniTest on the JVM ([Chapter 4](./ch04-00-testing)) — no native toolchain, no C caller — or serve the same logic over RPC ([Chapter 10](./ch10-00-rpc)). The C ABI is one more front door, not a fork of your code. * **JSON is the boundary contract.** Every language that can call C can also build a JSON string, so callers get rich structured input and output without you maintaining a C struct layout for each type. Add a field to `PriceQuote` and existing callers keep working. * **`pricing_free` completes the ownership story.** The returned string was `malloc`ed inside the Scala library, so the Scala library exports the function that frees it. Callers treat the pair as open/close: call `pricing_quote`, read the result, call `pricing_free`. Only static object methods can be exported, and their parameter and return types must be C-representable (primitives and pointers) — which is exactly why the JSON-string shape works so well. ## Build it as a library By default Scala Native produces an executable. A `nativeConfig` setting tells it to produce a library instead — dynamic (`.so` / `.dylib`) or static (`.a`): ```scala import scala.scalanative.build.BuildTarget // Dynamic library: libmylib.so / libmylib.dylib lazy val mylib = project .enablePlugins(ScalaNativePlugin) .settings( libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0", nativeConfig ~= { _.withBuildTarget(BuildTarget.libraryDynamic).withBaseName("mylib") } ) ``` The `uni` dependency is the same line as any Native project from [Chapter 11](./ch11-00-cross-platform) — Weaver and logging compile into the library like any other Scala code. Swap `libraryDynamic` for `BuildTarget.libraryStatic` to get a static `libmylib.a` instead. `sbt mylib/nativeLink` then emits the shared library, and Scala Native also generates a C header declaring your exported functions. One initialization rule: the Scala Native runtime must start before the first exported call. A *dynamic* library does this itself — Scala Native generates a constructor that runs when the library loads. A *static* library can't, so C callers linking `libmylib.a` must call the generated `ScalaNativeInit()` once (it returns `0` on success) before anything else. ## Call it from Rust Rust links the library and declares the exported functions in an `extern "C"` block — its native equivalent of Chapter 14's `@extern` object, pointing the other way: ```rust use std::ffi::{CStr, CString}; use std::os::raw::c_char; extern "C" { fn pricing_quote(request_json: *const c_char) -> *mut c_char; fn pricing_free(response_json: *mut c_char); } fn main() { let request = CString::new(r#"{"product":"keyboard","quantity":3}"#).unwrap(); unsafe { let response = pricing_quote(request.as_ptr()); println!("{}", CStr::from_ptr(response).to_str().unwrap()); pricing_free(response); } } ``` The Rust side mirrors the memory rules from the Scala side exactly: `CString::new` plays the role of `toCString` for the argument (freed by Rust when `request` drops), and the response — `malloc`ed inside the Scala library — goes back through `pricing_free`. Compile it against the library by pointing the linker at the output directory and naming the lib, then run it with the shared library on the loader's path: ```bash $ sbt mylib/nativeLink $ rustc -L target/scala-3.x -lmylib test.rs -o test $ LD_LIBRARY_PATH=target/scala-3.x ./test # DYLD_LIBRARY_PATH on macOS {"product":"keyboard","quantity":3,"total":29.97} ``` `-L` is the search path (where `libmylib.so` lives) and `-lmylib` is the library — the same two flags whatever the consuming language is. At run time the dynamic loader needs the same directory, hence `LD_LIBRARY_PATH`. ## Call it from C and C++ C and C++ are the same story: declare the functions, link the library. ```c // test.c #include char* pricing_quote(const char* request_json); void pricing_free(char* response_json); int main() { char* response = pricing_quote("{\"product\":\"keyboard\",\"quantity\":3}"); printf("%s\n", response); pricing_free(response); return 0; } ``` ```bash $ gcc -L target/scala-3.x -lmylib test.c -o test # g++ for C++ ``` Wvlet ships its query compiler this way, in exactly the JSON-in/JSON-out shape you just built: one Scala Native module exports `wvlet_compile_query_json`, which takes a JSON string of arguments and returns a `char*` of JSON (`{"success":true,"sql":...}`), builds to `libwvlet`, and its [test suite](https://github.com/wvlet/wvlet/tree/main/wvc-lib) links the same `.so` from Rust, C, *and* C++ — three languages, one implementation, no ports. ## Why ship Scala as a native library The usual ways to share logic across languages are a network service (now you operate a server and pay serialization on every call) or a rewrite (now you maintain the same logic twice and they drift). Exporting a C-ABI library is neither: the consumer makes a direct in-process function call into your compiled Scala, and there is exactly one implementation to maintain. Because the contract is the C ABI — the lingua franca every systems language speaks — you are not committing to Rust or to C++. Anything that can call C can call your Scala. You write the logic once, in the language you prefer, and hand it to everyone else as a `.so`. ## What you have, what comes next You can now ship Uni-powered Scala to the systems world: * **`@exported("name")`** gives a method a C ABI; **`fromCString`** reads arguments. * Return values go on the **heap** (`malloc`), never a `Zone` — and the library exports the matching **free function**, because whoever `malloc`s must `free`. * **Two files, one meeting point**: a pure-Scala service (`String` in, `String` out, Uni everywhere) in shared `src/`, and a conversions-only C bridge in `.native/` — `fromCString` / `toCStringHeap` are the only words the two worlds exchange. * **JSON strings are the boundary contract**: `Weaver.fromJson` inside the service on the way in, `Weaver.toJson` on the way out. * **`BuildTarget.libraryDynamic` / `libraryStatic`** + `nativeLink` produce a `.so` / `.dylib` / `.a` and a C header; static libraries need one **`ScalaNativeInit()`** call before use. * **`-L -l`** links it from Rust, C, or C++ alike. That closes Part VIII — and, with it, Uni's reach into both neighboring ecosystems: the JavaScript world through Scala.js ([Part VII](./ch12-00-npm-facades)) and the C/Rust world through Scala Native. One library, three runtimes, and a door into each runtime's native ecosystem. From here, the appendices collect supporting material: [Appendix A](./appendix-a-scala3) on Scala 3 syntax, [Appendix B](./appendix-b-airframe) on Uni and Airframe, and [Appendix C](./appendix-c-glossary), the glossary. [← 14. Calling C from Scala Native](./ch14-00-calling-c) | [Next → 16. Capstone — A Bookmarks Service](./ch16-00-capstone) --- --- url: https://wvlet.org/uni/book/ch16-00-capstone.md --- # 16. Capstone — A Bookmarks Service You've met every piece of Uni on its own. This chapter sets the platform-specific side-tracks aside and builds one small, complete thing with the core stack — a service that saves and lists bookmarks — so you can see how the pieces fit into a single program. By the end you'll have a typed RPC service, wired with Design, hardened with a retry, and tested without a network. Nothing here is new; the point is the *assembly*. ## The data and the contract Start with the data — a `Bookmark` — and the contract clients call, a trait. Both `derive Weaver` so they cross the wire as [Chapter 6](./ch06-00-data) showed: ```scala import wvlet.uni.weaver.Weaver case class Bookmark(id: Long, url: String, title: String) derives Weaver trait BookmarkService: def add(url: String, title: String): Bookmark def list(): Seq[Bookmark] ``` The trait is the whole API. Server and client are both checked against it, so they cannot drift ([Chapter 10](./ch10-00-rpc)). ## The implementation The implementation keeps an in-memory store. It takes nothing it doesn't need in its constructor — here, just a starting `Seq` of seed bookmarks, which makes it trivial to construct in a test: ```scala import java.util.concurrent.atomic.AtomicReference class BookmarkServiceImpl(seed: Seq[Bookmark]) extends BookmarkService: private val store = AtomicReference(seed.toVector) private val nextId = java.util.concurrent.atomic.AtomicLong(seed.size + 1L) def add(url: String, title: String): Bookmark = val bookmark = Bookmark(nextId.getAndIncrement(), url, title) store.updateAndGet(_ :+ bookmark) bookmark def list(): Seq[Bookmark] = store.get() ``` ## Wiring it with Design `Design` ([Chapter 3](./ch03-00-design)) decides how the service is built. Binding the seed as an instance and the service as a singleton is the entire dependency graph: ```scala import wvlet.uni.design.Design val appDesign = Design.newDesign .bindInstance[Seq[Bookmark]](Seq.empty) .bindSingleton[BookmarkServiceImpl] ``` That `appDesign` is the one artifact production and tests share. The test later swaps just the seed; everything else stays real. ## Serving it over RPC Turn the implementation into routes with `RPCRouter.of`, wrap it in an `RPCHandler`, and serve it on Netty ([Chapter 9](./ch09-00-http), [Chapter 10](./ch10-00-rpc)). The server runs inside the Design session, so it is built and torn down with everything else: ```scala import wvlet.uni.http.rpc.RPCRouter import wvlet.uni.http.Http import wvlet.uni.http.netty.RPCHandler appDesign.build[BookmarkServiceImpl] { service => val router = RPCRouter.of[BookmarkService](service) Http .server .withPort(8080) .withRxHandler(RPCHandler(router)) .start { server => println(s"Bookmarks service on ${server.localAddress}") server.awaitTermination() } } ``` A generated `BookmarkServiceClient` (set up as in [client generation](/http/rpc#generating-a-client)) then calls `add`/`list` as if they were local methods. ## Hardening one call Suppose `add` should fetch the page title when the caller omits it. That's a network call, and network calls fail — so wrap it in a retry ([Chapter 8](./ch08-00-control)), and only for this idempotent GET: ```scala import wvlet.uni.control.Retry import wvlet.uni.http.{Http, Request} class TitleFetcher(client: wvlet.uni.http.HttpSyncClient): def titleOf(url: String): String = Retry.withBackOff(maxRetry = 3).run { val html = client.send(Request.get(url)).contentAsString.getOrElse("") extractTitle(html).getOrElse(url) } private def extractTitle(html: String): Option[String] = val open = html.indexOf("") val close = html.indexOf("") if open >= 0 && close > open then Some(html.substring(open + 7, close)) else None ``` `TitleFetcher` takes its `HttpSyncClient` as a constructor parameter, so Design owns the client's lifecycle (`bindInstance(...).onShutdown(_.close())`, as in [Chapter 3](./ch03-00-design)) and a test can hand it a stand-in. ## Testing it, without a network Because the wiring is a value, the test takes `appDesign` and overrides exactly one binding — the seed — leaving the real `BookmarkServiceImpl` in place ([Chapter 4](./ch04-00-testing)): ```scala import wvlet.uni.design.Design import wvlet.uni.test.UniTest class BookmarkServiceTest extends UniTest: // addTestDesign: each test gets a fresh service and store addTestDesign( _ + appDesign + Design.newDesign.bindInstance[Seq[Bookmark]]( Seq(Bookmark(1, "https://wvlet.org", "Wvlet")) ) ) test("add appends and list returns everything") { (bookmarks: BookmarkServiceImpl) => bookmarks.list().size shouldBe 1 val added = bookmarks.add("https://scala-lang.org", "Scala") bookmarks.list().map(_.title) shouldContain "Scala" added.id shouldBe 2 } ``` The real `add`/`list` logic runs; only the seed is a fixture. No server, no socket — the suite finishes in milliseconds. ## What you built In one chapter you assembled the whole core stack into a working service: * **Data + contract** as `derives Weaver` case classes and a trait. * **Design** for the dependency graph, shared by production and tests. * **RPC + Netty** to serve the trait, with a generated typed client. * **Retry** around the one call that touches the network. * **UniTest + Design override** to test the real logic without a network. That is the shape of a Uni application — *parse, wire, do, clean up* from [Chapter 2](./ch02-00-cli-app), grown up. From here, the platform Parts ([VII](./ch12-00-npm-facades), [VIII](./ch14-00-calling-c)) take the same code to the browser and to native binaries, and the [appendices](./appendix-a-scala3) collect the supporting material. [← 15. Exposing Scala Native to C and Rust](./ch15-00-exposing-native) | [Next → Appendix A: Scala 3 Syntax Notes](./appendix-a-scala3) --- --- url: https://wvlet.org/uni/book/appendix-a-scala3.md --- # Appendix A: Scala 3 Syntax Notes for This Book This book uses a handful of Scala 3 features in nearly every example. If you are coming from Scala 2, Java, or another typed language, this appendix is the short reference for the syntax you'll see — just enough to read the chapters comfortably. ## Indentation-based syntax Scala 3 lets you replace braces with significant indentation. A class body, method body, or block opens with `:` (for definitions) or is simply indented: ```scala class Greeter: def greet(name: String): String = val message = s"Hello, ${name}" message ``` Braces still work and are still useful — for a short lambda passed to a method, the book often keeps them: `design.build[App] { app => … }`. Use whichever reads more clearly; they mean the same thing. ## `@main` entry points A program's entry point is a method annotated with `@main`, not a magic signature on an object: ```scala @main def run(): Unit = println("started") ``` Arguments become method parameters. `@main def fetch(args: String*)` gives you the command-line arguments directly, which is how the CLI app in [Chapter 2](./ch02-00-cli-app) starts. ## `given` / `using` — contextual parameters A `using` parameter is supplied by the compiler from a matching `given` in scope, instead of being passed explicitly at the call site: ```scala given Weaver[User] = Weaver.of[User] def toJson[A](a: A)(using weaver: Weaver[A]): String = weaver.toJson(a) toJson(user) // the Weaver[User] given is found and passed for you ``` This is how [Weaver](./ch06-00-data) codecs and other typeclass-style values travel through the code without cluttering every signature. A `derives` clause (`case class User(...) derives Weaver`) generates the `given` for you. ## Enums and pattern matching Scala 3 enums declare a closed set of cases, which you then match on: ```scala enum Color: case Red, Green, Blue def hex(c: Color): String = c match case Color.Red => "#f00" case Color.Green => "#0f0" case Color.Blue => "#00f" ``` The compiler warns if a `match` misses a case, so adding `Color.Black` later points you at every place that needs updating. Uni uses enums for closed sets like log levels and RPC status codes. ## Extension methods An `extension` adds methods to a type you don't own: ```scala extension (s: String) def shout: String = s.toUpperCase + "!" "hello".shout // "HELLO!" ``` Several Uni APIs read fluently because of extensions — the `shouldBe` in [Chapter 4](./ch04-00-testing)'s tests is an extension method on any value. ## Why `new` is almost never needed Scala 3 lets you construct a class by calling it like a function, so the book writes `StringBuilder()` and `FakeDatabase()`, not `new StringBuilder()`. You'll only see `new` in this book for the rare anonymous-class case (overriding methods inline, as with a `WebSocketHandler`). If you wrote Scala 2, dropping `new` is the habit to unlearn first. [← 16. Capstone — A Bookmarks Service](./ch16-00-capstone) | [Next → Appendix B: Uni and Airframe](./appendix-b-airframe) --- --- url: https://wvlet.org/uni/book/appendix-b-airframe.md --- # Appendix B: Uni and Airframe — History and Relationship If you've worked in the Scala ecosystem, the ideas in this book may feel familiar. That is not an accident: Uni is a refinement of code that began in the [Airframe](https://github.com/wvlet/airframe) project. This appendix explains the relationship — useful background if you have existing Airframe code, and reassurance that what you've learned transfers. ## Where Uni comes from Airframe is a broad Scala library and ecosystem built up over many years, spanning dependency wiring, logging, serialization, RPC, and more, across Scala 2 and Scala 3. Uni takes the most-used, most-foundational pieces of that work and re-presents them as a single, cohesive library built **for Scala 3 from the start**. The mental models you've built reading this book — `Design` as object wiring, `Rx` as a composable stream, `Surface` for compile-time type information, codecs derived rather than hand-written — all originated in Airframe. They carry over because they are the same ideas, sharpened. ## What changed Uni is a refinement, and the refinements pull in one direction: smaller and more modern. * **Scala 3 only.** Uni drops Scala 2 cross-building, so its APIs can use `given`/`using`, `enum`, `derives`, and indentation syntax directly instead of working around their absence. The [syntax notes](./appendix-a-scala3) are the features this buys. * **Minimal dependencies.** Uni keeps its dependency surface deliberately small, so adding it to a project doesn't pull in a framework. * **Trimmed scope.** Pieces of Airframe that were niche, or better served by a dedicated tool, are left out rather than carried forward. Uni aims to be the *essential* set, not the exhaustive one. * **A fresh package root.** Uni lives under `wvlet.uni.*`, distinct from Airframe's `wvlet.airframe.*`. ## If you have Airframe code Because Uni and Airframe occupy different package roots, they are separate libraries and can sit in the same build during a migration — you are not forced to move everything at once. The conceptual translation is usually direct: an Airframe `Design` and a Uni `Design` express the same wiring idea, an Airframe codec and a Uni `Weaver` solve the same serialization problem. The exact mapping — which APIs are identical, which were renamed, which were dropped — is a moving target better served by the project's migration notes than by a printed table here. Start from the concept you know in Airframe, find its chapter in this book, and you'll usually recognize the Uni shape immediately. [← Appendix A: Scala 3 Syntax Notes](./appendix-a-scala3) | [Next → Appendix C: Glossary](./appendix-c-glossary) --- --- url: https://wvlet.org/uni/book/appendix-c-glossary.md --- # Appendix C: Glossary Short definitions of terms as this book uses them. The intent is to make cross-references precise, not to define every word in Scala. Each entry points to the chapter where the concept is developed. **Binding** — One entry in a [Design](#design): a rule for how to produce a value of some type. Created with `bindSingleton`, `bindInstance`, `bindImpl`, or `bindProvider`. See [Chapter 3](./ch03-00-design). **Cancelable** — The handle returned by `Rx.subscribe` / `Rx.run`. Calling `cancel` tears down the subscription and stops further values. Holding and releasing it is how `Rx` avoids leaked streams. See [Chapter 7](./ch07-00-rx). **Circuit breaker** — A control-flow primitive that stops calling a backend once its failure rate crosses a threshold, "opening" to fail fast until the backend recovers. See [Chapter 8](./ch08-00-control). **Codec** — A bidirectional translator between bytes (JSON or MessagePack) and Scala values. In Uni the codec is a [Weaver](#weaver). See [Chapter 6](./ch06-00-data). **Cross-project** — An sbt module declared once with `crossProject` and compiled for the JVM, Scala.js, and Scala Native. Shared code lives in `src/`; platform-specific code in `.jvm` / `.js` / `.native`. See [Chapter 11](./ch11-00-cross-platform). **Design** — An immutable description of how types are wired together — which implementations satisfy which dependencies, and which values live as singletons. A `Design` is a value: building it runs nothing. See [Chapter 3](./ch03-00-design). **Launcher** — The annotation-driven CLI argument parser. It populates a plain case class from `Array[String]` using `@option` and `@argument`. See [Chapter 2](./ch02-00-cli-app). **LogSupport** — The trait a class mixes in to get `trace` / `debug` / `info` / `warn` / `error` methods and a logger named after the class. Log messages carry their source `(file:line)`, captured at compile time. See [Chapter 5](./ch05-00-logging). **Resource** — A control primitive (`Control.withResource`) that lends you a resource for a block and closes it on exit, on both the normal and exception paths — the loan pattern. See [Chapter 8](./ch08-00-control). **Retry** — A policy (`Retry.withBackOff`) that re-runs a failing operation with increasing delays. Safe only for idempotent operations. See [Chapter 8](./ch08-00-control). **RPC** — Calling a remote service through a shared Scala trait, so the client and server are checked against one contract by the compiler. See [Chapter 10](./ch10-00-rpc). **Rx** — Uni's abstraction for a value that arrives later or changes over time: a lazy description of zero or more values that you compose with `map` / `flatMap` / `filter` and consume with `subscribe`. See [Chapter 7](./ch07-00-rx). **RxVar** — A mutable `Rx` you can watch: created with `Rx.variable`, updated with `:=`, and observed by subscribers. See [Chapter 7](./ch07-00-rx). **Session** — The runtime context `Design.build` (or `withSession`) opens: it owns the singletons it constructs and runs their `onStart` / `onShutdown` lifecycle hooks. A session has a lifetime; closing it tears the graph down. See [Chapter 3](./ch03-00-design). **Surface** — Compile-time type reflection. It captures a type's structure (fields, parameters, type arguments) for the codec layer to use, without runtime reflection — which is what lets derivation work on Scala.js and Native. See [Chapter 6](./ch06-00-data). **Weaver** — Uni's derivation-based codec. One `Weaver[A]` serializes a type to JSON *or* MessagePack; you get it with `derives Weaver`. See [Chapter 6](./ch06-00-data). [← Appendix B: Uni and Airframe](./appendix-b-airframe) | [Back to the Book](./) --- --- url: https://wvlet.org/uni/guide.md --- # Introduction **Uni is the standard library Scala 3 didn't ship with.** Logging, object wiring, JSON & MessagePack, reactive streams, HTTP clients and servers, RPC, and a browser UI toolkit — small, composable pieces that work *identically* on the **JVM**, in the **browser and Node.js** (Scala.js), and as **native binaries** (Scala Native), with almost no external dependencies. It distills the most-used building blocks of the [Airframe](https://github.com/wvlet/airframe) ecosystem into one cohesive, Scala-3-first library. ::: tip Get going in 30 seconds Add one dependency ([Installation](./installation)) and you have all of it — no à-la-carte modules to assemble. ::: ## A quick taste Object wiring, structured logging, and lifecycle management — three things you usually reach for three libraries for — in a handful of lines: ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport class GreeterService extends LogSupport: def greet(name: String): String = info(s"Greeting ${name}") // logs with source file + line s"Hello, ${name}!" @main def main = Design.newDesign .bindSingleton[GreeterService] .build[GreeterService] { greeter => // wired, started, and cleaned up println(greeter.greet("Uni")) } ``` ## Why Uni? * 🪶 **Minimal dependencies** — foundational utilities without dragging in a heavy framework. * 🌍 **One codebase, three runtimes** — the same source compiles for JVM, Scala.js, and Scala Native. * 🧩 **Composable** — small, focused APIs designed to combine, not to lock you in. * ⚡ **Scala 3 first** — built around `derives`, `given`, enums, and macros. * 🔋 **Production-tested** — battle-hardened code, refined from the Airframe ecosystem. ## Uni and Airframe Uni is the Scala 3 successor of [Airframe](https://github.com/wvlet/airframe). The two projects have different goals: * **Uni** supports only Scala 3. Dropping Scala 2 lets it make full use of Scala 3 features in its APIs and implementation. It also bundles the core utilities into a few modules (`uni`, `uni-netty`, `uni-test`) instead of many `airframe-*` artifacts. * **Airframe** supports both Scala 2 and Scala 3, and it remains maintained. There is no plan to deprecate it. ::: tip Which one should I use? For a new Scala 3 project, use Uni. If your project still needs Scala 2, or you depend on Airframe modules that Uni doesn't cover, keep using Airframe. See the [Airframe migration table](./for-ai-agents#how-do-i-migrate-from-airframe) for how APIs map between them. ::: ## What's inside #### Core | Module | Description | |--------|-------------| | [Design](/core/design) | Object wiring with lifecycle management | | [Logging](/core/logging) | Logging with source-location tracking | | [Surface](/core/surface) | Compile-time type introspection | | [FileSystem](/core/filesystem) | Cross-platform file I/O with `IOPath` | #### Data & Serialization | Module | Description | |--------|-------------| | [JSON](/core/json) | Pure-Scala JSON parser and DSL | | [MessagePack](/core/msgpack) | Compact binary serialization | | [Weaver](/core/weaver) | Derivation-based codecs — JSON / MessagePack / `Map` from one `derives Weaver` | #### Async & Control Flow | Module | Description | |--------|-------------| | [Rx](/rx/) | Reactive streams and async data flows | | [Control](/control/) | Retry, circuit breaker, rate limiter, cache, resources | | [BackgroundTask](/control/background-task) | Cancellable, progress-pollable background workers | #### HTTP & RPC | Module | Description | |--------|-------------| | [HTTP](/http/) | Cross-platform client **and** server (Netty / Node.js / Native) | | [RPC](/http/rpc) | Type-safe remote calls, with client code generation | | [WebSocket](/http/websocket) | Cross-platform bidirectional WebSocket client | | [Server-Sent Events](/http/sse) | One-way server→client streaming | #### UI & CLI | Module | Description | |--------|-------------| | [CLI](/cli/) | Terminal styling, progress bars, command launching | | [Web UI](/dom/) | Reactive browser UIs (Scala.js): RxElement and the HTML DSL in `uni`, ready-made components in `uni-ui` | | [Desktop Apps](/http/electron) | Electron apps with a Scala.js renderer and typed RPC to the main process | #### Testing | Module | Description | |--------|-------------| | [UniTest](/core/unitest) | Lightweight, expressive, cross-platform test framework | ## Next steps * 📦 [**Installation**](./installation) — add Uni to your sbt / Scala CLI project * 🧭 [**Design Principles**](./principles) — the architecture and the *why* * 🔍 [**Core Utilities**](/core/) — start exploring the foundational APIs --- --- url: https://wvlet.org/uni/guide/installation.md --- # Installation ## Requirements * Scala 3.9 (LTS) or later. uni's artifacts are compiled with Scala 3.9, and older compilers cannot read their TASTy. * sbt 1.9+ or sbt 2.x ## Adding Dependencies Add uni to your `build.sbt`: ```scala // Core utilities (object wiring, logging, JSON, HTTP, Rx, etc.) libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" ``` ### HTTP Server on the JVM To run an HTTP server on the JVM, add the Netty-based server module (it pulls in `uni` transitively): ```scala // Netty-based HTTP server (JVM only) libraryDependencies += "org.wvlet.uni" %% "uni-netty" % "2026.2.0" ``` See the [REST Server guide](../http/server.md) for usage. On Scala.js and Scala Native, the HTTP server backends that `Http.server` uses are included in `uni` itself — no extra module is needed. ### Testing Framework Add [UniTest](../core/unitest.md) as a test dependency and register its test framework: ```scala libraryDependencies += "org.wvlet.uni" %% "uni-test" % "2026.2.0" % Test testFrameworks += new TestFramework("wvlet.uni.test.Framework") ``` ## Cross-Platform Projects For Scala.js or Scala Native projects on sbt 1.x, use `%%%`: ```scala // Scala.js / Scala Native (sbt 1.x) libraryDependencies += "org.wvlet.uni" %%% "uni" % "2026.2.0" libraryDependencies += "org.wvlet.uni" %%% "uni-test" % "2026.2.0" % Test ``` On sbt 2.x, `%%` resolves the platform-specific artifact for all platforms, so `%%%` is not needed. ::: tip Scala Native and libcurl No system libraries are needed to build a Scala Native binary against uni. Only reaching for the HTTP client pulls in libcurl, which must then be present as a shared library — see [Linking libcurl on Scala Native](../http/client.md#linking-libcurl-on-scala-native). ::: ## Imports Common imports for getting started: ```scala // Object wiring import wvlet.uni.design.Design // Logging import wvlet.uni.log.{LogSupport, Logger, LogLevel} // JSON import wvlet.uni.json.JSON // HTTP import wvlet.uni.http.{Http, HttpRequest, HttpResponse} // Reactive streams import wvlet.uni.rx.Rx // Control flow import wvlet.uni.control.{Retry, CircuitBreaker, Resource} ``` ## Verifying Installation Create a simple test to verify the installation: ```scala import wvlet.uni.log.LogSupport object Main extends App with LogSupport: info("uni is working!") ``` Run with: ```bash sbt run ``` You should see log output with your message. ## IDE Support uni works with all major Scala IDEs: * **IntelliJ IDEA** with Scala plugin * **VS Code** with Metals * **Neovim** with Metals The library uses standard Scala 3 features, so IDE support is seamless. --- --- url: https://wvlet.org/uni/guide/principles.md --- # Design Principles uni is built on a set of core principles that guide its design and implementation. ## Minimal Dependencies uni avoids heavy external dependencies. The core module has minimal dependencies, making it suitable for: * Applications with strict dependency requirements * Libraries that don't want to impose dependencies on users * Environments where classpath size matters (Scala.js, Native) ## Cross-Platform First Every feature is designed to work across: | Platform | Support | |----------|---------| | JVM | Full support | | Scala.js | Browser and Node.js | | Scala Native | Native binaries | Platform-specific code is isolated in `.jvm`, `.js`, and `.native` directories. ## Compile-Time Safety uni leverages Scala 3's type system for compile-time guarantees: ```scala // Object wiring is type-safe val design = Design.newDesign .bindImpl[UserRepository, PostgresUserRepository] // Surface provides compile-time type reflection val surface = Surface.of[User] ``` ## Composable Design Small, focused utilities that combine well: ```scala // Combine retry with HTTP client val response = Retry .withBackOff(maxRetry = 3) .run { httpClient.send(request) } // Combine Rx with resource management Rx.interval(1, TimeUnit.SECONDS) .take(10) .map(i => fetchData(i)) .subscribe(println) ``` ## Lifecycle Management Proper resource lifecycle through Design sessions: ```scala val design = Design.newDesign .bindSingleton[DatabasePool] .onStart(_.connect()) .onShutdown(_.close()) design.withSession { session => // DatabasePool is connected val pool = session.build[DatabasePool] // Use pool... } // Automatically closed ``` ## Functional Patterns Embrace functional programming patterns: * Immutable data structures * Pure functions where possible * Effect handling with Rx * Pattern matching over type checks ```scala // Transform with pattern matching json.transform { case Success(value) => processValue(value) case Failure(error) => handleError(error) } // Functional error handling Rx.single(riskyOperation()) .recover { case e: NetworkError => fallbackValue } .subscribe(handleResult) ``` ## Configuration Classes Config classes use a `withXXX` pattern for immutable updates: ```scala val config = HttpClientConfig() .withConnectTimeout(5000) .withReadTimeout(30000) .withMaxRetries(3) ``` Optional fields support `noXXX` methods: ```scala val config = HttpClientConfig() .noRetry // Disable retry .noLogging // Disable request logging ``` ## Avoid Try\[A] Return Types Instead of returning `Try[A]`, uni uses: * Direct exceptions for programming errors * `Either[Error, A]` for expected failures * `Rx[A]` for async operations with error handling This makes error handling explicit while avoiding the overhead of wrapping every result. --- --- url: https://wvlet.org/uni/guide/for-ai-agents.md description: >- How AI coding agents should pick and use Uni, the Scala 3 utility library for object wiring (Design), logging, JSON/MessagePack, HTTP, RPC, MCP servers, and testing on JVM, Scala.js, and Scala Native. --- # Uni for AI Agents **Uni is a single Scala 3 library (`org.wvlet.uni`) that covers object wiring, logging, JSON/MessagePack serialization, reactive streams, HTTP client/server, typed RPC, MCP servers, and unit testing, and the same code runs on the JVM, Scala.js, and Scala Native.** It is the Scala 3 successor of [Airframe](https://github.com/wvlet/airframe). This page is written for AI coding agents (Claude Code, Codex, Cursor, Copilot, and others) and for the people who configure them. It sums up when to choose Uni, the canonical imports, and the mistakes agents most often make. ## Machine-readable docs | URL | Contents | |-----|----------| | [`/uni/llms.txt`](https://wvlet.org/uni/llms.txt) | Index of every documentation page, with links to Markdown versions | | [`/uni/llms-full.txt`](https://wvlet.org/uni/llms-full.txt) | The full documentation in one Markdown file | | `/uni/
/llms.txt`, `/uni/
/llms-full.txt` | The same for one section, such as [`/uni/dom/llms-full.txt`](https://wvlet.org/uni/dom/llms-full.txt) for browser UIs or `/uni/http/llms-full.txt` for HTTP and RPC | | `.md` | Markdown version of a page, e.g. [`/uni/guide/for-ai-agents.md`](https://wvlet.org/uni/guide/for-ai-agents.md). A section index such as `/uni/guide/` is published as `/uni/guide.md`. | ## How do I install the Uni skill? The `wvlet/uni` repository is a Claude Code plugin marketplace. Its `uni` plugin adds an Agent Skill with the canonical imports, sbt setup, verified snippets, and the mistakes listed on this page. Claude Code loads it whenever a task touches Uni or asks for object wiring, logging, JSON, HTTP, RPC, MCP, or tests in Scala 3. ```text /plugin marketplace add wvlet/uni /plugin install uni@uni ``` On Claude Code 2.1.275 or later, `/plugin install uni --marketplace wvlet/uni` does both in one step. Agents without a plugin system can read [`llms-full.txt`](https://wvlet.org/uni/llms-full.txt) instead. ## When should I use Uni? Choose Uni when a Scala 3 project needs one or more of the following and you want few transitive dependencies: * Object wiring with lifecycle management (`Design`), instead of a framework * Structured logging with source locations (`LogSupport`) * JSON or MessagePack codecs derived from case classes (`derives Weaver`) * An HTTP client that works on the JVM, Node.js/browser, and native binaries * An HTTP/RPC server (Netty, JVM) or a stdio MCP server for AI tools * A test framework that runs on all three platforms (`UniTest`) Do not mix in Airframe artifacts for the same features. Uni replaces them. For scripts, teaching, Scala 2.13, or running subprocesses, the Scala Toolkit is often the better fit, and it works alongside Uni. See the next section and [Uni and the Scala Toolkit](./uni-vs-scala-toolkit). ## Should I use the Scala Toolkit or Uni? Use the [Scala Toolkit](https://docs.scala-lang.org/toolkit/introduction.html) (sttp, uPickle, os-lib, MUnit) for scripts, teaching, Scala 2.13, or Scala 3 before 3.9. Use Uni when the project also needs object wiring, logging, an HTTP server, RPC, or MCP servers, or must run the same code on Scala.js and Scala Native. The two coexist in one build. See [Uni and the Scala Toolkit](./uni-vs-scala-toolkit). ## How do I add Uni to a build? ```scala // build.sbt libraryDependencies ++= Seq( "org.wvlet.uni" %% "uni" % "2026.2.0", "org.wvlet.uni" %% "uni-test" % "2026.2.0" % Test ) testFrameworks += new TestFramework("wvlet.uni.test.Framework") // JVM-only Netty HTTP server libraryDependencies += "org.wvlet.uni" %% "uni-netty" % "2026.2.0" ``` Uni requires Scala `3.9.0` or later. On sbt 2.x, use `%%` for all platforms. On sbt 1.x, use `%%%` for Scala.js and Scala Native projects. ## What are the canonical imports? | Task | Import | Entry point | |------|--------|-------------| | Object wiring | `wvlet.uni.design.Design` | `Design.newDesign.bindSingleton[A].build[A] { a => ... }` | | Logging | `wvlet.uni.log.LogSupport` | `class A extends LogSupport` then `info(...)`, `debug(...)` | | JSON / MessagePack codec | `wvlet.uni.weaver.Weaver` | `case class P(...) derives Weaver`, `Weaver.toJson(p)`, `Weaver.fromJson[P](json)` | | JSON tree | `wvlet.uni.json.JSON` | `JSON.parse(text)` | | YAML config / frontmatter | `wvlet.uni.text.yaml.{YAML, Frontmatter}` | `YAML.fromYaml[P](text)`, `YAML.parse(text)`, `Frontmatter.parse(md).as[P]`. To edit in place and keep comments: `YAML.parseDocument(text).set(path, v).toYaml` (`YAML.parseDocuments` and `YAML.writeStream` for `---` streams), `Frontmatter.parse(md).update(json).toText`. See [YAML](../text/yaml) | | Markdown to HTML | `wvlet.uni.text.markdown.{Markdown, MarkdownConfig}` | `Markdown.toHtml(md)` (raw HTML escaped by default), `Markdown.parse(md)` for the AST, `.frontmatterAs[P]` for a YAML header, and `.toMarkdown` to write an edited AST (including `frontmatter`) back losslessly. See [Markdown](../text/markdown) | | Cron schedules | `wvlet.uni.text.cron.{Cron, UtcOffset}` | `Cron.parse("30 9 * * MON-FRI")`, `.next(instant)` / `.nextN(instant, n)` (UTC, or a fixed `UtcOffset`; resolve named zones yourself), `.matches(instant)`, `.describe` ("At 09:30, Monday through Friday"). 5 or 6 fields, macros like `@daily`, Vixie day-of-month/day-of-week semantics. See [Cron](../text/cron) | | Reactive streams | `wvlet.uni.rx.Rx` | `Rx.variable(v)`, `Rx.single(v)`, `.map`, `.flatMap`, `.scan(init)(f)` (running value), `itemsRx.split(_.id)` (one stable `Rx` per key, completed when the key leaves), `.onCancel(f)` (cleanup when a subscriber cancels early) | | Persisted settings | `wvlet.uni.config.SettingStore` | `SettingStore.of[AppSettings].withAppName("my-app").withVersion(n).load()`, then `update(...)`; saved to `~/.config/my-app/` (localStorage in a browser). See [SettingStore](../core/settings) | | HTTP client | `wvlet.uni.http.{Http, Request}` | `Http.client.newSyncClient.send(Request.get(url))` | | HTTP server (all platforms) | `wvlet.uni.http.Http` | `Http.server.withPort(8080).withRxHandler(handler).start()`: Netty on the JVM (add `uni-netty`), Node.js on Scala.js, native sockets on Scala Native. Backend-only options: `.withBackend(Netty.options.withHandlerExecutorThreads(8))` (`Native.options` on Scala Native). See [REST Server](../http/server#cross-platform-servers) | | HTTP server (JVM only) | `wvlet.uni.http.netty.Netty` | `Netty.server.withPort(8080).withHandlerExecutorThreads(8).withRxHandler(handler).start()`: every Netty setting in one config, for projects that never target Scala.js or Native. `NettyServer` was removed; use `Netty.server` (JVM only) or `Http.server`. See [REST Server](../http/server#jvm-only-apps-netty-server) | | Static files (JVM, Node.js, Native) | `wvlet.uni.http.StaticFiles` | `Http.server.withFilter(StaticFiles("dist").withSpaFallback(true)).withRxHandler(api)`: serves `GET` for files under `dist` and passes other requests on. It refuses traversal, symlinks, and dotfiles by default. See [REST Server](../http/server#static-files) | | CORS (JVM, Node.js, Native) | `wvlet.uni.http.{CorsFilter, CorsPolicy}` | `Http.server.withFilter(CorsFilter(CorsPolicy().withAllowedOrigins("https://app.example.com"))).withRxHandler(api)`: answers preflights and adds `Access-Control-*` headers for allowed origins. No origin is allowed by default. See [REST Server](../http/server#cors) | | REST router (JVM, `uni-netty`) | `wvlet.uni.http.netty.RouterHandler` | `Http.server.withRxHandler(RouterHandler(Router.of[Controller]))`. See [REST Server](../http/server) | | Typed RPC | `wvlet.uni.http.rpc.{RPCRouter, RPCClient}` | Server: `RPCRouter.of[Api](impl)`; client: `RPCClient.of[Api].newSyncClient(http).call[A]("method", args*)` (or `newAsyncClient` for `Rx[A]`); `newAsyncClient(http).stream[A]("method", args*)` streams every value of an `Rx` result over SSE or Electron IPC; cancelling it stops the server stream; declare such methods as returning `RxStream[A]` (`wvlet.uni.rx.RxStream`, built with `RxStream(rx)`) so sbt-uni's generated `AsyncClient` streams them. See [RPC](../http/rpc) | | Server-sent events | `wvlet.uni.http.{Response, ServerSentEvent}` | Server: `Response.eventStream(rx)`; client: `Http.client.newAsyncClient.sendSSE(request)`. See [SSE](../http/sse) | | WebSocket | `wvlet.uni.http.{WebSocketHandler, WebSocketContext}` | Server: `.withWebSocketRoute(path) { req => handler }`; client: `Http.webSocketClient.connect(url, handler)`. See [WebSocket](../http/websocket) | | OpenAPI | `wvlet.uni.http.openapi.{OpenAPI, OpenAPIConfig}` | `OpenAPI.of(Router.of[A], OpenAPIConfig()).toYAML`. See [OpenAPI](../http/openapi) | | Browser UI helpers (Scala.js) | `wvlet.uni.dom.all.*` | `itemsRx.each(_.id)(item => li(...))` renders a list item by item, keeping unchanged rows' DOM nodes (prefer it over `itemsRx.map(_.map(...))`, which rebuilds the whole list), `itemsRx.eachRx(_.id)((first, current) => li(current.map(_.text)))` (also keeps a row's nodes when its value changes, passing later values through `current`), `Keyboard.onEnter(() => send())` (skips Shift+Enter and IME-confirm Enter), `Keyboard.scoped("escape" -> (() => close()))`, `PaneResize(width, SizeRange(min, default, max), ResizeDirection.Right).bind` on a handle, `PointerDrag(onMove = (dx, dy) => ...)`. See [Browser Integrations](../dom/rxelement#browser-integrations) | | UI components (Scala.js, `uni-ui`) | `wvlet.uni.ui.*` | Each component takes one parameter list; name its functions, triggers, and multi-value arguments, and pass several values as a `Seq`: `Button("Send").primary.withDisabled(busy).onClick(() => send())`, `IconButton(label, icon)`, `Input(textVar)`, `val tabs = TabList(selectedVar, label = "Views", tabs = Seq(Tab(v, "Label"), ...))` with `TabPanel(tabs, render = v => ...)`, `FoldablePane(open, width = width, edge = Edge.Right, content = Seq(...)).withSplitter(Splitter(width, SizeRange(min, default, max), Edge.Right, "Resize"))`, `ColorScheme.bind(schemeVar)`. Overlays: `Popover(openVar, trigger = element, content = Seq(...))`, `Tooltip("Label", trigger = element)`, `Menu(openVar, trigger = element, entries = Seq(MenuItem("Copy").onSelect(f), MenuSeparator))`, `ContextMenu(target, entries = Seq(...))`, `Dialog(openVar, content = Seq(...)).withTitle(t).withActions(buttons*)`, `AlertDialog(openVar, title = "...").onConfirm(f).danger`, `Select(selectedVar, options = Seq(...), optionLabel = _.label)`, `val toasts = Toaster()` then `toasts.success(msg)`. Collections render only the rows in view (fixed row height): `VirtualList(itemsRx, rowHeight = 24, key = _.id, render = a => node)`, `Tree(rootsRx, children = _.children, key = _.path, render = a => node).withExpanded(setVar)`, `DataTable(rowsRx, key = _.id, columns = Seq(Column[Row]("name", "Name", cell = r => span(r.name)).sortBy(_.name))).withSort(sortVar)`; lists, trees, and tables select one row with `.withSelected(optionVar)` or several with `.withMultiSelect(setVar)`, and lists and tables move rows by drag or Alt+ArrowUp/Down with `.withReorder(itemsVar)` (`onChange` key `order`), `CommandPalette(openVar, commandsRx)` with `Command(id, label).withGroup(g).onRun(f)` (bind ⌘K yourself with `Keyboard.bindAll`); a `Dock(layoutVar, label = "Dock", panels = Seq(DockPanel(id, title = "...", content = element)))` of tab groups and splits the user rearranges, whose `DockLayout` (`DockNode.row/column/group`, and `floating = Seq(DockFloat.of(DockBox(x, y, w, h), ids*))` for groups over the grid) saves with `Storage.local(key, default)`, `.withDetach(true)` lets a panel open in a window of its own (`dock.detach(id)`), and `dock.focusGroup(i)` (0-based) or `dock.focusPanel(id)` moves keyboard focus; sides and alignment are `wvlet.uni.ui.base.{Side, Align}`. Load `uni-ui.css` once: `enablePlugins(UniPlugin)` (sbt-uni) copies it from the jar to `uniUiCssFile` on every compile, for an `@import` in the app stylesheet; restyle with `--uni-*` CSS variables. Every component takes `.onChange(d => ...)` to see, and `d.cancel()` to refuse, the changes it makes (`d.reason`, `d.source`: `Pointer`/`Keyboard`/`Programmatic`/`Agent`); callbacks read `ChangeCause.current`; parts carry `data-slot` (`menu-item`, `dialog-title`). `UiAgent.install()` (`wvlet.uni.ui.agent`) lets an AI agent `snapshot()` the components and `act(ref, action, value)` on them as `ChangeSource.Agent` (an open dialog makes the page behind it `inert`, so the agent reaches only the dialog), with `UiAgent.hidden`/`secret`/`confirm(msg)` marks and an `AgentPolicy` (name list, tree, and table rows for it with `.withRowLabel(r => text)`; otherwise lists and trees use the typeahead text, then every component the key; `.withAgentConfirm(r => Option(msg))` asks the human before an agent selects or drops a guarded row; a field with `.withReadOnly(true)` refuses agent edits; toasts offer `dismiss`, and an open `CommandPalette` offers `run`, so give agents an opener for it); `agent.api` (`wvlet.uni.agent.UiAgentApi`) serves as MCP tools or WebMCP (`agent.installWebMcp()`). `UiHistory.record()` records changes by source; `history.undoSource(ChangeSource.Agent)` reverts the agent's (Dock layouts and splitter sizes included) without overwriting later edits, and `history.stage(label)` collects agent suggestions to `accept()` or `revert()` together. See [Components](../dom/ui), [Changes & Parts](../dom/changes), and [Agents](../dom/agents) | | UI behaviors (Scala.js, `uni-ui`) | `wvlet.uni.ui.base.*` | Interaction logic for building your own widgets: `StickToBottom()` (`stick.binding` on a scroller, `stick.atBottom`, `stick.scrollToBottom()`), `InputHistory()` (`history.keys(draftVar)` on a textarea, `history.add(text)`), `Typeahead().onKey(e, labels, active)`, `Selection(selectedSetVar).press(key, order, e)` (Shift range, Ctrl/Cmd toggle), `Reorder(orderVar)` or `Reorder.by(itemsVar)(_.id)` (`reorder.item(k)` on each item: drag, or Alt+ArrowUp/Down; `Reorder.grip` or `Reorder.handle` for a grip, the only place a touch drag starts; `.withSelection(selectedSetVar)` moves the selected items together), `FocusRecovery.within("li")`, `Announce.polite(msg)`, `RovingFocus.nextIndex` (`rtl = TextDirection.mirrors(e)` mirrors Left/Right; uni-ui widgets do this on their own), `ListNavigation`, `FocusTrap`, `Dismiss`, `Anchored`. uni-dom's `OnMount(el => cancelable)` binds any behavior to an element. See [Behaviors](../dom/behaviors) | | Terminal emulator | `wvlet.uni.cli.term.{TerminalEmulator, TerminalConfig}` | `TerminalEmulator(TerminalConfig(cols = 80, rows = 24))`, `term.write(output)`, then `term.screen.text` or `term.screen.lineText(row)`: an xterm-compatible emulator on JVM, Scala.js, and Native, for checking what a TUI draws. `PtyProcess.connect(term, pty)` wires a shell; on Scala.js, `NodePty.spawn(nodePty, shell, args, options)` takes the app's `node-pty` module. On the JVM (Java 22+) and Native, `PosixPty.spawn(file, args, options)` starts the program in a real PTY on Linux and macOS (check `PosixPty.isSupported`). With shell integration (OSC 133), `term.commands` lists each `TerminalCommand(line, command, output, exitCode)` and `term.onCommandFinished` reports one as it ends | | Terminal pane (Scala.js) | `wvlet.uni.dom.{TerminalView, TerminalViewConfig, TerminalTheme}` | `TerminalView(term)` draws the emulator in the DOM, with Uni's `TerminalTheme.uniDark` by default; `view.setTheme(TerminalTheme.uniLight)` switches (`TerminalTheme.presets` lists all). OSC 8 links with `http`, `https`, or `mailto` (`TerminalLink.isAllowed`) open on Cmd+click (Ctrl elsewhere); in Electron pass `view.onLinkClick` a bridge to `shell.openExternal` in the main process. OSC 133 prompts get a green or red marker; `view.scrollToPreviousPrompt()` / `scrollToNextPrompt()` (Cmd+Up/Down, Ctrl+Shift+Up/Down elsewhere) jump between them | | Electron IPC (Scala.js) | `wvlet.uni.electron.{ElectronRPCServer, ElectronRenderer, ElectronMain}` | Renderer→main: `ElectronRPCServer.serve(ipcMain, router)` and `ElectronRenderer.install()`. Main→renderer: `ElectronRenderer.serve(router)` in the page (preload adds `serve`), `ElectronMain.newAsyncClient(ipcMain, webContents)` in main. See [Desktop Apps (Electron)](../http/electron) | | MCP server / client | `wvlet.uni.mcp.MCP` | `MCP.server.withTools[T](impl)...`, `MCP.client.connect(url)`; see [Build an MCP Server](../mcp/) | | Off-heap memory | `wvlet.uni.canvas.{Canvas, OffHeapMemoryAllocator}` | `val c = Canvas.newOffHeapCanvas(size)` (`Long` size, beyond 2 GB), `c.writeInt(offset, v)`, `c.readLongBigEndian(offset)`, `c.slice(offset, length)`, then `c.close()` to free it now. Little-endian with `*BigEndian` variants; bounds-checked. JVM needs Java 22+ (FFM; check `Canvas.isOffHeapSupported`); Scala Native frees memory only on `close()`. Heap canvases: `Canvas.newCanvas(n)`, `Canvas.wrap(bytes)`. See [Canvas](../core/canvas) | | Retry / circuit breaker | `wvlet.uni.control.{Retry, CircuitBreaker}` | `Retry.withBackOff().run { ... }` | | CLI arguments | `wvlet.uni.cli.launcher.*` | `Launcher.execute[A](args)` on a case class with `@option` fields. See [Command Launcher](../cli/launcher) | | Unit tests | `wvlet.uni.test.*` | `class T extends UniTest: test("...") { x shouldBe y }` | | Test fixtures | `wvlet.uni.test.*` | `addDesign(_.bindSingleton[A])` in a trait that extends `UniTest`, then `test("...") { (a: A) => ... }`. See [Reusable Fixtures](../core/unitest#reusable-fixtures) | | Error-path tests | `wvlet.uni.test.*` | `val logs = captureLogs { ... }; logs.warnings shouldContain "..."`; also `captureStdout` / `captureStderr`. See [Testing Error Paths](../core/unitest#testing-error-paths) | | uni-dom UI tests (Scala.js) | `wvlet.uni.dom.testing.*` | With `uni-test`, `class T extends DomTestSupport`, `val m = mount(MyView())`, `fireEvent.click(m.get("button"))` (also `pointerDown`/`Move`/`Up`, `keyDown(..., isComposing = true)`), and return `settle().map { _ => ... }` to assert on `onMount` effects. `checkPattern(el, AriaPattern.Menu).map(_ shouldBe empty)` checks a widget against its WAI-ARIA pattern ([guide](../dom/testing#checking-aria-patterns)). Run in headless Chromium with the [sbt-uni-playwright Plugin](../build/sbt-uni-playwright#testing-uni-dom-components) | ## How do I migrate from Airframe? | Airframe | Uni | |----------|-----| | `wvlet.airframe.Design` / `newDesign` | `wvlet.uni.design.Design` / `Design.newDesign` | | `wvlet.log.LogSupport` | `wvlet.uni.log.LogSupport` | | `wvlet.airframe.codec.MessageCodec` | `wvlet.uni.weaver.Weaver` (`derives Weaver`) | | `wvlet.airframe.surface.Surface` | `wvlet.uni.surface.Surface` | | `wvlet.airframe.rx.Rx` | `wvlet.uni.rx.Rx` | | `wvlet.airframe.http.Http` | `wvlet.uni.http.Http` | | `wvlet.airframe.http.netty.Netty.server` | `wvlet.uni.http.netty.Netty.server` (JVM only), or `Http.server` for cross-platform code | | `wvlet.airframe.http.filter.Cors` (`Cors.Policy`, `Cors.newFilter`) | `wvlet.uni.http.CorsFilter(CorsPolicy())`, added with `Http.server.withFilter` | | `wvlet.airframe.http.RPCStatus` / `RPCException` | `wvlet.uni.http.ServiceStatus` / `ServiceException`: same status names and codes, shared by RPC, Electron IPC, and MCP | | `wvlet.airframe.canvas.Canvas` | `wvlet.uni.canvas.Canvas`: `release` is `close()`, values are little-endian on every platform, and off-heap canvases need Java 22+ on the JVM | | `wvlet.airframe.control.Retry` | `wvlet.uni.control.Retry` | | `wvlet.airspec.AirSpec` | `wvlet.uni.test.UniTest` | | AirSpec `initDesign` / `initLocalDesign` | `addDesign` / `addTestDesign` | | AirSpec `test("...") { (a: A) => ... }` | the same: test arguments come from the suite's Design | Uni uses a separate package root (`wvlet.uni.*`), so both libraries can coexist during a migration. See [Appendix B: Uni and Airframe](../book/appendix-b-airframe) for background. ## What mistakes do agents make with Uni? * **Using Scala 2 syntax.** Uni is Scala 3 only. Use indentation syntax, `given`/`using`, `enum`, and `derives`. * **Using ScalaTest matchers in UniTest.** Write `(x >= 1) shouldBe true`, not `x should be >= 1`. For type checks, write `v shouldMatch { case _: T => }` instead of `asInstanceOf`. * **Importing only `UniTest`.** Use `import wvlet.uni.test.*`. `shouldBe defined` and `shouldBe empty` need matcher objects from that package. * **Checking `isSuccessful` after `send`.** The HTTP client throws for non-2xx responses. Most 4xx statuses throw `HttpException`. Retryable statuses (5xx, 429\) throw `HttpMaxRetryException` after the retries, and it is not a subclass of `HttpException`. Failed RPC client calls throw the same exceptions. Report server errors by throwing `ServiceStatus.NOT_FOUND_U5.newException("...")` (`wvlet.uni.http.{ServiceStatus, ServiceException}`): RPC, `Router`, and other `Http.server` endpoints answer with its HTTP status, the `X-RPC-Status` header, and a JSON error body. `RPCStatus` is its deprecated old name. * **Hand-writing test setup and teardown.** Bind servers, clients, and temp directories with `addDesign` / `addTestDesign` in a trait that extends `UniTest`, and take them as test arguments. A self-type fixture (`trait F { this: UniTest => }`) compiles, but when two of them override a hook, only the last one runs. * **Hand-writing JSON codecs.** Add `derives Weaver` to the case class. * **Mixing two libraries for one concern in the same module.** Uni works alongside community libraries. If a project already uses uPickle, MUnit, sttp, or another library for a concern, keep using it there. Use Uni's equivalent for new code that is built on Uni. ## Where are complete example apps? The [`examples/`](https://github.com/wvlet/uni/tree/main/examples) folder of the repository has small apps that CI compiles and tests against the current source. Copy one as a template: | Example | Shows | |---------|-------| | [`cli-tool`](https://github.com/wvlet/uni/tree/main/examples/cli-tool) | `Launcher` sub-commands, `LogSupport`, `derives Weaver`, the HTTP client, and a Scala Native binary | | [`rest-server`](https://github.com/wvlet/uni/tree/main/examples/rest-server) | `Http.server` with `Router` and `RPCRouter`, a typed RPC client, `Design` wiring, and a UniTest suite | | [`rpc-native`](https://github.com/wvlet/uni/tree/main/examples/rpc-native) | One RPC server built with `Http.server` and `Design`, the same code on the JVM (Netty) and as a Scala Native binary (no JVM), a typed client, a UniTest suite run on both, and a startup/memory/throughput benchmark | | [`mcp-server`](https://github.com/wvlet/uni/tree/main/examples/mcp-server) | A stdio MCP server with `MCP.server.withTools[...]` and how to add it to Claude Code | | [`web-ui`](https://github.com/wvlet/uni/tree/main/examples/web-ui) | A Scala.js todo list with `RxElement` and `Rx.variable` | ## Example: a wired service with logging and JSON ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport import wvlet.uni.weaver.Weaver case class Greeting(name: String, message: String) derives Weaver class GreeterService extends LogSupport: def greet(name: String): String = info(s"Greeting ${name}") Weaver.toJson(Greeting(name, s"Hello, ${name}!")) @main def main = Design.newDesign .bindSingleton[GreeterService] .build[GreeterService] { greeter => println(greeter.greet("Uni")) } ``` --- --- url: https://wvlet.org/uni/guide/uni-vs-scala-toolkit.md description: >- Scala Toolkit or Uni? When to choose the official Scala starter kit (sttp, uPickle, os-lib, MUnit), when to add Uni (object wiring, logging, HTTP server, RPC, MCP servers, and testing on JVM, Scala.js, and Scala Native), and how to use them together, with a feature table, side-by-side code, and an FAQ. --- # Uni and the Scala Toolkit **The [Scala Toolkit](https://docs.scala-lang.org/toolkit/introduction.html) is the official starter bundle of libraries for scripts, teaching, and everyday tasks. It includes sttp for HTTP requests, uPickle for JSON, os-lib for files and processes, and MUnit for tests, and you add it with one line, `//> using toolkit latest`. Uni is a single Scala 3 library for building applications and services. On top of JSON, HTTP, files, and tests, it adds object wiring (Design), logging, an HTTP server, typed RPC, MCP servers, Rx, and CLI tools, with one API on the JVM, Scala.js, and Scala Native.** In short, the Toolkit is the easiest start for scripts, and Uni covers the whole application. The two can live in the same project. See [Using them together](#using-them-together). ## Feature by feature Toolkit facts are from version 0.9.2 (April 2026) and its published POMs on Maven Central. Uni facts are from the current source. | Need | Scala Toolkit 0.9.2 | Uni | |------|---------------------|-----| | Object wiring and lifecycle | Not included | [Design](../core/design): constructor wiring, singletons, `onStart`/`onShutdown` hooks | | Logging | Not included | [`LogSupport`](../core/logging): `info`/`debug`/`warn` with source locations | | JSON / MessagePack | [uPickle](https://com-lihaoyi.github.io/upickle/): `derives ReadWriter`, JSON and MessagePack | [Weaver](../core/weaver): `derives Weaver`, JSON and MessagePack | | HTTP client | [sttp client4](https://sttp.softwaremill.com/): JVM, Scala.js, Native | [`Http.client`](../http/client): sync and async, retries on by default; JVM, Scala.js (sync on Node.js only), Native (libcurl) | | HTTP server | Not in the artifact; the Toolkit tutorials add [Cask](https://docs.scala-lang.org/toolkit/web-server-intro.html) separately, JVM only | [REST Server](../http/server): Netty on the JVM (`uni-netty`), Node.js on Scala.js, and a native server on Scala Native. Request handlers work on all three; the annotation router (`@Endpoint`) is JVM-only | | RPC | Not included | [Typed RPC](../http/rpc) from a Scala trait (`RPCRouter`, `RPCClient`) | | MCP servers | Not included | [`uni.mcp`](../mcp/): a stdio MCP server on all three platforms | | Reactive streams | Not included | [Rx](../rx/): `Rx.variable`, `Rx.single`, `map`/`flatMap` | | CLI | No argument parser; os-lib runs subprocesses | [Command Launcher](../cli/launcher) for arguments and sub-commands, plus terminal colors, progress bars, and spinners. No subprocess API | | File I/O | [os-lib](https://github.com/com-lihaoyi/os-lib): JVM and Native; **not in the Scala.js artifact** | [`IO`](../core/filesystem): JVM, Scala.js (Node.js; async APIs in browsers), Native | | Testing | [MUnit](https://scalameta.org/munit/) via `toolkit-test`: `assertEquals` | [UniTest](../core/unitest): `shouldBe`, `shouldMatch`, property checks | | Scala versions | Scala 3 (built on 3.3 LTS) and Scala 2.13 | Scala 3.9 or later only | | Platforms | JVM, Scala.js, Scala Native 0.5 | JVM, Scala.js, Scala Native | | Install | `//> using toolkit latest`, or `"org.scala-lang" %% "toolkit" % "0.9.2"` plus `toolkit-test` | `"org.wvlet.uni" %% "uni" % "2026.2.0"` plus `uni-test` ([Installation](./installation)) | ## Choose the Scala Toolkit when… * **You write a script, a notebook, or course material.** The Toolkit is the official answer, its tutorials sit on docs.scala-lang.org, and `//> using toolkit latest` is the shortest setup in Scala. * **You want widely used libraries.** sttp, uPickle, os-lib, and MUnit each have a large user base, many Stack Overflow answers, and broad coverage in AI training data. Uni is newer and has a smaller community. * **You need Scala 2.13 or a Scala 3 version before 3.9.** Uni requires Scala 3.9. * **You run shell commands.** os-lib's subprocess API has no Uni equivalent. * **You only need a few of these features.** Adding one Toolkit library, such as uPickle, is a smaller change than adopting a new library's conventions. ## Choose Uni when… * **You build an application or service, not a script.** Uni covers the parts the Toolkit leaves out: object wiring with lifecycle hooks, logging, an HTTP server, typed RPC, and Rx, all following one set of conventions. * **You build tools for AI agents.** [`uni.mcp`](../mcp/) turns a Scala trait into an MCP server. Compiled with Scala Native, it becomes a single binary that starts instantly. * **The same code must run everywhere.** The HTTP client, file I/O, MCP, and tests work on the JVM, Scala.js, and Scala Native, and so do HTTP servers built from request handlers (the annotation router is JVM-only). In the Toolkit, os-lib is missing on Scala.js and Cask runs on the JVM only. * **You want few transitive dependencies.** On the JVM, `uni` depends only on `uni-core` and the Scala library. * **You are moving from Airframe.** Uni is its Scala 3 successor. See the [migration table](./for-ai-agents#how-do-i-migrate-from-airframe). ## Side by side ### HTTP GET and decode JSON ::: code-group ```scala [Toolkit] skip //> using toolkit latest import sttp.client4.quick.* import upickle.default.* case class Repo(full_name: String, stargazers_count: Int) derives ReadWriter @main def showRepo = val response = quickRequest.get(uri"https://api.github.com/repos/scala/toolkit").send() val repo = read[Repo](response.body) println(s"${repo.full_name}: ${repo.stargazers_count} stars") ``` ```scala [Uni] //> using dep org.wvlet.uni::uni:2026.2.0 import wvlet.uni.http.{Http, Request} import wvlet.uni.weaver.Weaver case class Repo(full_name: String, stargazers_count: Int) derives Weaver @main def showRepo = val client = Http.client.newSyncClient val response = client.send(Request.get("https://api.github.com/repos/wvlet/uni")) val repo = Weaver.fromJson[Repo](response.contentAsString.getOrElse("{}")) println(s"${repo.full_name}: ${repo.stargazers_count} stars") client.close() ``` ::: Both decoders ignore JSON fields the case class does not declare. The Uni client throws `HttpException` for most 4xx responses and retries 5xx and 429 before it throws `HttpMaxRetryException`, so you do not need to check the status code. ### A unit test ::: code-group ```scala [Toolkit] skip class MyTests extends munit.FunSuite: test("sum of two integers") { val obtained = 2 + 2 val expected = 4 assertEquals(obtained, expected) } ``` ```scala [Uni] import wvlet.uni.test.* class MyTests extends UniTest: test("sum of two integers") { val obtained = 2 + 2 obtained shouldBe 4 } ``` ::: ### Write and read a file ::: code-group ```scala [Toolkit] skip val path = os.pwd / "notes.txt" os.write.over(path, "hello") println(os.read(path)) ``` ```scala [Uni] import wvlet.uni.io.IO IO.writeString("notes.txt", "hello") println(IO.readString("notes.txt")) ``` ::: The os-lib version runs on the JVM and Scala Native. The Uni version also runs on Scala.js under Node.js. ## Using them together Uni and the Toolkit coexist. Their packages do not overlap (`wvlet.uni.*` vs. `sttp`, `upickle`, `os`, `munit`), and Uni has no dependency that conflicts with them. We checked this with Scala CLI, Toolkit 0.9.2, and Uni on Scala 3.9: * One case class can derive both `ReadWriter` and `Weaver`. * A MUnit `FunSuite` can test Uni code, and MUnit and UniTest suites run in the same `test` command. Common combinations: * **Keep MUnit, add Uni.** Test Uni services with your existing MUnit suites, and register UniTest too (`testFrameworks += new TestFramework("wvlet.uni.test.Framework")` in sbt) only if you want its matchers. * **Keep os-lib for subprocesses** in a Uni application. * **Pick one JSON library per type.** Having both is possible, but two codecs for the same case class are two things to keep in sync. If you use Uni's HTTP server or RPC, use Weaver, because they encode with it. ## FAQ ### Should I use the Scala Toolkit or Uni? Use the Toolkit for scripts, teaching, Scala 2.13, or Scala 3 before 3.9. Use Uni when you build a Scala 3.9+ application or service that needs object wiring, logging, an HTTP server, RPC, or MCP servers, or the same code on Scala.js and Scala Native. Many projects use both. ### Can I use the Scala Toolkit and Uni in the same project? Yes. Their packages do not overlap, and Uni brings no dependency that conflicts with the Toolkit. See [Using them together](#using-them-together) for common combinations. ### What should I use when my Toolkit script grows into a service? Keep the Toolkit libraries that still do their job, and add what a service needs: object wiring with lifecycle hooks, logging, and an HTTP server. Uni provides these in one library, and you can add it one piece at a time. ### Does the Scala Toolkit include object wiring or logging? No. The Toolkit focuses on HTTP requests, JSON, files and processes, and tests. Uni's [Design](../core/design) and [`LogSupport`](../core/logging) cover object wiring and logging, and work next to the Toolkit libraries. ### Does Uni support Scala 2.13? No. Uni requires Scala 3.9 or later. For Scala 2.13, the Toolkit is a good choice, and [Airframe](https://github.com/wvlet/airframe) provides object wiring and logging. --- --- url: https://wvlet.org/uni/core.md --- # Core Utilities The `uni` module provides essential utilities for Scala application development. ## Overview | Component | Description | |-----------|-------------| | [Design](./design) | Object wiring with lifecycle management | | [UniTest](./unitest) | Lightweight testing framework | | [Logging](./logging) | Structured logging with LogSupport | | [JSON](./json) | Pure Scala JSON parser and DSL | | [MessagePack](./msgpack) | Binary serialization format | | [Weaver](./weaver) | Derivation-based serialization (JSON / MessagePack / Map) | | [Surface](./surface) | Compile-time type introspection | | [FileSystem](./filesystem) | Cross-platform file I/O with IOPath | | [Canvas](./canvas) | Off-heap memory buffers larger than 2 GB, with `Long` offsets | | [YAML](../text/yaml) | YAML 1.2 parser with Weaver decoding and frontmatter | | [Markdown](../text/markdown) | CommonMark + GFM parser and safe HTML renderer | | [Cron](../text/cron) | Cron expression parser with next-run times and English descriptions | | [Utilities](./utilities) | IDs (UUIDv7, ULID, NanoId), encodings (Base62, CrockfordBase32), value types (DataSize, Count, ElapsedTime), timing (StopWatch, Timer) | ## Quick Start ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport import wvlet.uni.json.JSON // Service with logging class UserService extends LogSupport: def findUser(id: String): Option[User] = debug(s"Finding user: ${id}") // Implementation None // Object wiring with Design val design = Design.newDesign .bindSingleton[UserService] design.build[UserService] { service => service.findUser("123") } // JSON parsing val json = JSON.parse("""{"name": "Alice", "age": 30}""") val name = json("name").toStringValue // "Alice" ``` ## Package Structure ``` wvlet.uni.design - Object wiring framework wvlet.uni.log - Logging framework wvlet.uni.json - JSON processing wvlet.uni.msgpack - MessagePack serialization wvlet.uni.surface - Type reflection wvlet.uni.weaver - Object serialization wvlet.uni.io - Cross-platform file system wvlet.uni.canvas - Off-heap memory buffers wvlet.uni.util - ID generators and value types ``` ## Cross-Platform Support All core utilities work across JVM, Scala.js, and Scala Native platforms. | Feature | JVM | JS | Native | |---------|-----|-----|--------| | Design | ✓ | ✓ | ✓ | | Logging | ✓ | ✓ | ✓ | | JSON | ✓ | ✓ | ✓ | | MessagePack | ✓ | ✓ | ✓ | | Surface | ✓ | ✓ | ✓ | | FileSystem | ✓ | ✓ | ✓ | | Utilities | ✓ | ✓ | ✓ | --- --- url: https://wvlet.org/uni/core/design.md --- # Design Design is a framework for building and wiring complex objects at runtime. It provides a declarative way to define how objects are constructed and connected, managing their lifecycles automatically. ## Core Concepts Design is built around two fundamental abstractions: * **Design**: An immutable configuration that maps types to their implementations or instances * **Session**: A runtime context that manages singleton instances and object lifecycles The framework emphasizes constructor-based wiring - dependencies are provided through class constructors, keeping your application code decoupled from the framework itself. ## Quick Start ### Step 1: Define Classes with Dependencies ```scala import wvlet.uni.design.Design case class AppConfig(appName: String) class MyApp(private val config: AppConfig): def greet(): String = s"Hello from ${config.appName}!" ``` ### Step 2: Create a Design ```scala val design = Design.newDesign .bindInstance[AppConfig](AppConfig("My Application")) ``` ### Step 3: Build and Use ```scala design.build[MyApp] { app => println(app.greet()) // Prints: Hello from My Application! } // Session automatically starts and shuts down ``` ## Design Design is an immutable object for holding object bindings and their lifecycle hooks: ```scala import wvlet.uni.design.Design val design: Design = Design.newDesign .bindImpl[A, AImpl] // Bind A to AImpl (singleton) .bindInstance[B](B(1)) // Bind to a specific instance .bindSingleton[S] // Bind S as a singleton .bindEagerSingleton[ES] // Eagerly initialized singleton .bindProvider { (d1: D1) => P(d1) } // Provider with 1 dependency .bindProvider { (d1: D1, d2: D2) => // Provider with 2 dependencies P(d1, d2) } .bindProvider { (d1: D1, d2: D2, d3: D3) => // Up to 5 dependencies supported P(d1, d2, d3) } ``` ### Binding Summary | Method | Description | |--------|-------------| | `bindImpl[A, AImpl]` | Bind interface A to implementation AImpl (singleton) | | `bindInstance[A](obj)` | Bind to a specific pre-created instance | | `bindSingleton[A]` | Bind A as a lazily-initialized singleton | | `bindEagerSingleton[A]` | Bind A as an eagerly-initialized singleton | | `bindProvider { (d1: D1) => A(d1) }` | Bind using a factory function with dependencies | ## Lifecycle Management Design provides comprehensive lifecycle management for your objects. ### Lifecycle Hooks ```scala val design = Design.newDesign .bindSingleton[DatabasePool] .onInit { pool => // Called when the object is first created pool.initialize() } .onStart { pool => // Called when the session starts pool.connect() } .onShutdown { pool => // Called when the session shuts down pool.close() } ``` ### Complete Lifecycle Order 1. `onInit`: Object initialization (called once when created) 2. `onInject`: After object is injected 3. `onStart`: When session starts 4. `afterStart`: After all onStart hooks complete 5. `beforeShutdown`: Before shutdown begins 6. `onShutdown`: Session shutdown (cleanup) ### AutoCloseable Support Classes implementing `AutoCloseable` are automatically closed on session shutdown: ```scala class MyDB(name: String) extends AutoCloseable: private val conn = openConnection(name) // Your connection logic override def close(): Unit = conn.close() // MyDB.close() called automatically when session ends design.bindSingleton[MyDB] ``` ## Session Management Sessions hold singleton instances and manage their lifecycles. ### Automatic Session Management The recommended approach - session lifecycle is handled automatically: ```scala design.build[App] { app => // Session started, app is ready to use app.run() } // Session automatically shuts down here ``` ### Manual Session Control For more control over the session lifecycle: ```scala val session = design.newSession try session.start val app = session.build[App] app.run() finally session.shutdown ``` ### Type-Safe Return Values Use `run` to return values from the session scope: ```scala val result: Int = design.run { (service: ComputeService) => service.calculate() } ``` ### Accessing the Session Inject the session itself to register dynamically created resources: ```scala import wvlet.uni.design.Session class MyApp(session: Session): def openDB(name: String): MyDB = val db = MyDB(name) session.register(db) // Register for lifecycle management db ``` ### Child Sessions Create child sessions for request-scoped lifecycles: ```scala import wvlet.uni.design.Session class MyServer(session: Session): def handleRequest() = val requestDesign = Design.newDesign .bindSingleton[RequestContext] session.withChildSession(requestDesign) { childSession => val ctx = childSession.build[RequestContext] // RequestContext is scoped to this request processRequest(ctx) } // RequestContext is cleaned up here ``` What a child session builds depends on where the type is bound: * **Bound in the child's design, or not bound anywhere:** built in the child, and closed when the child shuts down. * **Bound in a parent's design:** shared through the parent. A singleton gets its dependencies from the session that binds it, so they live as long as it does, even when a child session asks for it first. ## Design Composition Designs are immutable and can be combined: ```scala val loggingDesign = Design.newDesign .bindImpl[Logger, ConsoleLogger] val databaseDesign = Design.newDesign .bindImpl[DatabaseService, PostgresDatabase] val serviceDesign = Design.newDesign .bindImpl[UserService, UserServiceImpl] // Combine all designs val fullDesign = loggingDesign + databaseDesign + serviceDesign ``` Later bindings override earlier ones: ```scala val baseDesign = Design.newDesign .bindImpl[Cache, InMemoryCache] val redisDesign = Design.newDesign .bindImpl[Cache, RedisCache] // RedisCache will be used for Cache val combined = baseDesign + redisDesign ``` ## Production Mode In production mode, all singletons are initialized eagerly at session start: ```scala design .withProductionMode .build[App] { app => // All singletons already initialized app.run() } ``` This helps catch configuration errors early and ensures predictable startup behavior. ## Generic Type Binding Design distinguishes between different generic type parameters: ```scala // These are distinct bindings design .bindInstance[Seq[Int]](Seq(1, 2, 3)) .bindInstance[Seq[String]](Seq("a", "b", "c")) .bindInstance[Map[String, Int]](Map("x" -> 1)) ``` ## Tagged Type Binding Use tagged types to bind multiple instances of the same type: ```scala import wvlet.uni.surface.tag.* // Define tags as traits trait Production trait Staging case class DatabaseConfig(url: String) // Service that needs both configs class MigrationService( prodDb: DatabaseConfig @@ Production, stagingDb: DatabaseConfig @@ Staging ): def migrate(): Unit = println(s"Migrating from ${stagingDb.url} to ${prodDb.url}") // Bind different configs with tags val design = Design.newDesign .bindInstance[DatabaseConfig @@ Production](DatabaseConfig("jdbc:prod://...")) .bindInstance[DatabaseConfig @@ Staging](DatabaseConfig("jdbc:staging://...")) design.build[MigrationService] { service => service.migrate() } ``` ### Primitive Type Tagging Useful for configuration values: ```scala import wvlet.uni.surface.tag.* trait Port trait Host class ServerConfig(host: String @@ Host, port: Int @@ Port): def address: String = s"${host}:${port}" val design = Design.newDesign .bindInstance[String @@ Host]("localhost") .bindInstance[Int @@ Port](8080) ``` ## Testing Design makes testing straightforward by allowing you to override bindings: ```scala // Production design val prodDesign = Design.newDesign .bindImpl[EmailService, SmtpEmailService] .bindImpl[UserRepository, PostgresUserRepository] // Test design - override specific bindings val testDesign = prodDesign .bindImpl[EmailService, MockEmailService] .bindImpl[UserRepository, InMemoryUserRepository] // Use in tests testDesign.build[UserService] { service => val result = service.createUser("test@example.com") result.email shouldBe "test@example.com" } ``` ## Debugging ### Enable Debug Logging Add to your `log.properties`: ``` wvlet.uni.design=debug ``` This shows detailed information about binding resolution and object creation. ### Suppress Lifecycle Logging For cleaner output in tests: ```scala design .noLifeCycleLogging .build[App] { app => ... } ``` ## Best Practices 1. **Use traits for interfaces** - Enables easy substitution in tests 2. **Create designs at the entry point** - Main method or test setup 3. **Pass dependencies through constructors** - Keeps classes testable and explicit 4. **Use singletons for shared resources** - Database pools, HTTP clients, caches 5. **Leverage lifecycle hooks** - For proper resource initialization and cleanup 6. **Compose designs** - Build modular, reusable design configurations 7. **Prefer tagged types over type aliases** - For type-safe multi-binding of same types ## Common Patterns ### Application Configuration ```scala case class Config(host: String, port: Int) class Server(config: Config): def start(): Unit = println(s"Starting server on ${config.host}:${config.port}") val design = Design.newDesign .bindInstance[Config](Config("localhost", 8080)) .bindSingleton[Server] // Override for testing val testDesign = design .bindInstance[Config](Config("localhost", 18080)) ``` ### Resource Management ```scala case class DbConfig(url: String) class DatabaseConnection(config: DbConfig) extends AutoCloseable: private var conn: Connection = _ def connect(): Unit = conn = DriverManager.getConnection(config.url) def query(sql: String): ResultSet = conn.createStatement().executeQuery(sql) override def close(): Unit = if conn != null then conn.close() val design = Design.newDesign .bindSingleton[DatabaseConnection] .onStart(_.connect()) // close() called automatically via AutoCloseable ``` ### Multi-Handler Pattern ```scala trait RequestHandler: def handle(request: Request): Response class ApiHandler extends RequestHandler: def handle(request: Request): Response = ??? class StaticHandler extends RequestHandler: def handle(request: Request): Response = ??? class Router(apiHandler: ApiHandler, staticHandler: StaticHandler): def route(path: String, request: Request): Response = path match case p if p.startsWith("/api") => apiHandler.handle(request) case _ => staticHandler.handle(request) val design = Design.newDesign .bindSingleton[ApiHandler] .bindSingleton[StaticHandler] .bindSingleton[Router] ``` ## Known Limitations ### Type Aliases in Provider Bindings Type aliases may not work correctly in provider bindings because they are resolved at compile time: ```scala case class Service(value: String) // This may cause issues type MyString = String Design.newDesign .bindInstance[MyString]("hello") .bindProvider { (s: MyString) => Service(s) } // May fail ``` **Solution**: Use tagged types instead: ```scala import wvlet.uni.surface.tag.* case class Service(value: String) trait EnvTag Design.newDesign .bindInstance[String @@ EnvTag]("hello") .bindProvider { (s: String @@ EnvTag) => Service(s) } // Works correctly ``` --- --- url: https://wvlet.org/uni/core/unitest.md --- # UniTest UniTest is a lightweight testing framework for Scala 3. It provides a simple, expressive API for writing tests with minimal boilerplate while supporting cross-platform development (JVM, Scala.js, Scala Native). ## Quick Start Add the dependency to your build: ```scala sbt libraryDependencies += "org.wvlet.uni" %% "uni-test" % "2026.2.0" % Test testFrameworks += new TestFramework("wvlet.uni.test.Framework") ``` Write your first test: ```scala import wvlet.uni.test.UniTest class MyTest extends UniTest: test("addition works") { (1 + 1) shouldBe 2 } ``` Run tests: ```bash sbt test ``` ## Assertions in UniTest | Syntax | Meaning | |:-------|:--------| | `assert(x == y)` | Check x equals y | | `assertEquals(a, b, delta)` | Check Float/Double equality with tolerance | | `intercept[E] { ... }` | Catch an exception of type E | | `x shouldBe y` | Check x == y (supports deep equality for Array, Seq) | | `x shouldNotBe y` | Check x != y | | `x shouldBe null` | Check x is null | | `x shouldNotBe null` | Check x is not null | | `x shouldBe defined` | Check x.isDefined == true (Option, Seq, String) | | `x shouldBe empty` | Check x.isEmpty == true (Option, Seq, String) | | `x shouldBeTheSameInstanceAs y` | Check x eq y (reference equality) | | `x shouldNotBeTheSameInstanceAs y` | Check x ne y (reference inequality) | | `x shouldMatch { case .. => }` | Check x matches the pattern | | `x shouldContain y` | Check x contains y | | `x shouldNotContain y` | Check x does not contain y | | `fail("reason")` | Fail the test | | `ignore("reason")` | Ignore the test | | `cancel("reason")` | Cancel the test (e.g., setup failure) | | `pending("reason")` | Mark test as pending | | `pendingUntil("reason")` | Pending until condition is fixed | | `skip("reason")` | Skip the test (e.g., platform-specific) | ## Writing Tests ### Basic Test Structure ```scala import wvlet.uni.test.UniTest class CalculatorTest extends UniTest: test("add two numbers") { val result = 2 + 3 result shouldBe 5 } test("subtract two numbers") { val result = 5 - 3 result shouldBe 2 } ``` ### Nested Tests Tests can be nested for better organization: ```scala class MathTest extends UniTest: test("arithmetic operations") { val x = 10 test("addition") { (x + 5) shouldBe 15 } test("multiplication") { (x * 2) shouldBe 20 } } ``` Nested test names include their parent context: `"arithmetic operations / addition"`. ## Assertions ### Equality | Syntax | Description | |--------|-------------| | `a shouldBe b` | Assert `a` equals `b` | | `a shouldNotBe b` | Assert `a` does not equal `b` | ```scala test test("equality assertions") { 1 + 1 shouldBe 2 "hello" shouldBe "hello" List(1, 2, 3) shouldBe List(1, 2, 3) 1 shouldNotBe 2 "hello" shouldNotBe "world" } ``` ### Null Checks ```scala test test("null checks") { val value: String = null value shouldBe null val nonNull = "hello" nonNull shouldNotBe null } ``` ### Defined and Empty | Syntax | Description | |--------|-------------| | `a shouldBe defined` | Assert Option is Some, collection/string is non-empty | | `a shouldBe empty` | Assert Option is None, collection/string is empty | `defined` and `empty` are objects in the `wvlet.uni.test` package, so import `wvlet.uni.test.*` (not only `UniTest`) to use them. ```scala test test("defined and empty") { val some: Option[Int] = Some(42) val none: Option[Int] = None some shouldBe defined none shouldBe empty some shouldNotBe empty none shouldNotBe defined List(1, 2, 3) shouldBe defined List.empty[Int] shouldBe empty "hello" shouldBe defined "" shouldBe empty } ``` ### Collection Assertions | Syntax | Description | |--------|-------------| | `collection shouldContain element` | Assert collection contains element | | `collection shouldNotContain element` | Assert collection does not contain element | ```scala test test("collection assertions") { val list = List(1, 2, 3) list shouldContain 2 list shouldNotContain 5 } ``` ### String Assertions ```scala test test("string assertions") { val str = "Hello, World!" str shouldContain "World" str shouldNotContain "Goodbye" str.startsWith("Hello") shouldBe true str.endsWith("!") shouldBe true } ``` ### Pattern Matching Use `shouldMatch` for type-safe pattern matching assertions: ```scala test case class User(name: String, age: Int) test("pattern matching") { val result: Any = User("Alice", 30) result shouldMatch { case User(name, age) => name shouldBe "Alice" age shouldBe 30 } // Type checking result shouldMatch { case _: User => } } ``` Prefer `shouldMatch` over `asInstanceOf` for type-safe assertions. ### Reference Equality ```scala test test("reference equality") { val a = List(1, 2, 3) val b = a val c = List(1, 2, 3) a shouldBeTheSameInstanceAs b a shouldNotBeTheSameInstanceAs c } ``` ### Floating Point Comparisons ```scala test test("floating point with delta") { assertEquals(0.1 + 0.2, 0.3, 0.0001) assertEquals(3.14159f, 3.14f, 0.01f) } ``` ### Exception Testing ```scala test test("exception handling") { val e = intercept[IllegalArgumentException] { require(false, "invalid argument") } e.getMessage shouldContain "invalid argument" } ``` ### Boolean Assertions For comparisons, use boolean expressions with `shouldBe true`: ```scala test test("comparisons") { val value = 42 (value > 10) shouldBe true (value < 100) shouldBe true (value >= 42) shouldBe true (value <= 42) shouldBe true (value >= 0 && value <= 100) shouldBe true } ``` ## Testing Error Paths A test that makes code fail on purpose, such as a handler that throws, makes the code log a warning with a stack trace. Wrap the code in `captureLogs` to keep those records out of the test output and to check that they were logged: ```scala test import wvlet.uni.log.LogSupport class Importer extends LogSupport: def parse(line: String): Option[Int] = val n = line.toIntOption if n.isEmpty then warn(s"Skipping an invalid line: ${line}") n test("skip invalid lines with a warning") { val logs = captureLogs { Importer().parse("abc") shouldBe None } logs.warnings shouldContain "Skipping an invalid line: abc" } ``` `captureLogs` returns a `CapturedLogs`: | Member | Content | |--------|---------| | `warnings` | Messages of WARN records, one per line | | `errors` | Messages of ERROR records, one per line | | `messages` | Messages of all records, one per line | | `records` | The `LogRecord`s, for checks on level, logger name, or cause | A record with an exception adds a line with the exception, so `logs.warnings shouldContain "boom"` also matches the exception message. What it captures: * Records from the thread running the block, and from threads that run no test suite, such as a server's worker threads and `Future` pools. A test that starts a server and sends it a failing request captures the server's warnings. * Not records from threads running another suite, so suites running in parallel keep their own output. * `captureLogs[A] { ... }` captures only the logger of `A` and its children. Use it for long blocks, so that records of unrelated code stay visible. * Log levels are not changed. A record below its logger's level is not emitted, so it is not captured either. * If the block throws, the captured records are printed, so the failure stays debuggable. * The block must be synchronous: one that returns a `Future` or `Rx` fails, because the async code would run after the capture ends. `captureStdout` and `captureStderr` return what the block printed to `Console.out` and `Console.err`: ```scala test test("print a greeting") { val out = captureStdout { println("hello") } out shouldBe s"hello${System.lineSeparator()}" } ``` They redirect Scala's `Console` for the current thread and threads it starts, not the process-wide `System.out`/`System.err`, so they capture `println` but not output that Java code writes to `System.out` directly. ## Test Control ### Skip Tests ```scala test test("platform-specific test") { if isScalaJS then skip("Not supported on Scala.js") // JVM-only code, e.g., accessing a system property System.getProperty("java.version") shouldNotBe null } ``` ### Pending Tests ```scala test test("future feature") { pending("Implementation not complete yet") } test("blocked by issue") { pendingUntil("Issue #123 is fixed") } ``` ### Flaky Tests Mark tests as flaky to convert failures to skipped status: ```scala test test("network test", Flaky) { // Failures become skipped instead of failed fetchFromNetwork() shouldBe "expected" } // Or wrap specific code test("partially flaky") { val stableResult = computeLocally() stableResult shouldBe 42 flaky { val unstableResult = fetchFromNetwork() unstableResult shouldBe "expected" } } ``` ### Cancel and Ignore ```scala test test("requires setup") { if !setupComplete then cancel("Setup failed, cannot run test") runTest() } test("deprecated test") { ignore("This test is no longer relevant") } ``` ### Platform Detection ```scala test test("platform-specific behavior") { if isScalaJVM then // JVM-specific assertions System.getProperty("os.name") shouldBe defined if isScalaJS then // Scala.js-specific assertions skip("JVM-only test") if isScalaNative then // Scala Native-specific assertions skip("JVM-only test") } ``` ## Test Tags Pass one or more tags after the test name to group tests, then run or skip a group from sbt. A single suite can then hold unit, integration, and UI tests and still run one testing layer at a time, as VSCode does with its separate unit, integration, and UI test commands. ```scala test test("renders the toolbar", UI) { // ... } test("hits the real database", Integration, Slow) { // ... } test("end-to-end happy path", Smoke) { // ... } test("retried under load", Flaky) { // ... } ``` Built-in tags are in scope in any `UniTest`: | Tag | Name | Meaning | |-----|------|---------| | `Integration` | `integration` | Uses real external systems | | `Smoke` | `smoke` | Quick sanity check, run as a fast pre-merge subset | | `Slow` | `slow` | Usually excluded from the inner-loop run | | `Flaky` | `flaky` | A failure is reported as skipped instead of failing the build | | `UI` | `ui` | UI-layer test | | `Electron` | `electron` | Electron-layer test, for desktop apps built on Uni's Electron support | Define your own tags with `TestTag("name")`, or as an object when you reuse one across suites: ```scala test import wvlet.uni.test.TestTag case object Gpu extends TestTag("gpu") test("trains on the GPU", Gpu, Slow) { // ... } test("legacy path", TestTag("legacy")) { // ... } ``` A bare string also works, as in `test("x", "legacy")`, with `import scala.language.implicitConversions` at the call site. ### Selecting Tests by Tag Pass `--tags` and `--exclude-tags` after `--`. Both refer to a tag's name: ```bash sbt "test -- --tags ui" # only tests tagged ui sbt "test -- --tags ui --tags slow" # tests tagged both ui and slow sbt "test -- --exclude-tags slow" # everything except slow tests sbt "test -- --exclude-tags flaky" # skip known-flaky tests ``` * Repeating `--tags` narrows the selection: a test must carry every listed tag (AND), like GitHub label filters. * `--exclude-tags` drops tests carrying any listed tag, and wins over `--tags`. * With no `--tags`, every test is included. * Tags apply to top-level tests. Nested tests run with their parent. ## Design Integration A test whose body takes typed parameters gets them from the suite's [Design](./design). Add bindings with `addDesign`, and list what the test needs as the parameters of its body: ```scala import wvlet.uni.test.* class UserServiceTest extends UniTest: addDesign( _.bindImpl[UserRepository, InMemoryUserRepository] .bindImpl[UserService, UserServiceImpl] ) test("create user") { (service: UserService) => val user = service.createUser("Alice") user.name shouldBe "Alice" } test("find user") { (service: UserService, repo: UserRepository) => service.createUser("Bob") repo.findByName("Bob") shouldBe defined } ``` * **Shared or per test:** objects bound with `addDesign` are built once and shared by the tests of the suite. Objects bound with `addTestDesign`, and objects that are not bound at all, are built for each test and closed after it. * **Sessions:** the suite's Design session starts when the first such test runs, and shuts down after `afterAll`. Each test gets a child session, which shuts down after `after`, once a returned `Future` or `Rx` completes. Shutting a session down closes the objects it built (`AutoCloseable` or `onShutdown`) in reverse creation order. * **Arguments:** a test can take up to as many arguments as a Scala function literal allows, and can take `(session: Session)` to get the session itself. * **Plain tests:** a body without parameters is a plain test and opens no session. ## Lifecycle Hooks Override these protected hooks to run code around tests: | Hook | Runs | If it throws | |------|------|--------------| | `beforeAll` | Once, before the first test | The suite fails and no test runs; `afterAll` still runs | | `afterAll` | Once, after the last test, also after a failed `beforeAll` | Reported as a suite error | | `before` | Before each test, including each nested test | The test fails and its body does not run; `after` still runs | | `after` | After each test, once its `Future` or `Rx` result completes, also when the test or `before` fails | The test fails, unless it already failed | ```scala class CacheTest extends UniTest: private val cache = scala.collection.mutable.Map.empty[String, Int] override protected def after: Unit = cache.clear() test("put") { cache("a") = 1 cache.size shouldBe 1 } test("starts empty") { cache.isEmpty shouldBe true } ``` Tests in a suite run one at a time, in the order they are registered. Nested tests are queued after the tests already registered and run only when their parent passed, each with its own `before` and `after`. The hooks are synchronous. To open and close resources such as servers or clients, prefer binding them in a Design (see [Reusable Fixtures](#reusable-fixtures)) over writing hooks. ## Reusable Fixtures A fixture is a trait that adds bindings for resources such as a server, a client, or a temp directory, so that many suites can mix it in. Each fixture calls `addDesign` (or `addTestDesign`) from its body; the calls compose in trait initialization order, and a later binding of the same type wins: ```scala import wvlet.uni.test.* import wvlet.uni.http.{Http, HttpHandler, HttpServer, HttpSyncClient, Request, Response} import wvlet.uni.http.Http // Starts a server on a free port for the HttpHandler that each suite binds trait HttpServerFixture extends UniTest: addDesign( _.bindProvider[HttpHandler, HttpServer](handler => Http.server.withPort(0).withHandler(handler).start() ) ) // Depends on the server, so the session closes the client before it stops the server trait HttpClientFixture extends HttpServerFixture: addDesign( _.bindProvider[HttpServer, HttpSyncClient](server => Http.client.withBaseUri(s"http://localhost:${server.localPort}").newSyncClient ) ) class GreetingApiTest extends HttpClientFixture: addDesign(_.bindInstance[HttpHandler](request => Response.ok(s"hello ${request.path}"))) test("GET /ping") { (client: HttpSyncClient) => client.send(Request.get("/ping")).contentAsString shouldBe Some("hello /ping") } test("the client is shared by the tests of the suite") { (client: HttpSyncClient) => client.send(Request.get("/again")).contentAsString shouldBe Some("hello /again") } ``` * **Shutdown order:** the session closes objects in reverse creation order, so dependencies decide the order. If one `close()` throws, the session still closes the rest and the error is reported. * **Startup failures:** an object that fails to build fails the test that needs it; the objects already built are still closed. * **When to call:** call `addDesign` and `addTestDesign` from the body of the test class or a fixture trait. Calling them once the tests run throws. These fixtures, with tests that check startup, reuse, and shutdown against a real server, are in [`HttpClientFixtureTest.scala`](https://github.com/wvlet/uni/blob/main/uni-netty/src/test/scala/wvlet/uni/http/netty/HttpClientFixtureTest.scala). ### Per-Test Resources Bind what each test needs fresh with `addTestDesign`: ```scala import java.nio.file.{Files, LinkOption, Path} class TempDir extends AutoCloseable: val path: Path = Files.createTempDirectory("test") override def close(): Unit = deleteRecursively(path) private def deleteRecursively(p: Path): Unit = // Do not follow symlinks out of the temp directory if Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS) then val children = Files.list(p) try children.forEach(deleteRecursively) finally children.close() Files.deleteIfExists(p) trait TempDirFixture extends UniTest: addTestDesign(_.bindSingleton[TempDir]) ``` * **Async tests:** a test's objects stay open until its `Future` or `Rx` completes. A loan helper such as `withTempDir { dir => ... }` closes them as soon as the body returns, which is too early when the body returns a `Future`. * **Nested tests:** each nested test that takes arguments gets its own session. Take the arguments in the nested test; do not capture the parent's. ### Combining Fixtures Mix fixtures with `extends A with B`. Their bindings are added in trait initialization order: a trait's after those of the traits it extends, and B's after A's. ```scala class UploadApiTest extends HttpClientFixture with TempDirFixture: addDesign(_.bindInstance[HttpHandler](request => Response.ok(s"uploaded ${request.path}"))) test("upload a file") { (client: HttpSyncClient, dir: TempDir) => val file = Files.writeString(dir.path.resolve("a.txt"), "hello") // ... send it with `client` } ``` The fixtures in [`DesignTestTest.scala`](https://github.com/wvlet/uni/blob/main/uni-test/src/test/scala/wvlet/uni/test/DesignTestTest.scala) run on all platforms. They and [`DesignLifecycleTest.scala`](https://github.com/wvlet/uni/blob/main/uni-test/.jvm/src/test/scala/wvlet/uni/test/DesignLifecycleTest.scala) check the behavior above with the sbt runner and the JUnit engine used by IDEs. ### Hooks in Fixtures When a fixture also overrides a lifecycle hook, write `override` and call `super`, so that the hooks of the other fixtures still run: ```scala trait AuditFixture extends UniTest: override protected def afterAll: Unit = try info("suite finished") finally super.afterAll ``` ## Property-Based Testing UniTest ships a self-contained property-based testing toolkit — no external dependency — and it's part of the base `UniTest` trait. Any test class gets `forAll` automatically. Call it with a body that holds for every randomly generated input; a failing run is automatically *shrunk* to a minimal counter-example, and the seed is reported so the run can be replayed. ```scala import wvlet.uni.test.UniTest class ListLawsTest extends UniTest: test("addition is commutative") { forAll { (a: Int, b: Int) => (a + b) shouldBe (b + a) } } test("reverse is an involution") { forAll { (xs: List[Int]) => xs.reverse.reverse shouldBe xs } } ``` ### Generators Generators live in `wvlet.uni.test.check.Gen`. Every `forAll` body receives randomly generated values — by default drawn from the type's implicit `Arbitrary` instance, or from a `Gen` you supply explicitly. ```scala test import wvlet.uni.test.check.Gen test("positive integers") { forAll(Gen.posNum[Int]) { n => (n > 0) shouldBe true } } test("bounded integers") { forAll(Gen.chooseNum(1, 100)) { n => (n >= 1 && n <= 100) shouldBe true } } ``` Common combinators: | Factory | Produces | |---------|----------| | `Gen.const(x)` | Always `x` | | `Gen.chooseNum[T](min, max)` | Uniform integer in `[min, max]` | | `Gen.posNum[T]` | Positive, non-zero value | | `Gen.oneOf(a, b, c)` | Uniform choice from values | | `Gen.oneOfGen(g1, g2)` | Uniform choice from generators | | `Gen.frequency(w1 -> g1, w2 -> g2)` | Weighted choice from generators | | `Gen.listOf(g)` / `Gen.nonEmptyListOf(g)` | List of `g`, size-aware | | `Gen.listOfN(n, g)` | List of exactly `n` elements | | `Gen.setOf(g)` / `Gen.mapOf(gK, gV)` | Set / Map, size-aware | | `Gen.option(g)` | `Some(g)` or `None` | | `Gen.alphaChar` / `.numChar` / `.alphaNumChar` / `.asciiChar` | Single character | | `Gen.alphaStr` / `.numStr` / `.alphaNumStr` / `.asciiStr` | Size-aware string | | `Gen.identifier` | `[A-Za-z][A-Za-z0-9]*` | | `Gen.sized(n => g)` / `Gen.resize(n, g)` | Read or override the current size | Generators compose like `Option`s: `g.map`, `g.flatMap`, `g.filter`, `g.zip`, plus for-comprehensions. ```scala val evenPositive: Gen[Int] = Gen.posNum[Int].map(_ * 2) val labeledInt: Gen[(String, Int)] = for label <- Gen.alphaStr value <- Gen.chooseNum(0, 100) yield (label, value) ``` ### Arbitrary and derivation Implicit `Arbitrary[T]` instances drive the argument-less `forAll` overload. Defaults ship for primitives, `String`, `Array[Byte]`, `List`, `Vector`, `Option`, and small tuples. For your own types, use Scala 3's `derives`: ```scala test import wvlet.uni.test.check.Arbitrary case class Point(x: Int, y: Int) derives Arbitrary sealed trait Shape derives Arbitrary case class Circle(r: Int) extends Shape case class Rect(w: Int, h: Int) extends Shape case class Triangle(a: Int, b: Int, c: Int) extends Shape test("shapes round-trip through the renderer") { forAll { (s: Shape) => Renderer.parse(Renderer.show(s)) shouldBe s } } ``` Derivation is recursive: a `derives Arbitrary` on a sealed trait picks up each case class automatically, and fields of user types that themselves have an `Arbitrary` given (or a `Mirror`) are threaded through. To summon a default generator explicitly, use `Arbitrary.arbitrary[T]`: ```scala forAll(Arbitrary.arbitrary[String]) { s => s.length >= 0 shouldBe true } ``` ### Shrinking When a property fails, the runner shrinks the counter-example to a minimal value. Default shrinkers ship for numeric primitives, `Char`, `String`, `Array[Byte]`, `List`, `Option`, and tuples up to arity 5. ```scala test test("sum is never negative for non-negative inputs") { forAll { (xs: List[Int]) => // Sum as Long: an Int sum of large inputs overflows xs.filter(_ >= 0).map(_.toLong).sum >= 0 shouldBe true } } ``` If this property were broken, the error message would point at a minimal list — typically `List(...)` with one or two elements — rather than the raw random failing input. User types get an empty shrinker by default, so `forAll[MyCaseClass]` compiles even without a shrink instance. To customize, provide a given: ```scala import wvlet.uni.test.check.Shrink given Shrink[Point] = Shrink { p => LazyList(Point(0, 0), Point(p.x, 0), Point(0, p.y)) } ``` ### Preconditions with `==>` / `implies` Use `==>` (or its English alias `implies`) to discard samples that don't satisfy a precondition. The runner retries with a new sample and fails the test only if the discard budget (default: 500) runs out. ```scala test test("division by non-zero is self-inverse") { forAll { (a: Int, b: Int) => (b != 0) ==> { // Multiply as Long: a * b can overflow Int ((a.toLong * b) / b) shouldBe a.toLong } } } test("reads the same way in prose") { forAll { (xs: List[Int]) => xs.nonEmpty implies { xs.head shouldBe xs(0) } } } ``` ### Statistics: `classify` and `collect` Break down what the generator is actually producing to make sure your property is exercising the cases you care about. Counts print after the run. ```scala test test("partition respects predicate") { forAll(Gen.listOf(Gen.chooseNum(-100, 100))) { xs => classify(xs.isEmpty, "empty") classify(xs.size > 50, "large") collect(s"size=${xs.size / 10 * 10}") val (neg, nonNeg) = xs.partition(_ < 0) (neg ++ nonNeg).sorted shouldBe xs.sorted } } ``` Output (example): ``` [property] 42 × size=10, 31 × size=0, 18 × large, 9 × size=20, 7 × empty ``` ### Configuration Override `propertyConfig` on the test class to change sample count, seed, size range, discard limit, or shrink budget for every `forAll` in that class. For a one-off tweak of the sample count, override `minSuccessfulTests`. ```scala import wvlet.uni.test.check.PropertyConfig class HeavyPropertyTest extends UniTest: override protected def propertyConfig: PropertyConfig = PropertyConfig.default .withMinSuccessful(500) .withSize(0, 256) .withSeed(1_234L) // reproducible runs ``` | Knob | Method | Default | |------|--------|---------| | Samples | `withMinSuccessful(n)` | 100 | | Discard limit | `withMaxDiscarded(n)` | 500 | | Size range | `withSize(min, max)` | `0..100` | | Shrink budget | `withMaxShrinks(n)` | 1000 | | Seed | `withSeed(s)` | `System.nanoTime()` | Every failure includes the seed. To reproduce a flaky failure, copy the seed from the error message into `propertyConfig.withSeed(...)` and rerun — the exact same samples are drawn. ## Running Tests ### sbt Commands ```bash # Run all tests sbt test # Run tests in a specific module sbt coreJVM/test # Run a specific test class sbt "my-project/testOnly *MyTest" # Run with debug logging sbt "coreJVM/testOnly * -- -l debug" # Run with trace logging for specific package sbt "test -- -l:wvlet.uni.*=trace" # Filter tests by name sbt "test -- -t:ChatSession" # Filter tests by tag (see Test Tags) sbt "test -- --tags integration" sbt "test -- --exclude-tags slow" ``` ::: tip Scala.js tests in a real browser To run Scala.js tests in a real browser (headless Chromium/Firefox/WebKit) with ES module support — for DOM, web, and Electron code — see the [sbt-uni-playwright Plugin](/build/sbt-uni-playwright). ::: ### Test Output Test results are displayed with status symbols: | Symbol | Status | Description | |--------|--------|-------------| | `+` | Success | Test passed | | `-` | Failure | Assertion failed | | `x` | Error | Unexpected exception | | `~` | Skipped | Test was skipped | | `?` | Pending | Test not implemented | | `!` | Cancelled | Setup failed | A suite that skips or cancels itself in its constructor or `beforeAll` is not counted as failed. In CI (when the `CI` environment variable is set), UniTest on the JVM writes log messages from the thread running a suite (its constructor, hooks, and test bodies) into sbt's output for that suite, so they appear right above the result of the test that logged them. sbt may hold a suite's output until the suite ends, so local runs keep logs going straight to the console, where they show up live. Logs from other threads, such as a server's worker pool or a `Future` on the global pool, always go to the console. Override the default with a test argument: ```scala sbt Test / testOptions += Tests.Argument("--log-capture") // or "--no-log-capture" ``` ## Best Practices 1. **Avoid mocks** - Use real implementations or in-memory versions 2. **Use Design for wiring** - Bind test objects with `addDesign` / `addTestDesign` and take them as test arguments; share setup through fixture traits that extend `UniTest`. See [Reusable Fixtures](#reusable-fixtures) 3. **Prefer `shouldMatch`** - Use pattern matching for type checks instead of `asInstanceOf` 4. **One behavior per test** - Keep tests focused on a single behavior 5. **Descriptive names** - Test names should describe the expected behavior 6. **Use boolean expressions** - For comparisons: `(x > 5) shouldBe true` 7. **Capture expected errors** - Wrap code that fails on purpose in `captureLogs` and assert on the warning, instead of lowering log levels. See [Testing Error Paths](#testing-error-paths) ## Cross-Platform Support UniTest works across all Scala 3 platforms: | Feature | JVM | Scala.js | Scala Native | |---------|:---:|:--------:|:------------:| | Basic assertions | ✓ | ✓ | ✓ | | Nested tests | ✓ | ✓ | ✓ | | Flaky tests | ✓ | ✓ | ✓ | | Property-based testing | ✓ | ✓ | ✓ | | `captureLogs` from other threads | ✓ | - | ✓ | | IDE integration | ✓ | - | - | ## Package ```scala import wvlet.uni.test.UniTest // Property-based testing is part of UniTest — nothing else to import. // For custom generators / shrinkers: import wvlet.uni.test.check.{Arbitrary, Gen, Shrink, PropertyConfig} ``` --- --- url: https://wvlet.org/uni/core/logging.md --- # Logging uni provides a comprehensive logging framework with structured logging support. ## LogSupport Trait The easiest way to add logging is to extend `LogSupport`: ```scala import wvlet.uni.log.LogSupport class MyService extends LogSupport: def process(data: String): Unit = info(s"Processing: ${data}") debug("Detailed information") try riskyOperation() catch case e: Exception => error("Operation failed", e) ``` ## Log Levels Available log levels in order of severity: | Level | Method | Use Case | |-------|--------|----------| | ERROR | `error()` | Errors requiring attention | | WARN | `warn()` | Potential issues | | INFO | `info()` | General information | | DEBUG | `debug()` | Debugging details | | TRACE | `trace()` | Fine-grained tracing | ## Logger Configuration ### Setting Log Levels ```scala import wvlet.uni.log.{Logger, LogLevel} // Set global default Logger.setDefaultLogLevel(LogLevel.DEBUG) // Set for specific logger Logger("MyService").setLogLevel(LogLevel.TRACE) ``` ### Creating Named Loggers ```scala val logger = Logger("MyApp") logger.info("Application started") logger.debug("Configuration loaded") ``` ## Logging with Exceptions Include stack traces in error logs: ```scala import java.io.IOException try riskyOperation() catch case e: IOException => error("IO operation failed", e) case e: Exception => error(s"Unexpected error: ${e.getMessage}", e) ``` ## Zero-Overhead Logging with Scala Macros The logging methods use Scala 3 `inline` macros, which means: 1. **Automatic lazy evaluation**: The message is only evaluated if the log level is enabled 2. **Zero overhead**: If the log level is disabled, there is no runtime cost for creating log messages ```scala // expensiveComputation() is only called if DEBUG is enabled debug(s"Result: ${expensiveComputation()}") ``` Unlike traditional logging frameworks, you don't need to wrap expensive computations with level checks. ## Source Location Log messages automatically include source location at the end of the message: ``` 2024-01-15 10:30:45.123+0900 info [MyService] Processing: data - (MyService.scala:14) ``` The source code location `(file:line)` is captured at compile time using Scala macros. ## Writing Logs to a File `FileLogHandler` writes log records to a file with automatic rotation. It runs unchanged on JVM, Scala.js (Node.js), and Scala Native, using the [FileSystem](/core/filesystem) abstraction underneath. ```scala import wvlet.uni.log.{FileLogHandler, FileLogHandlerConfig, Logger} val handler = FileLogHandler("app.log") Logger.setDefaultHandler(handler) ``` By default, `FileLogHandler` rotates daily and whenever the active file exceeds 100 MB, keeps the most recent 100 rotated files, and gzips each rotated file. Rotated files are named `{stem}-YYYY-MM-DD.{index}.log.gz` and sit next to the active log. ### Tuning rotation Configure the handler through `FileLogHandlerConfig`: ```scala import wvlet.uni.log.{FileLogHandler, FileLogHandlerConfig} val config = FileLogHandlerConfig("app.log") .withMaxSizeInBytes(10 * 1024 * 1024) // 10 MB per file .withMaxNumberOfFiles(30) // keep 30 rotated files .withCompressRotated(true) // gzip rotated files val handler = FileLogHandler(config) ``` `FileLogHandlerConfig` ships with both `withXxx` setters and these escape hatches: | Builder | Effect | |---------|--------| | `withPath(p)` | Change the active log file path. | | `withMaxSizeInBytes(n)` | Rotate once the active file exceeds `n` bytes. Default 100 MB. | | `withMaxNumberOfFiles(n)` | Keep at most `n` rotated files; oldest are deleted on rotation. Default 100. | | `withFormatter(f)` | Override the log formatter. Default `AppLogFormatter`. | | `withLogFileExt(ext)` | Override the active-log extension (default `".log"`). | | `withCompressRotated(b)` | Toggle gzip of rotated files. Default `true`. | | `noCompression` | Disable gzip; rotated files keep their configured extension (default `.log`). | | `noRotation` | Disable both size and count limits — write a single file forever. | ### Writing without rotation When you just want a plain file sink (for example, a short-lived CLI that appends to a debug log), use `noRotation`: ```scala val handler = FileLogHandler( FileLogHandlerConfig("debug.log").noRotation ) ``` ## Combining Multiple Handlers A `Logger` can fan log records out to several handlers at once — each with its own formatter and (optionally) its own level. Use this when you want, say, terminal-friendly output for humans and a rotated file for forensics on the same logger. ```scala import wvlet.uni.log.{ ConsoleLogHandler, FileLogHandler, FileLogHandlerConfig, LogFormatter, LogLevel, Logger } val console = ConsoleLogHandler(LogFormatter.AppLogFormatter) val file = FileLogHandler( FileLogHandlerConfig("app.log").withFormatter(LogFormatter.SourceCodeLogFormatter) ) val root = Logger.rootLogger root.clearHandlers root.addHandler(console) root.addHandler(file) ``` `addHandler` accepts any `java.util.logging.Handler`, so the same pattern wires up `BufferedLogHandler` (for tests), `NullHandler`, or any custom handler you write. ### Different formats per sink Each handler carries its own `LogFormatter`. The bundled ones are: | Formatter | Shape | Typical use | |-----------|-------|-------------| | `AppLogFormatter` | Color, timestamp, level, logger | Default for interactive consoles. | | `SourceCodeLogFormatter` | Adds the `(file:line)` source pin | Files / forensic logs where you'll grep later. | | `IntelliJLogFormatter` | Renders source as an IntelliJ-clickable link | Local dev runs inside IntelliJ. | | `PlainSourceCodeLogFormatter` | Like `SourceCodeLogFormatter` without ANSI color | Files / CI logs that mangle ANSI. | | `SimpleLogFormatter` | Level + message only | Smoke tests, prototypes. | | `BareFormatter` | Message only | When the surrounding tool already adds context. | | `TSVLogFormatter` | Tab-separated fields | Quick offline analysis with `cut` / `awk`. | | `ThreadLogFormatter` | Adds the thread name | Debugging concurrency. | ### Different levels per sink Handlers respect `java.util.logging.Handler#setLevel`, so you can let the logger itself be permissive and let each handler decide what to keep. `LogLevel.jlLevel` bridges to the underlying `java.util.logging` level: ```scala root.setLogLevel(LogLevel.DEBUG) // permissive at the source console.setLevel(LogLevel.INFO.jlLevel) // console stays quiet file.setLevel(LogLevel.DEBUG.jlLevel) // file captures everything ``` This is the right way to keep a noisy `DEBUG` trail on disk without flooding the terminal a human is reading. ## Best Practices 1. **Use appropriate levels** - Don't log everything as INFO 2. **Include context** - Log relevant data for debugging 3. **Avoid sensitive data** - Don't log passwords, tokens, etc. 4. **Use structured data** - Include key-value pairs for parsing 5. **Keep messages concise** - Clear, actionable messages ## Example: Service with Logging ```scala import wvlet.uni.log.LogSupport class OrderService(db: Database) extends LogSupport: def createOrder(userId: String, items: List[Item]): Order = info(s"Creating order for user: ${userId}, items: ${items.size}") val order = try val order = db.createOrder(userId, items) info(s"Order created: ${order.id}") order catch case e: DatabaseException => error(s"Failed to create order for user: ${userId}", e) throw e debug(s"Order details: ${order}") order ``` --- --- url: https://wvlet.org/uni/core/json.md --- # JSON Processing uni includes a pure Scala JSON parser with a convenient DSL for querying and manipulating JSON data. ## Parsing JSON ```scala import wvlet.uni.json.* val jsonString = """ { "user": { "id": 123, "name": "Alice", "email": "alice@example.com" }, "posts": [ {"id": 1, "title": "Hello World"}, {"id": 2, "title": "Scala Tips"} ] } """ val json = JSON.parse(jsonString) ``` ## Extracting Values ### Direct Access ```scala // Access nested values val userId = json("user")("id").toLongValue // 123 val userName = json("user")("name").toStringValue // "Alice" // Access array elements val firstPost = json("posts")(0)("title").toStringValue // "Hello World" ``` ### Path Navigation Use `/` for path-based navigation: ```scala val email = (json / "user" / "email").toStringValue // "alice@example.com" // Navigate into arrays val titles = (json / "posts" / "title").values // Seq("Hello World", "Scala Tips") ``` ### Safe Access with Option ```scala // `/` returns an empty Seq when a field is missing val email: Option[String] = (json / "user" / "email").headOption.map(_.toStringValue) ``` ## Value Types JSON values have specific types: ```scala import wvlet.uni.json.JSON.* json match case JSONObject(fields) => // Object with fields (Seq[(String, JSONValue)]) case JSONArray(items) => // Array of values case JSONString(s) => // String value case JSONLong(n) => // Integer value case JSONDouble(d) => // Floating point case JSONBoolean(b) => // Boolean case _: JSONNull => // Null value ``` ## Creating JSON ### Programmatic Construction ```scala import wvlet.uni.json.JSON.* val userJson = JSONObject(Seq( "id" -> JSONLong(456), "name" -> JSONString("Bob"), "active" -> JSONBoolean(true), "scores" -> JSONArray(IndexedSeq( JSONLong(95), JSONLong(87), JSONLong(92) )) )) ``` ### Converting to String ```scala val jsonStr = userJson.toJSON // {"id":456,"name":"Bob","active":true,"scores":[95,87,92]} ``` ## Working with Arrays ```scala val posts = json("posts") // Get all items as IndexedSeq[JSONValue] val allPosts = posts.toArrayValue // Map over items val titles = allPosts.map(p => p("title").toStringValue) // Filter items val filteredPosts = allPosts.filter(p => p("id").toLongValue > 1 ) ``` ## Error Handling JSON parsing can fail: ```scala try val json = JSON.parse(invalidJson) catch case e: JSONParseException => println(s"Parse error: ${e.getMessage}") ``` Safe parsing with Try: ```scala import scala.util.Try val result = Try(JSON.parse(maybeInvalidJson)) result match case scala.util.Success(json) => // Use json case scala.util.Failure(e) => // Handle parse failure ``` ## JSONC Support uni's JSON parser supports [JSONC](https://jsonc.org/) (JSON with Comments) out of the box. Line comments (`//`), block comments (`/* */`), and trailing commas are all accepted by `JSON.parse`: ```scala val config = JSON.parse(""" { // Database configuration "host": "localhost", // server address "port": 5432, "options": { /* Connection pool settings */ "minConnections": 5, "maxConnections": 20, } } """) ``` ### Comment Round-Tripping Comments are preserved as mutable metadata on value nodes for round-tripping: ```scala val v = JSON.parse("""{ "key": "value" // important }""") // Comments are attached to nearby value nodes val keyVal = v("key") keyVal.trailingComment // Some(JSONComment("// important")) // toJSON outputs valid JSON (no comments) v.toJSON // {"key":"value"} // JSON.format pretty-prints with comments JSON.format(v) // { // "key": "value" // important // } ``` ### Comment Attachment Rules * **New-line comments** are attached as `leadingComments` on the **next** value node * **Inline comments** (same line) are attached as `trailingComment` on the **previous** value node ### JSONComment ```scala val comment = JSONComment("// server host") comment.commentBody // "server host" comment.isLineComment // true comment.isBlockComment // false ``` ## YAML Output Convert JSON to YAML format: ```scala import wvlet.uni.json.YAMLFormatter // toYaml takes a JSON string val yaml = YAMLFormatter.toYaml(jsonString) // user: // id: 123 // name: Alice // email: alice@example.com ``` ## Best Practices 1. **Use path navigation** for nested access 2. **Handle missing keys** with `get` or `Option` 3. **Validate structure** before deep traversal 4. **Use pattern matching** for type-safe extraction --- --- url: https://wvlet.org/uni/core/msgpack.md --- # MessagePack Serialization MessagePack is a binary serialization format that's more compact and faster than JSON. ## Basic Usage ### Packing Data ```scala import wvlet.uni.msgpack.spi.MessagePack // Create a packer val packer = MessagePack.newPacker() // Pack primitive values packer.packString("Alice") packer.packInt(30) packer.packBoolean(true) // Get the bytes val bytes = packer.toByteArray ``` ### Unpacking Data ```scala // Create an unpacker val unpacker = MessagePack.newUnpacker(bytes) // Unpack in the same order val name = unpacker.unpackString // "Alice" val age = unpacker.unpackInt // 30 val active = unpacker.unpackBoolean // true ``` ## Packing Complex Structures ### Arrays ```scala val packer = MessagePack.newPacker() // Pack array header with size packer.packArrayHeader(3) packer.packInt(1) packer.packInt(2) packer.packInt(3) ``` ### Maps ```scala val packer = MessagePack.newPacker() // Pack map header with size packer.packMapHeader(2) packer.packString("name") packer.packString("Alice") packer.packString("age") packer.packInt(30) ``` ## Unpacking Complex Structures ### Arrays ```scala val unpacker = MessagePack.newUnpacker(bytes) val size = unpacker.unpackArrayHeader val items = (0 until size).map(_ => unpacker.unpackInt) ``` ### Maps ```scala val unpacker = MessagePack.newUnpacker(bytes) val size = unpacker.unpackMapHeader val map = (0 until size).map { _ => val key = unpacker.unpackString val value = unpacker.unpackInt key -> value }.toMap ``` ## Supported Types | Type | Pack Method | Unpack Method | |------|-------------|---------------| | Boolean | `packBoolean` | `unpackBoolean` | | Int | `packInt` | `unpackInt` | | Long | `packLong` | `unpackLong` | | Float | `packFloat` | `unpackFloat` | | Double | `packDouble` | `unpackDouble` | | String | `packString` | `unpackString` | | Binary | `packBinaryHeader` + write | `unpackBinaryHeader` + read | | Nil | `packNil` | `unpackNil` | ## Object Weaving For automatic serialization of case classes, use Weaver: ```scala import wvlet.uni.weaver.Weaver // Using derives clause case class User(name: String, age: Int) derives Weaver // Or explicit derivation case class Address(city: String, country: String) given Weaver[Address] = Weaver.of[Address] // Serialize to MessagePack bytes val userBytes = Weaver.weave(User("Alice", 30)) val addressBytes = Weaver.weave(Address("Tokyo", "Japan")) // Deserialize from bytes val user = Weaver.unweave[User](userBytes) val address = Weaver.unweave[Address](addressBytes) ``` ## MessagePack vs JSON | Aspect | MessagePack | JSON | |--------|-------------|------| | Format | Binary | Text | | Size | Smaller | Larger | | Speed | Faster | Slower | | Human-readable | No | Yes | | Schema | Optional | None | Use MessagePack when: * Performance is critical * Bandwidth is limited * Human readability isn't needed Use JSON when: * Debugging/logging * API responses * Configuration files ## Best Practices 1. **Match pack/unpack order** - Data must be unpacked in the same order it was packed 2. **Include length headers** - For arrays and maps 3. **Use Weaver** - For automatic case class serialization 4. **Handle format errors** - Wrap unpacking in try-catch --- --- url: https://wvlet.org/uni/core/weaver.md --- # Weaver `Weaver[A]` is uni's derivation-based serialization framework. A single `Weaver` instance can read and write a value of type `A` as **MessagePack**, **JSON**, or a loosely-typed `Map[String, Any]` — so you derive the codec once and pick the wire format at the call site. Weaver is the engine behind JSON/MessagePack serialization in the [HTTP client](../http/client) and [RPC](../http/rpc) layers, and it builds on [Surface](./surface) for compile-time type information. ```scala import wvlet.uni.weaver.Weaver case class Person(name: String, age: Int) derives Weaver val json = Weaver.toJson(Person("Alice", 30)) // {"name":"Alice","age":30} val back = Weaver.fromJson[Person](json) // Person(Alice,30) ``` ## Deriving a Weaver A `Weaver[A]` is derived at compile time for case classes, enums, and sealed traits. There are three equivalent ways to obtain one: ```scala // 1. derives clause (recommended for types you own) case class Person(name: String, age: Int) derives Weaver // 2. Weaver.of for an explicit given given Weaver[Person] = Weaver.of[Person] // 3. Inline at the call site val w: Weaver[Person] = Weaver.of[Person] ``` Most API methods take the `Weaver[A]` as a `using` parameter, so a `derives` clause or a `given` in scope is all you need. ## Serialization Formats The same derived `Weaver` exposes every format. The companion-object methods resolve the `Weaver[A]` implicitly: ```scala import wvlet.uni.weaver.Weaver case class User(name: String, age: Int) derives Weaver val user = User("Alice", 30) // JSON val json: String = Weaver.toJson(user) val u1: User = Weaver.fromJson[User](json) // MessagePack (compact binary) val bytes = Weaver.weave(user) // Array[Byte] val u2 = Weaver.unweave[User](bytes) // Map[String, Any] — handy with YAML/HOCON-style parsers val map: Map[String, Any] = Weaver.toMap(user) val u3 = Weaver.fromMap[User](map) ``` The instance methods on `Weaver[A]` mirror these and add a couple of lower-overhead entry points when you already hold a `Weaver`: | Method | Direction | Format | |--------|-----------|--------| | `toJson(v)` / `fromJson(s)` | encode / decode | JSON string | | `weave(v)` / `unweave(b)` | encode / decode | MessagePack `Array[Byte]` | | `toMap(v)` / `fromMap(m)` | encode / decode | `Map[String, Any]` | | `toMsgPack(v)` | encode | MessagePack `Array[Byte]` | | `fromJSONValue(v)` | decode | parsed [`JSONValue`](./json) (no string roundtrip) | | `pack(p, v, c)` / `unpack(u, c)` | encode / decode | low-level [MessagePack](./msgpack) packer/unpacker | ## Supported Types Weaver resolves codecs for these out of the box (cross-platform): * **Primitives**: `Int`, `Long`, `Short`, `Byte`, `Double`, `Float`, `Boolean`, `Char`, `String`, `BigInt`, `BigDecimal` * **Common value types**: `UUID`, `java.time.Instant`, [`ULID`](./utilities#ulid), [`ElapsedTime`](./utilities#elapsedtime), `scala.concurrent.duration.Duration`, `java.net.URI` * **Collections**: `Option`, `Seq`/`List`/`Vector`/`IndexedSeq`, `Set`, `Map`, `ListMap`, `Array`, `Either`, tuples * **Java collections**: `java.util.List`, `java.util.Set`, `java.util.Map` * **Case classes** with any combination of the above * **Enums and sealed traits** (see [ADTs](#enums-and-sealed-traits)) ### JVM-only types On the JVM, additional `given` weavers are available by importing them explicitly (they live in `JvmWeaver` because they depend on JDK types not available on Scala.js / Native): ```scala import wvlet.uni.weaver.codec.JvmWeaver.given // adds: ZonedDateTime, OffsetDateTime, LocalDate, LocalDateTime, // java.time.Duration, java.io.File, java.net.URL, // java.nio.file.Path, java.util.Optional[A] ``` ## Enums and Sealed Traits Scala 3 enums whose cases have no parameters encode as their **case name** string: ```scala enum Color derives Weaver: case Red, Green, Blue Weaver.toJson(Color.Green) // "Green" Weaver.fromJson[Color](""""Blue"""") // Color.Blue ``` Sealed traits (ADTs) encode as a **flat object with a discriminator field** added alongside the case's own fields. The default discriminator is `@type`: ```scala sealed trait Shape derives Weaver case class Circle(radius: Double) extends Shape derives Weaver case class Rectangle(w: Double, h: Double) extends Shape derives Weaver case object Unknown extends Shape derives Weaver // Encode as the trait type to get the discriminator; // Weaver.toJson(Circle(1.0)) uses Circle's own Weaver: {"radius":1.0} Weaver.toJson[Shape](Circle(1.0)) // {"@type":"Circle","radius":1.0} Weaver.toJson[Shape](Unknown) // {"@type":"Unknown"} ``` Children without their own `derives Weaver` are derived along with the trait, and recursive types work: a child may refer back to the trait through `Seq`, `Option`, or any other field type. An enum with a **parameterized case** uses the same discriminator format, so the case's fields are kept. Its cases without parameters encode as `{"@type":"Name"}`: ```scala enum Layout derives Weaver: case Empty case Split(children: Seq[Layout], sizes: Seq[Double]) case Group(panels: Seq[String], active: Option[String]) Weaver.toJson[Layout](Layout.Split(Seq(Layout.Empty), Seq(1.0))) // {"@type":"Split","children":[{"@type":"Empty"}],"sizes":[1.0]} ``` Codecs built at runtime with `Weaver.fromSurface`, which RPC and HTTP use, write the same format. When reading, a case without parameters may also be a bare string (`"Empty"`). Change the discriminator via [`WeaverConfig`](#configuration): ```scala import wvlet.uni.weaver.WeaverConfig val cfg = WeaverConfig().withDiscriminatorFieldName("kind") Weaver.toJson[Shape](Circle(1.0), cfg) // {"kind":"Circle","radius":1.0} ``` ## Configuration `WeaverConfig` is an optional last argument on every method (it defaults to `WeaverConfig()`): | Field | Default | Effect | |-------|---------|--------| | `discriminatorFieldName` | `"@type"` | Field name used to tag sealed-trait cases | ```scala import wvlet.uni.weaver.WeaverConfig val config = WeaverConfig().withDiscriminatorFieldName("type") val json = Weaver.toJson(shape, config) ``` ## Runtime Weavers from Surface When you only have a [`Surface`](./surface) — for example deriving a codec for a method's parameter types in the RPC layer — build a `Weaver` at runtime instead of compile time: ```scala import wvlet.uni.weaver.Weaver import wvlet.uni.surface.Surface val surface = Surface.of[Person] val weaver = Weaver.fromSurface(surface) // Weaver[?] ``` `fromSurface` caches results, supports self-recursive types (e.g. `class Tree(children: List[Tree])`), and is what the RPC framework uses to wire up codecs without compile-time type information. For types that aren't directly supported, `fromSurface` falls back to a lossy empty-object weaver. Use `Weaver.fromSurfaceOpt(surface)`, which returns `None` when the resulting weaver tree contains that fallback at any position, if you want to detect the gap and choose a different encoding. See the [ADR](https://github.com/wvlet/uni/blob/main/adr/2026-05-04-fromsurfaceopt-and-innerweavers.md) for the rationale. ## Custom Weavers Provide a `given Weaver[A]` to control encoding for a type Weaver can't derive (or shouldn't derive losslessly — e.g. an open abstract type). Implement `pack` and `unpack` against the low-level [MessagePack](./msgpack) packer/unpacker: ```scala import wvlet.uni.weaver.{Weaver, WeaverConfig, WeaverContext} import wvlet.uni.msgpack.spi.{Packer, Unpacker} opaque type Email = String given Weaver[Email] with def pack(p: Packer, v: Email, config: WeaverConfig): Unit = p.packString(v) def unpack(u: Unpacker, context: WeaverContext): Unit = context.setObject(u.unpackString) ``` Once in scope, the custom weaver participates in derivation: any case class with an `Email` field will use it automatically. ## Cross-Platform Support Weaver works on JVM, Scala.js, and Scala Native. The core type set is identical on all three; only the `JvmWeaver` extras above are JVM-specific. --- --- url: https://wvlet.org/uni/core/surface.md --- # Type Introspection Surface provides compile-time type reflection for Scala 3, enabling introspection of types without runtime reflection. ## Basic Usage ```scala import wvlet.uni.surface.Surface case class User(id: Long, name: String, email: Option[String]) val surface = Surface.of[User] println(surface.name) // "User" println(surface.fullName) // "com.example.User" ``` ## Inspecting Parameters ```scala val surface = Surface.of[User] for param <- surface.params do println(s"${param.name}: ${param.surface.name}") // id: Long // name: String // email: Option[String] ``` ## Generic Types Surface handles generic types: ```scala val listSurface = Surface.of[List[String]] println(listSurface.name) // "List[String]" val mapSurface = Surface.of[Map[String, Int]] println(mapSurface.name) // "Map[String,Int]" ``` ## Type Aliases Surface resolves type aliases: ```scala type UserId = Long val surface = Surface.of[UserId] println(surface.name) // "Long" ``` ## Methods Inspect method signatures: ```scala trait UserService: def findUser(id: Long): Option[User] def createUser(name: String, email: String): User val methods = Surface.methodsOf[UserService] for m <- methods do println(s"${m.name}(${m.args.map(_.name).mkString(", ")}): ${m.returnType.name}") // findUser(id): Option[User] // createUser(name, email): User ``` ## Zero Values Surface can provide zero/default values: ```scala import wvlet.uni.surface.{Surface, Zero} Zero.zeroOf(Surface.of[Int]) // 0 Zero.zeroOf(Surface.of[String]) // "" Zero.zeroOf(Surface.of[Option[Int]]) // None Zero.zeroOf(Surface.of[List[String]]) // Nil Zero.zeroOf(Surface.of[Map[String, Int]]) // Map.empty ``` ## Use Cases ### Object Wiring Surface powers uni's Design system: ```scala import wvlet.uni.design.Design // Design uses Surface to understand type structure val design = Design.newDesign .bindImpl[UserService, UserServiceImpl] ``` ### Serialization Weaver uses Surface for automatic serialization: ```scala import wvlet.uni.weaver.Weaver // Surface describes the structure for serialization val json = Weaver.toJson(user) val restored = Weaver.fromJson[User](json) ``` ### Validation Build validators based on type structure: ```scala import scala.collection.mutable.ListBuffer def validate[T](value: T)(using surface: Surface): List[String] = val errors = ListBuffer[String]() for param <- surface.params do val fieldValue = param.get(value) if param.surface.name == "String" && fieldValue == "" then errors += s"${param.name} cannot be empty" errors.toList ``` ## Annotations Surface captures annotations, with their literal arguments, on parameters, methods, and classes with a public constructor: ```scala import scala.annotation.StaticAnnotation class label(val value: String) extends StaticAnnotation class required extends StaticAnnotation class maxLength(val value: Int) extends StaticAnnotation @label("account") case class User( @required id: Long, @maxLength(100) name: String ) val surface = Surface.of[User] for param <- surface.params do // Check if @required is present val required = param.hasAnnotation("required") // Class-level annotations, matched by simple or full name surface.findAnnotation("label").flatMap(_.getAs[String]("value")) // Some("account") ``` ## Performance Surface uses compile-time macros, so: * **No runtime reflection** - Fast at runtime * **Compile-time verification** - Errors caught during compilation * **Cross-platform** - Works on JVM, JS, Native ## Best Practices 1. **Cache Surface instances** when used repeatedly 2. **Use at compile time** when possible 3. **Prefer Surface.of\[T]** over runtime reflection 4. **Leverage Zero** for default values in serialization --- --- url: https://wvlet.org/uni/core/io.md --- # IO The `IO` object is uni's unified I/O facade, providing both file system operations and subprocess execution in a single entry point. ```scala import wvlet.uni.io.{IO, WriteMode} ``` ## File System Operations `IO` exposes all cross-platform file system operations from `FileSystem`: ```scala // Read and write files — paths can be plain strings val content = IO.readString("file.txt") IO.writeString("file.txt", "hello", WriteMode.Create) // Check existence and type IO.exists("file.txt") // true IO.isFile("file.txt") // true IO.isDirectory("some/dir") // false // Directory operations IO.list("some/dir") IO.createDirectory("some/nested/dir") // Copy, move, delete IO.copy("src.txt", "dst.txt") IO.move("old.txt", "new.txt") IO.delete("file.txt") IO.deleteRecursively("some/dir") // Temporary files val tmp = IO.createTempFile("prefix", ".txt", None) val tmpDir = IO.createTempDirectory("prefix", None) // Platform info IO.currentDirectory IO.homeDirectory IO.tempDirectory // Use IO.path(...) to build an IOPath for composition or to inspect parts val path = IO.path("some") / "nested" / "dir" / "file.txt" println(path.fileName) // "file.txt" ``` See [FileSystem](filesystem.md) for the full file system API reference. ## Subprocess Execution The `IO` object provides three methods for running external commands: | Method | Behavior | |--------|----------| | `IO.run` | Execute and capture output, return `CommandResult` | | `IO.call` | Like `run`, but throws on non-zero exit code | | `IO.spawn` | Start process without waiting, return `Process` handle | ### IO.run Execute a command and capture its output. Accepts a single command line string (automatically tokenized) or separate arguments: ```scala import wvlet.uni.io.IO // Single command line string — tokenized automatically val result = IO.run("ls -la /tmp") // Separate arguments val result = IO.run("ls", "-la", "/tmp") println(result.exitCode) // 0 println(result.stdout) // file listing println(result.stderr) // empty println(result.isSuccess) // true ``` Quoted arguments are handled correctly: ```scala IO.run("sh -c 'echo hello world'") IO.run("""grep -r "TODO" src/""") ``` Non-zero exit codes are returned without throwing: ```scala val result = IO.run("sh -c 'exit 42'") result.exitCode // 42 result.isSuccess // false ``` ### IO.call Like `run`, but throws `NonZeroExitCodeException` on failure: ```scala import wvlet.uni.io.{IO, NonZeroExitCodeException} val result = IO.call("echo", "hello") result.stdout.trim // "hello" // Throws NonZeroExitCodeException try IO.call("sh", "-c", "exit 1") catch case e: NonZeroExitCodeException => println(s"Exit code: ${e.exitCode}") ``` ### IO.spawn Start a process without waiting for completion. Returns a `Process` handle with access to stdin/stdout/stderr streams: ```scala import wvlet.uni.io.IO val proc = IO.spawn("cat") proc.stdin.write("hello".getBytes("UTF-8")) proc.stdin.close() val output = String(proc.stdout.readAllBytes(), "UTF-8") proc.waitFor() // 0 ``` Timed waiting to avoid hanging: ```scala import java.util.concurrent.TimeUnit val proc = IO.spawn("long-running-command") if proc.waitFor(5, TimeUnit.SECONDS) then println(s"Exited with: ${proc.exitValue()}") else proc.destroyForcibly() ``` ## ProcessConfig All three methods accept a `ProcessConfig` for advanced options: ```scala import wvlet.uni.io.{IO, ProcessConfig} val config = ProcessConfig.default .withWorkingDirectory(IO.path("/tmp")) .withEnv("MY_VAR", "value") .withRedirectErrorToOutput(true) val result = IO.run(Seq("my-command", "--flag"), config) ``` | Option | Description | |--------|-------------| | `withWorkingDirectory(dir)` | Set the working directory | | `withEnv(key, value)` | Add an environment variable | | `withEnv(vars)` | Add multiple environment variables | | `withInheritIO(true)` | Inherit parent's stdin/stdout/stderr | | `withRedirectErrorToOutput(true)` | Merge stderr into stdout | ## Platform Support | Feature | JVM | Scala Native | Scala.js | |---------|-----|--------------|----------| | File operations | Supported | Supported | Node.js only (async recommended) | | Subprocess execution | Supported | Supported | Not supported | --- --- url: https://wvlet.org/uni/core/canvas.md --- # Canvas (Off-Heap Memory) `wvlet.uni.canvas.Canvas` is a memory buffer addressed by `Long` offsets. It can be larger than the 2 GB limit of `Array[Byte]`, and its off-heap form lives outside the managed heap, so it doesn't count toward `-Xmx` on the JVM and you can free it right away with `close()`. The API is the same on the JVM, Scala.js, and Scala Native. It is a port of airframe-canvas. ```scala import wvlet.uni.canvas.Canvas import wvlet.uni.control.Control // withResource frees the memory when the block ends, even if it throws Control.withResource(Canvas.newOffHeapCanvas(1024)) { c => c.writeInt(0, 10) c.writeLongBigEndian(8, 1234L) c.readInt(0) // 10 c.readLongBigEndian(8) // 1234 } ``` ## Creating canvases | Factory | Memory | |---------|--------| | `Canvas.newOffHeapCanvas(size: Long)` | Off-heap memory, not guaranteed to be zero-filled. Free it with `close()` | | `Canvas.newCanvas(size: Int)` | A new zero-filled heap byte array | | `Canvas.wrap(bytes)`, `Canvas.wrap(bytes, offset, length)` | An existing byte array, without copying | | `Canvas.wrap(byteBuffer)` | The remaining bytes of an array-backed `ByteBuffer`, without copying | `canvas.slice(offset, length)` returns a view that shares memory with its parent. Closing any view frees the memory for all of them. ## Reading and writing * `readByte`, `readShort`, `readInt`, `readLong`, `readFloat`, `readDouble`, `readBoolean`, and the matching `write*` methods take a `Long` offset. * Multi-byte values use little-endian byte order on every platform. `readIntBigEndian`, `writeLongBigEndian`, and the other `*BigEndian` methods use network byte order. * `readBytes` and `writeBytes` copy to and from byte arrays and other canvases. `toByteArray` copies a whole canvas (up to 2 GB). * Every access checks its range and throws `IndexOutOfBoundsException` when it falls outside the canvas. Using an off-heap canvas after `close()` throws `IllegalStateException`. ## Managing off-heap memory `OffHeapMemoryAllocator` tracks the memory its canvases still hold. `Canvas.newOffHeapCanvas` uses `OffHeapMemoryAllocator.default`. Create your own allocator to free a group of canvases together: ```scala import wvlet.uni.canvas.OffHeapMemoryAllocator val allocator = OffHeapMemoryAllocator() val a = allocator.newCanvas(4096) val b = allocator.newCanvas(4096) allocator.allocatedMemorySize // 8192 a.close() allocator.allocatedMemorySize // 4096 allocator.close() // frees b and anything else still open ``` ## Platforms | Platform | Off-heap memory | Freed without `close()` | |----------|-----------------|-------------------------| | JVM (Java 22+) | A `MemorySegment` from the Foreign Function & Memory API | Yes, after GC (`java.lang.ref.Cleaner`) | | JVM (Java 17–21) | Not supported: `newOffHeapCanvas` throws `UnsupportedOperationException` | — | | Scala.js | A JavaScript `ArrayBuffer`; `close()` detaches it where `ArrayBuffer.transfer` exists (Node.js 21+) | Yes, after GC (`FinalizationRegistry`) | | Scala Native | `malloc` / `free` | No: call `close()`, or close the allocator | On Scala Native, don't close a canvas while another thread still reads or writes it. The JVM and Scala.js report that case as `IllegalStateException`; Native can read freed memory. `Canvas.isOffHeapSupported` tells you whether `newOffHeapCanvas` works on the current platform. Heap canvases work everywhere. Close canvases explicitly, with `Control.withResource` or a `Resource` from `wvlet.uni.control`. Freeing after GC is a safety net for the JVM and Scala.js. It runs only when the GC notices the canvas is unreachable, which can be much later. --- --- url: https://wvlet.org/uni/core/filesystem.md --- # FileSystem Cross-platform file I/O abstraction for JVM, Scala.js (Node.js and browser), and Scala Native. Uni's `IO` object is the single entry point for file operations — it exposes path construction, reads, writes, directory listings, metadata, and async variants uniformly across platforms. ```scala import wvlet.uni.io.IO // Read and write files — pass paths as plain strings val content = IO.readString("config.json") IO.writeString("output.txt", "hello") // Use IO.path(...) to build an IOPath for composition or to inspect parts val path = IO.path("/home/user") / "documents" / "file.txt" println(path.fileName) // "file.txt" println(path.extension) // "txt" ``` ## Paths For most `IO` operations — read/write, list, copy, move, delete, exists, watch, and the gzip/zip helpers — you can pass paths as plain `String`s and skip the `IO.path(...)` wrapper. `IOPath` is uni's cross-platform path abstraction — reach for it (via `IO.path(...)`) when you need composition (`/`), path queries (`fileName`, `parent`, `extension`, ...), or path arithmetic (`normalize`, `relativeTo`). A few APIs that take an `Option[IOPath]` (such as the `directory` parameter of [`createTempFile`](#temporary-files)) still expect an `IOPath`. ### Creating Paths ```scala import wvlet.uni.io.IO // From string val path = IO.path("/home/user/file.txt") // Join segments val joined = IO.path("home", "user", "file.txt") // Using / operator val composed = IO.path("/home") / "user" / "file.txt" // Well-known directories val cwd = IO.currentDirectory val home = IO.homeDirectory val tmp = IO.tempDirectory ``` ### Path Properties ```scala val path = IO.path("/home/user/project/README.md") path.fileName // "README.md" path.baseName // "README" path.extension // "md" path.isAbsolute // true path.segments // Seq("home", "user", "project", "README.md") path.parent // Some(IO.path("/home/user/project")) ``` ### Path Operations ```scala // Normalize . and .. IO.path("/home/user/../admin/./config").normalize // IO.path("/home/admin/config") // Relative path val base = IO.path("/home/user") val file = IO.path("/home/user/project/src/Main.scala") file.relativeTo(base) // IO.path("project/src/Main.scala") // POSIX format (always forward slashes) path.posixPath // "/home/user/project/README.md" // Checks path.startsWith(IO.path("/home")) // true path.endsWith(IO.path("README.md")) // true ``` ## Reading and Writing Files ### Reading Files ```scala import wvlet.uni.io.IO // Read as string (UTF-8) val text: String = IO.readString("data.txt") // Read as bytes val bytes: Array[Byte] = IO.readBytes("data.txt") // Read line by line val lines: Seq[String] = IO.readLines("data.txt") ``` ### Writing Files ```scala import wvlet.uni.io.{IO, WriteMode} // Create or overwrite (default) IO.writeString("output.txt", "hello world") // Create new file, fail if exists IO.writeString("output.txt", "content", WriteMode.CreateNew) // Append to file IO.writeString("output.txt", "more content", WriteMode.Append) // Write bytes IO.writeBytes("output.bin", Array[Byte](1, 2, 3)) // Append shorthand IO.appendString("output.txt", "\nnew line") ``` ### WriteMode | Mode | Description | |------|-------------| | `CreateNew` | Create a new file, fail if it already exists | | `Create` | Create or truncate the file (default) | | `Append` | Append to the file, create if it doesn't exist | ## Directory Operations ### Listing Files ```scala import wvlet.uni.io.{IO, ListOptions} // List immediate children val files = IO.list("src") // Recursive listing val allFiles = IO.list("src", ListOptions().withRecursive(true)) // Filter by extension val scalaFiles = IO.list("src", ListOptions() .withRecursive(true) .withExtensions("scala") ) // Filter by glob pattern val testFiles = IO.list("src", ListOptions() .withRecursive(true) .withGlob("**/*Test.scala") ) // Limit depth val shallow = IO.list("src", ListOptions() .withRecursive(true) .withMaxDepth(2) ) // Include hidden files val withHidden = IO.list("src", ListOptions().withIncludeHidden(true)) ``` ### Creating, Deleting, Copying, Moving ```scala import wvlet.uni.io.{IO, CopyOptions} // Create directory (including parents) IO.createDirectory("a/b/c") // Create only if it doesn't exist IO.createDirectoryIfNotExists("output") // Delete file or empty directory IO.delete("temp.txt") // Delete recursively IO.deleteRecursively("build") // Delete if exists (no error if missing) IO.deleteIfExists("maybe.txt") // Copy IO.copy("src.txt", "dst.txt") IO.copy("srcDir", "dstDir", CopyOptions().withOverwrite(true).withPreserveAttributes(true) ) // Move / rename IO.move("old.txt", "new.txt") IO.move("old.txt", "new.txt", overwrite = true) ``` ### Temporary Files ```scala // Temporary file val tmpFile = IO.createTempFile(prefix = "data", suffix = ".json") // Temporary directory val tmpDir = IO.createTempDirectory(prefix = "work") // In a specific directory val custom = IO.createTempFile( prefix = "report", suffix = ".csv", directory = Some(IO.path("output")) ) ``` ## File Metadata ```scala import wvlet.uni.io.{IO, FileType} val info = IO.info("README.md") info.fileType // FileType.File info.size // file size in bytes info.lastModified // Option[Instant] info.createdAt // Option[Instant] info.isFile // true info.isDirectory // false info.isReadable // true info.isWritable // true info.isExecutable // false info.isHidden // false // Existence checks IO.exists("README.md") // true IO.isFile("README.md") // true IO.isDirectory("src") // true ``` ### FileType | Type | Description | |------|-------------| | `File` | Regular file | | `Directory` | Directory | | `SymbolicLink` | Symbolic link | | `Other` | Other file type | | `NotFound` | Path does not exist | ## Async Operations All async operations return `Future[...]` and work on every platform, including browsers. ```scala import wvlet.uni.io.{IO, IOPath, FileInfo} import scala.concurrent.Future // Async read/write val content: Future[String] = IO.readStringAsync("data.txt") val bytes: Future[Array[Byte]] = IO.readBytesAsync("image.png") val written: Future[Unit] = IO.writeStringAsync("output.txt", "hello") // Async directory listing val files: Future[Seq[IOPath]] = IO.listAsync("src") // Async metadata val info: Future[FileInfo] = IO.infoAsync("file.txt") val exists: Future[Boolean] = IO.existsAsync("file.txt") ``` `IOPath` and `FileInfo` are the underlying types — import them when you need explicit type annotations. ## Gzip Compression Cross-platform gzip utilities for compressing and decompressing data. ```scala import wvlet.uni.io.{IO, Gzip} // In-memory compression val data = "hello world".getBytes("UTF-8") val compressed = Gzip.compress(data) val decompressed = Gzip.decompress(compressed) // File-based compression (streaming) Gzip.compressFile("large.txt", "large.txt.gz") Gzip.decompressFile("large.txt.gz", "large.txt") ``` ## Cross-Platform Support | Operation | JVM | JS (Node) | JS (Browser) | Native | |-----------|-----|-----------|-------------|--------| | Sync read/write | Yes | Yes | No | Yes | | Async read/write | Yes | Yes | Yes | Yes | | Directory operations | Yes | Yes | No | Yes | | File metadata | Yes | Yes | No | Yes | | Temporary files | Yes | Yes | No | Yes | | Gzip | Yes | Yes | No | Yes | Sync operations throw `UnsupportedOperationException` in browser environments. Use async operations for cross-platform code that needs to run in browsers. ## Best Practices 1. **Use `IO` as the single entry point** — `IO.readString(...)`, `IO.list(...)`, etc. Pass paths as plain strings, and use `IO.path(...)` only when you need an `IOPath` value. 2. **Prefer async operations** for code that must run on all platforms 3. **Use `ListOptions`** with glob or extension filters instead of filtering results manually 4. **Use `WriteMode.CreateNew`** when you want to avoid overwriting existing files 5. **Use `deleteIfExists`** to avoid error handling for missing files --- --- url: https://wvlet.org/uni/core/settings.md --- # SettingStore `SettingStore` keeps user settings, such as a theme, recent files, or window size, across restarts. It is an `RxVar`: read it with `get`, change it with `set` or `update`, and subscribe to it like any other Rx value. Every change is saved as JSON through [Weaver](./weaver). If you have used zustand's `persist` middleware in a JavaScript app, `SettingStore` covers the same ground: a reactive store, a storage backend, a version number, and migrations. ```scala import wvlet.uni.config.SettingStore import wvlet.uni.weaver.Weaver case class AppSettings(theme: String = "light", fontSize: Int = 14) derives Weaver val settings = SettingStore.of[AppSettings].withAppName("my-app").load() settings.get.theme // "light" on the first run settings.update(_.copy(theme = "dark")) // saved to ~/.config/my-app/settings.json // Subscribe to one field, as with a zustand selector val cancelable = settings.map(_.fontSize).subscribe { size => println(s"font size: ${size}") } ``` Start from `SettingStore.of[A]`, chain `withXXX(...)` options, and finish with `load(fileName)`. `load()` reads `settings.json`; pass another name to keep a second file. The store starts from the case-class default values. Use `withDefault(...)` for another starting value, or for a type with a field that has no default value: ```scala case class Credentials(user: String, token: String) derives Weaver val credentials = SettingStore .of[Credentials] .withAppName("my-app") .withDefault(Credentials("guest", "")) .load("credentials.json") // ~/.config/my-app/credentials.json ``` ## Where settings are stored | Platform | Default storage | |----------|-----------------| | JVM, Scala Native, Node.js | `~/.config//`, or `$XDG_CONFIG_HOME//` when that variable is set | | Browser (Scala.js) | `localStorage`, under the item key `/` | Use `withLocation` to pick another directory: ```scala import wvlet.uni.io.IOPath import wvlet.uni.config.SettingLocation // ~/Library/Application Support/my-app on macOS, %APPDATA%\my-app on Windows val osConfig = SettingStore .of[AppSettings] .withAppName("my-app") .withLocation(SettingLocation.OSConfig) .load() // /.my-app/, for settings that belong to one project val project = SettingStore .of[AppSettings] .withAppName("my-app") .withLocation(SettingLocation.Project(IOPath("/work/my-project"))) .load() // Any explicit directory val custom = SettingStore .of[AppSettings] .withAppName("my-app") .withLocation(SettingLocation.Directory(IOPath("/etc/my-app"))) .load() ``` Each write goes to a temporary file first and then replaces the target file, so a crash during a write never leaves a half-written settings file. ## Schema changes The stored file records a schema version: ```json {"version": 2, "state": {"theme": "dark", "fontSize": 14}} ``` * **Adding a field**: give it a default value in the case class. Older files load, and the new field takes its default. * **Removing a field**: unknown fields in the stored file are ignored. * **Renaming or reshaping a field**: raise the version and convert the old JSON in `withMigrate`. The migrated value is written back, so each migration runs once. ```scala import wvlet.uni.json.JSON.{JSONObject, JSONValue} val migrating = SettingStore .of[AppSettings] .withAppName("my-app") .withVersion(2) .withMigrate { (state: JSONValue, fromVersion: Int) => state match // Version 1 called the field "colorScheme" case JSONObject(fields) if fromVersion < 2 => JSONObject(fields.map { case ("colorScheme", v) => "theme" -> v case other => other }) case other => other } .load() ``` If the stored data cannot be read, `SettingStore` logs a warning, keeps the data for inspection (the file is renamed to `.corrupt-`), and starts from the default value. ## Changes from other processes By default, a store reads its value once, when it is created. With `withWatchChanges(true)` it also reloads when another process changes the file, or when another browser tab changes `localStorage`: ```scala val shared = SettingStore .of[AppSettings] .withAppName("my-app") .withWatchChanges(true) .load() // Call shared.stop() to stop watching ``` ## Tests Use `InMemoryStoreBackend` so tests do not touch the real settings directory: ```scala import wvlet.uni.config.InMemoryStoreBackend val inMemory = SettingStore .of[AppSettings] .withAppName("my-app") .withBackend(InMemoryStoreBackend()) .load() ``` `withBackend` also accepts your own `StoreBackend`, for example one that stores settings in a database. --- --- url: https://wvlet.org/uni/core/result.md --- # Result `Result[A]` is Uni's standard container for "a value that may have failed". It is a Rust-flavored counterpart to `scala.util.Try`: the error channel is always a `Throwable`, and the combinators match [`Rx`](/rx/)'s vocabulary so interop is mechanical. ```scala import wvlet.uni.util.Result ``` `Result` lives in `uni-core` and is available on the JVM, Scala.js, and Scala Native. ## When to Use Result Use `Result[A]` at API boundaries where failure is an expected outcome that callers need to handle as a value — parsers, external lookups, settled `Rx` evaluations — while keeping `throw` / `try` / `catch` inside internal code. Uni deliberately does **not** introduce a type-level error channel (like ZIO's `E` parameter): Scala's exception mechanism already carries the error type, and fixing `E = Throwable` keeps the shape single-parameter like `Option[A]` and `Rx[A]`. | Situation | Recommended type | |--------------------------------------------------------|-------------------------| | Internal helper that can throw | Exceptions + `NonFatal` | | Public API that distinguishes "failed" from "returned" | `Result[A]` | | Async stream that produces zero or more values | `Rx[A]` | ## Constructing a Result `Result.apply` evaluates a block and wraps any non-fatal exception. Fatal errors (e.g. `InterruptedException`, `VirtualMachineError`) escape — this matches `scala.util.control.NonFatal`. ```scala val parsed: Result[Int] = Result(Integer.parseInt("42")) // Result.Success(42) val failed: Result[Int] = Result(Integer.parseInt("not-a-number")) // Result.Failure(java.lang.NumberFormatException: For input string: "not-a-number") ``` Direct constructors and conversions are also available: ```scala Result.success(1) // Result.Success(1) Result.failure(new RuntimeException("no")) // Result.Failure(...) Result.fromTry(scala.util.Try("parse this".toInt)) Result.fromEither(Right[Throwable, Int](42)) Result.fromOption(Option.empty[Int], new NoSuchElementException("empty")) ``` ## Composing Results `map`, `flatMap`, and `filter` work like any other monadic container, and they **catch any exceptions thrown inside the supplied function**, turning them into `Failure`. This is the "Rx-like propagation" property: exceptions never bypass the wrapper. ```scala val r: Result[Int] = for a <- Result(Integer.parseInt("10")) b <- Result(Integer.parseInt("20")) if a + b > 0 yield a + b // Result.Success(30) ``` A `Failure` anywhere in the chain short-circuits the rest — no need to thread the error manually. ## Handling Failure `recover` and `recoverWith` mirror the same-named methods on `Rx` and only fire when the partial function matches the wrapped throwable: ```scala val recovered: Result[Int] = Result(Integer.parseInt("nope")).recover { case _: NumberFormatException => 0 } // Result.Success(0) val retried: Result[Int] = Result.failure(new java.io.IOException("timeout")).recoverWith { case _: java.io.IOException => Result(42) } // Result.Success(42) ``` Other handlers: ```scala Result.failure(boom).mapError(new IllegalStateException(_)) // rewrap result.fold(onFailure = _.getMessage, onSuccess = _.toString) result.getOrElse(0) result.orElse(Result.success(0)) ``` ## Conversions `Result` interoperates with the standard Scala types: ```scala result.toOption // Option[A] — Failure becomes None result.toEither // Either[Throwable, A] result.toTry // scala.util.Try[A] result.get // A; rethrows on Failure ``` ## Rx Interop `Rx[A].materialize` reifies each upstream event as a `Result[A]`, so errors are delivered as values instead of terminating the stream: ```scala import wvlet.uni.rx.Rx val events: Rx[Result[Int]] = Rx.exception[Int](new RuntimeException("boom")).materialize // Emits Result.Failure(RuntimeException("boom")) ``` To go the other way, use `Rx.fromResult` (or the `toRx` extension on `Result`, available after importing `wvlet.uni.rx.*`): ```scala import wvlet.uni.rx.* val rx1: Rx[Int] = Rx.fromResult(Result.success(1)) val rx2: Rx[Int] = Result.success(1).toRx ``` `Result.Failure(e)` converts to an `Rx` that emits `OnError(e)` — the same termination signal a thrown exception would produce. --- --- url: https://wvlet.org/uni/core/utilities.md --- # Utilities Human-readable value types and ID generators for common programming tasks. ## UUIDv7 Time-ordered UUIDs (RFC 9562) — the recommended ID format for internal use. UUIDv7 embeds a millisecond-precision Unix timestamp, is monotonically sortable, and can be compactly encoded with Base62. ```scala import wvlet.uni.util.UUIDv7 // Generate a new UUIDv7 val id = UUIDv7.newUUIDv7() println(id) // e.g., "019078e5-3f6a-7b1c-8d4e-2f9a0b1c3d5e" // Compact 22-character Base62 representation (URL-safe, sort-order preserving) val short: String = id.toBase62 // e.g., "0K9mFb3xYz1Qw5Rv8NpJ2a" // Parse back from Base62 val recovered = UUIDv7.fromBase62(short) ``` ### Timestamps and Conversion ```scala val id = UUIDv7.newUUIDv7() // Extract timestamp val millis: Long = id.timestamp // Convert to/from java.util.UUID val uuid: java.util.UUID = id.toUUID val back: UUIDv7 = UUIDv7.fromUUID(uuid) // Binary representation val bytes: Array[Byte] = UUIDv7.toBytes(id) // 16 bytes val fromBytes: UUIDv7 = UUIDv7.fromBytes(bytes) // Parse from standard UUID string val parsed = UUIDv7.fromString("019078e5-3f6a-7b1c-8d4e-2f9a0b1c3d5e") ``` ### Custom Generator ```scala // Create an independent generator (useful for testing or isolated contexts) val gen = UUIDv7.createGenerator() val id = gen.newUUIDv7() // With a custom random source val gen2 = UUIDv7.createGenerator(new scala.util.Random(42)) ``` ## Base62 Sort-order preserving encoding using the `0-9A-Za-z` alphabet (62 characters). Encodes 128-bit values to compact 22-character URL-safe strings. Use `UUIDv7.toBase62` / `UUIDv7.fromBase62` for the common case. ```scala import wvlet.uni.util.{Base62, UUIDv7} // Most common usage: via UUIDv7 val id = UUIDv7.newUUIDv7() val encoded: String = id.toBase62 // 22 chars val decoded: UUIDv7 = UUIDv7.fromBase62(encoded) // Encode / decode raw 128-bit values val raw: String = Base62.encode128bits(0x0123456789abcdefL, 0xfedcba9876543210L) val (hi, low): (Long, Long) = Base62.decode128bits(raw) // Validate Base62.isValid("0K9mFb3xYz1Qw5Rv8NpJ2a") // true ``` ## CrockfordBase32 [Crockford's Base32](https://www.crockford.com/base32.html) encoding — the case-insensitive, human-friendly alphabet (it excludes `I`, `L`, `O`, `U` to avoid ambiguity) that backs [ULID](#ulid). Use it directly when you need to encode raw 128-bit or 48-bit values in the same format. ```scala import wvlet.uni.util.CrockfordBase32 // Encode / decode a 128-bit value (26 characters) val s: String = CrockfordBase32.encode128bits(hi = 0x0123456789abcdefL, low = 0xfedcba9876543210L) val (hi, low): (Long, Long) = CrockfordBase32.decode128bits(s) // Decode a 48-bit value (e.g. a ULID timestamp prefix) val millis: Long = CrockfordBase32.decode48bits("01ARZ3NDEK") // Validate CrockfordBase32.isValidBase32("01arz3ndektsv4rrffq69g5fav") // true ``` For ID generation prefer [ULID](#ulid) (which encodes with this alphabet) or [Base62](#base62); reach for `CrockfordBase32` only when you need the raw codec. ## NanoId Compact, URL-safe random IDs for cases where time-ordering is not needed. Useful as user-facing tokens, short links, or external keys that map back to an internal UUIDv7. ```scala import wvlet.uni.util.NanoId // Generate a default NanoId (21 chars, A-Za-z0-9_-) val id: String = NanoId.generate() // e.g., "V1StGXR8_Z5jdHi6B-myT" // Custom size val short = NanoId.generate(10) // Custom alphabet and size val hex = NanoId.generate("0123456789abcdef", 32) ``` ::: tip ID Strategy Use **UUIDv7** as the internal primary key — it is time-ordered, monotonic, and embeds a timestamp. For user-facing URLs and APIs, either: * Expose the UUIDv7 in **Base62** format (22 chars, sortable, reversible), or * Generate a **NanoId** as an external key and maintain a mapping to the internal UUIDv7. ::: ## ULID Universally Unique Lexicographically Sortable Identifiers — 128-bit IDs encoded as 26-character Crockford Base32 strings. ULID predates UUIDv7 and serves a similar purpose; **prefer UUIDv7 for new projects**. ```scala import wvlet.uni.util.ULID // Generate a new ULID val id = ULID.newULID println(id) // e.g., "01arz3ndektsv4rrffq69g5fav" ``` ### Parsing and Validation ```scala val parsed = ULID.fromString("01arz3ndektsv4rrffq69g5fav") ULID.isValid("01arz3ndektsv4rrffq69g5fav") // true ``` ### Extracting Timestamps ```scala val id = ULID.newULID val millis: Long = id.epochMillis val instant: java.time.Instant = id.toInstant val historical = ULID.ofMillis(1609459200000L) ``` ### Converting to/from UUID ```scala import java.util.UUID val ulid = ULID.newULID val uuid: UUID = ulid.toUUID val back: ULID = ULID.fromUUID(uuid) val bytes: Array[Byte] = ulid.toBytes // 16 bytes val fromBytes: ULID = ULID.fromBytes(bytes) ``` ## PrefixedULID A [ULID](#ulid) tagged with a human-readable type prefix — handy for self-describing IDs like `user:01arz3ndektsv4rrffq69g5fav` where the prefix identifies the entity. The string form is `:` (delimiter `:`), and values sort by prefix first, then by the embedded ULID timestamp. ```scala import wvlet.uni.util.PrefixedULID // Generate val id: PrefixedULID = PrefixedULID.newPrefixedULID("user") println(id) // "user:01arz3ndektsv4rrffq69g5fav" // Or directly as a string val s: String = PrefixedULID.newPrefixedULIDString("order") // Access parts id.prefix // "user" id.ulid // the underlying ULID // Parse back (splits on the last ':' so prefixes may contain ':') val parsed = PrefixedULID.fromString("user:01arz3ndektsv4rrffq69g5fav") ``` ## DataSize Human-readable data size representation with parsing and unit conversion. ```scala import wvlet.uni.util.DataSize // Parse from string val size = DataSize("128MB") // Create from bytes val fromBytes = DataSize(1073741824L) // 1GB // Auto-select best unit val succinct = DataSize.succinct(1536000L) println(succinct) // "1.46MB" ``` ### Unit Conversion ```scala val size = DataSize("2.5GB") size.toBytes // 2684354560L size.valueOf(DataSize.MEGABYTE) // 2560.0 size.convertTo(DataSize.MEGABYTE) // DataSize(2560.0, MEGABYTE) size.mostSuccinctDataSize // DataSize(2.5, GIGABYTE) ``` ### Units | Unit | Symbol | Bytes | |------|--------|-------| | `BYTE` | B | 1 | | `KILOBYTE` | kB | 1,024 | | `MEGABYTE` | MB | 1,048,576 | | `GIGABYTE` | GB | 1,073,741,824 | | `TERABYTE` | TB | 1,099,511,627,776 | | `PETABYTE` | PB | 1,125,899,906,842,624 | ## Count Human-readable large number representation. ```scala import wvlet.uni.util.Count // Parse from string val count = Count("1.5M") // Auto-select best unit val succinct = Count.succinct(1500000L) println(succinct) // "1.50M" // Raw value count.toLong // 1500000L ``` ### Unit Conversion ```scala val count = Count(2500000L) count.mostSuccinctCount // Count(2.50, MILLION) count.convertTo(Count.THOUSAND) // Count(2500, THOUSAND) count.valueOf(Count.MILLION) // 2.5 ``` ### Units | Unit | Symbol | Value | |------|--------|-------| | `ONE` | (none) | 1 | | `THOUSAND` | K | 1,000 | | `MILLION` | M | 1,000,000 | | `BILLION` | B | 1,000,000,000 | | `TRILLION` | T | 1,000,000,000,000 | | `QUADRILLION` | Q | 1,000,000,000,000,000 | ## ElapsedTime Human-readable duration representation with unit conversion. ```scala import wvlet.uni.util.ElapsedTime // Parse from string val duration = ElapsedTime("5ms") val timeout = ElapsedTime("30s") val window = ElapsedTime("2.5h") // Create from measurements val fromNanos = ElapsedTime.succinctNanos(1500000L) println(fromNanos) // "1.50ms" val fromMillis = ElapsedTime.succinctMillis(3600000L) println(fromMillis) // "1.00h" // Measure elapsed time val start = System.nanoTime() // ... do work ... val elapsed = ElapsedTime.nanosSince(start) println(elapsed) // e.g., "42.30ms" ``` ### Unit Conversion ```scala val duration = ElapsedTime("90s") duration.toMillis // 90000.0 duration.valueIn(java.util.concurrent.TimeUnit.MINUTES) // 1.5 duration.convertToMostSuccinctTimeUnit // ElapsedTime(1.50, MINUTES) ``` ### Units | Unit | Symbol | Example | |------|--------|---------| | `NANOSECONDS` | ns | `"500ns"` | | `MICROSECONDS` | us | `"100us"` | | `MILLISECONDS` | ms | `"5ms"` | | `SECONDS` | s | `"30s"` | | `MINUTES` | m | `"5m"` | | `HOURS` | h | `"2.5h"` | | `DAYS` | d | `"1d"` | ## StopWatch A simple elapsed-time timer. It starts running on creation and reports seconds as a `Double`. ```scala import wvlet.uni.util.StopWatch val sw = StopWatch() // ... do work ... val seconds: Double = sw.getElapsedTime // elapsed since creation/reset sw.stop // pause; returns the last interval sw.resume // continue measuring sw.reset // restart from zero println(sw.reportElapsedTime) // e.g. "0.42 sec." ``` ## Timer For micro-benchmarking, extend the `Timer` trait and wrap code in `time` / nested `block`. A `TimeReport` captures total and per-block timing, and `repeat` runs blocks multiple times to smooth out JIT/GC noise. ```scala import wvlet.uni.util.Timer class Benchmark extends Timer: val report = time("search", repeat = 10) { block("linear") { // candidate A } block("binary") { // candidate B } } // Inspect per-block statistics report("linear").average // average seconds over the repeats report("binary").min // min / max / median / elapsedSeconds also available val b = Benchmark() println(b.report) // formatted multi-line timing report ``` ## Best Practices 1. **Use UUIDv7** for internal IDs — time-ordered, monotonic, with an embedded timestamp 2. **Use Base62** encoding for user-facing UUIDv7 — compact (22 chars), URL-safe, sort-order preserving 3. **Use NanoId** for opaque external tokens — map them back to internal UUIDv7 when needed 4. **Use succinct formatting** in logs and UIs for readability (`DataSize.succinct`, `Count.succinct`) 5. **Parse user input** with the string constructors — they handle common formats (`"128MB"`, `"1.5M"`, `"30s"`) 6. All value types implement `Comparable` for sorting and comparison --- --- url: https://wvlet.org/uni/text.md --- # Text Formats Uni reads and writes common text formats in pure Scala. They work on JVM, Scala.js, and Scala Native with no extra dependencies. JSON is part of the core library, and the other formats are in `wvlet.uni.text`. | Package | Description | |---------|-------------| | [`wvlet.uni.json`](../core/json) | JSON parser, `JSONValue` tree, and query DSL. Weaver encodes and decodes case classes to JSON | | [`wvlet.uni.text.yaml`](./yaml) | YAML 1.2 parser that reads into the same `JSONValue` tree and decodes into case classes with Weaver, plus Markdown frontmatter | | [`wvlet.uni.text.markdown`](./markdown) | CommonMark + GitHub Flavored Markdown parser and HTML renderer | | [`wvlet.uni.text.cron`](./cron) | Cron expression parser with next-run times and English descriptions | The `wvlet.uni.text` parsers share `wvlet.uni.text.parser`. `LineReader` is a cursor for line- and indentation-oriented formats like YAML, and `ScannerBase` is a tokenizer for expression-like languages such as cron. Errors are thrown as `TextParseException`, which carries the offset of the error. The YAML, Markdown, and cron parsers also put the line, the column, and the source line with a caret in the message: ```text Unclosed flow sequence (line 2, column 4) b: [1, 2 ^ ``` --- --- url: https://wvlet.org/uni/text/yaml.md --- # YAML `wvlet.uni.text.yaml` reads YAML 1.2 into the same `JSONValue` tree that [JSON processing](../core/json) uses, so [Weaver](../core/weaver) can decode it into case classes. It works on JVM, Scala.js, and Scala Native. ## Decoding into Case Classes ```scala import wvlet.uni.text.yaml.YAML import wvlet.uni.weaver.Weaver case class ServerConfig(name: String, port: Int = 8080, tags: Seq[String] = Nil) derives Weaver val config = YAML.fromYaml[ServerConfig](""" name: api tags: [public, v2] """) // ServerConfig(api, 8080, List(public, v2)) ``` Missing fields take their case-class defaults. ## Parsing to JSONValue ```scala import wvlet.uni.json.JSON.JSONValue val v: JSONValue = YAML.parse(""" server: host: localhost ports: [80, 443] """) v.toJSON // {"server":{"host":"localhost","ports":[80,443]}} ``` `YAML.parse` reads a single document, and returns `JSONNull` for an empty one. For a `---`-separated stream, use `YAML.parseAll`: ```scala val docs: Seq[JSONValue] = YAML.parseAll("a: 1\n---\nb: 2") ``` ## Frontmatter `Frontmatter.parse` splits a YAML header delimited by `---` lines from the rest of a text, as used in Markdown files and agent skills: ```scala import wvlet.uni.text.yaml.Frontmatter case class SkillHeader(name: String, description: String = "") derives Weaver val f = Frontmatter.parse("""--- name: review description: Review a pull request --- # Instructions """) f.as[SkillHeader] // SkillHeader(review, Review a pull request) f.body // "# Instructions\n" ``` When the text has no frontmatter, `data` is `None` and `body` is the whole text. To change the header, pass the new value to `update` (or `copy(data = ...)`) and write the text back with `toText`. Only the parts of the header that changed are rewritten, so its comments and formatting stay, and the body is unchanged: ```scala import wvlet.uni.json.JSON val text = """--- # Owned by the docs team name: review # the skill name --- # Instructions """ Frontmatter.parse(text) .update(JSON.parse("""{"name":"review-pr","tags":["git"]}""")) .toText // --- // # Owned by the docs team // name: review-pr # the skill name // tags: // - git // --- // # Instructions ``` A text without frontmatter gets a new `---` header, and `copy(data = None)` removes it. [`Markdown.parse`](./markdown#frontmatter) reads the header the same way, and `toMarkdown` writes changes to `frontmatter` back. ## Supported YAML * Block mappings and sequences, including a sequence at its key's column * Flow collections: `[a, b]`, `{a: 1}`, and single-pair entries like `[a: 1]` * Plain, single-quoted, and double-quoted scalars (all YAML escapes), with multi-line folding * Literal (`|`) and folded (`>`) block scalars, with chomping (`-`, `+`) and indentation indicators * Comments, multiple documents (`---`, `...`), and `%YAML` directives * Anchors (`&name`), aliases (`*name`), and merge keys (`<<: *base`) * Tags `!!str`, `!!int`, `!!float`, `!!bool`, and `!!null`. Other tags are ignored, and the value resolves as if untagged Plain scalars resolve with the YAML 1.2 core schema: | YAML | Value | |------|-------| | `~`, `null`, empty | `JSONNull` | | `true`, `False` | `JSONBoolean` | | `42`, `0x1F`, `0o17` | `JSONLong` | | `1.5`, `1e3`, `.inf`, `.nan` | `JSONDouble` | | `yes`, `on`, anything else | `JSONString` | YAML 1.1 booleans like `yes` and `on` stay strings, as YAML 1.2 specifies. Not supported: * Explicit keys (`? key`) and complex (non-scalar) mapping keys * `%TAG` handles. Tags are ignored, apart from the ones listed above Duplicate keys are an error. Mapping keys keep their source text, so `1: a` has the key `"1"`. ## Safety Aliases share the anchored value instead of copying it. To stop "billion laughs" inputs, where nested aliases expand exponentially, parsing fails once aliases expand to more than `YAML.defaultMaxAliasNodes` (1,000,000) nodes. To change the limit, pass `maxAliasNodes`: ```scala YAML.parseAll(untrustedYaml, maxAliasNodes = 10_000) ``` ## Editing YAML `YAML.parseDocument` reads a document into a `YAMLDocument` that keeps its source text. `toYaml` writes it back: without changes, the output is the input byte for byte, including comments, blank lines, indentation, `\r\n` line breaks, and quoting. Edit it by path, and only the changed values are rewritten: ```scala val doc = YAML.parseDocument("""# Server settings server: host: localhost port: 8080 # default port # Set in production tls: false """) doc .set(Seq("server", "port"), 9090) // keeps "# default port" .set(Seq("server", "tags"), Seq("a", "b")) // adds an entry at the end of server .remove(Seq("server", "tls")) // removes tls and the comment above it .toYaml // # Server settings // server: // host: localhost // port: 9090 # default port // tags: // - a // - b ``` * A path is a list of mapping keys (`String`) and sequence indexes (`Int`). `set` adds missing keys, and missing parent mappings, at the end of their mapping; the index equal to a sequence's size appends to it. `remove` ignores a missing path. * `set` takes a `JSONValue` or any value with a `Weaver`. * `update(value)` changes the document to resolve to a new `JSONValue`, editing only the entries that differ. * `toJSON` resolves the document, as `YAML.parse` does. A replaced scalar keeps its quoting style (`'x'`, `"x"`, `|`) and the comment after it. An edited flow collection (`[a, b]`, `{k: v}`) keeps its comments and line breaks, and a new item follows the layout of the items before it. New values are written in block style with two-space indentation, or in flow style inside a flow collection. A new string is quoted when it would otherwise read as another type, so `"123"` stays a string. An anchor on a replaced value stays, so aliases to it still resolve. ### Multiple documents `YAML.parseDocument` reads a single document. For a `---`-separated stream, such as Kubernetes manifests, `YAML.parseDocuments` returns one `YAMLDocument` per document. Edit any of them, and `YAML.writeStream` writes them all back. The documents you didn't change are written byte for byte: ```scala val docs = YAML.parseDocuments("""# Deployment kind: Deployment replicas: 1 --- # Service kind: Service """) YAML.writeStream(docs.updated(0, docs(0).set(Seq("replicas"), 3))) // # Deployment // kind: Deployment // replicas: 3 // --- // # Service // kind: Service ``` Each document holds its part of the stream. A comment on its own line before a `---` marker belongs to the document below it, like a comment above a key. A comment after a document's content on the same line, and a `...` end marker, belong to the document they end. So removing a document from the `Seq` also removes its comments. `writeStream` adds a `---` before a document that doesn't start with one, unless the previous document ends with `...`. A stream with no documents gives one empty document that keeps its text, such as comments. The tree is a `YAMLNode` (`Scalar`, `Mapping`, `Sequence`, `Alias`), and you can also change it with `copy`. As with the [Markdown AST](./markdown), each node's source text is an attachment that does not take part in equality, and a node whose content differs from what was parsed is written in the canonical style. ## Writing YAML To edit an existing YAML text, use `YAMLDocument` (above). To write a value as YAML, use `YAMLFormatter.toYaml` from `wvlet.uni.json`. It converts a JSON string to YAML: ```scala import wvlet.uni.json.YAMLFormatter YAMLFormatter.toYaml("""{"name":"api","port":8080}""") // name: api // port: 8080 ``` --- --- url: https://wvlet.org/uni/text/markdown.md --- # Markdown `wvlet.uni.text.markdown` parses [CommonMark](https://spec.commonmark.org/0.31.2/) with the [GitHub Flavored Markdown](https://github.github.com/gfm/) extensions, and renders it to HTML. It works on JVM, Scala.js, and Scala Native. It passes all 652 examples of the CommonMark 0.31.2 spec, plus the GFM table, task list, strikethrough, and autolink examples. ## Rendering HTML ```scala import wvlet.uni.text.markdown.Markdown Markdown.toHtml("""# Release notes - [x] Add a **YAML** parser - [ ] Add a cron parser """) //

Release notes

//
    //
  • Add a YAML parser
  • //
  • Add a cron parser
  • //
``` The output follows the CommonMark reference renderer, so it matches other CommonMark implementations line for line. ## Safe by Default By default, `Markdown.toHtml` is safe for user-written text: * Raw HTML (` ``` ```js // src/renderer/index.js import { main } from 'scalajs:main.js' main() ``` ::: tip Styling The example styles the renderer with [Tailwind CSS](https://tailwindcss.com/) v4 via `@tailwindcss/vite`, pointing `@source` at the Scala sources so Tailwind finds the `cls` class strings used in `RendererApp.scala`. It's optional — plain CSS works too. ::: ## Step 6: the build pipeline [`electron-vite`](https://electron-vite.org/) drives the three Vite builds (main / preload / renderer). [`@scala-js/vite-plugin-scalajs`](https://www.scala-js.org/doc/tutorial/scalajs-vite.html) links a Scala.js project and exposes it as `import 'scalajs:main.js'`; its `projectID` picks the sbt project: ```js // electron.vite.config.mjs import { defineConfig, externalizeDepsPlugin } from 'electron-vite' import scalaJSPlugin from '@scala-js/vite-plugin-scalajs' export default defineConfig({ main: { plugins: [externalizeDepsPlugin(), scalaJSPlugin({ cwd: '.', projectID: 'main' })] }, preload: { plugins: [externalizeDepsPlugin()] }, renderer: { plugins: [scalaJSPlugin({ cwd: '.', projectID: 'renderer' })] } }) ``` ```json // package.json { "name": "uni-electron-example", "type": "module", "main": "out/main/index.js", "scripts": { "dev": "electron-vite dev", "build": "electron-vite build", "package": "electron-vite build && electron-builder" }, "devDependencies": { "@scala-js/vite-plugin-scalajs": "^1.0.0", "electron": "^34.0.0", "electron-builder": "^25.1.8", "electron-vite": "^2.3.0", "vite": "^5.4.11" }, "pnpm": { "onlyBuiltDependencies": ["electron", "esbuild"] } } ``` ## Step 7: run and package ```bash pnpm install pnpm dev # compiles Scala.js, starts the renderer dev server, launches Electron (hot reload) ``` Click the buttons — each is an RPC call to the main process, which owns the counter. To ship installers (dmg / nsis / AppImage via [electron-builder](https://www.electron.build/)): ```bash pnpm package # → installers under dist/ ``` ## Gotchas worth knowing * **`scalajs-java-securerandom`** — Uni's Scala.js code reaches `java.security.SecureRandom` (via ULID in the serialization layer). Recent Uni releases pull it in transitively; on older releases add it yourself, or linking fails with "non-existent class java.security.SecureRandom": ```scala libraryDependencies += ("org.scala-js" %%% "scalajs-java-securerandom" % "1.0.0").cross(CrossVersion.for3Use2_13) ``` * **ESM preload path** — under `"type": "module"`, electron-vite emits the preload as `index.mjs`. Point `preload:` at `../preload/index.mjs`, and set `sandbox: false` (ESM preloads don't load in a sandboxed renderer; `contextIsolation` still isolates it). * **Renderer is async-only** — a sandboxed renderer has no synchronous IPC, so use `Http.client.newAsyncClient`. `newSyncClient` throws. ## Where to go next * [Desktop Apps (Electron)](/http/electron) — the transport reference (channels, server, marshaling). * [RPC](/http/rpc) — defining services, generated clients, error handling. * [`examples/electron-app`](https://github.com/wvlet/uni/tree/main/examples/electron-app) — the complete, runnable project this tutorial distills. * [`examples/uni-harness`](https://github.com/wvlet/uni/tree/main/examples/uni-harness) — a larger template to grow into: a chat workspace shell (icon rail, foldable and resizable panes, a chat with a composer, a right dock) built on the same pieces. It goes beyond the counter in a few ways: * The same renderer runs in Electron and in a plain browser. `ElectronRenderer.installIfAvailable()` picks IPC when the preload bridge exists, and fetch otherwise. * The web build serves the service and the built renderer from one `Http.server`, using `StaticFiles` with an SPA fallback. * Components are tested in headless Chromium with `DomTestSupport` from uni-test (see [Testing components](/dom/testing)). --- --- url: https://wvlet.org/uni/build/sbt-uni.md --- # sbt-uni Plugin `sbt-uni` is uni's sbt 2.x plugin. It does four jobs: 1. **HTTP/RPC client generation** — turn a Scala 3 service trait into a type-safe client at build time (see [RPC](/http/rpc) for the full guide). 2. **Background fork-run** — start your application in a forked JVM and relaunch it on every code change with `~uniRestart`. 3. **OpenAPI generation** — write `openapi.yaml` for your `@Endpoint` routers with `uniOpenAPI`. 4. **uni-ui stylesheet** — copy `uni-ui.css` out of the [uni-ui](/dom/ui) jar into your web assets with `uniUiCss`. ::: tip sbt 2.x The plugin targets **sbt 2.x** (the metabuild runs on Scala 3, which lets the plugin call uni directly as a library). It is not published for sbt 1.x. The uni build the plugin loads in-process is pinned to a release built with sbt 2.0.x's metabuild Scala (3.8), independently of the uni and Scala versions your project depends on. Declare `uni` only in `build.sbt`: adding it to `project/plugins.sbt` would replace the plugin's pinned uni with one sbt's metabuild cannot load. ::: ## Installation In `project/plugins.sbt`: ```scala addSbtPlugin("org.wvlet.uni" % "sbt-uni" % "2026.2.0") ``` `UniPlugin` is not a triggered plugin, so enable it explicitly on each project that should use it: ```scala lazy val app = project .enablePlugins(UniPlugin) ``` ## Background Fork-Run `uniRestart` runs your application in a **forked JVM in the background**, so the sbt shell stays free. It is a port of [sbt-revolver](https://github.com/spray/sbt-revolver)'s `reStart` for sbt 2.x. Starting a new run stops the previous one first, which makes it ideal under sbt's file watch: ``` sbt> ~app/uniRestart ``` `~uniRestart` recompiles and relaunches the process whenever a source file changes — a tight edit/run loop for servers and long-running apps. Without the `~`, `uniRestart` starts (or restarts) the app once. | Task | Description | | ------------ | -------------------------------------------------------- | | `uniRestart` | (Re)start the app in a background forked JVM | | `uniStop` | Stop the running app (kills the forked JVM) | | `uniStatus` | Report whether the app is currently running | The forked JVM is also stopped automatically when you `reload` the build or quit sbt, so it never leaks. ### Passing arguments Everything after `uniRestart` is passed to your application's `main`. Arguments after a `---` separator become **JVM options** for the forked process instead: ``` sbt> app/uniRestart --port 8080 --- -Xmx512m -Dconfig.file=dev.conf ``` Here `--port 8080` reaches `main(args)`, while `-Xmx512m` and the `-D` property configure the forked JVM. Defaults that should always apply can be set with `uniRestartArgs`: ```scala uniRestartArgs := Seq("--port", "8080") ``` ### Working directory By default the forked process starts from the project's base directory. Override `uniRestart / baseDirectory` when the app must run from somewhere else (for example a directory holding config or static assets): ```scala uniRestart / baseDirectory := baseDirectory.value / "server" ``` ### Main class The main class is auto-detected from `Compile / run / mainClass`. When a project has several `main` methods, pin the one to fork: ```scala uniRestart / mainClass := Some("com.example.MyServer") ``` ### Settings reference | Setting | Type | Default | Description | | --------------------------- | ------------- | -------------------------------- | ---------------------------------------------------- | | `uniRestart / mainClass` | `Option[String]` | from `Compile / run / mainClass` | Main class to fork | | `uniRestart / baseDirectory`| `File` | project base directory | Working directory of the forked JVM | | `uniRestart / javaOptions` | `Seq[String]` | project `javaOptions` | JVM options for the forked process | | `uniRestart / envVars` | `Map[String,String]` | project `envVars` | Environment variables for the forked process | | `uniRestartArgs` | `Seq[String]` | `Seq.empty` | Default program arguments | | `uniRestartForkOptions` | `ForkOptions` | derived from the above | Full fork configuration (advanced override) | | `uniRestartLogTag` | `String` | project name | Prefix tagging the forked app's console output | | `uniRestartColors` | `Seq[String]` | basic colors + underlined | Console colors assigned to background apps | ::: tip Migrating from sbt-revolver The tasks are intentionally uni-prefixed (`uniRestart` vs `reStart`) so both plugins can coexist on a build while you migrate. Map `reStart` → `uniRestart`, `reStop` → `uniStop`, `reStatus` → `uniStatus`. ::: ## HTTP/RPC Client Generation Enable `UniPlugin`, depend on the project that defines the service trait, and list your generation targets: ```scala lazy val app = project .enablePlugins(UniPlugin) .dependsOn(api) // project containing the service trait .settings( uniHttpClients := Seq("com.example.api.UserService:rpc") ) ``` `uniHttpClients` is wired into `Compile / sourceGenerators`, so clients are regenerated and compiled on the next `compile`. Generation forks a JVM that runs uni's `HttpCodeGeneratorMain` from the JVM uni release your app depends on, also for Scala.js and Scala Native apps. The fork runs only when the service classes or targets changed, and it skips files whose content is unchanged. See [RPC](/http/rpc) for the target spec format and generated client API. | Setting | Type | Default | Description | | ---------------------- | ------------- | ------------------------ | -------------------------------------- | | `uniHttpClients` | `Seq[String]` | `Seq.empty` | Generation targets (`fqcn:type[:pkg]`) | | `uniHttpCodegenOutDir` | `File` | `Compile / sourceManaged`| Output directory for generated code | | `uniHttpCodegenVersion` | `String` | uni in `libraryDependencies` | uni release that runs the generator | ## OpenAPI Generation `uniOpenAPI` writes an OpenAPI document for your `@Endpoint` routers. It forks a JVM that runs uni's generator on the project's runtime classpath, so it uses the uni version your app depends on, and the build never loads your classes. ```scala lazy val server = project .enablePlugins(UniPlugin) .settings( uniOpenAPIRouters := Seq("com.example.api.Routes.router"), uniOpenAPITargetDir := baseDirectory.value / "doc" ) ``` `sbt server/uniOpenAPI` writes `doc/openapi.yaml`, and `package` regenerates it. See [OpenAPI](../http/openapi.md#with-sbt-uni) for all settings and for how routes map to the document. | Setting | Default | Description | |---|---|---| | `uniOpenAPIRouters` | empty (the task does nothing) | Scala object members (or objects) that return a `Router` | | `uniOpenAPITitle` | project `name` | `info.title` | | `uniOpenAPIVersion` | project `version` | `info.version` | | `uniOpenAPISchemaPackagePrefix` | `None` | Package prefix stripped from schema names | | `uniOpenAPIErrorResponses` | `Seq(400, 500)` | Error statuses every operation lists | | `uniOpenAPIFormat` | `yaml` | `yaml` or `json` | | `uniOpenAPITargetDir` | `target/openapi` | Output directory | ## uni-ui Stylesheet `uniUiCss` copies `uni-ui.css` from the [uni-ui](/dom/ui) dependency into a file your app's stylesheet can `@import`. Enable `UniPlugin` on the Scala.js project that depends on `uni-ui`: ```scala lazy val app = project .enablePlugins(ScalaJSPlugin, UniPlugin) .settings( libraryDependencies += "org.wvlet.uni" %% "uni-ui" % "2026.2.0", uniUiCssFile := baseDirectory.value / "web" / "uni-ui.css" ) ``` The task runs after every `compile`, and Vite's Scala.js plugin compiles on `vite dev` and `vite build`, so the copy always matches the uni-ui version the app links. It rewrites the file only when the content changes, and does nothing when `uni-ui` is not on the classpath. | Setting | Default | Description | |---|---|---| | `uniUiCssFile` | `/target/uni-ui.css` | Where the stylesheet is copied | --- --- url: https://wvlet.org/uni/build/sbt-uni-playwright.md --- # sbt-uni-playwright Plugin `sbt-uni-playwright` runs your **Scala.js tests in a real browser** (headless Chromium, Firefox, or WebKit) via [Playwright](https://playwright.dev/java/). Unlike jsdom it supports **ES modules** and a faithful DOM, and Chromium matches the Electron renderer — so the same tests cover web and Electron app code. It bundles a Scala.js [`JSEnv`](https://www.scala-js.org/doc/project/js-environments.html) (`uni-jsenv-playwright`) and wires it into `Test / jsEnv` for you, plus a task to pre-download the browser binaries. ::: tip No Node.js required The underlying Java Playwright runtime bundles its own driver and downloads browsers on demand, so you do **not** need Node.js or an npm `playwright` package to run the tests. ::: ::: warning sbt 2.x / Scala.js only The plugin targets **sbt 2.x** (its metabuild runs on Scala 3) and is meant for Scala.js projects. It is not published for sbt 1.x. ::: ## Installation In `project/plugins.sbt`, add the Scala.js plugin and this one: ```scala addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.22.0") addSbtPlugin("org.wvlet.uni" % "sbt-uni-playwright" % "2026.2.0") ``` `UniPlaywrightPlugin` is not triggered automatically, so enable it (alongside `ScalaJSPlugin`) on each Scala.js project that should test in a browser: ```scala import org.scalajs.linker.interface.ModuleKind lazy val app = project .enablePlugins(ScalaJSPlugin, UniPlaywrightPlugin) .settings( // Recommended: build ES modules so modern npm/ESM packages work. scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) } ) ``` The plugin sets `Test / jsEnv` to a Playwright environment, so `Test` runs launch a real browser: ``` sbt> app/test ``` ::: tip sbt 2.x dependencies On sbt 2.x, `%%` already encodes the Scala.js platform suffix (`_sjs1`), so use `%%` (not the old `%%%`) for your Scala.js library dependencies. ::: ## Testing uni-dom components To render `uni-dom` components and simulate clicks, typing, and pointer drags, mix in `DomTestSupport` from `uni-test` (Scala.js), which unmounts what each test rendered: ```scala import org.scalajs.dom import wvlet.uni.dom.testing.* class CounterTest extends DomTestSupport: test("clicking +1 increments the counter") { val m = mount(Counter()) fireEvent.click(m.getByText("+1")) m.text shouldContain "count=1" } test("onMount wiring") { val m = mount(AutoFocusInput()) // onMount runs a step after mount returns settle().map { _ => dom.document.activeElement shouldBe m.get("input") } } ``` `fireEvent` also has `pointerDown` / `pointerMove` / `pointerUp` (with `clientX`, `clientY`, `pointerId`, `pointerType`) and `keyDown(..., isComposing = true)` for a key pressed during IME composition. ## Configuration Pick the browser and headed/headless mode with these settings: ```scala uniPlaywrightBrowser := "chromium" // or "firefox" / "webkit" uniPlaywrightHeadless := true ``` | Setting | Type | Default | Description | | ------------------------ | ------------- | ------------ | -------------------------------------------------------- | | `uniPlaywrightBrowser` | `String` | `"chromium"` | Browser for `Test / jsEnv`: `chromium`, `firefox`, `webkit` | | `uniPlaywrightHeadless` | `Boolean` | `true` | Run the browser without a visible window | | `uniPlaywrightBrowsers` | `Seq[String]` | the single `uniPlaywrightBrowser` | Browsers that `uniPlaywrightInstall` downloads | | `uniPlaywrightScreenshotDir` | `File` | `target.value / "uni-playwright" / "screenshots"` | Where `screenshot` files and `expectScreenshot` actual/diff images are written | | `uniPlaywrightSnapshotDir` | `File` | `src/test/screenshots` | Golden images for `expectScreenshot` | | `uniPlaywrightUpdateSnapshots` | `Boolean` | `false` | Overwrite goldens instead of comparing (also `UNI_PLAYWRIGHT_UPDATE_SNAPSHOTS=1`) | ## Installing browsers Java Playwright downloads the browser on first use, but you can pre-download and pin it (handy in CI, to avoid a first-run download mid-test): ``` sbt> uniPlaywrightInstall ``` | Task | Description | | ----------------------- | ------------------------------------------------------- | | `uniPlaywrightInstall` | Download and pin the configured Playwright browser(s) | ::: tip CI on Linux On a Linux runner, install the browser's OS libraries too. Pin the npm CLI to the same Playwright version the runtime uses so the cached build matches: ``` pnpm dlx playwright@1.49.0 install --with-deps chromium ``` ::: ## Screenshots and visual regression Tests running in the browser can call JVM-side Playwright through `wvlet.uni.test.playwright.Playwright` (in `uni-test`, Scala.js only). Each call returns a lazy `Rx`: the command is sent when the `Rx` runs, so return it from the test body and chain steps with `flatMap` or a `for` comprehension: ```scala import wvlet.uni.test.UniTest import wvlet.uni.test.playwright.Playwright class DialogTest extends UniTest: test("dialog renders") { mountDialog() Playwright.expectScreenshot("dialog-open", selector = "#dialog") } ``` | Method | Description | | ------ | ----------- | | `screenshot(name, selector = "", fullPage = false): Rx[String]` | Write `.png` to the screenshot dir; returns its absolute path | | `expectScreenshot(name, selector = "", fullPage = false, maxDiffPixelRatio = 0.0, threshold = 0.1): Rx[Unit]` | Compare with the golden `--.png` in the snapshot dir | | `isAvailable: Boolean` | Whether the page runs under a compatible Playwright JSEnv | * `name` may contain only letters, digits, `.`, `_`, and `-`. * A pixel differs when any color channel differs by more than `threshold × 255`; the test fails when the differing-pixel ratio exceeds `maxDiffPixelRatio` or the image size changed. On failure, `-actual.png` and `-diff.png` (differences in red) are written to the screenshot dir. * A **missing golden** is written from the actual screenshot and the test **fails**, so review and commit it, then re-run. * Golden names include the browser and OS (`linux`, `darwin`, `win32`) because font rendering differs across them. Generate the goldens CI compares against on the CI OS. * To accept intended changes, run once with `uniPlaywrightUpdateSnapshots := true` or `UNI_PLAYWRIGHT_UPDATE_SNAPSHOTS=1`. * The viewport is fixed at 1280×720 with device scale factor 1. Outside this JSEnv (e.g. on Node.js) the calls fail with an explanatory error; use `Playwright.isAvailable` to skip instead. ## Trusted input and viewport Events created with `dispatchEvent` have `isTrusted = false` and skip default actions such as moving focus, inserting text, or submitting a form on Enter. These methods drive the browser through Playwright instead, so the page gets real input: ```scala test("submits on Enter") { mountForm() for _ <- Playwright.click("#name") _ <- Playwright.typeText("uni") _ <- Playwright.press("Enter") yield submitted shouldBe true } test("collapses the menu on narrow screens") { mountMenu() Playwright.withViewportSize(500, 800) { Playwright.expectScreenshot("menu-narrow", selector = "#menu") } } ``` | Method | Description | | ------ | ----------- | | `click(selector, timeoutMillis = 5000): Rx[Unit]` | Click the matching element | | `hover(selector, timeoutMillis = 5000): Rx[Unit]` | Move the mouse over the matching element (`:hover` applies) | | `fill(selector, text, timeoutMillis = 5000): Rx[Unit]` | Replace the value of an input, textarea, or contenteditable element | | `typeText(text): Rx[Unit]` | Type `text` key by key into the focused element | | `press(key): Rx[Unit]` | Press a key or combination on the focused element, e.g. `"Enter"`, `"Control+A"` | | `setViewportSize(width, height): Rx[(Int, Int)]` | Resize the viewport; returns the previous size | | `withViewportSize(width, height)(body: Rx[A]): Rx[A]` | Run `body` at that size, then restore the previous size | * Selectors are [Playwright selectors](https://playwright.dev/java/docs/locators) (CSS by default). A selector matching more than one element fails rather than picking one. * Element commands wait up to `timeoutMillis` for the element to be actionable (visible, stable, enabled). The default is 5s, shorter than Playwright's 30s, because a waiting command pauses the test run's console output. * All tests in a run share one page, so a viewport change persists. Prefer `withViewportSize`, which keeps the 1280×720 baseline that screenshots rely on. * These commands need `uni-jsenv-playwright` 2026.1.27 or later; an older one fails the call with "requires a newer uni-jsenv-playwright". ## Failure artifacts On an **uncaught JS error**, the environment saves a screenshot and a Playwright trace under `target/uni-playwright`, and logs a hint to open the trace: ``` npx playwright show-trace target/uni-playwright/trace-.zip ``` ## Using the JSEnv directly (without the plugin) If you only want the environment and prefer to wire `Test / jsEnv` yourself, add the library to `project/plugins.sbt`: ```scala libraryDependencies += "org.wvlet.uni" %% "uni-jsenv-playwright" % "2026.2.0" ``` Then set the environment. sbt 2.x caches setting values and a `JSEnv` is not serializable, so wrap it in `Def.uncached`: ```scala import wvlet.uni.jsenv.playwright.PlaywrightJSEnv Test / jsEnv := Def.uncached(new PlaywrightJSEnv("chromium", headless = true)) ``` For finer control, construct it from a `PlaywrightConfig`: ```scala import wvlet.uni.jsenv.playwright.{PlaywrightConfig, PlaywrightJSEnv} Test / jsEnv := Def.uncached( new PlaywrightJSEnv( PlaywrightConfig() .withBrowserName("webkit") .withHeadless(true) .noArtifactCapture ) ) ``` | `PlaywrightConfig` field | Type | Default | Description | | ----------------------------- | ------------- | ---------------------- | ------------------------------------------------- | | `browserName` | `String` | `"chromium"` | `chromium`, `firefox`, or `webkit` | | `headless` | `Boolean` | `true` | Run without a visible window | | `captureArtifactsOnFailure` | `Boolean` | `true` | Save a screenshot + trace on an uncaught JS error | | `artifactDir` | `Path` | `target/uni-playwright`| Where failure artifacts are written | | `launchArgs` | `List[String]`| `Nil` | Extra browser CLI flags appended to the defaults | Each field has a `withXxx(...)` setter, plus `noArtifactCapture` to disable artifact capture. --- --- url: https://wvlet.org/uni/build/sbt-uni-crossproject.md --- # sbt-uni-crossproject Plugin `sbt-uni-crossproject` lets one source tree cross-build for **JVM, Scala.js, and Scala Native**. It is a small, uni-owned re-implementation of [portable-scala/sbt-crossproject](https://github.com/portable-scala/sbt-crossproject), which has not been ported to sbt 2.x. It provides just the surface uni uses: `crossProject(...)` with the **`CrossType.Pure`** layout — shared sources in `/src`, platform-specific code in `/.jvm`, `.js`, and `.native`. ::: warning sbt 2.x only The plugin targets **sbt 2.x** (its metabuild runs on Scala 3). It is not published for sbt 1.x — if you are on sbt 1.x, use the original `sbt-crossproject` instead. ::: ::: tip One plugin, all three platforms Unlike upstream's three separate artifacts (`sbt-crossproject` + `sbt-scalajs-crossproject` + `sbt-scala-native-crossproject`), this is a single plugin that depends on both `sbt-scalajs` and `sbt-scala-native` and defines all three platforms. ::: ## Installation In `project/plugins.sbt`, add the Scala.js and Scala Native plugins (for their `scalaJSLinkerConfig` / `nativeConfig` settings) and this one: ```scala addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.22.0") addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.5.12") addSbtPlugin("org.wvlet.uni" % "sbt-uni-crossproject" % "2026.2.0") ``` The plugin is triggered automatically, so `crossProject`, the platforms, and `CrossType` are available in `build.sbt` without an explicit `enablePlugins`. ## Usage ```scala lazy val core = crossProject(JVMPlatform, JSPlatform, NativePlatform) .crossType(CrossType.Pure) .in(file("core")) .settings(/* shared settings */) .jvmSettings(/* JVM-only */) .jsSettings(/* Scala.js-only */) .nativeSettings(/* Scala Native-only */) lazy val app = crossProject(JVMPlatform, JSPlatform, NativePlatform) .crossType(CrossType.Pure) .in(file("app")) .dependsOn(core, core % "test") ``` `crossProject` must be assigned directly to a `val` — it derives the project id from the **val name** (just like sbt's own `project`). So `val core = …` defines the sub-projects `coreJVM`, `coreJS`, and `coreNative`, which you reach as `core.jvm`, `core.js`, and `core.native` (e.g. when aggregating or depending on a single platform): ```scala lazy val root = project .in(file(".")) .aggregate(core.jvm, core.js, core.native, app.jvm, app.js, app.native) sbt> coreJVM/test ``` ::: tip sbt 2.x dependencies On sbt 2.x, `%%` already encodes the platform suffix (`_sjs1` for Scala.js, `_native0.5` for Native), so use `%%` (not the old `%%%`) for your cross-platform library dependencies inside `.settings(...)`. ::: ## Directory layout (`CrossType.Pure`) ``` core ├── .js // core/.js/src/main/scala — Scala.js-only sources ├── .jvm // core/.jvm/src/main/scala — JVM-only sources ├── .native // core/.native/src/main/scala — Scala Native-only sources └── src // core/src/main/scala — shared across all platforms // core/src/main/scala-3, scala-2.13, ... — shared, version-specific ``` Shared sources live under `/src`. Scala-version-specific shared sources (`src/main/scala-3`, `src/main/scala-2.13`, …) are picked up too when `crossPaths` is enabled (the default). The same structure applies under `src/test` for tests. ## Supported API The cross-project value supports the methods uni's own build relies on: | Method | Description | | ------------------------------------------------- | ------------------------------------------------------------- | | `.crossType(CrossType.Pure \| CrossType.Full)` | Choose the directory layout (default `Pure`) | | `.in(file("..."))` | Set the cross-project base directory | | `.settings(...)` | Settings applied to every platform project | | `.jvmSettings` / `.jsSettings` / `.nativeSettings`| Settings applied to one platform only | | `.configure(...)` / `.jvmConfigure` / `.jsConfigure` / `.nativeConfigure` | Apply `Project => Project` transforms | | `.enablePlugins(...)` / `.disablePlugins(...)` | Enable/disable sbt plugins on every platform project | | `.dependsOn(other, other % "test")` | Depend on another cross-project, optionally scoped to a config| | `.aggregate(other)` | Aggregate another cross-project | | `.jvm` / `.js` / `.native` | The underlying single-platform `Project` for that platform | ::: tip Scope Only the `CrossType.Pure` (and `CrossType.Full`) layouts are supported. Upstream features uni does not use — partially-shared sources, the `Dummy` layout, and `withoutSuffixFor` — are intentionally omitted. ::: --- --- url: https://wvlet.org/uni/build/sbt-uni-javadoc.md --- # sbt-uni-javadoc Plugin `sbt-uni-javadoc` shrinks the `-javadoc.jar` your build publishes, so a release stays within [Maven Central's publishing limits](https://central.sonatype.org/publish/maven-central-publishing-limits/). It works for any sbt 2.x project, with or without the uni library. ## When to use it Maven Central caps how much each organization can publish per month, and Scaladoc output is often the largest part of a Scala release ([scala/scala3#26387](https://github.com/scala/scala3/issues/26387)). Maven Central still requires a `-javadoc.jar` for every artifact, so the jar cannot simply be dropped. Reach for this plugin when: * your organization publishes many artifacts or frequent releases and is close to the limit, or * you cross-build for Scala.js or Scala Native, whose Scaladoc repeats the JVM artifact's API, or * you publish sbt plugins, whose users read guides rather than Scaladoc. Uni uses it for its own releases. About 58% of a uni release was `-javadoc.jar` before. ::: warning sbt 2.x only The plugin targets **sbt 2.x** (its metabuild runs on Scala 3). ::: ## Installation In `project/plugins.sbt`: ```scala addSbtPlugin("org.wvlet.uni" % "sbt-uni-javadoc" % "2026.2.0") ``` This also brings in [sbt-salad-days](https://github.com/sbt/sbt-salad-days), which strips fonts and `inkuire.js` from Scaladoc output automatically. sbt-salad-days is a great choice on its own if that is all you need; this plugin adds the reductions below on top of it. Nothing else changes until you add a setting: choosing which artifacts get which javadoc is your build's decision. Each setting below is a `Seq[Setting[?]]` you add to a project's settings. ## Settings ### `minimizeScaladoc`: keep the full Scaladoc, smaller ```scala lazy val core = project .settings(minimizeScaladoc) ``` By default Scaladoc embeds the whole navigation side menu in every HTML page (about 100 KB per page). `minimizeScaladoc` adds `-dynamic-side-menu`, which writes the menu once to `dynamicSideMenu.json` and renders it with JavaScript. Scaladoc up to 3.10 builds broken side-menu links when the docs are not served from the root of a host, as on javadoc.io ([scala/scala3#27403](https://github.com/scala/scala3/pull/27403)). The setting patches `scripts/ux.js` in the jar with that fix, and warns once a Scaladoc version no longer needs the patch. On Scala 2 the setting does nothing, because Scala 2 Scaladoc has no `-dynamic-side-menu` option. It is safe to add to settings shared by Scala 2 and Scala 3 builds. ### `minimizeJavadoc`: link Scala.js and Native artifacts to the JVM Scaladoc ```scala lazy val core = crossProject(JVMPlatform, JSPlatform, NativePlatform) .settings(minimizeScaladoc) .jsSettings(minimizeJavadoc) .nativeSettings(minimizeJavadoc) ``` For a Scala.js or Scala Native artifact whose JVM artifact is also published, the jar holds only `index.html` and `README.md`. They link to the JVM artifact's Scaladoc on javadoc.io (`https://javadoc.io/doc//_/`) and to `javadocSiteUrl`. Scaladoc does not run, so the release build gets faster too. Do not add it to a module that is Scala.js or Native only: its Scaladoc is the only place its API is published. ### `minimizePluginJavadoc`: link to the guide and the source ```scala lazy val plugin = project .enablePlugins(SbtPlugin) .settings(minimizePluginJavadoc) ``` For sbt plugins and other artifacts that users learn from guides, the jar holds only `index.html` and `README.md` linking to `javadocSiteUrl` and `javadocSourceUrl`. To link to one guide page and one source directory, pass their paths: ```scala lazy val plugin = project .enablePlugins(SbtPlugin) .settings( minimizePluginJavadoc(guide = "build/my-plugin", sourceDir = "my-plugin/src/main/scala") ) ``` This links to `/build/my-plugin` and `/tree//my-plugin/src/main/scala`, the GitHub URL layout, where `` is `v` for a release and `main` for a snapshot. ## Link settings | Setting | Default | Used for | | ------------------ | --------------------- | ------------------------------ | | `javadocSiteUrl` | `homepage` | The guides (website) link | | `javadocSourceUrl` | `scmInfo` `browseUrl` | The source code link | Set them when the defaults point elsewhere, for example when `homepage` is the repository rather than the website: ```scala ThisBuild / javadocSiteUrl := "https://example.org/my-library/" ``` A link whose setting and default are both unset is left out of the page. --- --- url: https://wvlet.org/uni/blog/introducing-uni.md description: >- Uni is one Scala 3 library with one set of conventions for object wiring, logging, object serialization (JSON and MessagePack), HTTP, typed RPC, MCP servers, Rx, CLI tools, and testing, on the JVM, Scala.js, and Scala Native. It is the Scala 3 successor of Airframe and is built to be read by AI coding agents as well as people. --- # Introducing Uni: One Scala 3 Library for the Whole App **Uni is a Scala 3 library that gives an application everything it needs from one dependency, with one set of conventions: object wiring, logging, object serialization (JSON and MessagePack), an HTTP client and server, typed RPC, MCP servers, Rx, CLI tools, and a test framework. The same code runs on the JVM, Scala.js, and Scala Native.** Uni has shipped 37 releases since March 2026, and this post is its first proper introduction. ![Many libraries, or one Uni? On the left, a developer and an AI assistant sit among piles of manuals beneath a tangled tower of boxes labeled HTTP client, JSON, HTTP server, logging, RPC, object wiring, MCP, CLI, and testing, next to a sign reading "Assemble it yourself". On the right, a unicorn carries all of those pieces in one bag, beside a sign reading "Uni: designed for Scala 3, one API, JVM, Scala.js, and Native, one style for you and your AI agent". A banner at the bottom says "Love the ecosystem? Mix and match. Uni plays well with others."](/blog/many-libraries-or-one-uni.webp) ## Many libraries, or one? Building a Scala application usually starts with choosing libraries: one for HTTP, one for JSON, one for logging, one for tests, maybe one for wiring services together. Each is good at its job, and each comes with its own documentation, its own style, and its own release schedule. Before writing business logic, you learn several APIs and keep their versions compatible. Platform support also varies from library to library when you target Scala.js or Scala Native. Uni takes the other path: **learn one library, build the whole app.** * **One dependency.** `"org.wvlet.uni" %% "uni"` brings object wiring, logging, codecs, HTTP, RPC, MCP, Rx, and CLI utilities. On the JVM it depends only on the Scala 3 standard library. * **One set of conventions.** A case class with `derives Weaver` becomes JSON, MessagePack, an RPC payload, and an MCP tool argument through the same codec. Services are plain classes wired by `Design`, and any class gets logging by mixing in `LogSupport`. * **One version to upgrade.** All the pieces are released together, so they never disagree on transitive dependencies. * **One codebase on three platforms.** The same code runs on the JVM, in Node.js or the browser, and as a Scala Native binary. ## What is in the box | Need | Uni | |------|-----| | Object wiring and lifecycle | [Design](/core/design): constructor wiring, singletons, `onStart`/`onShutdown` hooks | | Logging | [`LogSupport`](/core/logging): `info`/`debug`/`warn` with source locations | | Object serialization | [Weaver](/core/weaver): `derives Weaver` for JSON and MessagePack | | HTTP client | [`Http.client`](/http/client): sync and async, retries, Server-Sent Events, WebSocket | | HTTP server | [REST Server](/http/server): Netty on the JVM (`uni-netty`), Node.js on Scala.js, a native server on Scala Native | | Typed RPC | [RPC](/http/rpc): services defined as Scala traits, with type-safe clients | | MCP servers | [`wvlet.uni.mcp`](/mcp/): a Scala trait becomes tools that AI agents can call | | Reactive streams | [Rx](/rx/): composable streams and variables for async code and UI state | | CLI | [Command Launcher](/cli/launcher), terminal colors, progress bars | | Web UI (Scala.js) | [RxElement](/dom/): reactive HTML components driven by `Rx` | | Desktop apps | [Electron](/http/electron): typed RPC between the UI and the main process over IPC | | Testing | [UniTest](/core/unitest) (`uni-test`): `shouldBe`, `shouldMatch`, property checks | ## Quick start Uni requires Scala 3.9 or later. Add it to `build.sbt`: ```scala sbt scalaVersion := "3.9.0" libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" // Testing libraryDependencies += "org.wvlet.uni" %% "uni-test" % "2026.2.0" % Test testFrameworks += new TestFramework("wvlet.uni.test.Framework") ``` Define a service as a trait, implement it as a plain class with logging, and let `Design` wire it: ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport import wvlet.uni.mcp.description import wvlet.uni.weaver.Weaver case class Greeting(name: String, message: String) derives Weaver trait GreeterService: @description("Greet a person by name") def greet(@description("Who to greet") name: String): Greeting class GreeterServiceImpl extends GreeterService with LogSupport: def greet(name: String): Greeting = info(s"Greeting ${name}") Greeting(name, s"Hello, ${name}!") @main def hello = Design.newDesign.bindImpl[GreeterService, GreeterServiceImpl].build[GreeterService] { greeter => println(Weaver.toJson(greeter.greet("Uni"))) // {"name":"Uni","message":"Hello, Uni!"} } ``` The same trait is also an MCP server. Every public method becomes a tool that Claude Code or another MCP client can call, with its input schema derived from the method signature: ```scala import wvlet.uni.mcp.MCP @main def greeterMcp(): Unit = MCP.server .withName("greeter") .withVersion("0.1.0") .withTools[GreeterService](GreeterServiceImpl()) .serveStdio() ``` And it is tested with UniTest: ```scala test test("greet a person") { GreeterServiceImpl().greet("Uni").message shouldBe "Hello, Uni!" } ``` For a longer walk through, read the [Guide](/guide/) or [The Uni Book](/book/), which builds a CLI, an HTTP service, and a cross-platform app step by step. ## Demo: one trait, from server to browser to desktop Uni's conventions carry across a whole application. Here, one service trait becomes an HTTP API, a web UI, and an Electron desktop app. Define the service once, in code shared by every platform: ```scala import wvlet.uni.rx.Rx case class CounterState(value: Int) trait CounterApi: def get(): Rx[CounterState] def increment(amount: Int): Rx[CounterState] class CounterApiImpl extends CounterApi: private var value = 0 def get(): Rx[CounterState] = Rx.single(CounterState(value)) def increment(amount: Int): Rx[CounterState] = value += amount Rx.single(CounterState(value)) ``` **Serve it over HTTP.** On the JVM, `RPCRouter` turns the trait into routes, and `uni-netty` serves them: ```scala import wvlet.uni.http.netty.{Netty, RPCHandler} import wvlet.uni.http.rpc.RPCRouter @main def counterServer(): Unit = Netty.server .withPort(8080) .withRxHandler(RPCHandler(RPCRouter.of[CounterApi](CounterApiImpl()))) .start(_.awaitTermination()) ``` **Build the UI in Scala.js.** `RxElement` renders HTML that updates itself when an `Rx.variable` changes, and `RPCClient` calls the trait's methods with the same JSON codec the server uses. The same component runs in a browser page or in an Electron window: ```scala skip import wvlet.uni.dom.all.* import wvlet.uni.dom.all.given import wvlet.uni.http.Http import wvlet.uni.http.rpc.RPCClient import scala.language.implicitConversions class CounterUI extends RxElement: private val rpc = RPCClient.of[CounterApi] private lazy val client = Http.client.newAsyncClient private val count = Rx.variable(0) override def render: RxElement = div( h1("Uni Counter"), p(count.map(_.toString)), // re-renders when count changes button( onclick -> { () => rpc.callAsync[CounterState](client, "increment", Seq(1)).run(show) }, "+1" ) ) private def show(s: CounterState): Unit = count := s.value override def onMount(node: Any): Unit = rpc.callAsync[CounterState](client, "get", Seq.empty).run(show) ``` In a browser, the client sends these calls over HTTP to the server above. Serve the page from the same origin as the server (a dev-server proxy works), because the server does not add CORS headers. **Ship it as a desktop app.** In Electron, the main process serves the same trait over IPC instead of a network port, and the renderer calls `ElectronRenderer.install()` once so `CounterUI`'s calls go over IPC too. No HTTP server, no open ports: ```scala skip import wvlet.uni.electron.{ElectronRenderer, ElectronRPCServer} import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel // Main process (Node.js) @JSExportTopLevel("wireMainProcess") def wireMainProcess(ipcMain: js.Dynamic): Unit = ElectronRPCServer.serve(ipcMain, RPCRouter.of[CounterApi](CounterApiImpl())) // Renderer (Chromium) @JSExportTopLevel("main") def main(): Unit = ElectronRenderer.install() CounterUI().renderTo("app") ``` The whole app (service, UI, and business logic) is Scala, built from one codebase. [`examples/electron-app`](https://github.com/wvlet/uni/tree/main/examples/electron-app) is the runnable version with Tailwind CSS styling and packaging for macOS, Windows, and Linux, and the [Electron Tutorial](/http/electron-tutorial) builds it step by step from an empty directory. ## Built for AI agents, too More and more Scala code is written together with AI coding agents, so Uni treats agents as primary readers of its documentation: * [`llms.txt`](https://wvlet.org/uni/llms.txt) and [`llms-full.txt`](https://wvlet.org/uni/llms-full.txt) publish the docs as Markdown, and every page has a `.md` copy. * [Uni for AI Agents](/guide/for-ai-agents) lists the canonical imports, an Airframe-to-Uni mapping, and the mistakes agents most often make. * A Claude Code plugin teaches the agent idiomatic Uni code, with snippets that are compile-checked in CI: ```text /plugin marketplace add wvlet/uni /plugin install uni@uni ``` * The docs are indexed by [Context7](https://context7.com/wvlet/uni) and [DeepWiki](https://deepwiki.com/wvlet/uni). Because Uni has one style across all of these features, an agent that has learned one part of it can write the rest in the same style. ## The Scala 3 successor of Airframe Uni grew out of [Airframe](https://github.com/wvlet/airframe). It keeps Airframe's most-used ideas (`Design` for object wiring, `Rx`, `Surface` for compile-time type information, and derived codecs) and rebuilds them for Scala 3 only, with fewer dependencies and a trimmed scope under the `wvlet.uni.*` package. [Appendix B of the book](/book/appendix-b-airframe) tells the story, and the [migration table](/guide/for-ai-agents#how-do-i-migrate-from-airframe) maps Airframe imports to Uni. Uni is already in production use: [Wvlet](https://github.com/wvlet/wvlet), a flow-style query language with its CLI and server, is built on `uni`, `uni-test`, and `uni-netty`. ## Uni and the rest of the ecosystem The Scala ecosystem has many good libraries. The [Scala Toolkit](https://docs.scala-lang.org/toolkit/introduction.html), with sttp, uPickle, os-lib, and MUnit, is the easiest start for scripts, teaching, and everyday tasks, and Cask is a simple way to serve HTTP on the JVM. Uni works alongside them: you can add Uni for object wiring and logging and keep using the libraries you already rely on. If a focused library already serves you well, there is no need to switch. [Uni and the Scala Toolkit](/guide/uni-vs-scala-toolkit) explains when each fits and how to use them together. ## Try it * [Guide](/guide/) and [Installation](/guide/installation) * [The Uni Book](/book/) * [Uni and the Scala Toolkit](/guide/uni-vs-scala-toolkit) * [Uni for AI Agents](/guide/for-ai-agents) * [GitHub: wvlet/uni](https://github.com/wvlet/uni) Questions, ideas, and bug reports are welcome on [GitHub](https://github.com/wvlet/uni/issues). --- --- url: https://wvlet.org/uni/index.md description: >- Uni is the Scala 3 successor of Airframe: object wiring, logging, JSON/MessagePack, Rx, HTTP, RPC, MCP servers, and testing with minimal dependencies, on JVM, Scala.js, and Scala Native. --- # Uni ## What is Uni? **Uni is a Scala 3 library that gives you object wiring (Design), logging, JSON/MessagePack, Rx, HTTP client/server, RPC, MCP servers, and testing from one project, with minimal dependencies, and the same code runs on JVM, Scala.js, and Scala Native.** It is the Scala 3 successor of [Airframe](https://github.com/wvlet/airframe), for people who build services, CLIs, and tools in Scala 3 and want one consistent set of conventions across these concerns. ## Install ::: code-group ```scala [sbt] libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.2.0" // Testing libraryDependencies += "org.wvlet.uni" %% "uni-test" % "2026.2.0" % Test testFrameworks += new TestFramework("wvlet.uni.test.Framework") // Netty HTTP server (JVM only) libraryDependencies += "org.wvlet.uni" %% "uni-netty" % "2026.2.0" ``` ```scala [Scala CLI] //> using dep org.wvlet.uni::uni:2026.2.0 ``` ::: ## Example: Design, logging, and JSON ```scala import wvlet.uni.design.Design import wvlet.uni.log.LogSupport import wvlet.uni.weaver.Weaver case class Greeting(name: String, message: String) derives Weaver class Greeter extends LogSupport: def greet(name: String): String = info(s"Greeting ${name}") Weaver.toJson(Greeting(name, s"Hello, ${name}!")) @main def hello = Design.newDesign.bindSingleton[Greeter].build[Greeter] { greeter => println(greeter.greet("Uni")) // {"name":"Uni","message":"Hello, Uni!"} } ``` ## Why one library? * **Minimal dependencies.** On the JVM, `uni` depends only on the Scala 3 standard library. Scala.js and Scala Native add only the platform shims they need, such as `java.time` support. * **One version to upgrade.** Object wiring, logging, codecs, HTTP, and tests are released together, so they never disagree on transitive dependencies. * **One codebase on three platforms.** The same code runs on the JVM, in Node.js or the browser, and as a Scala Native binary. * **One set of conventions.** Case classes become JSON, RPC payloads, and MCP tool arguments through the same `Weaver` codecs. Focused libraries and ecosystems such as sttp, circe, ZIO, and MacWire are good choices, and if they already serve you well there is no need to switch. Uni fits best when you want these pieces from one place, especially when targeting Scala.js or Scala Native. ## Used by Wvlet [Wvlet](https://github.com/wvlet/wvlet), a flow-style query language and its CLI and server, is built on `uni`, `uni-test`, and `uni-netty`. ## For AI agents * [`llms.txt`](https://wvlet.org/uni/llms.txt) (page index) and [`llms-full.txt`](https://wvlet.org/uni/llms-full.txt) (all docs in one file) * [Uni for AI Agents](/guide/for-ai-agents): canonical imports, an Airframe migration table, and common mistakes * [Context7](https://context7.com/wvlet/uni) * Claude Code plugin: `/plugin marketplace add wvlet/uni`, then `/plugin install uni@uni` ## Modules | Module | Contents | Platforms | |--------|----------|-----------| | `uni` | Design, logging, JSON/MessagePack, Rx, HTTP client, Node.js/Native HTTP servers, RPC, MCP, [CLI utilities](/cli/), [Web UI](/dom/) (Scala.js) | JVM, Scala.js, Scala Native | | `uni-netty` | Netty HTTP server, annotation router, HTTP RPC server | JVM | | `uni-ui` | [UI components](/dom/ui) for uni-dom: controls, overlays, virtualized collections, a dock, and `UiAgent` for AI agents | Scala.js | | `uni-test` | UniTest framework | JVM, Scala.js, Scala Native | --- --- url: https://wvlet.org/uni/uni-walkthrough.md --- # Uni Walkthrough ::: info This walkthrough has moved The single-page walkthrough has been replaced by two maintained, deeper resources: * **[The Uni Book](/book/)** — a narrative, front-to-back guide to building applications with Uni (the *how* and *why*). * **The module references** — exhaustive, verified API docs for each module. The map below points each old section to its new home. ::: ## Where each topic lives now | Topic | Narrative (Book) | Reference | |-------|------------------|-----------| | Getting started | [Ch 1: Getting Started](/book/ch01-00-getting-started) · [Ch 2: A URL Fetcher](/book/ch02-00-cli-app) | [Installation](/guide/installation) | | Object wiring with Design | [Ch 3: Wiring with Design](/book/ch03-00-design) | [Design](/core/design) | | Testing | [Ch 4: Testing with UniTest](/book/ch04-00-testing) | [UniTest](/core/unitest) | | Logging | [Ch 5: Logging That Finds You](/book/ch05-00-logging) | [Logging](/core/logging) | | JSON & MessagePack | [Ch 6: Data In, Data Out](/book/ch06-00-data) | [JSON](/core/json) · [MessagePack](/core/msgpack) · [Weaver](/core/weaver) | | FileSystem | [Ch 11: One Codebase, Three Runtimes](/book/ch11-00-cross-platform) | [FileSystem](/core/filesystem) | | Reactive streams (Rx) | [Ch 7: Rx, the Composable Stream](/book/ch07-00-rx) | [Rx](/rx/) | | Control flow | [Ch 8: Living With Failure](/book/ch08-00-control) | [Control Flow](/control/) | | Surface (type reflection) | — | [Surface](/core/surface) | | Object weaving | [Ch 6: Data In, Data Out](/book/ch06-00-data) | [Weaver](/core/weaver) | | HTTP & RPC | [Ch 9–10](/book/ch09-00-http) | [HTTP](/http/) | | Cross-platform & native interop | [Ch 11–15](/book/ch11-00-cross-platform) | [Cross-platform](/guide/principles) | New here? Start with **[The Uni Book](/book/)**, or jump straight to the [module reference](/core/) for the piece you need. --- --- url: https://wvlet.org/uni/design/rx-concurrency.md --- # uni-rx Concurrency Design Note ## Overview This document outlines the gap between cats-effect's concurrency model and uni-rx, along with a phased implementation plan to bring high-concurrency support to uni-rx while maintaining its lightweight, cross-platform nature. ## Background ### Current State of uni-rx uni-rx is a lightweight reactive stream library optimized for: * Simple sequential pipelines * Cross-platform Scala (JVM/JS/Native) * UI reactivity patterns (RxVar for DOM binding) * Integration with Scala Futures However, it has significant limitations for high-concurrency workloads: | Aspect | Current Implementation | Limitation | |--------|----------------------|------------| | Execution Model | Single-threaded, eager pull-based | Cannot utilize multiple cores | | Concurrency Unit | OS threads via `ExecutionContext.global` | ~1MB stack per thread, limited scalability | | Synchronization | `synchronized` blocks, `AtomicBoolean` | Coarse-grained locking, contention | | Parallelism | None - `flatMap` is sequential | Cannot parallelize within a pipeline | | Backpressure | Not implemented | Risk of OOM under load | | Resource Safety | Basic `Cancelable` trait | No guaranteed cleanup on errors | ### cats-effect Concurrency Model cats-effect 3 provides a sophisticated concurrency runtime with: 1. **Fibers**: Lightweight logical threads (~200 bytes each), millions can run concurrently 2. **Work-Stealing Scheduler**: Fiber-aware scheduling with auto-yielding, 1.5-5x faster than thread pools 3. **Semantic Blocking**: Fibers suspend without blocking OS threads 4. **Concurrent Primitives**: `Ref`, `Deferred`, `Semaphore`, `Queue` built on lock-free algorithms 5. **Structured Concurrency**: Fiber hierarchy with cancellation propagation 6. **Resource Safety**: `Resource[F, A]` with bracket semantics for guaranteed cleanup ## Gap Analysis ### Critical Missing Features ``` ┌─────────────────────────────────────────────────────────────────┐ │ CONCURRENCY CAPABILITY GAP │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ cats-effect uni-rx │ │ ─────────── ────── │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Fibers │ ──── missing ────▶ │ OS Threads │ │ │ │ (millions) │ │ (hundreds) │ │ │ └─────────────┘ └─────────────┘ │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │Work-Stealing│ ──── missing ────▶ │ Fixed Pool │ │ │ │ Scheduler │ │ (no stealing)│ │ │ └─────────────┘ └─────────────┘ │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Ref/Deferred│ ──── missing ────▶ │ RxVar only │ │ │ │ Semaphore │ │ (synchronized)│ │ │ └─────────────┘ └─────────────┘ │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ parMap │ ──── missing ────▶ │ Sequential │ │ │ │ parTraverse │ │ only │ │ │ └─────────────┘ └─────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` ### Performance Implications | Scenario | cats-effect | uni-rx (current) | |----------|-------------|------------------| | 10K concurrent HTTP requests | ~10ms latency, low memory | Thread exhaustion or OOM | | CPU-bound parallel processing | Linear scaling with cores | Single-threaded | | Mixed I/O + compute workload | Efficient multiplexing | Blocking I/O starves compute | | Backpressured stream processing | Controlled memory usage | Unbounded buffering | ## Design Goals 1. **No cats-effect dependency**: Keep uni minimal; implement similar semantics natively 2. **Cross-platform**: Parallelism gracefully degrades to sequential on Scala.js 3. **Opt-in complexity**: Simple pipelines remain simple; concurrency is explicit 4. **Backward compatible**: Existing `Rx` code continues to work unchanged 5. **Minimal footprint**: Only add what's needed for high-concurrency support ## Implementation Plan ### Phase 1: Core Concurrency Primitives #### RxRef\[A] - Lock-free Concurrent State A functional wrapper around `AtomicReference` providing safe concurrent state access: ```scala trait RxRef[A]: /** Get the current value */ def get: Rx[A] /** Set a new value */ def set(a: A): Rx[Unit] /** Atomically update the value */ def update(f: A => A): Rx[Unit] /** Atomically modify and return a result */ def modify[B](f: A => (A, B)): Rx[B] /** Compare-and-set */ def compareAndSet(expected: A, newValue: A): Rx[Boolean] object RxRef: def apply[A](initial: A): RxRef[A] ``` **Implementation notes:** * Uses `java.util.concurrent.atomic.AtomicReference` on JVM * Falls back to simple mutation on JS (single-threaded) * Retry loop for `update`/`modify` on CAS failure #### RxDeferred\[A] - One-shot Synchronization A synchronization primitive for communicating a single value between fibers: ```scala trait RxDeferred[A]: /** Semantically block until a value is available */ def get: Rx[A] /** Complete with a value, returns false if already completed */ def complete(a: A): Rx[Boolean] /** Check if completed without blocking */ def tryGet: Rx[Option[A]] object RxDeferred: def apply[A](): RxDeferred[A] // Direct creation def of[A](): Rx[RxDeferred[A]] // Creation within Rx context ``` **Implementation notes:** * Uses `RxRef[Option[A]]` + callback list for waiters * `get` registers a callback if not yet completed * `complete` triggers all registered callbacks #### RxSemaphore - Concurrency Limiting Controls the number of concurrent operations: ```scala trait RxSemaphore: /** Acquire a permit, semantically blocking if none available */ def acquire: Rx[Unit] /** Release a permit */ def release: Rx[Unit] /** Execute an Rx with automatic acquire/release */ def withPermit[A](rx: Rx[A]): Rx[A] /** Try to acquire without blocking */ def tryAcquire: Rx[Boolean] /** Current number of available permits */ def available: Rx[Long] object RxSemaphore: def apply(permits: Long): RxSemaphore // Direct creation def of(permits: Long): Rx[RxSemaphore] // Creation within Rx context ``` ### Phase 2: Fiber-like Execution Model #### RxFiber\[A] - Lightweight Concurrency Unit Represents a running computation that can be joined or cancelled: ```scala trait RxFiber[A]: /** Wait for the fiber to complete and get its result */ def join: Rx[A] /** Request cancellation of this fiber */ def cancel: Rx[Unit] /** Check completion status without blocking */ def poll: Rx[Option[Try[A]]] extension [A](rx: Rx[A]) /** Fork this Rx to run concurrently, returning a handle */ def start: Rx[RxFiber[A]] /** Fork and forget - fire and forget execution */ def startAndForget: Rx[Unit] ``` #### RxScheduler - Work-Stealing Thread Pool Platform-specific scheduler optimized for fiber-like workloads: ```scala trait RxScheduler: /** Execute a task on the scheduler */ def execute(task: Runnable): Unit /** Schedule a delayed task */ def schedule(delay: Long, unit: TimeUnit)(task: => Unit): Cancelable /** Number of worker threads */ def parallelism: Int object RxScheduler: /** Default work-stealing scheduler */ def default: RxScheduler /** Create a scheduler with specific parallelism */ def apply(parallelism: Int): RxScheduler ``` **JVM Implementation:** * Work-stealing `ForkJoinPool` with FIFO async mode * Sized to `Runtime.getRuntime.availableProcessors()` * Separate blocking pool for `Rx.blocking` operations **JS Implementation:** * Uses microtask queue (`Promise.resolve().then(...)`) * Single-threaded, no actual parallelism * `parallelism = 1` always **Native Implementation:** * Fixed-size thread pool * Work-stealing if available in Scala Native runtime ### Phase 3: Parallel Operators #### Parallel Combinators ```scala extension [A](rx: Rx[A]) /** Map with bounded parallelism */ def parMap[B](parallelism: Int)(f: A => B): Rx[B] /** FlatMap with concurrent inner streams */ def parFlatMap[B](parallelism: Int)(f: A => Rx[B]): Rx[B] /** Merge emissions from another stream */ def merge[B >: A](other: Rx[B]): Rx[B] /** Run concurrently with another, take first result */ def race[B](other: Rx[B]): Rx[Either[A, B]] object Rx: /** Run multiple Rx in parallel, return first to complete */ def race[A](a: Rx[A], b: Rx[A]): Rx[A] /** Run multiple Rx in parallel, collect all results */ def parSequence[A](rxs: Seq[Rx[A]]): Rx[Seq[A]] /** Traverse with bounded parallelism */ def parTraverse[A, B](as: Seq[A], parallelism: Int)(f: A => Rx[B]): Rx[Seq[B]] /** Run all and return when all complete */ def parZip[A, B](a: Rx[A], b: Rx[B]): Rx[(A, B)] ``` ### Phase 4: Resource Safety and Backpressure #### RxResource - Bracket Semantics ```scala trait RxResource[A]: /** Use the resource with guaranteed cleanup */ def use[B](f: A => Rx[B]): Rx[B] /** Compose resources */ def flatMap[B](f: A => RxResource[B]): RxResource[B] def map[B](f: A => B): RxResource[B] object RxResource: /** Create a resource with acquire and release */ def make[A](acquire: Rx[A])(release: A => Rx[Unit]): RxResource[A] /** Create from AutoCloseable */ def fromAutoCloseable[A <: AutoCloseable](acquire: Rx[A]): RxResource[A] /** Lift a pure value (no cleanup needed) */ def pure[A](a: A): RxResource[A] ``` #### RxBoundedQueue - Backpressure Support ```scala trait RxBoundedQueue[A] extends RxSource[A]: /** Offer an element, returning false if full */ def tryOffer(a: A): Rx[Boolean] /** Offer an element, semantically blocking until space available */ def offer(a: A): Rx[Unit] /** Take an element, semantically blocking until available */ def take: Rx[A] /** Current queue size */ def size: Rx[Int] object RxBoundedQueue: def apply[A](capacity: Int): Rx[RxBoundedQueue[A]] ``` ## Cross-Platform Considerations | Feature | JVM | Scala.js | Scala Native | |---------|-----|----------|--------------| | `RxRef` | AtomicReference | Direct mutation | AtomicReference | | `RxDeferred` | Lock-free with CAS | Promise-based | Lock-free with CAS | | `RxSemaphore` | Lock-free queue | Sequential permits | Lock-free queue | | `RxFiber.start` | ForkJoinPool | Microtask queue | Thread pool | | `parMap(n)` | True parallelism | Sequential (n=1) | True parallelism | | `RxScheduler` | Work-stealing pool | Event loop | Fixed pool | ## Migration Path ### Existing Code Compatibility All existing uni-rx code continues to work: ```scala // Before and after - no changes needed Rx.fromSeq(1 to 10) .map(_ * 2) .filter(_ > 5) .run(println) ``` ### Opting into Parallelism ```scala // Sequential (existing behavior) Rx.fromSeq(urls) .flatMap(url => fetchUrl(url)) .run(process) // Parallel (new capability) Rx.fromSeq(urls) .parFlatMap(parallelism = 10)(url => fetchUrl(url)) .run(process) ``` ## Performance Targets | Metric | Target | |--------|--------| | Fiber creation overhead | < 1μs | | Context switch between fibers | < 100ns | | `parMap` scaling | Linear up to core count | | Memory per fiber | < 1KB | | Throughput (ops/sec) | > 1M on 8-core machine | ## Testing Strategy 1. **Unit tests**: Each primitive in isolation 2. **Stress tests**: High contention scenarios 3. **Cross-platform tests**: Verify behavior consistency 4. **Benchmarks**: Compare with cats-effect baseline 5. **Property-based tests**: Verify concurrency invariants ## References * [Cats Effect 3 Concurrency](https://typelevel.org/blog/2020/10/30/concurrency-in-ce3.html) * [Cats Effect Thread Model](https://typelevel.org/cats-effect/docs/thread-model) * [Work-Stealing Scheduler Design](https://github.com/typelevel/cats-effect/issues/634) * [Java ForkJoinPool](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/ForkJoinPool.html)