
# HSL Script Reference

Scripts let a tenant automate what a form, a condition or an automation
cannot express: look up records, decide, write, notify, start an automation.
They are written in **HSL level 2** — the statements around the conditions
you already know from filters and validations (HSL level 1).

This page is the reference for the language. How to manage scripts in the
product (Settings → Rules and evaluation → Scripts) is described in the
product help.

> Every example on this page is compiled against a test model by the build
> (`ScriptReferenceExamplesTest`). An example that stops compiling breaks the
> build, so what you read here is what the compiler accepts.

The test model used by the examples has three object types:

| Type | Fields |
|---|---|
| `workOrder` | `name` (text), `priority` (number), `requiredSkill` (text), `dueAt` (date and time), `startsOn` (date), `category` (picklist), `requester` (user), `number` (auto number), `building` (reference → `building`), `suggestedAssignee` (reference → `person`), `contacts` (multi-reference → `person`), `trades` (multi-picklist), `tags` (multi-text), `watchers` (multi-user), `opensAt` (time), `takes` (duration), `closedAt` (date and time), `urgent` (yes/no), `wasteCode` (catalogue) |
| `person` | `name` (text), `skills` (text), `openWorkOrders` (number), `building` (reference → `building`) |
| `building` | `name` (text), `city` (text) |

## 1. A first script

On the event “work order created”: suggest the technician in the same
building with the fewest open work orders, or start an escalation.

```hsl
// context: event
// Suggest the technician with the fewest open work orders in the building
let candidates = query person
    where building == $record.building and skills.contains($record.requiredSkill)
    order by openWorkOrders asc
    limit 5

if candidates.isEmpty() {
    workflow.start("escalate-unassigned", record)
    return
}

record.suggestedAssignee = candidates.first()
```

A check before saving:

```hsl
// context: check
if record.priority > 5 {
    fail("Priority may be at most 5.")
}
```

## 2. Where a script runs

**A script does not name its trigger.** Whether it runs when a record is
created, every Monday at six or before a record is saved is part of the
script's settings, not of its text. The text is the body only.

| Context | What the body has | What it may do |
|---|---|---|
| Check before saving | `record` (the new state), `before` when changing | read (`query`), `fail` — no writing, nothing outside |
| On event (created, changed, state changed) | `record`, `before` on `changed` | read, write, library |
| Step of an automation | `record` | read, write, library |
| On schedule | `rows` — one page of matching records | read, write, library |
| Mapping in an import | `input` — one row of the file | `return { … }`, `fail` — no reading, no writing, nothing outside |

What a context does not allow is an error **when the script is saved**, not
when it runs:

```hsl
// context: check
// expect: script.notInContext
record.priority = 1
```

A scheduled script receives one page of at most 500 records in `rows` and
runs once per page. The platform pages, not the script:

```hsl
// context: schedule
for row in rows {
    if row.dueAt < now() {
        row.priority = 5
    }
}
```

### Mapping in an import

A mapping is attached to one level of a saved import plan (“Import data”) and
runs once for every row of the file. It turns the row into fields when a
column assignment is not enough: a value from two columns, a code the file
spells differently, a row that should be rejected.

- **`input` is the row.** Each column is reached by a name derived from its
  heading: trimmed, lower case, `ä` `ö` `ü` `ß` spelled out as `ae` `oe` `ue`
  `ss`, accents removed, anything other than letters and digits becomes one
  `_`, a leading digit gets a `c`, a keyword gets a trailing `_`. `Raum-Nr.`
  becomes `raum_nr`, `Fläche m²` becomes `flaeche_m2`, `2. Name` becomes
  `c2_name`. Two headings that give the same name are rejected.
- **Every value in `input` is text**, exactly as it stands in the file.
- **`return { field: value }` names fields of the level's type.** What comes
  back is treated like a cell and converted the same way (numbers and dates
  as written in the file, picklist labels or codes). A mapping cannot write
  anything a file could not have contained, and only fields the person
  importing may write.
