Examples
You'll leave with: how Nudo observes real call sites, how sidecar contracts gate obligations, and what still degrades to unknown.
Product path first. Observation is nudo check signatures (call sites are evidence). Contracts are *.nudo.js / @nudo:contract. @nudo:case is a debug witness only — optional, not the contract product.
Every output block below is excerpted from a real engine run of the code above it (nudo check / nudo test header lines and the assertions summary are elided where noted). The repo's CI-pinned suite lives in docs/examples/ (pnpm run verify:examples); this guide browses the same engine by theme.
The suite's topic directories at a glance (exit codes are the command matrix's pinned expectations — negative rows exit non-zero on purpose, the reported lines are the demo):
| Topic directory | What it demonstrates | Representative files | Expected exit |
|---|---|---|---|
constraints/ | @nudo:contract × Pred: scalars / shapes / return refinement; an if is not a refinement | set-delay.js · register.js · return-contract.js · similarity.js · levenshtein.js | 1 negatives · 0 register / test:cli / @nudo:assume / @nudo:invariant |
structure/ | Abs leq: assignment / argument structure (width subtyping) | assign.js · arg-structure.js | 1 (both rows) |
vs-ts/ | Same logic, side by side with TypeScript | constraints/nudo.js · constraints/tsc.ts · structure/nudo.js | nudo 1 · tsc 0 / 2 |
mini-repo/ | Multi-file integration (ESM + class + async) | user-service.js · store.js · validators.js | 1 user-service check (L2) · 0 rest |
algebra/ | Types as computation (spread / HOF / reduce / mixin) | 0-add-intensional.js · b-hof-map.js · c-reduce-sum.js | 0 |
contract-derivation/ | Contract tier derivation (handwritten root → generated rows) | lib.js · lib.nudo.js · add.js | 0 |
contract-draft/ | Code first: reviewable contract drafts from logic | greet.js · README.md | 0 (contract --draft) |
migrate/ | Retire the tsc boilerplate package (one-way before/after gate) | before/src/math.ts · after/src/math.js · before/package.json | 0 (status / strip / verify / retire) |
errors/ | Top-10 error faces (Nudo real output) | 01-constraint-gt.js · 04-entry-throws.js · 10-fix-path.js | 1 (all ten) |
retire-real/ | Real-package ms retire-tsc case (not a synthetic fixture) | before/src/age.ts · after/src/age.js | 0 |
retire-debug/ | Real-package debug retire-tsc case (visionmedia/debug) | before/src/logger.ts · after/src/logger.js | 0 |
Root-level l2-export-any.js pins L2 export-any gating outside any directory: check exits 1, --ignore-throws TypeError exits 0. One command verifies the whole matrix: pnpm run verify:examples.
Try any sample in the Playground.
Call sites and contracts (product path)
1. Call-site subtraction — Observation
Plain JS + call sites. No annotations. nudo check prints signatures; call sites supply evidence.
export function subtract(a, b) {
return a - b;
}
subtract(5, 3);
subtract(1, 10);
npx nudojs check subtract.js
nudo check subtract.js
OK
0 error · 0 warning · 0 info · 1 fn
signatures
subtract(a: any, b: any) => number
(no issues)
Unconstrained entry params display as any. With richer call evidence (or a sidecar), Abs keeps literals and algebra — run nudo check --abs or open the file in the IDE.
Optional debug case report (nudo test — not required for the gate):
=== subtract ===
call@L5 (5, 3) => 2
call@L6 (1, 10) => -9
2. Sidecar contract — Contracts obligation
// pricing.js
export function lineTotal(price, qty) {
return price * qty;
}
lineTotal(12, 3);
lineTotal(0, 2);
// pricing.nudo.js — contract (also plain JS)
import { number, fn } from "@nudojs/core";
export const lineTotal = fn(
{ price: number().gt(0), qty: number().ge(1) },
number().gt(0)
);
npx nudojs check pricing.js
nudo check pricing.js
FAILED
1 error · 0 warning · 0 info · 1 fn
signatures
lineTotal(price: number, qty: number) => number
issues
[ERROR L6 lineTotal] lineTotal[price]: argument ⊭ precondition (nudo:constraint-violated)
actual: 0 #exact
expected: price > 0
→ use a value satisfying price > 0, or relax the precondition on price
if guards are not refinements. Obligations come from the sidecar / @nudo:contract. See Contracts and nudo check.
3. Object shapes from call sites
function greet(user) {
return user.name + " is " + user.age;
}
greet({ name: "Alice", age: 30 });
=== greet ===
call@L4 ({ name: "Alice", age: 30 }) => "Alice is 30"
Concatenation keeps the literal result "Alice is 30" — not a flattened string. Parameter destructuring folds argument shapes the same way:
function addP({ x, y }) { return x + y; }
addP({ x: 1, y: 2 });
=== addP ===
call@L2 ({ x: 1, y: 2 }) => 3
Shape merge through spread:
function mixin(base, ext) {
return { ...base, ...ext };
}
mixin({ host: "localhost", port: 8080 }, { port: 3000, debug: true });
=== mixin ===
call@L9 ({ host: "localhost", port: 8080 }, { port: 3000, debug: true }) => { host: "localhost", port: 3000, debug: true }
Strings and templates
4. Template strings — beyond declared types
export function coupon(code) {
return `SAVE-${code.toUpperCase()}`;
}
coupon("vip");
=== coupon ===
call@L5 ("vip") => "SAVE-VIP"
TypeScript often widens this to string. Nudo observes the concrete template result at the call site. Compare the table in Why Nudo and the homepage “Beyond declared types” section.
5. Precise string methods
toUpperCase, toLowerCase, slice, .length, and split (literal receiver) produce exact results on the call-site path: "a,b,c".split(",") folds to ["a", "b", "c"]. See Language semantics for the full precise/degrade map.
Loops and ranges
6. Concrete-bound loops
function sumTo(n) {
let sum = 0;
for (let i = 0; i < n; i++) sum += i;
return sum;
}
sumTo(5);
=== sumTo ===
call@L6 (5) => 10
Loop sums stay literal when bounds are concrete — same Abs algebra powers nudo check.
7. Range narrowing
Path predicates narrow Abs inside branches (x > 5 → range preds on the term). Details: Control flow narrowing.
Unions and safe access
8. Discriminated by typeof
export function transform(x) {
if (typeof x === "string") return x.toUpperCase();
if (typeof x === "number") return x + 1;
return null;
}
transform("hi");
transform(41);
transform(null);
Each call site keeps its precise arm ("HI", 42, null). Symbolic unknown conditions currently join branches — see semantics.
9. Optional chaining
Known-shape receivers fold at any depth (a.b.c ?? 5 with { b: {} } → 5); on unconstrained (any) receivers the result stays any with throws TypeError (engine debt unknown does not apply — see Control flow narrowing).
Runtime environments and mocks
10. Web APIs via @nudo:env web
/// @nudo:env web
Built-in es / web / node env modules type common APIs; third-party @types fill in automatically at analysis time. See Dependency types. Env/harvest is not a substitute for mocks on native runtime callbacks — see Limits.
11. Mock external dependencies
// @nudo:mock fetch = (url) => ({ ok: true, json: () => ({ id: 1 }) })
Prefer the single-line arrow mock form. Full syntax: Mocking External Dependencies.
Debug witnesses (optional, not the product)
@nudo:case injects scenario inputs for nudo test / LSP case switching. It does not create CI obligations.
/**
* @nudo:case "double digits" (10)
*/
export function scale(x) {
return x + 1;
}
=== scale ===
debug "double digits" (10) => 11
Prefer concrete values or constraint builders (number(), lit(42)). Assertions (=> expected) only from declared cases affect nudo test exit code — synthetic call@ / entry@ never fail the run.
Where to go next
| Topic | Page |
|---|---|
| Contract draft / accept / emit | Contracts |
| CI gate + diagnostic codes | nudo check · Diagnostics |
What degrades to unknown | Language semantics |
| Abs algebra | Abs |
| Recipes (CI, monorepo, export) | Recipes |
| Directive | Role in this guide |
|---|---|
| Call sites | Observation evidence (primary) |
*.nudo.js / @nudo:contract | Contracts (primary) |
@nudo:env / @nudo:mock | Environment & boundaries |
@nudo:case | Optional debug witnesses only |