Brands and refinements on schemas
A brand makes a schema nominal: a NoteId and an OrgId are both strings, but neither is assignable to the other. A where clause refines a schema with a range, a regular expression or a predicate, checked whenever a value is decoded or made. Use them where you would write Schema.brand and Schema.check. VIP-77 defines the forms.
export schema NoteId = brand string
export schema OrgId = brand string
export schema Port = int where 1..65535
export schema Ratio = number where 0..<1
export schema Email = brand string where /^[^@\s]+@[^@\s]+$/
export schema Slug = string where /^[a-z0-9-]+$/ && (s) => s.length <= 32
export schema Member {
readonly id: brand string
readonly age: int where 0..150
readonly bio?: string where (s) => s.length <= 280
}
export effect function decodePort(input: unknown) {
return try Schema.decodeUnknownEffect(Port)(input)
}
// Run in an effect function:
// try Console.log(try decodePort(8080))
// try Console.log(try (decodePort(70000) catch () => "rejected"))
// try Console.log(Email.make("ada@example.com"))8080
rejected
ada@example.comEach declaration lowers to an Effect Schema constant and its type: Port is Schema.Int.pipe(Schema.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))). The refinements run before the brand, so a branded value always satisfies them.
The clauses
| Clause | Means |
|---|---|
brand string | A string with the schema's own brand, named after the schema |
brand "app/NoteId" string | The same, with the brand name written out |
where 1..65535 | A number from 1 to 65535, both included |
where 0..<1 | A number from 0, included, to 1, excluded |
where /re/ | A string the regular expression matches |
where (s) => s.length <= 32 | A value the predicate accepts |
where a && b | Every joined constraint |
brand and where also apply to a field of a schema declaration, as in Member above. Outside a schema they are ordinary identifiers, so const where = 42 still works.
Making and decoding values
Decode untrusted input with Schema.decodeUnknownEffect(Port)(input): it fails with a SchemaError that your Effect's type records. Port.make(443) builds a value directly. When its argument is a literal, the compiler checks the constraints at compile time, so Port.make(0) is an error. With a value known only at run time, .make can throw, so in effect code decode it instead.
Rules
| Mistake | Code |
|---|---|
A literal passed to .make(…) that violates a range or a regular expression | EK7704 |
A where predicate that uses try, await or throw; a refinement is pure | EK7705 |
| A value of one brand where another brand, or the plain base type, is expected | TS2322 |
// expect-error: EK7704
export schema Percent = int where 0..100
export const tooMuch = Percent.make(101)