- A field the mapping returns **wins** over the column assigned to it. The
  key rule of the level always stays with the columns.
- **`fail("…")` rejects this row** with the message; the other rows go on.
  Reaching a limit does the same.
- Saving the plan checks the mapping: it exists, it is a mapping, every
  `input.name` is a column of the file, every returned field may be written.
  It must be **switched on** before the plan runs. Each import with a
  mapping is one line in the script's run log. It does **not** count
  towards the monthly script runs and runs even when they are used up,
  like a check before saving.

```hsl
// context: mapping
// The file has the columns “Raum-Nr.”, “Bezeichnung” and “Prio”
if input.raum_nr == "" {
    fail("Row without a room number")
}
if input.prio == "hoch" {
    return { name: input.bezeichnung, priority: 5 }
}
return { name: input.bezeichnung }
```

A mapping does not read other records:

```hsl
// context: mapping
// expect: script.notInContext
let rooms = query building where name == $input.bezeichnung limit 1
return { name: input.bezeichnung }
```

## 3. Names

| Written as | Means | Example |
|---|---|---|
| `record`, `before`, `rows` | given by the context | `record.priority` |
| a name bound with `let` or `for` | a variable | `deadline`, `job.name` |
| `$name` — **only inside `where`** | a value from outside the query | `dueAt < $deadline` |

Outside a query there is no row a bare field name could refer to, so a bare
name is always a variable:

```hsl
// context: event
// expect: script.unknownName
if priority > 3 {
    log(1)
}
```

Inside `where`, bare names are fields of the queried type, and values from
outside carry `$`:

```hsl
// context: event
let deadline = record.dueAt
let late = query workOrder where dueAt < $deadline and priority > 2 limit 20
log(late.count())
```

`record.field` inside `where` is refused rather than read as a field of the
queried type — `dueAt < record.dueAt` would compare each row with itself.
Write `$record.dueAt` for the triggering record:

```hsl
// context: event
// expect: script.recordInQuery
let late = query workOrder where dueAt < record.dueAt limit 20
log(late.count())
```

**Variables are bound once.** `let x = …` cannot be assigned again; take a
new name. A variable lives until the end of its block and may not hide an
outer one. Reserved are the keywords below and `record`, `before`, `rows`,
`input`, `user`.

## 4. Statements

```
script      := statement*

statement   := "let" name "=" expression
             | "if" condition block ( "else" "if" condition block )* ( "else" block )?
             | "for" name "in" expression block
             | target "=" value
             | call
             | "return" value?
             | "fail" "(" value ")"
block       := "{" statement* "}"

expression  := value | query | call | object | list
query       := "query" type ( "where" condition )?
               ( "order" "by" field ( "asc" | "desc" )? ( "," field ( "asc" | "desc" )? )* )?
               "limit" number
target      := ( "record" | name ) "." field
comment     := "//" to the end of the line
```

`condition` and `value` are HSL level 1 and mean exactly what they mean in a
filter. One statement per line, no semicolons; a query may span lines and
ends with `limit`.

### Decisions you may not expect

1. **`limit` is required.** A query without a limit is rejected when saving,
   not silently capped. The number may not exceed the limit of the context
   (section 7).
2. **No loop without a list.** There is `for … in`, but no `while`, no
   recursion and no functions of your own. A list comes from a query, a
   literal or a multi-value field, so every script ends by construction.
3. **Unknown takes the `else` branch.** If a condition is unknown because a
   field is empty, `if` goes to `else` (or past it). `fail` inside an `if`
   therefore only refuses what is *provably* wrong. To refuse an empty field,
   write `record.x == null`.
4. **Numbers are decimals**, not floating point: `0.1 + 0.2 == 0.3` is true.

```hsl
// context: check
if record.requiredSkill == null {
    fail("Please name the required skill.")
}
```

## 5. Writing

