<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/hero-dark.svg">
<img alt="pactum — Transport-free Rust contracts, shared business logic & polyglot codecs" src="assets/hero-light.svg" width="880">
</picture>
<br/>
<br/>
[](https://crates.io/crates/pactum)
[](https://github.com/kevinrodriguez-io/pactum/stargazers)
[](https://github.com/kevinrodriguez-io/pactum/commits/main)
[](https://www.rust-lang.org/)
[](https://spec.openapis.org/oas/v3.1.0)
[](LICENSE)
</div>
**pactum** lets you define wire models, normalization pipelines, validation rules, HTTP/WebSocket contracts, and **any shared pure business logic** **once** in a pure Rust crate with zero IO, then share identical codecs, schemas, typed route metadata, and domain logic across **Rust, C#, Python, Go, Node.js, Swift, Kotlin, WebAssembly, and OpenAPI 3.1** surfaces so calculations, rules, and behavior stay consistent everywhere.
- **Rust contract & logic crates (`*-contract`, `*-logic`):** Own data shapes, composable Zod-style rules (`define_rule!`, `#[norm]`, `#[check]`, `#[constraint]`), shared pure business logic (`#[pactum::export] pub fn` or direct `#[uniffi::export]` for pricing/scoring calculations, state machines, permission checks, derived state, parsers, and `pactum::validate_model`), MessagePack/JSON codecs, typed `Endpoint` descriptors, IDL snapshots, JSON Schema (Draft 2020-12), OpenAPI 3.1, and RPC schema catalogs.
- **Backend host (Rust, C#, Python, Go, Node.js):** Owns web frameworks, WebSocket servers, routing, authentication, and databases, while running the exact same Rust contracts and business logic.
- **Client apps:** Compute quotes/scores, query valid transitions and derived UI state, validate drafts before leaving the device, and encode/decode payloads via UniFFI (Swift, Kotlin, browser WASM2) / NAPI-RS, or consume `/openapi.json` directly with zero WASM overhead.
> **Hard boundary:** Contract and logic crates (`*-contract`, `*-logic`) contain **zero** HTTP routers, WebSocket servers, database drivers, async runtimes, `std::{fs,net,process,env}` or `std::os::*` IO calls, compile-time `include*!` file embeds, `trait Controller`, `fn dispatch`, or `fn/mod ws_channel` definitions (enforced by `cargo pactum check` across default + non-NAPI features dependency trees and `syn` AST inspection).
## Architecture
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/architecture-dark.svg">
<img alt="pactum architecture: Zero-IO Rust contracts and shared business logic bridging server hosts and Swift, Kotlin, WASM2, and OpenAPI 3.1 clients" src="assets/architecture-light.svg" width="880">
</picture>
</div>
---
## Setup & Installation
### 1. Prerequisites by Target
| Target | Required Tooling | Notes |
|---|---|---|
| **Core (Rust)** | [Rust `1.90+` & `cargo`](https://rustup.rs) | Required for all contract & logic crates |
| **CLI & Python / Kotlin / Swift** | `cargo install cargo-pactum` | Installs `cargo pactum` / `pactum` with built-in UniFFI `=0.31.2` bindgen (no separate install) |
| **Browser / React (`WASM2`)** | `rustup target add wasm32-unknown-unknown` | Frontend `package.json` needs `@ubjs/core@0.31.0-8`, `@ubjs/wasm@0.31.0-8`, and devDep `uniffi-bindgen-react-native@0.31.0-8` (optional `wasm-opt` for release shrinking) |
| **Node.js (`NAPI-RS`)** | Node.js `18+` | `cargo pactum init --targets node` scaffolds the addon crate |
| **Go (`UniFFI`)** | `cargo install --git https://github.com/NordSecurity/uniffi-bindgen-go --tag v0.7.1+v0.31.0` | Pinned to match `uniffi = "=0.31.2"` |
| **C# (`UniFFI`)** | `cargo install --git https://github.com/NordSecurity/uniffi-bindgen-cs --tag v0.11.1+v0.31.0` | Pinned to match `uniffi = "=0.31.2"` |
| **TypeScript Client (`pactum-client`)** | `npm install pactum-client` (Node `20+` or browser `fetch` / `WebSocket`) | Zero-WASM typed HTTP & WS client via `cargo pactum ts --client` |
| **OpenAPI 3.1 (zero-WASM)** | None | Serve `contract_openapi_json()` or run `cargo pactum openapi` |
---
### 2. Setup for Coding Agents
Install the `pactum` Agent Skill so Claude Code, Cursor, Codex, Antigravity, and Gemini CLI follow contract boundaries, wire-key rules, and polyglot bindgen workflows automatically:
```bash
# Install into the current repository (`.agents/skills/pactum/`)
npx skills add kevinrodriguez-io/pactum
# Or install globally across all projects
npx skills add kevinrodriguez-io/pactum -g
```
Without Node/`npx`, install the exact same embedded skill offline via the CLI:
```bash
cargo pactum skill # writes `.agents/skills/pactum/` (add `--claude` for `.claude/skills` symlink)
cargo pactum skill --global # writes `~/.agents/skills/pactum/`
```
*(Note: `cargo pactum init` also installs `.agents/skills/pactum/` automatically unless `--no-skill` is passed.)*
---
### 3. Setup via CLI (`cargo pactum`)
Install the CLI once (exposes both `cargo pactum <cmd>` and standalone `pactum <cmd>`):
```bash
cargo install cargo-pactum
```
#### Option A — New project or existing non-Rust repo (Python, Go, Node, .NET, React, iOS, Android)
```bash
cargo pactum init my-app --with-logic --targets wasm
```
This creates a clean zero-IO workspace alongside your existing backend/clients:
```text
my-app/
├── Cargo.toml # Workspace + [profile.release] + [profile.wasm]
├── ubrn.config.yaml # Added when `--targets wasm` is passed
├── .agents/skills/pactum/ # Embedded agent skill (omit with `--no-skill`)
├── logic/ # Pure FFI-free `my-app-logic` crate (`--with-logic`)
└── contract/ # `my-app-contract` (`cdylib` + `staticlib` + `rlib`, feature-gated `uniffi`)
├── Cargo.toml
├── src/{lib.rs, logic.rs}
└── tests/roundtrip.rs
```
Pass `--targets wasm,node` if you also want a `bindings-node/` NAPI-RS addon crate (`pactum::setup_napi!()`). Whenever `--targets` is non-empty (`python`, `swift`, `kotlin`, `go`, `cs`, `node`, `wasm`), `init` also writes a ready-to-run `pactum.toml` with one `[[target]]` per requested target so `cargo pactum bindgen --all` works immediately.
#### Option B — Existing Rust workspace or single-crate repo
Run inside your repository root:
```bash
cargo pactum init billing --with-logic
```
- **Existing `[workspace]`:** Creates `crates/billing-contract` (and `crates/billing-logic`) and inserts only the new paths into `[workspace].members` without touching existing crates.
- **Single-package `[package]`:** Creates `crates/billing-contract` and appends `[workspace]`. Add `billing-contract = { path = "crates/billing-contract" }` to your server crate's `[dependencies]` (e.g. Axum, Actix).
#### Option C — Existing shared Rust core (UniFFI / NAPI-RS / `rust-domain`)
If you already share a zero-IO Rust crate across mobile or Node.js — such as a [`kevinrodriguez-io/rust-domain`](https://github.com/kevinrodriguez-io/rust-domain) `core/` workspace, a hand-rolled UniFFI/NAPI-RS setup, `wasm-bindgen`, or a `serde` DTO crate — you can standardize incrementally without rewriting existing `#[uniffi::export]` objects or mobile build pipelines:
- **Wrap or adopt in-place:** Keep `core/` pure and add a `*-contract` crate in front of it, or add `pactum` directly inside `core/` alongside existing UniFFI types.
- **Standardize validation & drop NAPI mirrors:** Replace ad-hoc field validation with `define_rule!` + `Model` (`FieldIssue` errors, OpenAPI 3.1, `cargo pactum diff`) and retire `bindings/napi/` `#[napi(object)]` mirror structs with `pactum::setup_napi!()` / `#[pactum::export]`.
- **Enforce purity on existing crates:** Lint any crate name with `cargo pactum check -p <your-core-crate>`.
See [docs/existing-rust-cores.md](docs/existing-rust-cores.md) for the step-by-step migration guide, before/after examples, and UniFFI `0.32.1` vs `0.31.2` alignment rules.
#### Day-to-day workflow: add items, check boundaries, generate bindings
```bash
# Scaffold rules, models, HTTP operations, WS commands, and pure logic
cargo pactum add rule handle
cargo pactum add model BookingView --fields "id:i64,hostHandle:String"
cargo pactum add operation create_booking --method POST --path "/api/bookings" --body CreateBookingBody --response BookingView --status 201
cargo pactum add operation get_booking --method GET --path "/api/bookings/{id}" --response BookingView --params BookingParams --query BookingQuery --headers BookingHeaders --errors 404,409
cargo pactum add command SendPing --reply OkView
cargo pactum add logic quote_booking_cents
cargo pactum add logic validate_booking_draft
# Run round-trip tests and enforce zero-IO contract boundaries
cargo test --workspace
cargo pactum check
# Generate bindings for any target (use `--features server` / `--features client` to split scoped contracts)
cargo pactum bindgen --lang python --features server --out backend/generated
cargo pactum bindgen --lang kotlin --features client --out android/app/src/main/java
cargo pactum bindgen --lang swift --features client --out ios/App/Generated
cargo pactum bindgen --lang wasm --dir frontend --release
cargo pactum bindgen --lang node --features server --out backend/native --release
cargo pactum bindgen --lang go --features server --out backend/internal
cargo pactum bindgen --lang cs --features server --out backend/Generated
```
---
### 4. Manual Crate Setup (`Cargo.toml` + `src/lib.rs`)
Choose the `Cargo.toml` shape that matches your targets:
**Pure-Rust / Axum / OpenAPI 3.1 contract crate:**
```toml
[package]
name = "bookings-contract"
version = "0.1.0"
edition = "2021"
rust-version = "1.90"
[dependencies]
pactum = "0.7"
serde = { version = "1.0", features = ["derive"] }
```
**Polyglot UniFFI & Browser WASM2 contract crate** (adds feature-gated UniFFI so pure-Rust tests stay FFI-free):
```toml
[package]
name = "bookings-contract"
version = "0.1.0"
edition = "2021"
rust-version = "1.90"
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
[features]
default = []
uniffi = ["dep:uniffi"]
server = [] # Optional compile-time scope gate (`--features server`)
client = [] # Optional compile-time scope gate (`--features client`)
[dependencies]
async-trait = "0.1" # Only required if exporting async foreign traits over uniffi =0.31.2
pactum = "0.7"
serde = { version = "1.0", features = ["derive"] }
uniffi = { version = "=0.31.2", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
uniffi = { version = "=0.31.2", features = ["wasm-unstable-single-threaded"] }
uniffi-runtime-wasm = "=0.31.0-8"
```
Define reusable rules, annotated models, commands, events, and operations in `src/lib.rs`:
```rust
use serde::{Deserialize, Serialize};
use pactum::{contract, define_rule, export, Model};
#[cfg(feature = "uniffi")]
pactum::setup_uniffi!();
define_rule! {
pub rule handle: String => [
norm(trim, lowercase),
check(string(min = 2, max = 32), charset("a-z0-9_-")),
];
pub rule tag: String => [
norm(trim, lowercase),
check(slug, string(min = 1, max = 24)),
];
}
pub fn no_control_chars(s: &str) -> bool {
!s.chars().any(char::is_control)
}
#[export]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(rename_all = "camelCase")]
#[constraint(
self.end_at_ms > self.start_at_ms,
code = "INVALID_WINDOW",
field = "endAtMs",
reason = "end time must be after start time"
)]
pub struct CreateBookingBody {
#[check(rule = handle)]
pub host_handle: String,
#[norm(trim)]
#[check(
string(min = 1, max = 80),
with(no_control_chars, code = "CONTROL_CHARS", reason = "control characters are not allowed")
)]
pub guest_name: String,
#[norm(trim)]
#[check(any(email, phone))]
pub reach_at: String,
#[check(list(max = 5, unique), each(rule = tag))]
pub tags: Vec<String>,
pub start_at_ms: i64,
pub end_at_ms: i64,
}
#[export]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(rename_all = "camelCase")]
pub struct BookingView {
pub id: i64,
pub host_handle: String,
}
#[export]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
pub struct OkView {
pub ok: bool,
}
#[export(reply_enum = PeerReply)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(tag = "command", rename_all = "camelCase")]
pub enum PeerCommand {
#[reply(OkView)]
#[serde(rename_all = "camelCase")]
SendPing {
#[norm(trim)]
#[check(string(min = 1, max = 64))]
client_id: String,
},
}
#[export]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum BookingEvent {
#[serde(rename_all = "camelCase")]
BookingCreated { id: i64 },
}
contract! {
name: "bookings",
commands: [PeerCommand],
operations: [
create_booking(CreateBookingBody) -> BookingView @ POST "/api/bookings" = 201,
health() -> OkView @ GET "/health" = 200,
],
events: [BookingEvent],
models: [CreateBookingBody, BookingView, OkView, PeerReply, BookingEvent],
}
```
### Generated Surface
- **Per `#[export]` struct/enum:** `encode_<type>`, `decode_<type>`, `encode_<type>_with`, `decode_<type>_with`, plus `*_host` (UniFFI) and `*_napi` (Node.js). When `scope(...)` / `resolver = ...` is configured, also emits scoped sync/async helpers (`validate_<type>_<scope>`, `encode_<type>_<scope>`, `decode_<type>_<scope>`, `validate_<type>_<scope>_async`, `decode_<type>_<scope>_async`, plus `*_host` / `*_napi`). Command enums also generate `<cmd>_catalog()` / `<cmd>_catalog_host()` and an optional deduplicated `reply_enum`.
- **Per `#[export]` pure/async function or resolver trait:**
- `#[export] pub fn` keeps its idiomatic Rust signature (`&str`, `&[T]`, `&T`, `Result<T, Error>`) while exporting UniFFI/WASM2 and Node.js NAPI (`<fn>_napi`) bindings.
- `#[export] pub trait` + `#[export] pub async fn(..., r: &dyn Resolver)` lets contract crates declare host-resolved async interfaces (DB uniqueness, permission/policy lookups) with zero IO or Tokio dependencies inside the contract crate, generating UniFFI `with_foreign` async callbacks and NAPI `ThreadsafeFunction` JS-object adapters.
- **Per `pactum::contract!`:** `Endpoint` enum (`Endpoint::CreateBooking.path()`, `.colon_path()`, `.path_with(PathStyle)`, `.format_path(&[...])`, `.route()` returning `RouteMeta`), `route_of(Endpoint)` (`PactumRoute`), `route_with(Endpoint, PactumPathStyle)`, `format_path(Endpoint, args)`, `route_of_napi`/`route_with_napi`/`format_path_napi`, `contract_catalog()`, `contract_operations()`, `contract_idl_json()`, `contract_json_schema()`, `contract_openapi_json()`, `contract_agent_tools_json()`, `contract_typescript()` (plus `*_host` / `*_napi` wrappers for the catalog/schema/IDL/agent-tools helpers), and `contract_typescript_client()` (Rust-only). Operations also accept optional `params <Type>`, `query <Type>`, `headers <Type>`, and `errors [404, 409]` clauses after `@ METHOD "/path" = status` to emit typed OpenAPI/Agent-Tools parameters, error responses, TypeScript `ContractOperations` metadata, and typed client methods.
---
## Composable Normalization & Validation
Both `encode` and `decode` run the same two-phase pipeline before returning a value or producing bytes:
1. **Normalize (`Normalize`):** Field `#[norm(...)]` -> `rule` normalizers -> collection `each(...)` / `values(...)` normalizers -> `#[check(nested)]` child normalization.
2. **Validate (`Validate`):** Field `#[check(...)]` -> `rule` checks -> collection element/key/value checks -> `nested` child validation -> struct/enum/variant `#[constraint(...)]`.
> **Strict separation:** Validators (`email`, `phone`, `date(rfc3339)`, etc.) do not implicitly trim whitespace. Pair them with `#[norm(trim)]` (or `norm(trim)` in `define_rule!`) whenever leading/trailing whitespace should be stripped before validation.
### Docs, Deprecation, Newtypes, `transparent`, `default` & `flatten`
- **Rust docs become contract docs:** `///` comments on models, fields, enum variants, command variants, and `contract!` operations flow into `contract_catalog()` / IDL (`doc`), JSON Schema `description`, OpenAPI `summary` / `description` / parameter descriptions, Agent Tools `description`, and TypeScript JSDoc (`*/` is escaped). Operations take docs as leading `///` comments inside `operations: [ ... ]`.
- **Deprecation:** `#[deprecated]` or `#[pactum(deprecated)]` on models, fields, variants, commands, and operations emits `deprecated: true` in JSON Schema / OpenAPI / Agent Tools and an `@deprecated` JSDoc tag. `cargo pactum diff` reports newly deprecated items as non-breaking.
- **Newtypes, `#[serde(transparent)]` & unit structs:** single-field tuple structs (`struct HostId(#[norm(trim)] #[check(hostname)] String);`) and single-active-field `#[serde(transparent)]` named structs derive `Model`, normalize/validate their inner payload, report issues at the parent field (`host`, `replicas[1]`), render as the inner JSON Schema type, and export as TypeScript type aliases (`kind: "newtype"`). Unit structs (`struct Ping;`) also derive `Model`.
- **`#[serde(default)]`, `#[serde(flatten)]`, `#[serde(skip)]` & `rename_all_fields`:** field- or container-level `#[serde(default)]` marks fields optional in the IDL, JSON Schema `required`, and TypeScript (`retries?: number`). `#[serde(skip)]` (plus `skip_serializing` / `skip_deserializing`), `#[serde(rename_all_fields = "...")]` on enums, and `#[serde(rename(serialize = "...", deserialize = "..."))]` follow exact `serde` wire semantics. Flattened fields merge into the parent (`allOf` in JSON Schema, `{ ... } & Inner` in TypeScript) with flat validation issue keys; list flattened inner models in `contract!`'s `models: [...]` so OpenAPI/Agent Tools can expand them.
- **Standard-library types out of the box:** `NonZero*` integers, `IpAddr` / `Ipv4Addr` / `Ipv6Addr`, `Cow<'_, T>`, `Box` / `Rc` / `Arc`, `VecDeque`, `HashSet` / `BTreeSet`, `HashMap` / `BTreeMap` (including custom hashers), tuples, and fixed-size arrays `[T; N]` implement `Normalize`, `Validate`, `ScopedValidate`, and `AsyncValidate` with matching JSON Schema / TypeScript mappings.
### Rules, Normalizers & Checks
| Category | Syntax & Examples |
|---|---|
| **Normalizers (`#[norm(...)]`)** | `trim`, `lowercase`, `uppercase`, `strip_whitespace`, `clamp(min = …, max = …)` (any int/float via `ClampNum`), `with = fn_or_closure` (`Fn(&mut T)`), `rule = path` |
| **Strings & text shapes** | `string(min = 1, max = 32, unit = "chars" \| "bytes" \| "utf16")`, `non_empty`, `ascii`, `alphanumeric`, `digits`, `slug`, `charset("a-z0-9_-")`, `starts_with("x")`, `ends_with("y")`, `one_of("a", "b")` |
| **Identifiers, web & phone** | `uuid`, `url`, `https_url`, `email`, `phone`, `phone(locale = "US")`, `phone(locale = self.country_code)` |
| **Network, versions & encodings** | `ipv4`, `ipv6`, `ip`, `hostname` (RFC 1123), `semver` (strict SemVer 2.0.0), `hex` — zero-dependency, IO-free checks that map to JSON Schema / OpenAPI `format` or `pattern` |
| **Numbers & booleans** | `number(min, max, gt, lt, multiple_of)`, `positive`, `non_negative`, `finite` (all signed/unsigned integer and float primitives), `bool(is_true)` |
| **Dates & timestamps** | `date(ymd)` (`CivilDate`), `date(rfc3339)` (strict `Z` or `±HH:MM` offset), `timestamp_ms(after_now, before_now, min, max)` (checked against `ValidationContext`) |
| **Collections & maps** | `list(min, max, unique)`, `each(norm(...), check(...))`, `keys(...)`, `values(...)`, `nested` |
| **Combinators & custom** | `any(email, phone)`, `not(digits)`, `with = fn_path` (`bool`, `Result<(), E>`, or `Result<bool, E>` via `IntoSyncError`), `with(\|v: &str\| !v.contains(".."), code = "NO_DOTDOT", reason = "...")`, `rule = path` |
| **Named pipelines** | `define_rule! { pub rule name: Type => [ norm(...), check(...), rule(other) ]; }` or `#[pactum_rule(code = "...")]` |
| **Cross-field invariants** | `#[constraint(expr, code = "...", field = "...", reason = "...")]`, `#[constraint(async_with(fn_path), ...)]`, `#[constraint(resolve(method \| scope::method), ...)]` on structs, enums, or variants |
| **Scopes & async checks** | `server(...)`, `client(...)`, `scope(name, ...)`, `resolve(method \| scope::method, code = "...", reason = "...", always = true)`, `async_with(fn_path)`, `async_rule(path)`, `async_nested` |
---
## Host-Resolved Async Logic & Validation Scopes
Contracts remain 100% pure and IO-free (zero Tokio, HTTP, or database drivers), while letting hosts supply async side-effect resolvers and separating server-only from client-only validation rules:
1. **Declare host resolver traits cleanly in `*-contract`:** Annotate a trait with `#[export]` (or `#[export(feature = "server")]` to strip it from client builds). Each `async fn` runs on the caller's executor (`asyncio`, Swift `async/await`, Kotlin coroutines, JS `Promise`, Tokio, or a zero-dep Rust poller).
2. **Scope checks cleanly across client & server (`examples/todos`):** Attach `scope(server, resolver = UserStore, feature = "server")` and `scope(client, feature = "client")` to `CreateUserBody`, then express rules in one place:
```rust
#[export(feature = "server")]
pub trait UserStore {
async fn email_available(&self, email: &str) -> Result<bool, pactum::Error>;
}
#[export(
scope(server, resolver = UserStore, feature = "server"),
scope(client, feature = "client")
)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Model)]
#[serde(rename_all = "camelCase")]
pub struct CreateUserBody {
#[norm(trim, lowercase)]
#[check(
email,
resolve(server::email_available, code = "EMAIL_TAKEN", reason = "an account with this email already exists")
)]
pub email: String,
#[norm(trim)]
#[check(string(min = 1, max = 80), client(string(min = 2)))]
pub display_name: String,
}
```
- **Host adapters (zero boilerplate):**
- **Python FastAPI (`examples/todos`):** Subclass `contract.UserStore` with `async def email_available(self, email: str) -> bool` and call `await contract.decode_create_user_body_server_async_host(raw, FORMAT, USER_STORE)`.
- **Rust Axum:** Implement `#[pactum::async_trait] impl UserStore for AppDb` and call `decode_create_user_body_server_async(...)`.
- **Node.js (NAPI-RS):** Pass either an ES6 `class` instance (bound `this` preserved across `await`) or a plain JS object with sync or Promise-returning methods; rejecting Promises surface cleanly as `Error::Host`.
- **Execution & error semantics:**
- All synchronous checks on a field run first; if a field already has a sync error, its async check is skipped unless `always = true` is set.
- Validation failures aggregate into `Error::Invalid { issues }` (`422`), whereas host IO/network/exception failures short-circuit immediately as `Error::Host { code, reason }` (`502`/`503` — `PactumBindError.Host` over UniFFI).
- **Split builds for isomorphic targets (Rust, JS/TS, Swift, Kotlin, Python, C#):** Gate scopes with `feature = "server"` / `feature = "client"` and build separately via `cargo pactum bindgen --features server` and `--features client` (or `wasm2.features: [uniffi, client]` in `ubrn.config.yaml`) so client binaries never carry server traits or schemas.
---
## Shared Business Logic Across Surfaces
Contracts define what crosses the wire; **business logic outside `pactum::contract!`** lets every surface (web, iOS, Android, desktop, CLI, and backend hosts) share **any pure, deterministic business logic** without duplicating and drifting logic in TypeScript, Swift, Kotlin, Python, Go, or C#:
- **Not just validation:** Share pricing/fee/quota calculations (`wip_remaining`, `evaluate_todo_urgency`), state machines & workflow queries (`allowed_next_columns`), permission/eligibility checks, derived UI state, text/URL parsers (`extract_mentions`, `bookmark_domain`), multi-input policy guards (`validate_card_move`), and live in-memory form validation (`pactum::validate_model`).
- **Module inside a contract crate (`src/logic.rs`):** Export `#[export] pub fn` helpers right next to your contract models (see [examples/todos/contract/src/logic.rs](examples/todos/contract/src/logic.rs) and [examples/peer-chat/contract/src/logic.rs](examples/peer-chat/contract/src/logic.rs)).
- **Standalone `*-logic` crate:** Keep pure domain policies (`define_rule!`, pricing, state machines, WIP limits, eligibility checks) in an FFI-free `*-logic` crate, then re-export them via `#[export] pub fn` wrappers in `*-contract` (see [examples/kanban/logic](examples/kanban/logic) -> [examples/kanban/contract/src/logic.rs](examples/kanban/contract/src/logic.rs)).
```rust
use pactum::{export, validate_model, Error};
/// Deterministic urgency scoring returning a typed derived view (`TodoUrgency`).
#[export]
pub fn evaluate_todo_urgency(
priority: &str,
due_date: Option<String>,
today_ymd: &str,
completed: bool,
) -> Result<TodoUrgency, Error> {
todos_logic::evaluate_todo_urgency(priority, due_date, today_ymd, completed)
}
/// Pure state-machine query: returns valid next columns for UI controls and menus.
#[export]
pub fn allowed_next_columns(
current_column: &str,
assignee: Option<String>,
doing_count: u32,
) -> Vec<String> {
kanban_logic::allowed_next_columns(current_column, assignee, doing_count)
}
/// Multi-input workflow transition guard with structured field-level issues.
#[export]
pub fn validate_card_move(
from_column: &str,
to_column: &str,
assignee: Option<String>,
doing_count: u32,
) -> Result<String, Error> {
kanban_logic::validate_card_move(from_column, to_column, assignee, doing_count)
}
/// Live in-memory form/draft validation (no byte serialization overhead).
#[export]
pub fn validate_todo_draft(
title: &str,
priority: &str,
due_date: Option<String>,
notes: &str,
) -> Result<CreateTodoBody, Error> {
validate_model(CreateTodoBody {
title: title.to_string(),
priority: priority.to_string(),
due_date: due_date.filter(|d| !d.trim().is_empty()),
notes: notes.to_string(),
})
}
```
- **Shared calculations, derived state & UI affordances:** React WASM2, Swift, and Kotlin call `evaluateTodoUrgency(...)`, `wipRemaining(doingCount)`, `allowedNextColumns(...)`, `extractMentions(...)`, `bookmarkDomain(...)`, and `validateTodoDraft(...)` directly in memory with zero HTTP round-trips so badges, disabled buttons, quotes, and parsed outputs always match the backend.
- **Identical server execution:** ASP.NET Core (`KanbanContractMethods.ValidateCardMove`), Python FastAPI (`contract.evaluate_todo_urgency`), Go, and Node.js NAPI (`contract.extractMentions` / `contract.validateDirectMessage`) call the exact same Rust functions so client state, calculations, and server enforcement never diverge.
- **`#[pactum::export]` vs direct `#[uniffi::export]`:**
- **`#[pactum::export]` (Recommended — especially for Node.js NAPI, `Error`, and feature-gated builds):** Supports `&str`, `&[T]`, `&T`, owned values, `Option<T>`, `Vec<T>`, `#[export]` structs/enums, `FieldIssue` / `Vec<FieldIssue>`, and `Result<T, Error>`. Automatically generates UniFFI/WASM2 scaffolding (gated by `feature = "uniffi"`) **and** Node.js NAPI (`*_napi`) wrappers without manual NAPI struct mirroring.
- **Direct `#[uniffi::export]` (or `#[cfg_attr(feature = "uniffi", ::uniffi::export)]`):** Works out of the box alongside `pactum::setup_uniffi!()` for UniFFI-only stacks (Swift, Kotlin, Python, Go, C#, Browser WASM2), including `#[derive(uniffi::Record, uniffi::Enum, uniffi::Error, uniffi::Object)]` (see `bookmark_domain` in [examples/bookmarks/contract/src/lib.rs](examples/bookmarks/contract/src/lib.rs)). Requires manual NAPI wrappers if a Node.js host also calls the function.
---
## Target Compatibility Matrix
> **Legend:** ✅ Supported natively · ⚠️ Partial / manual or server-side only · ❌ Unsupported (static schema outlier)
| Target | Codecs (`JSON` & `MsgPack`) | Typed `Endpoint` Routes | `#[norm]` & `#[constraint]` | `#[pactum::export] fn` *(Shared Business Logic — recommended)* | Scoped & Async (`#[export] trait` / `resolve`) | Direct `#[uniffi::export] fn` |
|---|---|---|---|---|---|---|
| **Rust** (`rlib`) | ✅ Both | ✅ `Endpoint` | ✅ Auto | ✅ Native | ✅ Native (`#[async_trait]`) | ✅ Native |
| **Browser / React (`WASM2`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Auto | ✅ Native (UniFFI `?Send`) | ✅ Native (UniFFI) |
| **Swift (`iOS / macOS`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Auto | ✅ Native (UniFFI `async`) | ✅ Native (UniFFI) |
| **Kotlin (`Android / JVM`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Auto | ✅ Native (UniFFI `suspend`) | ✅ Native (UniFFI) |
| **Python** | ✅ Both | ✅ `route_of` | ✅ Auto | ✅ Auto | ✅ Native (UniFFI `asyncio`) | ✅ Native (UniFFI) |
| **Go** | ✅ Both | ✅ `RouteOf` (`Pattern`) | ✅ Auto | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **C# (`.NET`)** | ✅ Both | ✅ `RouteOf` | ✅ Auto | ✅ Auto | ✅ Native (UniFFI `Task`) | ✅ Native (UniFFI) |
| **Node.js (`NAPI-RS`)** | ✅ Both | ✅ `routeOfNapi` | ✅ Auto | ✅ Auto | ✅ Native (`Promise` / JS objects) | ⚠️ Manual NAPI wrapper |
| **OpenAPI 3.1** *(outlier)* | ⚠️ JSON only | ✅ `paths` + `operationId` | ⚠️ Server-side (`422` + `x-pactum-*`) | ❌ Not executable | ⚠️ Server-side (`422` + `x-pactum-rules` `scope`) | ❌ Not executable |
> **Why OpenAPI 3.1 is the only outlier:** OpenAPI 3.1 is a static JSON/YAML contract description rather than an executable runtime. Zero-WASM OpenAPI clients cannot run `#[norm]` normalizers, `#[constraint]` expressions, or `#[export] pub fn` shared business logic (such as calculations, state transitions, permissions, derived UI state, or live form validation) in the browser — they rely on the server's Rust `decode_*` and logic pass, handling structured `422` `{ code, reason, issues }` responses (see [examples/contacts](examples/contacts)).
### Serde Wire-Key Fidelity
`FieldIssue.field`, `ModelSchema`, JSON Schema, and OpenAPI 3.1 emit the actual **wire keys** declared by `#[serde(rename_all = "...")]` and `#[serde(rename = "...")]`.
> **Tip for internally tagged enums:** Serde applies enum-level `rename_all` to variant names only. Add `#[serde(rename_all = "camelCase")]` to individual struct variants as well so their fields serialize in camelCase and match schema/issue keys.
---
## Codecs, Envelopes & Schema Exports
```rust
pactum::encode(value, Format::Binary, max_frame_bytes)?;
pactum::decode::<CreateBookingBody>(bytes, Format::Json, max_frame_bytes)?;
pactum::decode_with::<CreateBookingBody>(bytes, Format::Json, max_frame_bytes, &ctx)?;
```
- **`Format::Binary`:** MessagePack named maps (`rmp_serde::to_vec_named`). Unknown fields are ignored; pair with `#[serde(default)]` for backwards/forwards schema evolution.
- **`Format::Json` & feature flags:** UTF-8 JSON (both `json` and `msgpack` are enabled by default on `pactum` and `pactum-core`). Use `--no-default-features --features msgpack` to build without `serde_json`, `--no-default-features --features json` to build without `rmp-serde`, or `--no-default-features` for validation/catalog primitives only. `setup_napi!` and `contract!`'s JSON/OpenAPI/TypeScript/agent-tools renderers are gated on the `json` feature.
- **Pre-decode inspection:** `peek_string_field(bytes, format, "id")` extracts a top-level string field via streaming deserialization without validating the full payload (bounded by `DEFAULT_PEEK_MAX_BYTES`, 512 KiB), and `peek_string_field_bounded(bytes, format, "id", max_frame_bytes)` sets an explicit frame-size limit.
- **Opt-in WebSocket envelopes:** `ClientEnvelope<C>` (`{ id, command }`) and `ServerEnvelope<R, E>` (`Reply`, `Event`, `Error { id, code, reason, issues }`).
- **Schema & catalog renderers:**
- `contract_idl_json()` — Full contract IR (`ContractCatalog`) for CI diffs and offline tooling.
- `contract_json_schema()` — JSON Schema Draft 2020-12 (`$defs`, `pattern`, numeric/string/array bounds, and `x-pactum-*` metadata).
- `contract_openapi_json()` — OpenAPI 3.1.0 spec combining passive `operations` routes, schemas, and structured `422` validation error payloads.
- `contract_agent_tools_json()` — Function/RPC parameter-schema JSON definitions derived from `commands` and `operations`.
- `contract_typescript()` — Standalone TypeScript declarations (`.d.ts`) for models, discriminated command/event unions, reply maps, and `ContractOperations`.
- `contract_typescript_client()` — Thin, transport-agnostic typed TypeScript client (`.ts`) backed by the zero-dependency [`pactum-client`](packages/pactum-client) runtime package for HTTP operations (`PactumTransport<RequestOptions>` + default `createFetchTransport` with `HeadersInit`, full `RequestInit`/`credentials`, `PactumHttpError`, `CONTRACT_ROUTES`, `ContractRouteName`, `ContractClient<RequestOptions>`, `createClient`) and/or WebSocket commands & events (`PactumWsTransport<SendOptions>` + default `createWebSocketTransport`, `PactumClientEnvelope`/`PactumServerEnvelope`/`PactumWsError`, `ContractWsClient<SendOptions>`, `createWsClient`). Pass `--runtime-import <specifier>` to override `pactum-client`.
---
## Host Integration & Client Tracks
### Idiomatic Routing with Typed `Endpoint` & Cross-Framework Paths
Passive `@ METHOD "/path/{id}" = status` metadata (also accepting `:id` or trailing `{*rest}` wildcards) is validated at compile time and exported through `Endpoint` + `route_of(Endpoint) -> PactumRoute` with zero-verbosity defaults (`path` for `/{id}` & `/{*rest}`, `colon_path` for `/:id` & `/*rest`, `pattern` for Go 1.22+ `METHOD /{id}` & `/{rest...}`), plus `route_with(Endpoint, PactumPathStyle)` (`Brace`, `BraceStar`, `BraceDots`, `BracePath`, `ColonStar`, `ColonWildcard`, `Angle`), a `segments` (`Static` | `Param` | `Wildcard`) AST escape hatch, and percent-encoded, traversal-safe `format_path`. OpenAPI 3.1 automatically normalizes `{*rest}` to `{rest}` with `"x-pactum-wildcard": true`.
**C# (ASP.NET Core + UniFFI via `uniffi-bindgen-cs`):**
```csharp
var createRoute = KanbanContractMethods.RouteOf(Endpoint.CreateCard);
app.MapPost(createRoute.Path, async (HttpRequest req, BoardDb db, BoardHub hub) =>
{
using var ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
var body = KanbanContractMethods.DecodeCreateCardBodyHost(ms.ToArray(), HostFormat.Json);
var card = db.CreateCard(body);
return Results.Bytes(
KanbanContractMethods.EncodeCardViewHost(card, HostFormat.Json),
"application/json",
statusCode: createRoute.Status
);
});
```
**Python (FastAPI + UniFFI):**
```python
r = contract.route_of(contract.Endpoint.CREATE_USER)
@app.api_route(r.path, methods=[r.method], status_code=r.status)
async def create_user(request: Request):
body = contract.decode_create_user_body_host(await request.body(), FORMAT)
...
# Explicit wildcard style when needed (FastAPI `{filepath:path}` or Flask `<path:filepath>`):
rf = contract.route_with(contract.Endpoint.READ_FILE, contract.PactumPathStyle.BRACE_PATH)
```
**Go (`net/http` + UniFFI via `uniffi-bindgen-go`):**
```go
mux := http.NewServeMux()
mux.HandleFunc(contract.RouteOf(contract.EndpointListBookmarks).Pattern, server.List) // "GET /api/bookmarks"
mux.HandleFunc(contract.RouteOf(contract.EndpointCreateBookmark).Pattern, server.Create) // "POST /api/bookmarks"
// Colon-style frameworks (Gin/Echo) use .ColonPath; Hono/Fastify use PactumPathStyle.COLON_WILDCARD
```
**Rust (Axum):**
```rust
let router = Router::new()
.route(Endpoint::ListContacts.path(), get(list_contacts))
.route(Endpoint::CreateContact.path(), post(create_contact))
.route(Endpoint::DeleteContact.path(), delete(delete_contact))
.route("/openapi.json", get(openapi_spec));
// Struct destructuring works in Rust too:
let pactum::RouteMeta { path, colon_path, status, .. } = Endpoint::CreateContact.route();
```
**TypeScript (WASM2 destructuring + traversal-safe URLs) & Kotlin:**
```ts
const { method, colonPath } = routeOf(Endpoint.ListTodos); // colonPath -> "/api/users/:user_id/todos"
const path = formatPath(Endpoint.ListTodos, [userId.toString()]);
const res = await fetch(`${api}${path}`, { method });
```
```kotlin
val (_, method, path, _, status) = routeOf(Endpoint.CREATE_GROUP)
```
**Node.js (`pactum::setup_napi!()` — direct JS objects without `JSON.parse`):**
```ts
const catalog = contract.peerCommandCatalog();
const command = contract.decodePeerCommand(payload, "json");
const outBytes = contract.encodePeerServerFrame(frame, "json");
```
### Three Client Consumption Tracks
1. **Shared Rust Codec & Logic (UniFFI, WASM2, NAPI):** Swift, Kotlin, and browser WASM2 apps build native types, run shared `#[export] pub fn` business logic (calculations, state transitions, permissions, derived UI state, parsers, and live form validation), validate on `encode_*_host(...)` before sending bytes, decode replies with `decode_*_host(...)`, and catch structured `PactumBindError::Invalid { code, reason, issues }` directly without parsing JSON strings.
2. **Zero-WASM Typed TypeScript Client (`pactum-client`):** TypeScript frontends, Node/Bun/Deno services, and edge workers run `cargo pactum ts --client` + `npm install pactum-client` to get end-to-end typed HTTP operations (`createClient`) and correlated WebSocket command/event sessions (`createWsClient`) with traversal-safe URLs and structured `PactumHttpError` / `PactumWsError` handling — while relying on the server's Rust `decode_*` and shared business-logic pass (see [examples/contacts/client-ts](examples/contacts/client-ts)).
3. **Zero-WASM OpenAPI 3.1 Consumers (language-agnostic static spec):** Frontends or third-party services in any language fetch `/openapi.json` (or run `cargo pactum openapi`), resolve routes by `operationId`, and rely on the server's Rust `decode_*` and shared business-logic pass for calculations, domain rules, normalization, and structured `422` `{ code, reason, issues }` error responses (see [examples/contacts/client-openapi](examples/contacts/client-openapi)).
---
## CLI (`cargo-pactum`)
`cargo install cargo-pactum` provides `cargo pactum <cmd>` (and `pactum <cmd>`) with `clap`-powered help (`--help` / `-V` on every subcommand):
```bash
# Scaffold a contract workspace (or add to an existing Rust/polyglot repo) + agent skill
cargo pactum init [name] [--with-logic] [--targets wasm,node] # also writes pactum.toml for the chosen targets
# Add a model, operation, command, rule, or pure logic function
cargo pactum add operation create_item --method POST --path "/api/items" --body CreateItemBody --response ItemView --status 201
cargo pactum add operation get_item --method GET --path "/api/items/{id}" --response ItemView --params ItemParams --query ItemQuery --headers ItemHeaders --errors 404,409
# Build & generate bindings (single target or all `[[target]]` entries in `pactum.toml`)
cargo pactum bindgen --lang <python|kotlin|swift|wasm|node|go|cs> [--features <csv>] [--out <dir>] [--lib-out <dir>] [--no-format]
cargo pactum bindgen --all [--only <csv>]
# Install the `.agents/skills/pactum/` skill offline
cargo pactum skill [--dir <path>] [--global] [--claude]
# Expand globbed workspace members (honoring exclude), check default + non-NAPI features
# dep trees for banned IO crates (with `[check]` overrides in `pactum.toml`), and AST-check .rs files
cargo pactum check [--dir <path>] [--skill <dir>] [-p <crate>]
# Extract ContractCatalog IDL JSON directly from a contract crate
cargo pactum idl [-p <crate>] [--features <csv>] [--out contract.idl.json]
# Detect breaking vs non-breaking changes (file-to-file or against a git branch/tag/commit; exits 1 on breaking)
cargo pactum diff [--refine <type>]... <old.idl.json> <new.idl.json>
cargo pactum diff --against <git-ref> [<tracked.idl.json> | -p <crate>]
# Render JSON Schema, Agent Tools, TypeScript, typed TS fetch client, or OpenAPI 3.1 (from an IDL file OR directly via `-p <crate>`)
cargo pactum schema [<idl.json> | -p <crate>] [--format json-schema|agent-tools|typescript|typescript-client] [--out <file>]
cargo pactum typescript [<idl.json> | -p <crate>] [--client [--types-import ./types]] [--out <file>] # alias: `ts`
cargo pactum openapi [<idl.json> | -p <crate>] [--routes <routes.json>] [--out <file>]
```
---
## Workspace Crates & Examples
### Crates
| Crate | Role |
|---|---|
| `crates/pactum` | Single-import facade (`Model`, `Error`, `Format`, `setup_uniffi!`, `setup_napi!`) |
| `crates/pactum-syntax` | Shared `syn`/`quote` expansion engine for `Model`, `#[pactum_rule]`, `define_rule!`, and `scope(...)` parsing |
| `crates/pactum-annotations` | Normalizers, composable checks, `define_rule!` support traits, `CivilDate`, `ValidationContext`, and schemas |
| `crates/pactum-annotations-macros` | `#[derive(Model)]`, `#[pactum_rule]`, `define_rule!` |
| `crates/pactum-core` | MessagePack/JSON codec (`msgpack` / `json` features), envelopes, path AST, catalog, IDL, JSON Schema, OpenAPI 3.1 |
| `crates/pactum-macros` | `#[export]`, `#[describe]`, and `pactum::contract!` |
| `crates/cargo-pactum` | `cargo-pactum` / `pactum` CLI (`init`, `add`, `bindgen`, `skill`, `check`, `idl`, `diff`, `schema`, `typescript`/`ts`, `openapi`) |
| `packages/pactum-client` | Zero-dependency `pactum-client` TypeScript HTTP & WebSocket runtime for generated clients |
| `uniffi-bindgen` | Standalone excluded UniFFI (`=0.31.2`) CLI wrapper (`cargo run --manifest-path uniffi-bindgen/Cargo.toml`) for external bindgens |
### Examples
| Example | Transport | Host Stack | Client Stack |
|---|---|---|---|
| [examples/peer-chat](examples/peer-chat) | WebSocket | Node.js (NAPI direct JS objects + shared `validate_direct_message`) + SQLite | Android (Kotlin Compose), iOS (SwiftUI) |
| [examples/todos](examples/todos) | HTTP | Python FastAPI (`Endpoint`, `route_of`, `/openapi.json`, `SqliteUserStore` async `server` scope via `--features server`) + SQLite | React (WASM2 via `features: [uniffi, client]`, live `validate_todo_draft` / `evaluate_todo_urgency`, `encodeCreateUserBodyClientHost`) |
| [examples/group-chat](examples/group-chat) | HTTP + WebSocket | Rust Axum (`Endpoint`) + SQLite | React (WASM2), Kotlin, SwiftUI |
| [examples/bookmarks](examples/bookmarks) | HTTP | Go `net/http` (`RouteOf(Endpoint*)`) + SQLite | React (WASM2 + TS destructuring + `#[uniffi::export] bookmark_domain`) |
| [examples/contacts](examples/contacts) | HTTP + OpenAPI 3.1 | Rust Axum (`Endpoint` + `/openapi.json`) + SQLite | TypeScript (`client-ts` generated `pactum-client` consumer + `client-openapi` zero-WASM OpenAPI consumer) |
| [examples/kanban](examples/kanban) | HTTP + WebSocket | ASP.NET Core (C# UniFFI `Endpoint` + `kanban-logic` WIP/transition guards) + SQLite | React (WASM2 + WS + live `validate_card_draft` / `allowed_next_columns`) |
---
## Development, Publishing & Verification
- **Toolchain:** Rust `1.90+` (`rust-version = "1.90"`).
- **Dependency policy:** FFI crates use exact `=` pins (`uniffi = "=0.31.2"`, `uniffi-runtime-wasm = "=0.31.0-8"`, `napi = "=3.16.3"`) so scaffolding matches bindgen; pure-Rust dependencies use standard SemVer ranges.
- **Docs & policies:** See [CHANGELOG.md](CHANGELOG.md), [CONTRIBUTING.md](CONTRIBUTING.md), [SECURITY.md](SECURITY.md), and [PUBLISHING.md](PUBLISHING.md) (automated publishing via [scripts/publish.sh](scripts/publish.sh)).
```bash
# Run workspace unit and doc tests
cargo test --workspace && cargo test --doc --workspace
# Check contract crate isolation
cargo run -p cargo-pactum -- check
# Regenerate all targets declared in pactum.toml (UniFFI, Node NAPI, WASM2)
bash scripts/generate-bindings.sh
# Verify Rust tests, clippy, feature isolation, Python FastAPI tests, and TS typechecks
bash scripts/verify-examples.sh --offline-only
# Full end-to-end verification (also boots live Node, Axum, Go, and OpenAPI consumer integration tests)
bash scripts/verify-examples.sh
```
## License
Apache-2.0