pactum-annotations 0.1.0

Declarative field normalization and validation for pactum contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<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 &amp; polyglot codecs" src="assets/hero-light.svg" width="880">
</picture>

<br/>
<br/>

[![Crates.io](https://img.shields.io/crates/v/pactum?style=flat-square&color=ea580c)](https://crates.io/crates/pactum)
[![Stars](https://img.shields.io/github/stars/kevinrodriguez-io/pactum?style=flat-square&color=eab308)](https://github.com/kevinrodriguez-io/pactum/stargazers)
[![Last Commit](https://img.shields.io/github/last-commit/kevinrodriguez-io/pactum?style=flat-square&color=38bdf8)](https://github.com/kevinrodriguez-io/pactum/commits/main)
[![Rust 1.90+](https://img.shields.io/badge/rust-1.90%2B-ea580c?style=flat-square&logo=rust&logoColor=white)](https://www.rust-lang.org/)
[![OpenAPI 3.1](https://img.shields.io/badge/OpenAPI-3.1-6ba539?style=flat-square&logo=openapiinitiative&logoColor=white)](https://spec.openapis.org/oas/v3.1.0)
[![License](https://img.shields.io/badge/license-Apache--2.0-22c55e?style=flat-square)](LICENSE)

</div>

**pactum** lets you define wire models, normalization pipelines, validation rules, HTTP/WebSocket contracts, and **shared pure business logic** **once** in a pure Rust crate with zero IO, then share identical codecs, schemas, typed route metadata, and domain rules across **Rust, C#, Python, Go, Node.js, Swift, Kotlin, WebAssembly, and OpenAPI 3.1** clients.

- **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]`, plus `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.
- **Client apps:** Validate inputs and run shared domain rules before leaving the device using 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, `Controller` traits, or `dispatch` macros (enforced by `cargo pactum check`).

## 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>

---

## Installation & Getting Started

### For Humans (CLI)

Install `cargo-pactum` once (provides both `cargo pactum` and `pactum`):

```bash
cargo install cargo-pactum
```

Bootstrap a greenfield project or drop a contract crate into an existing Rust or polyglot repository:

```bash
# Greenfield or existing Python / Go / Node / .NET / React / mobile repo
cargo pactum init my-app --with-logic --targets wasm

# Add contract items without boilerplate
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 command SendPing --reply OkView
cargo pactum add logic validate_booking_draft

# Lint zero-IO boundaries & generate bindings (Python/Kotlin/Swift built-in, plus WASM2/Node/Go/C#)
cargo test --workspace
cargo pactum check
cargo pactum bindgen --lang python --out backend/generated
```

### For Coding Agents

Install the `pactum` Agent Skill (`.agents/skills/pactum/`) so Claude Code, Cursor, Codex, Antigravity, and Gemini CLI follow contract boundaries and polyglot workflows automatically:

```bash
npx skills add kevinrodriguez-io/pactum
```

*(Running `cargo pactum init` also installs `.agents/skills/pactum/` into your repository automatically, or run `cargo pactum skill [--global] [--claude]` offline.)*

---

## Quickstart (Manual Crate)

Add `pactum` and `serde` to your contract crate's `Cargo.toml` — `pactum` re-exports `Model`, `define_rule`, `pactum_rule`, `export`, `describe`, `contract`, `Error`, `Format`, and all validation/schema primitives under a single dependency:

```toml
[dependencies]
pactum = "0.1"
serde = { version = "1.0", features = ["derive"] }
```

Define reusable rules, annotated models, commands, and operations in `src/lib.rs`:

```rust
use serde::{Deserialize, Serialize};
use pactum::{contract, define_rule, export, Model};

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,
    },
}

contract! {
    name: "bookings",
    commands: [PeerCommand],
    operations: [
        create_booking(CreateBookingBody) -> BookingView @ POST "/api/bookings" = 201,
        health() -> OkView @ GET "/health" = 200,
    ],
    events: [BookingCreated],
    models: [CreateBookingBody, BookingView, OkView, PeerReply],
}
```

### Generated Surface

- **Per `#[export]` struct/enum:** `encode_<type>`, `decode_<type>`, `encode_<type>_with`, `decode_<type>_with` (plus `*_host` with UniFFI scaffolding and `*_napi` for Node.js). Command enums also generate `<cmd>_catalog()` / `<cmd>_catalog_host()` and an optional deduplicated `reply_enum`.
- **Per `#[export]` pure function (`pub fn`):** Keeps the idiomatic Rust function (`&str`, `&[T]`, `&T`, `Result<T, Error>`) untouched while exporting UniFFI/WASM2 bindings (`#[uniffi::export]`) and Node.js NAPI wrappers (`<fn>_napi`), including `Error` -> `PactumBindError` and `FieldIssue` -> `PactumIssue` mapping.
- **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()`, and `contract_agent_tools_json()` (plus `*_host` / `*_napi` wrappers).

---

## 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(...)]`.

### 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)` |
| **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`, `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 = "...")]` on structs, enums, or individual enum variants |

> **Pure, synchronous checks only:** Custom `with(...)` predicates, rules, and `#[export]` functions are pure CPU logic (e.g. Unicode character checks, checksums, workflow transitions, scoring, or structural syntax) that run identically across WASM, mobile, and server hosts. Async or stateful checks (database uniqueness, blocklists, permissions) belong in the host after decode.

---

## Shared Business Logic & Client/Server Form Validation

Contracts define what crosses the wire; **business logic outside `pactum::contract!`** lets clients and servers share deterministic domain behavior without duplicating rules in TypeScript, Swift, Kotlin, Python, Go, or C#:

- **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!`, state machines, pricing, WIP limits) 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};

/// Live in-memory form 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(),
    })
}

/// Custom domain error with field-level issue metadata.
#[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 form validation & UI state:** React WASM2, Swift, and Kotlin call `validateTodoDraft(...)`, `validateCardDraft(...)`, `wipRemaining(doingCount)`, `allowedNextColumns(...)`, `evaluateTodoUrgency(...)`, and `bookmarkDomain(...)` directly in the UI with zero HTTP round-trips.
- **Identical server enforcement:** ASP.NET Core (`KanbanContractMethods.ValidateCardMove`), Python FastAPI (`contract.validate_todo_draft`), and Node.js NAPI (`contract.validateDirectMessage`) call the exact same Rust functions so client hints and server rejections never drift.
- **`#[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` &amp; `MsgPack`) | Typed `Endpoint` Routes | `#[norm]` &amp; `#[constraint]` | `#[pactum::export] fn` *(Logic &amp; Form Validation — recommended)* | Direct `#[uniffi::export] fn` |
|---|---|---|---|---|---|
| **Rust** (`rlib`) | ✅ Both | ✅ `Endpoint` | ✅ Auto | ✅ Native | ✅ Native |
| **Browser / React (`WASM2`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **Swift (`iOS / macOS`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **Kotlin (`Android / JVM`)** | ✅ Both | ✅ `routeOf` / `formatPath` | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **Python** | ✅ Both | ✅ `route_of` | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **Go** | ✅ Both | ✅ `RouteOf` (`Pattern`) | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **C# (`.NET`)** | ✅ Both | ✅ `RouteOf` | ✅ Auto | ✅ Native (UniFFI) | ✅ Native (UniFFI) |
| **Node.js (`NAPI-RS`)** | ✅ Both | ✅ `routeOfNapi` | ✅ Auto | ✅ Native (`*_napi`) | ⚠️ Manual NAPI wrapper |
| **OpenAPI 3.1** *(outlier)* | ⚠️ JSON only | ✅ `paths` + `operationId` | ⚠️ Server-side (`422` + `x-pactum-*`) | ❌ Not executable | ❌ 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` custom business logic (such as live client-side form validation or workflow checks) 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`:** UTF-8 JSON (enabled by default via `pactum-core`'s `json` feature; `--no-default-features --features msgpack` builds without `serde_json`).
- **Pre-decode inspection:** `peek_string_field(bytes, format, "id")` extracts a top-level string field without validating the full payload.
- **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`.

---

## 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");
```

### Two Client Consumption Tracks

1. **Shared Rust Codec & Logic (UniFFI, WASM2, NAPI):** Swift, Kotlin, and browser WASM2 apps build native types, run live client-side form validation and shared `#[export] pub fn` business rules, 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 OpenAPI 3.1 Consumers (the static-spec outlier):** Frontends or services that do not embed Rust/WASM fetch `/openapi.json` (or run `cargo pactum openapi`), resolve routes by `operationId`, and rely on the server's Rust `decode_*` and business-logic pass for normalization, custom rules, and structured `422` `{ code, reason, issues }` error responses — without client-side form validation or custom logic execution (see [examples/contacts](examples/contacts)).

---

## CLI (`cargo-pactum`)

`cargo install cargo-pactum` provides `cargo pactum <cmd>` (and `pactum <cmd>`):

```bash
# Scaffold a contract workspace (or add to an existing Rust/polyglot repo) + agent skill
cargo pactum init [name] [--with-logic] [--targets wasm,node]

# 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

# Build & generate bindings (Python/Kotlin/Swift built-in; WASM2/Node/Go/C# drivers)
cargo pactum bindgen --lang <python|kotlin|swift|wasm|node|go|cs> [--out <dir>]

# Install the `.agents/skills/pactum/` skill offline
cargo pactum skill [--dir <path>] [--global] [--claude]

# Verify *-contract and *-logic crates pull zero banned IO/DB/runtime crates or handler tokens
cargo pactum check [-p <crate>]

# Detect breaking vs non-breaking contract changes between two IDL snapshots (exits 1 on breaking)
cargo pactum diff <old.idl.json> <new.idl.json>

# Render JSON Schema (Draft 2020-12) or function-schema JSON from an IDL snapshot
cargo pactum schema <idl.json> [--format json-schema|agent-tools]

# Render OpenAPI 3.1.0 from an IDL snapshot (with optional route overrides JSON)
cargo pactum openapi <idl.json> [--routes <routes.json>]
```

---

## 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]`, and `define_rule!` |
| `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`, `diff`, `schema`, `openapi`) |
| `uniffi-bindgen` | Workspace-pinned UniFFI (`=0.31.2`) CLI binaries (`uniffi-bindgen-go`, `uniffi-bindgen-cs`, etc.) |

### 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`) + SQLite | React (WASM2 + TS destructuring + live `validate_todo_draft` / `evaluate_todo_urgency`) |
| [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 (`zero-WASM` OpenAPI consumer — static schema outlier) |
| [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.
- **Publishing to crates.io:** See [PUBLISHING.md](PUBLISHING.md) and [scripts/publish.sh](scripts/publish.sh).

```bash
# Run workspace unit and doc tests
cargo test --workspace

# Check contract crate isolation
cargo run -p cargo-pactum -- check

# Regenerate UniFFI (Python, Go, C#, Swift, Kotlin), Node NAPI, and WASM2 React bindings
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