`record.field = value` and `variable.field = value` change a record that
came from `record`, a query or `create`. `create(type, { field: value })`
creates one and returns it; `deactivate(x)` deactivates one. **There is no
delete.**

```hsl
// context: event
let hall = create("building", { name: "Hall 3", city: record.name })
record.building = hall
```

**Everything is written at the end of the run, in one transaction**, through
the same path as the form: all permission layers, required fields,
validations and events. If one record fails, the run fails and nothing is
written. Until then a script reads its own changes to those records, but a
query does **not** see them — it reads the database.

The platform's own fields (number, identifier, timestamps) are never written
by a script:

```hsl
// context: event
// expect: script.fieldNotWritable
record.number = 5
```

## 6. Library

| Call | Where | What |
|---|---|---|
| `create(type, { … })`, `deactivate(x)` | step, event, schedule | see section 5 |
| `notify(x.field, text)` | step, event, schedule | notifies the people in a user, multi-user or reference field of `x`; each recipient must be allowed to read the record |
| `workflow.start("name", x)` | step, event, schedule | starts the automation `name` (trigger “started”) on the record `x` — from `record`, a query, a loop or `create` |
| `ai.classify(target, field, …)` | step, event, schedule | proposes a value for a picklist or reference field from up to 20 fields of the same record; returns no value unless the model is certain |
| `log(value)` | everywhere | writes a line to the run's log |
| `now()`, `today()` | everywhere | the start of the run |
| `x.first()`, `x.count()`, `x.isEmpty()` | everywhere | on a list or a multi-value field |
| `x.contains(v)`, `x.startsWith(v)` | everywhere | on text; `contains` also on multi-value fields |
| `lower`, `upper`, `trim`, `length`, `abs`, `round` | everywhere | the level 1 functions |

```hsl
// context: event
notify(record.watchers, "Work order changed")
let choice = ai.classify(record.category, record.name, record.requiredSkill)
if choice != null {
    record.category = choice
}
```

A function that is not listed is rejected with “not yet available in
scripts” rather than computed differently from a filter.

### Multi-value fields

A multi-picklist, a multi-text, a multi-user and a multi-reference field is a
list: `count()`, `first()`, `isEmpty()` and `for … in` work on it, and
`contains(v)` compares one element exactly. Looping over a multi-reference
reads the targets like a query, with the same limits.

```hsl
// context: event
if record.trades.contains("electrical") and record.tags.count() > 0 {
    log(record.tags.first())
}
for person in record.contacts {
    log(person.name)
}
```

A multi-value field takes another field of the same kind, one field deep, as
it is: same order, nothing split or joined. A choice must know every value of
the source, a reference must point to the same type.

```hsl
// context: event
for job in query workOrder where building == $record.building limit 20 {
    job.contacts = record.contacts
}
```

A variable can hold a multi-value field. It is read once, where `let` stands,
and works wherever the field itself would: in `for`, with `count()`,
`first()`, `isEmpty()` and `contains(v)`, and as the source of a copy.
`log` writes a multi-picklist and tags as their elements, separated by a
comma; an empty field logs `null`. A multi-reference and a multi-user field
cannot be logged — their elements are ids, which a script never shows.

```hsl
// context: event
let earlier = record.tags
record.tags.add("checked")
log(earlier)
let trades = record.trades
if trades.contains("electrical") {
    record.zones = trades
}
```

```hsl
// context: event
// expect: script.notYetInScripts
log(record.contacts)
```

`x.field.add(value)` and `x.field.remove(value)` change one element. They work
on a **multi-picklist**, with one of its codes written as a fixed text, on
**tags**, with a text that has no comma, and on a **multi-reference**, with a
record of its target type — a variable or a single reference one field deep.
On a **multi-user** field they take a person who is already in a **user
field**, one field deep (`record.watchers.add(record.requester)`); never an
identifier written by hand. Whether that person still has access is checked
when the record is written, as in the form.
Adding an element that is already there changes nothing; removing the last
one leaves the field empty. A value that is unknown changes nothing either.

