Skip to content

Projects and modules ​

A TypeRule project is a folder with a typerule.toml file. Every .tr file under it is a module, and modules see each other only through explicit imports. Two folders are special: tests/ and migrations/ hold scripts, which see the whole project without imports.

Layout ​

text
shop/
├── typerule.toml            marks the project root
├── core/
│   └── base.tr            module core.base
├── partners.tr            module partners
├── sales.tr               module sales
├── metrics.lock           written by `typerule certify`
├── customs.csv            data for a migration (`load from`)
├── migrations/
│   └── 2026-12-01_customs.tr   script: migrations.2026-12-01_customs
├── tests/
│   ├── fixtures.tr        script: tests.fixtures
│   └── sales.test.tr      script: tests.sales.test
└── .typerule/
    └── data.db            default SQLite database (created by `typerule db init`)
RuleDetail
Project rootThe nearest folder, from the given path upwards, that contains a typerule.toml file. Every command accepts a path inside the project.
Source filesEvery *.tr file below the root, at any depth.
Skipped foldersFolders whose name starts with ., target, node_modules, and any sub-folder that has its own typerule.toml (a nested project).
EncodingUTF-8. See Syntax.

typerule.toml ​

toml
[project]
name = "shop"
edition = "2026"

[database]
url = "sqlite:data/shop.db"
KeyUsed for
[project] nameThe name of the project. The tools do not read it yet: the file's presence is what marks the root.
[project] editionThe edition of the language the project is written in. Today there is one, 2026, also the default when the key is missing. An edition this version of TypeRule does not know stops every command with an error, rather than reading the code differently.
[database] urlThe database of the typerule db, typerule change, typerule token and typerule serve commands, when --url is not given. A relative sqlite: path is resolved from the project root.
[vars]The variables whose values depend on where the app runs, some of them secret: Variables and connections.
[connections.<name>]The systems the app sends to (HTTP, SMTP): Variables and connections.
[files]Where the files of File fields are kept: Files.
[data]How much the project keeps: history (the default of its entities: full, none, "last 10", "1 year"), inbox and outbox (how long the messages received and the events sent are kept once closed: "90 days", "forever", "30 days, then archive"), archive_after (the history older than that moved to archives by the sweep, "2 years"): Retention and erasure.

When neither --url nor [database] url is given, the database is sqlite:<root>/.typerule/data.db. Database URLs are described in Storage.

Files ​

The bytes of the files of File fields (Types) are kept outside the database. Without a [files] section they are in the folder .typerule/files of the project, and the server itself answers their signed URLs. In production they go to an S3 compatible bucket (AWS, Hetzner, Cloudflare R2, MinIO):

toml
[vars]
FILES_KEY = { secret = true }
FILES_SECRET = { secret = true }
CDN_TOKEN_KEY = { secret = true }

