Packages
Build Elixir structs with validation, sanitization, nested sub-structs, conditional fields, pattern-keyed maps, and an Ash extension. Built on Spark.
Current section
Files
Jump to
Current section
Files
usage-rules/dsl.md
# GuardedStruct DSL — `field`, `sub_field`, `conditional_field`, `virtual_field`, `dynamic_field`
Every entity lives inside one `guardedstruct do … end` block.
## `field name, type, opts`
```elixir
field :email, :string,
enforce: true,
default: nil,
derives: "sanitize(trim, downcase) validate(string, not_empty, email_r)",
validator: {MyApp.Checks, :no_disposable_email},
auto: {Ecto.UUID, :generate},
from: "headers::auth_user_id",
on: "profile::owner_id",
hint: "primary-email"
```
| Option | Type | Purpose |
|---|---|---|
| `name` (positional) | atom | Field name. |
| `type` (positional) | quoted type | E.g. `:string`, `String.t()`, `:integer`. |
| `enforce` | boolean | Add to `@enforce_keys`. Missing input → `:required_fields` error. |
| `default` | quoted | Default if input omits the key. |
| `derives` | string | Op-string (see `guarded_struct:derive`). |
| `derive` | string | Legacy singular alias for `derives`. Honored for 0.0.x compat; prefer `derives`. |
| `validator` | `{Mod, :fn}` | Per-field validator MFA, called as `Mod.fn(name, value)`. |
| `auto` | `{Mod, :fn}` or `{Mod, :fn, arg}` | Auto-fill the field. |
| `from` | string | Copy the value of another path into the field when that path has one. |
| `on` | string | The field is only allowed when another path is present. |
| `domain` | string | Cross-field constraint expression. |
| `struct` | atom | Build value via `Mod.builder/1` (external GuardedStruct). |
| `structs` | atom or boolean | List-of items via `Mod.builder/1`, or `true` for list-of-self. |
| `hint` | string | Label propagated into the field's error maps. |
| `priority` | boolean | Meaningful on a `conditional_field` only: when no child matches, keep just the first child's error. Ignored on the other entities. |
| `doc` | string or `false` | What the field holds (Markdown): its row text in the field table of the `t()` docs. `false` leaves the field out of the table. On `field`, `virtual_field`, `dynamic_field`, `conditional_field`; on `sub_field` it is also the module's `@moduledoc` (below). |
## `sub_field name, type, opts do … end`
Defines a nested submodule (e.g. `MyApp.User.Profile`) generated at compile time.
Same options as `field` plus:
* `error: true` — generates a per-level `Error` exception.
* `authorized_fields: true` — reject keys not declared in this sub_field.
* `main_validator: {Mod, :fn}` — runs after every nested field validates, with the
sub_field's own attrs. A `main_validator/1` of the parent module does not run
for a sub_field.
* `doc: "..."` — the `@moduledoc` of the generated submodule, so `Code.fetch_docs/1`
and ExDoc show it. `doc: false` hides the submodule (`@moduledoc false`); with no
`doc:` it has no `@moduledoc`. Works on a list `sub_field` and on a
`conditional_field`'s `sub_field` (its numbered module, e.g. `Plan1`).
Rules: `doc:` only sets the generated module's doc, never the parent's
`@moduledoc`, which stays exactly as written: your `@moduledoc` wins. There is no
`guardedstruct`-level doc option. Giving both `doc:` and the `doc "..."` setter in
the block fails with `Spark.Error.DslError` (multiple values for `:doc`). The
generated module name belongs to the sub_field: a module of your own with the same
name next to a `sub_field` **with** a `do` block (nested in the parent, or one
already compiled) fails to compile, and one defined later is reported by a
verifier.
### A `sub_field` without a `do` block uses your own module
`sub_field :address, struct()` (or `sub_field :items, list(struct()), structs: true`)
with no `do` block generates nothing: it uses your module of the generated name
(`MyApp.Order.Address`) as it is, like `field :address, struct(), struct:
MyApp.Order.Address` (`structs:` in list mode). Your module's `@moduledoc` and
`@typedoc` stay, and the parent's `t()` links to it. Rules:
* The module must exist and have `builder/1` (any `use GuardedStruct` module);
otherwise it fails to compile with `Spark.Error.DslError` ("define … or give the
sub_field a do block"). The compiler waits for a module in another file
(`Code.ensure_compiled/1`), so the parent depends on it at compile time. A module
nested in the parent or one earlier in the same file works too; one *later* in the
same file is not compiled yet.
* `authorized_fields:`, `main_validator:` and `error:` shape a generated module, so
they fail to compile here: set them in your module's `guardedstruct`.
* `doc:` is only the row text in the parent's table.
Children: nested `field`, `sub_field`, `conditional_field`.
## `conditional_field name, type, opts do … end`
Pick one child based on the input value. Children share the parent's `name`.
Each child is tried in order; the first whose `validator:` returns `{:ok, ...}`
wins. Put `priority: true` on the `conditional_field` itself to report only the
first child's error when none match.
* `structs: true` on the conditional — iterate a list, apply children
per element.
* Aggregated error shape (on no match):
```elixir
%{field: name, action: :conditionals, errors: [child_attempt_errors...]}
```
Each inner `errors` entry follows the canonical error shape.
## `virtual_field name, type, opts`
Same surface as `field`, but the value is **dropped** from the final struct.
Useful for `password_confirmation`-style inputs consumed by `main_validator`
but not persisted. Schema accepts `name`, `type`, `enforce`, `default`,
`derives` (+ legacy `derive`), `validator`, `auto`, `from`, `on`, `domain`,
`hint`. Does **not** accept `struct`, `structs`, or `priority`.
## `dynamic_field name, opts`
Free-form map slot. The inner map is **identity-preserved** — keys are *not*
atomized at any depth, wherever the `dynamic_field` is declared (top level,
`sub_field` of any depth, a `struct:` module, a `conditional_field`'s
`sub_field`). Used for attacker-controlled metadata where atom-table growth
would be a DoS risk. Schema accepts the same options as `virtual_field`
(no `struct` / `structs` / `priority`).
Defaults baked into the entity schema:
* `type` → `map()`
* `default` → `%{}`
* `derives` → `"validate(map)"`
The entity also auto-sets `__dynamic__: true` (internal flag — drives the
`:dynamic_field` kind in `__fields__/0` and tells `Parser.convert_to_atom_map`
to leave inner values untouched).
## `@derives "..."` / `@derive_rules "..."` decorators
Module attributes consumed by the **next** entity declaration. One-shot — the
attribute is cleared after the consuming entity, like `@doc`. Useful for
keeping fields short:
```elixir
@derives "sanitize(trim, downcase) validate(string, not_empty, email_r)"
field :email, :string, enforce: true
@derives "sanitize(trim) validate(string, max_len=24)"
field :nickname, :string
```
Available on `field`, `sub_field`, `conditional_field`, `virtual_field`,
`dynamic_field`.
## Section options — `guardedstruct opts do … end`
```elixir
guardedstruct enforce: true, authorized_fields: true, json: true do
...
end
```
| Option | Default | Purpose |
|---|---|---|
| `enforce` | `false` | Cascade `enforce: true` to every child without a default. |
| `opaque` | `false` | Generate `@opaque t()` instead of `@type t()`. |
| `module` | nil | Emit the struct into a sub-module name. |
| `error` | `false` | Generate a `Module.Error` exception. |
| `authorized_fields` | `false` | Reject unknown top-level keys with `:authorized_fields` error. |
| `main_validator` | nil | `{Mod, :fn}` runs after per-field validators. Wins over a `main_validator/1` defined in the module. |
| `validate_derive` | nil | Module (or list) whose `validate/3` serves the ops the built-ins and derive extensions don't know. Tried before the `:validate_derive` application config, which still serves what they leave unhandled. |
| `sanitize_derive` | nil | Module (or list) whose `sanitize/2` serves unknown sanitize ops. Same precedence as `validate_derive`. |
| `json` | `false` | Auto-derive `Jason.Encoder` (or built-in `JSON.Encoder` ≥ 1.18). |
| `auto_wire` | `false` | Ash-only: inject `GuardedStruct.AshResource.Change` automatically. |
## Pattern-keyed maps
A `field` whose `name:` is a regex makes the module a *pattern map* — its
`builder/1` returns a plain map keyed by matching string keys, no defstruct.
Use for shard tables, dynamic configuration.
## What gets generated
Every guarded module gains at compile time:
* `defstruct`, `@enforce_keys`, `@type t()` / `@opaque t()` (see "Types and docs"),
* `keys/0,1`, `enforce_keys/0,1`, `example/0`,
* `__information__/0`, `__fields__/0`, `__field_meta__/1`,
* `__guarded_information__/0`, `__guarded_fields__/0`, `__guarded_field_meta__/1`
(Ash-compatible aliases),
* `builder/1,2`,
* compile-time flags: `__guarded_has_validator__/0`,
`__guarded_has_main_validator__/0`, `__guarded_error_module__/0`,
`__guarded_derive_extensions_opt__/0`,
* sub_field submodules with the same surface.
## Types and docs of `t()`
The type of each field in `t()` is precise, so ExDoc links each nested type to its page:
| Field | Type in `t()` |
|---|---|
| `field :a, struct(), struct: Mod` | `Mod.t()` |
| `field :a, list(struct()), structs: Mod` | `[Mod.t()]` |
| `sub_field :a, struct() do … end` | `Parent.A.t()` (`[Parent.A.t()]` with `structs: true`) |
| `conditional_field :a, any() do … end` | union of its branches (`String.t() \| Parent.A1.t()`); `[union]` with `structs: true` |
Only a loose declared type is replaced: `struct()`, `map()`, `any()`, `term()`,
`list()`, a list of those, or a union of them. Any other type you write is kept as
written (`field :a, Mod.t(), struct: Mod`). A `sub_field` with `doc: false` keeps its
declared type, as its module has no page. A field that is not enforced adds `| nil`.
A pattern-keyed module has `@type t() :: %{optional(String.t()) => value types}` unless
it defines its own `t`.
`t()` gets a generated `@typedoc`: a Markdown table of every field — name, type
(linked when the field builds a struct), required (`enforce`), default, derives and
`validator:`, and the field's `doc:`. Virtual fields are in a second table. Generated
`sub_field` modules get the same. Rules:
* Your own `@typedoc` written above `guardedstruct do` wins; your `@moduledoc` is
never changed.
* A `doc: false` module has no page.
* ExDoc warns about a link to a module hidden with `@moduledoc false`. A `struct:`
module that is hidden makes that warning in `t()`: document the module, or list it
in ExDoc's `skip_undefined_reference_warnings_on`.
* Typespec change for upgrades: a field that said `struct()` now says `Mod.t()`, so
Dialyzer checks more. The `struct:` module must define `t()` (every GuardedStruct
module does); for a hand-written module without one, write the field's type yourself.