```hsl
// context: event
if record.priority == 1 {
    record.tags.add("urgent")
    record.tags.remove(record.name)
}
for person in query person where building == $record.building limit 3 {
    record.contacts.add(person)
}
record.contacts.remove(record.suggestedAssignee)
record.watchers.add(record.requester)
```

```hsl
// context: event
// expect: script.multiChangeValue
record.watchers.add("u-7")
```

```hsl
// context: event
// expect: script.multiChangeValue
record.tags.add("roof, facade")
```

### Time and durations

Time-of-day and duration fields are read, written and compared like numbers.
A point in time minus a point in time is a duration, cut to whole seconds
towards zero.

```hsl
// context: event
if record.closedAt != null and record.dueAt != null {
    let late = record.closedAt - record.dueAt
    if late > record.takes {
        log("closed later than planned")
    }
}
```

### Yes and no

A yes/no field is compared with `true` or `false`, without quotes — also
inside `where`:

```hsl
// context: schedule
for job in query workOrder where urgent == true and closedAt == null limit 100 {
    job.priority = 1
}
```

`isEmpty()`, `contains(…)` and `startsWith(…)` may be compared with `true`
or `false`. A comparison on the right of `=` writes yes or no — and **no**
when a value is unknown, as an `if` takes its `else` branch.

```hsl
// context: event
let open = query workOrder where closedAt == null limit 10
if open.isEmpty() == false {
    record.urgent = open.count() > 5
}
```

`contains` and `startsWith` cannot be negated; write the condition the other
way round and use `else`:

```hsl
// context: event
// expect: condition.methodNotNegatable
if record.name.contains("test") == false {
    log(1)
}
```

### Catalogue fields

A catalogue field holds the **code** of its entry, such as a waste code
`17 06 05*` or a cost group `KG 420`. A script reads it as that code and
compares it with `==`, `!=`, `in` and `not in`. `contains` and `startsWith`
search in the code, not in the label, and ignore upper and lower case, as on
text — the asterisk of a hazardous waste code is found like this:

```hsl
// context: event
if record.wasteCode.contains("*") {
    record.urgent = true
}
```

A catalogue code has no order: `<` and `>` are rejected, as in a condition.

```hsl
// context: event
// expect: expression.operatorNotForType
if record.wasteCode < "20" {
    log(1)
}
```

Writing a catalogue field takes a code of its catalogue, written as the code
and not as the label. A fixed code the catalogue does not know is rejected
when the script is checked (`script.notInCatalog`). Whether the entry is
still valid, selectable and shown is checked by the run, on the day it
writes: a catalogue can change after the script was saved, and an entry that
has expired is refused then.

## 7. Limits

Every run has fixed limits per context. Reaching one aborts the run; nothing
is written.

| Context | CPU time | Wall clock | Queries | Rows read | Rows per query | Records written | Notifications | Automations started |
|---|---|---|---|---|---|---|---|---|
| check | 100 ms | 1 s | 5 | 500 | 100 | 0 | 0 | 0 |
| step | 1 s | 10 s | 50 | 5000 | 5000 | 100 | 20 | 5 |
| event | 1 s | 10 s | 50 | 5000 | 5000 | 100 | 20 | 5 |
| schedule | 5 s | 60 s | 200 | 50000 | 50000 | 1000 | 20 | 5 |
| mapping | 200 ms | 1 s | 0 | 0 | 0 | 0 | 0 | 0 |

Runs per month are part of the edition. Checks before saving do not count:
they run as long as scripts are enabled for the tenant.

## 8. Errors

Errors found when saving point at the start of the statement they are in,
with a pointer line, in the user's language:

```
The field 'priorty' does not exist on 'workOrder'. (character 1):
  if record.priorty > 2 { log(1) }
  ^
```

Errors at run time are results of the run, not platform errors: aborted at a
limit, a refused write, `fail`. Every run leaves a line in the script's run
log.