[files]
url = "s3://acme-files/prod"
endpoint = "https://fsn1.your-objectstorage.com"
region = "eu-central"
key = { var = "FILES_KEY" }
secret = { var = "FILES_SECRET" }
cdn = "https://files.acme.example.com"
cdn_secret = { var = "CDN_TOKEN_KEY" }
KeyMeaning
urls3://bucket/prefix: the bucket, and the prefix every key goes under. Or a folder of the machine: file:/srv/acme/files, or relative to the project (file:data/files).
endpointThe address of an S3 compatible service other than AWS (reached with paths, https://endpoint/bucket/…). Without it, AWS.
regionThe bucket's region (us-east-1 when not said).
key, secretThe access key and its secret: always secret variables ({ var = "NAME" }), never written in the file. Needed for a bucket.
cdnOptional: downloads go through this CDN, whose origin is the bucket.
cdn_secretWith cdn: the secret variable its download tokens are signed with.

url, endpoint, region and cdn may also be variables ({ var = "FILES_URL" }).

In the store, a file is at files/<sha256> (under the prefix) and never changes, so a cache may keep it for ever; an upload waits at uploads/<id> until the server checks it. The browser puts and gets the bytes itself, with URLs the server signs: they never pass through the server. For a bucket, allow the web client's origin in the bucket's CORS rules (PUT and GET).

With a CDN, a download is https://files.acme.example.com/<prefix>/files/<sha256>?expires=<unix time>&token=<hex>, where token is the HMAC-SHA256, with the value of cdn_secret, of the path and the expiry written one after the other (/prod/files/ab12…1767225600). The CDN checks the token at its edge (as Bunny's and CloudFront's signed URLs do) and fetches the object from the bucket. A download forced with ?download goes to the bucket, so that it gets the disposition asked for.

Modules ​

Each file is one module. Its name is its path relative to the root, without the extension, with / replaced by .:

FileModule
sales.trsales
core/base.trcore.base
tests/sales.test.trtests.sales.test

A module contains top-level declarations: entity, record, trait, extend, enum, ledger, fn, const, event, seed, reactions (on …, before …), role, deny / allow rules, view, report, metric, control, migration, change, fixture and test. Each is described in its own page.

Two declarations with the same name in one module are an error:

text
error: `Customer` is already declared at sales.tr:3

Imports ​

typerule
from core.base import Address, Document
from partners import Partner, PaymentTerm

from <module> import <name>, … makes declarations of another module visible by their name. There is no import module form and no renaming; every name is imported explicitly.

SituationMessage
A name used without importing itunknown type `Customer`: it is declared in `sales`, add `from sales import Customer`
The module does not existunknown module `sale`
The name is not in that module`Nope` is not declared in module `sales`
A module imports itselfa module cannot import itself
Two imports of the same namewarning: `Partner` is imported more than once
Cycles between modulesimport cycle: billing → sales → billing (use `extend` in the higher module instead)

Imports may not form cycles. Organize modules in layers (for example core → partners → products → sales → invoicing). When a lower module's entity needs a field that refers to a higher one, add it from the higher module with extend:

typerule
# invoicing.tr: sales.tr cannot import Invoice, so invoicing adds the link itself
from sales import SalesOrder, SalesLine

extend SalesOrder:
    live invoices          # keeps following new invoices after the order is frozen
    invoices = lines.flat_map(l => l.invoice_lines).map(i => i.invoice).distinct()

The standard library ​

Three modules are built into the compiler and are visible in every file without an import. Their names are reserved: declaring an entity, enum or function with one of them is an error (`Company` is declared in the standard library (`std.org`): use `extend Company:`); use extend to add to their entities.

ModuleDeclares
std.moneyenum Rounding: HalfEven, HalfUp, Up, Down · entity Currency (code, name, symbol, decimals default 2, rounding default HalfEven: how .round() rounds its amounts, active) · entity ExchangeRate (base, quote, date, rate) · fn exchange_rate(src: Currency, dst: Currency, on: Date) -> Decimal · seeds for EUR, USD, GBP, CHF, JPY (0 decimals) and CNY
std.uomentity UomCategory (name, uoms, reference) · entity Uom (code, name, category, factor, precision default 0.001) · seeds for pcs, kg, g, t, l, ml, m, cm, h, min
std.orgentity Company (name, currency) · entity User (login, name, roles) · entity Sequence (company, code, pattern default "{code}/{year}/{n:05}", gapless) · builtin fn next_number(company: Company, code: Code, on: Date = today()) -> Code

next_number gives the next number of a sequence, per company, code and year, filling the pattern's {code}, {year} and {n} (with an optional f-string format: {n:05}). Every sequence is gapless: the number is taken inside the transaction and kept only if it commits, so a transaction that fails or is refused leaves no gap, and two transactions that take a number of the same sequence at the same time are serialized (the later one is refused as a conflict and retried). gapless: true states the requirement for the readers of the model (invoices must have no gaps); gapless: false does not make the engine skip numbers.

Projects add fields to these entities with extend, for example extend Company: vat_number: VatNumber unique.

Currency and unit codes are names in every expression: EUR is the Currency record with code EUR, kg is the Uom with code kg. The type checker learns which codes exist, and which units belong to the same category, from the seed blocks (see Types). To add a unit or a currency, add a seed:

typerule
seed:
    let packs = UomCategory(name="Packs")
    Uom(code="box", name="Box", category=packs, factor=1, precision=1)
    Currency(code="SEK", name="Swedish krona", symbol="kr")

Money, Price, Qty, Exact, convert(), allocate() and the other built-in functions are part of the language itself, not of the standard library; see Types and Expressions.

Scripts: tests/ and migrations/ ​

A .tr file inside a top-level tests/ or migrations/ folder is a script. Scripts differ from modules in two ways:

ModulesScripts
Sees declarations of other modulesonly what it importsevery declaration of every module, without imports
Can be imported by modulesyesno: `tests.fixtures` is a script (tests, migrations): modules cannot import from it
Can import from other scripts—yes (from tests.fixtures import italy)

Scripts usually contain test, fixture, migration, change and temporary entity declarations, but these can be written in any file: a small project can keep its tests next to its entities. A file directly in the root named tests.tr is an ordinary module.

typerule
# tests/order_to_cash.test.tr
from tests.fixtures import italy

test "an order is invoiced":
    use italy
    let so = SalesOrder(customer=rossi, lines=[SalesLine(product=widget, qty=3 pcs)])
    expect so.total == 36.60 EUR

Here SalesOrder and SalesLine need no import (scripts see all modules), but the fixture italy, declared in another script, does.

Naming ​

The compiler does not enforce a naming style, but it relies on one convention:

KindStyleExamples
Entities, records, traits, enums, ledgers, roles, eventsPascalCaseSalesOrder, Stock, SendEmail
Enum variants and flow statesPascalCaseDraft, Confirmed, OneProduct
Fields, formulas, actions, functions, metrics, fixturessnake_casecredit_limit, create_invoice, italy
Unit and currency codesas seededEUR, pcs, kg

In a match pattern, a name that starts with an upper-case letter is a variant (or an entity type); a lower-case name binds the value. Name your variants with a capital letter.

Most keywords are contextual, so ordinary words remain available as field names (key, parent, by, check…). The reserved words are listed in Syntax.

TypeRule: the books balance.