Each message has a key. The keys below belong to scripts; a message inside an
expression (`expression.…`, `condition.…`) is the same one a condition in a
list or a rule gives, because the expressions are the same.

### Reading the text

| Key | Means | Do instead |
|---|---|---|
| `script.statementExpected` | A line starts with something that is not a statement — a bare expression, a stray word, or `name = value` on a variable: variables are bound once and never reassigned. | Start with `let`, `if`, `for`, `return`, `fail`, a call or `x.field = value`. |
| `script.blockExpected` | `if`, `else` or `for` is not followed by `{`. | Every branch and loop body is in braces, even a single line. |
| `script.blockNotClosed` | A `{` is never closed. | Add the `}`; the pointer shows where the block began. |
| `script.inExpected` | `for` without `in`. | `for job in jobs { … }` |
| `script.limitMissing` | A `query` without `limit`. | Every query states how many rows it reads at most: `limit 50`. |
| `script.byExpected` | `order` without `by`. | `order by dueAt desc` |
| `script.colonExpected` | In `create(type, { … })` a field is not followed by `:`. | `{ name: "Hall 3" }` |
| `script.equalsExpected` | A `let` without `=`. | `let total = 0` |
| `script.reservedWord` | A keyword is used as a name (`let limit = 5`). | Choose another name. |

### Names and types

| Key | Means | Do instead |
|---|---|---|
| `script.unknownName` | A bare name that no `let` or `for` has bound. Outside a query a bare name is never a field. | `record.priority`, or bind the name first. |
| `script.nameTaken` | A name is bound a second time — also inside an inner block: names never hide each other. | Choose another name, or bind a new one: `let total2 = total + 1`. |
| `script.notARecord` | `x.field` on something that is not a record — a number, a text, a list. | Only records, `record`, `before`, query rows and references have fields. |
| `script.notAList` | `for` over something that is not a list. | Loop over a query, `rows` or a multi-value field. |
| `script.recordInQuery` | `record.field` inside `where`. There it would mean the field of the rows searched. | `$record.field` for the value of the triggering record. |
| `script.multiCopyOnly` | A multi-value field gets something other than a multi-value field: a value, a text, a path over a reference. | Copy a field of the same kind: `x.trades = record.trades`. |
| `script.multiChangeValue` | `add` or `remove` on a field that is not a multi-picklist, tags, a multi-reference or a multi-user field; with a code the choice list does not know or that is not written as a fixed text; with a tag containing a comma; with something other than a record of the reference's target type; or, on a multi-user field, with anything but a user field one field deep. | `record.trades.add("hvac")` with a code of the field; `record.tags.add("roof")`; `record.contacts.add(person)`; `record.watchers.add(record.requester)`. |
| `script.notInCatalog` | A catalogue field is given a fixed code its catalogue does not contain, often a typo or the label instead of the code. | Write the code of an entry, as the catalogue lists it: `record.wasteCode = "17 01 01"`. |
| `script.multiCopyMismatch` | The source is another kind of field, points to another type, or has choice values the target does not know. | Copy between fields of the same kind; extend the target's choice list first. |
| `script.fieldNotWritable` | The field is the platform's own: identifier, number, timestamps, formulas, files, images. | Write another field; these are computed. |
| `script.notYetInScripts` | A function or form that the language knows but scripts cannot run yet. | See section 6 for what is available. |

### Context and limits

| Key | Means | Do instead |
|---|---|---|
| `script.notInContext` | The context does not allow it: writing or a call with effect in a check, `return` with a value outside a mapping, `before` where there is no before, `rows` outside a schedule. | See section 2 for what each context has. |
| `script.limitTooHigh` | `limit` above what the context may read in one query. | See section 7; page across runs on a schedule. |
| `script.aiClassifyForm` | `ai.classify` with the wrong shape. | `ai.classify(record.category, [record.description])` — a choice field and up to 20 fields of the same record. |
| `script.aiClassifyNotChoice` | The target has no fixed choices. | A picklist, a catalogue or a reference. |
| `script.aiReadsPersonal` | A field the AI must not read: people, files, personal data. | Leave it out; it is never sent. |

### Saving, switching on and test runs

These come from the settings and the actions around a script, not from its
text, so they have no pointer.

| Key | Means |
|---|---|
| `script.notUnlocked` | Scripts are not part of the tenant's edition. |
| `script.unknown` | No script with this name. |
| `script.nameMissing` | A script needs a name. |
| `script.contextUnknown` | The context named in the settings does not exist. |
| `script.stateUnknown` | The state is neither `active` nor `draft`. |
| `script.triggerUnknown` | The trigger named in the settings does not exist. |
| `script.triggerFieldUnknown` | The trigger watches a field the type does not have. |
| `script.triggerTimeInvalid` | A schedule time that is not a time of day (`06:00`). |
| `script.roleUnknown` | The role to switch the script on under does not exist. |
| `script.roleNotHeld` | You may switch a script on only under a role you hold completely yourself. |
| `script.missingRights` | The script reads or writes something you may not yourself. |
| `script.roleMissingRights` | The role lacks a right the script needs; the message names them. |
| `script.roleHidesType` | The role cannot see the type at all — often the field a view sorts by. |
| `script.changedMeanwhile` | Someone changed the script after you opened it. Review and switch it on again. |
| `script.testRunContext` | A test run needs a record: on event, as a check or as a step. |
| `script.testRunNoAi` | A script that calls `ai.` does not test-run, because every call costs. |
| `script.testRunRecord` | The record for the test run does not exist. |
| `script.testsFull` | A script keeps a limited number of tests; delete one first. |
| `script.testNotKept` | Only a run that completes, or rejects with `fail`, can be kept as a test. |
| `script.testsFailing` | A kept test no longer gives its expected result. Fix the script, or keep the test anew if the new result is right; then switch it on. |
| `script.testUnknown` | The test does not exist. |

### In an import

A mapping is checked when the import plan is saved and again when it runs.
These messages reach the person importing:

| Key | Means |
|---|---|
| `recordImport.scriptMissing` | The plan names a script that does not exist. |
| `recordImport.scriptNotMapping` | The script exists but its context is not “mapping”. |
| `recordImport.scriptNotActive` | The script is not switched on. After every change it is a draft again and must be switched on before the plan runs. |
| `recordImport.scriptInvalid` | The script does not compile against today's model; the message says why. |
| `recordImport.scriptColumnsCollide` | Two headings give the same name in `input`, or one gives none. Rename a column. |
| `recordImport.scriptColumnUnknown` | The script reads `input.name`, but the file has no column of that name; the message lists the names it has. |
| `recordImport.scriptFailed` | The script rejected one row with `fail`, or the row reached a limit. The other rows go on. |

### Drafting a mapping from a description

A draft for a mapping is written against the file's headings and the type of
the plan's level, and checked against both before it is shown:

| Key | Means |
|---|---|
| `script.draftMappingColumns` | A draft for a mapping was asked for without the file's headings or without the level's type. Both are needed; otherwise the names in `input` would be guesses. |
| `script.inputUnknown` | The draft reads `input.name`, but the file has no column of that name; the message lists the names it has. |
| `recordImport.fieldMissing` | The draft returns a field the level's type does not have. |

### When a record is saved

A check before saving runs for the person saving. Two messages reach them, not
the author of the script:

| Key | Means |
|---|---|
| `script.checkNotPermitted` | The check reads data the person saving may not see, so it does not run for them. Nothing was saved. |
| `script.checkCannotRun` | The check could not run — a limit or an error. Nothing was saved. The administrator tries the record in a test run of the script. |

## 9. Version

A script carries the language version `hsl 2` in its settings, not in its
text. A change that reads a saved script differently needs `hsl 3`, a
migration aid and twelve months' notice. An extension that makes previously
rejected text valid is not a break.
