diff --git a/.changeset/37407-skills-multi-reason-refusal.md b/.changeset/37407-skills-multi-reason-refusal.md new file mode 100644 index 00000000000..58c4804f502 --- /dev/null +++ b/.changeset/37407-skills-multi-reason-refusal.md @@ -0,0 +1,10 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): data hooks and actions teach the multi-reason refusal throw + +Clause-②: no (published prose only; teaches the list throw already on main) +Metadata-protocol: none + +`skills/objectstack-data/references/data-hooks.md` (Declared refusals) now teaches the list form beside the single `reason`: throw `reasons: [{ reason, params? }, …]`; each line is translated and filled from its own `params`; `userMessage` joins the lines and closes with the entry's `message`, filled from the throw's top-level `params` (else its holes render empty); the HTTP doors answer `details.refusals`. It says how an entry declares `reasons` (a snake_case reason to `{ message }` only; another status needs another code), that every listed reason must be declared (refused at save when literal, a `500` at run), and that a `reasons` that is not a non-empty list of `{ reason, params? }`, or one beside `reason`, is a `500`. `skills/objectstack-ui/rules/actions.md` (Refusing by code) shows an action's body the same list shape, `reasons: [{ reason, params? }, …]` instead of `reason`, closed by the code's `message`, and points at the hook section for the rules. Both files sat at zero token headroom, so the words are paid for by tightening prose in the same file; no fact is removed (one redundant `condition` example and a sample field go). diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index e9747c32cf5..a0275976061 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -17,13 +17,11 @@ data hooks. ### What Are Hooks? -Hooks are **event handlers** that execute during the ObjectQL data access lifecycle. -They intercept operations at specific points (before/after) — see [Before vs After](#before-vs-after-hooks). +Hooks are **event handlers** in the ObjectQL data access lifecycle, run before or +after an operation — see [Before vs After](#before-vs-after-hooks). ### Hook Lifecycle Events -ObjectStack provides lifecycle events organized by operation type: - | Event | When It Fires | Use Cases | |:------|:--------------|:----------| | **Read Operations** | | | @@ -66,12 +64,11 @@ ObjectStack provides lifecycle events organized by operation type: ## Hook Definition Schema -Every hook must conform to the `HookSchema`. Author it with `defineHook()` — -preferred over a bare `: Hook` literal (the same rule as `defineDatasource`): -it validates when the module is imported, so constraint-level mistakes a bare -annotation can't catch — a non-`snake_case` `name`, a misspelled key routed -through a spread — fail while you author instead of at deploy, and the export -carries defaults already materialized. +Every hook must conform to `HookSchema`. Author it with `defineHook()`, not a +bare `: Hook` literal (the same rule as `defineDatasource`): it validates when the +module is imported, so constraint-level mistakes an annotation can't catch — a +non-`snake_case` `name`, a misspelled key routed through a spread — fail while you +author, not at deploy, and the export carries defaults already materialized. ```typescript @@ -125,20 +122,15 @@ const myHook = defineHook({ #### `condition` — Declarative Filtering -Skip the hook if the condition is false. Author it as a **CEL +Skips the hook when false. Author it as a **CEL predicate** over `record` and `previous` (use `P\`...\`` from `@objectstack/spec`; SQL-style `=` / `AND` / `IN (...)` is not CEL): ```typescript -// Only run for high-value accounts condition: P`record.annual_revenue != null && record.annual_revenue > 1000000` -// Only run for specific statuses condition: P`record.status in ['pending', 'in_review']` -// Complex conditions -condition: P`record.type == 'enterprise' && record.region == 'APAC' && record.is_active == true` - // A TRANSITION — fires only on the update that completes the task, // not on later updates of an already-done record condition: P`previous.done != true && record.done == true` @@ -180,8 +172,8 @@ in neither). So: - **Guard optional values with `!= null`, never with `has(...)`.** A declared field holding `null` is *present*, so `has(record.spent)` is uniformly true and `has(record.spent) && record.spent > record.budget` still faults on - `null > null`. `has()` answers "is this key declared at all", which is a - question about your spelling, not about your data. + `null > null`. `has()` asks whether the key is declared at all: your + spelling, not your data. ⚠️ **An unevaluable condition ABORTS the operation.** A typo'd key (`record.stauts`), a column read off `previous` on an insert, or a comparison @@ -280,15 +272,12 @@ await ctx.api.object('task').find({ where: { $and: [{ done: false }, { owner_id: > `filter:` is tolerated as an **object-valued** alias (normalised to `where`), > but prefer `where`. Do **not** pass an array-of-triples such as -> `[['id', '=', x]]` — that is not a supported value shape and silently matches -> nothing. +> `[['id', '=', x]]` — an unsupported shape that silently matches nothing. -**`findOne` must say which record it wants.** It reads a single row, so an -absent or empty predicate does not come back as `null` — it comes back as the -object's **first row**: a real, plausible-looking record with nothing to do with -what you asked for, which your `if (!row)` cannot catch. So `findOne()`, -`findOne({})` and `findOne({ where: {} })` **throw**. Be specific in one -of three ways: +**`findOne` must say which record it wants.** An absent or empty +predicate would return not `null` but the object's **first row**, an unrelated +record your `if (!row)` cannot catch. So `findOne()`, `findOne({})` +and `findOne({ where: {} })` **throw**. Be specific in one of three ways: ```js await ctx.api.object('candidate').findOne({ where: { id } }); // by predicate @@ -298,15 +287,14 @@ await ctx.api.object('audit') await ctx.api.object('candidate').find({ limit: 1 }); // any row will do ``` -An unpredicated `find` / `count` is fine — returning or counting every row is an -honest answer. +An unpredicated `find` / `count` is fine: every row is an honest answer. ### Capabilities — the complete list A body may only touch a `ctx` API it declared in `capabilities`. Calling an undeclared one **throws inside the VM** — `capability '' not granted to -hook '' …` — which surfaces as a hook error (see Troubleshooting). The full -set of legal tokens (`HookBodyCapability`) is exactly seven: +hook '' …` — which surfaces as a hook error (see Troubleshooting). The legal +tokens (`HookBodyCapability`) are exactly seven: | Token | Unlocks | |:--|:--| @@ -424,17 +412,14 @@ export default fillPositionOnHire; `log` capability the call **throws** (surfaces as a hook error); (2) **with** the capability it emits only when the runtime wired a logger into the hook context — otherwise it is a **silent no-op**. Treat `ctx.log` as best-effort diagnostics, - not a reliable side-channel or proof a hook ran; to observe an effect, assert on - the data it writes. + never proof a hook ran; to observe an effect, assert on the data it writes. --- ## Hook Context API -> The `ctx` below is the deprecated in-process `handler`'s; a `body` sees the -> [sandbox subset](#what-lives-on-the-sandbox-ctx). - -The engine's `HookContext` provides: +> The `ctx` below, the engine's `HookContext`, is the deprecated in-process +> `handler`'s; a `body` sees the [sandbox subset](#what-lives-on-the-sandbox-ctx). ### Context Properties @@ -504,7 +489,7 @@ const org = ctx.user?.organizationId ?? ctx.session?.organizationId; ### `input` — Operation Parameters -The structure of `ctx.input` varies by event: +`ctx.input` varies by event: **Insert operations:** ```typescript @@ -513,7 +498,6 @@ The structure of `ctx.input` varies by event: // All field values being inserted name: 'Acme Corp', industry: 'Technology', - annual_revenue: 5000000, ... } ``` @@ -770,7 +754,6 @@ ctx.ql.registerHook('beforeInsert', async (hookCtx) => { /* ... */ }, file, default-exported, then listed in the stack's `hooks` array (method 1). This is the layout both real hook modules in the repo use. - --- ## Best Practices @@ -791,7 +774,6 @@ hook (its `ctx.api` writes roll back with the write) or record it in the caller, where the write is made; assume `ctx.session` exists — system operations carry no user. - --- ## Error Handling @@ -802,10 +784,9 @@ A throw aborts the operation and rolls back its transaction; `onError: 'log'` ### Declared refusals (`refusals`) A hook that enforces a business rule declares a `refusals` catalogue, one -SCREAMING_SNAKE code per rule, and the hook throws the code. Without one, a `body`'s -throw is answered `HOOK_ABORTED`, the platform's code: fine for a failure you did not -plan, not for a rule the user can act on. A cross-object guard a validation rule -cannot read: +SCREAMING_SNAKE code per rule, and throws the code. Without one, a `body`'s +throw is answered `HOOK_ABORTED`, the platform's code: fine for an unplanned failure, not +for a rule the user can act on. A cross-object guard a validation rule cannot read: ```typescript @@ -840,15 +821,21 @@ export default defineHook({ - A `js` `body` or a `handler` (inline or named) can declare one; an `expression` body, or neither, is refused at save. - The wire `code` is the status's (default 400), with the hook's as `declaredCode`. -- `reasons` (snake_case, thrown as `reason`) add sentences that keep the code's wire - `code` and status. -- `params` names what a `{{ name }}` hole may fill (thrown as `params`); a hole - over any other name, or any hole with no `params`, is refused. +- `reasons` maps a snake_case reason (thrown as `reason`) to `{ message }` only: a + sentence under the code's wire `code` and status; another status needs another code. +- `params` names what a `{{ name }}` hole, a reason's too, may fill (thrown as + `params`); a hole over any other name, or any hole with no `params`, is refused. +- For several reasons throw `reasons: [{ reason: 'on_loan', params: { due } }, …]`, not + `reason`: one translated line each, filled from its own `params`. `userMessage` joins + them by newlines and ends with the entry's `message`, filled from the throw's + top-level `params` (else its holes are empty); the HTTP doors answer + `details.refusals: [{ reason, message }]`, absent for a single `reason`. - Translated via `hooks..refusals..message` (or `…..reasons..message`); the thrown text and `status` are unused. -- An undeclared code (or none), or a reason missing from a code's `reasons`, is - refused: at save if thrown literally, else as a `500`. Unchanged `ctx.api` - errors and crashes pass through. +- An undeclared code (or none), or a reason missing from a code's `reasons` (a listed + one even when the code declares none), is refused: at save if thrown literally, else + as a `500`. A `reasons` not a non-empty list of `{ reason, params? }`, or beside + `reason`, is a `500`. Unchanged `ctx.api` errors and crashes pass through. ### Declared texts (`texts`) diff --git a/skills/objectstack-ui/rules/actions.md b/skills/objectstack-ui/rules/actions.md index 5aa84bafab5..c8d8fb2872f 100644 --- a/skills/objectstack-ui/rules/actions.md +++ b/skills/objectstack-ui/rules/actions.md @@ -1,6 +1,6 @@ # Actions -Actions are user-triggered operations attached to an object or a view. +Actions are user-triggered operations on an object or a view. Register them under `defineStack({ actions: [...] })`; the six types: [Action Types](../SKILL.md#action-types). A parameterized bulk mutation is `script`. @@ -21,7 +21,7 @@ in `language: 'js'` (an `expression` body has no I/O) with |:-----------------|:--------| | `record_header` | Detail page header | | `record_more` | Detail page overflow menu (⋯) | -| `record_related` | Related-list section inside a record | +| `record_related` | Related-list section in a record | | `record_section` | Body section/tab of a record | | `list_item` | Per-row action in list views | | `list_toolbar` | Toolbar button; one ticked row is its `recordId`, several are refused (no `_selectedIds`) | @@ -42,19 +42,19 @@ there: a wrong name draws nothing. ## Visibility, Disable & Feedback -- `visible` — a bare CEL predicate over the current record (prefer the `P\`...\`` template; `record.` resolves identically on every surface, never `${…}`- or `{…}`-wrapped — see `objectstack-formula`); when false the action is **hidden**. -- `disabled` — `boolean` **or** a CEL predicate; when true the action **shows but greys out**. A bare field ref in either (`done` for `record.done`) fails `os validate`. +- `visible` — a bare CEL predicate over the current record (prefer the `P\`...\`` template; `record.` resolves identically on every surface, never `${…}`- or `{…}`-wrapped — see `objectstack-formula`); when false it is **hidden**. +- `disabled` — `boolean` **or** a CEL predicate; when true it **shows but greys out**. A bare field ref in either (`done` for `record.done`) fails `os validate`. - `disabledReason` — an I18nLabel (a sentence or an inline locale map) a greyed action shows as its hover title and accessible description. Display-only: never a predicate or a gate (the hook or permission still refuses). Omit it to keep the console's default "Not available for this record"; a blank one is refused, and `disabledMessage` / `disabledTooltip` / `disabledHint` / `disabledText` are refused naming this key. The reason goes here, not in `description`. - `pressed` — a CEL predicate over the same scope as `visible` that marks the action as already done by this reader: while TRUE the record header draws it pressed (`aria-pressed`). Display-only, never a gate; a boolean literal is refused (a constant is a style, not a reader's state), and `active` / `activeWhen` / `pressedWhen` are refused naming this key. A per-reader fact (the reader's vote) is a block the object declares under `attachedOnRead`, filled per caller by a service or `afterFind` hook, read as `has(record.viewer) && record.viewer.vote == 'helpful'`. - `confirmText` — set for any destructive or irreversible operation; the confirm dialog of a param-less action. A registered action is refused it beside a non-empty `params` (put the question on `description`); a view's `bulkActionDefs` entry pairs the two by its own contract. - `submitText` — the verb on the param dialog's submit button ("Send", "Log Call") in place of "Confirm": an I18nLabel, refused blank and refused without a non-empty `params` (no dialog opens); `submitLabel` / `confirmLabel` are refused naming this key. - `preflight` — a read the param dialog shows above the params before submit: `{ read: { url }, path?, fields?, seed? }` sends one `GET` (no other `method`, no body or credentials) to a same-origin API path (one leading `/`) whose only holes are `${param.NAME}` (a declared param; re-read when it changes), `${ctx.recordId}` and `${ctx.record.FIELD}`. `path` selects the answer's sub-tree (`data`); `fields` rows are `resultDialog.fields`' (omitted: JSON). Each `seed: [{ param, path }]` entry fills a declared param, drawn read-only and submitted as shown: seeded once, no `defaultValue` / `defaultFromRow` / `carryOver`, read by no hole; mark it `required` so Confirm waits for the answer. Refused without a non-empty `params` and beside `execution: 'aggregate'`. UX, not authorization: the endpoint still checks a seeded value. - `resultDialog` — a one-shot dialog that shows the server answer in place of the success toast (so no `successMessage`; `outcomeMessages` is refused beside it): `{ title?, description?, acknowledge?, format?, fields? }`. `fields: [{ path, label?, format? }]`, `path` a dot path into `result.data` (omitted: the whole answer as JSON); `format` is one of `qrcode`, `code-list`, `secret`, `text`, `json`, or `table` with `columns: [{ path, label?, format? }]` (one row per element of the array at `path`, one cell per column; required with `table` and refused beside any other format). The dialog-level `format` (default `json`) and a cell's (default `text`) take every format but `table`. A `text` or `code-list` cell draws the value with no copy control; a `secret` or `qrcode` cell keeps its own. -- `successMessage` / `errorMessage` — toast copy; without `successMessage` the UI shows a generic "Action completed". +- `successMessage` / `errorMessage` — toast copy; without `successMessage` the UI shows "Action completed". - Copy holes are `{{ }}`: `confirmText`, `description` and a param's `helpText` read `record`; `successMessage` and each `outcomeMessages` entry (`resent: 'Invitation resent to {{ result.email }}'`) read `result` and `record`; `errorMessage` takes none. A `bulkActionDefs` entry's `confirmText` reads `{{ count }}` and its params by bare name (`{{ tier }}`). In all of them `${record.name}`, `{name}`, logic in a hole and a blank sentence fail `os validate`. - A param's `helpText`, like `description`, is a sentence or an inline locale map (`{ en: 'Why {{ record.name }} is paused', 'zh-CN': '暂停原因' }`); the map is how a page button's inline `action` (no bundle reaches it) writes its hint per locale. - `undoable: true` — an **Undo** in the success toast (and `Ctrl+Z`). Snapshot: runtime on `operation: 'update'`, console on `type: 'api'`; else refused. -- A list view's `bulkActions: ['']` runs the action once per ticked row. A body that writes each selected row takes that form: declare `execution: 'perRecord'` and write the row it is handed (`ctx.record`, `ctx.recordId`; `crm_create_campaign` below); a row whose run throws is listed with its message. A `bulkActionDefs` entry `{ name, operation: 'custom', execution: 'aggregate' }` runs it once for the selection. A script body or a flow receives the ids under the built-in key `params._selectedIds` (`input._selectedIds`), at most 5000 and only ids the caller can read: one the caller cannot read refuses the whole call (`404 RECORD_NOT_FOUND`) before it starts. A throw is one outcome for the selection; a return value's top-level `succeeded` or `failed` is read as a `BulkActionResult` (`@objectstack/spec/ui`), and in any other form (counts, one list) reported as unreadable. +- A list view's `bulkActions: ['']` runs it once per ticked row. A body that writes each selected row takes that form: declare `execution: 'perRecord'` and write the row it is handed (`ctx.record`, `ctx.recordId`; `crm_create_campaign` below); a row whose run throws is listed with its message. A `bulkActionDefs` entry `{ name, operation: 'custom', execution: 'aggregate' }` runs it once for the selection. A script body or a flow receives the ids under the built-in key `params._selectedIds` (`input._selectedIds`), at most 5000 and only ids the caller can read: one the caller cannot read refuses the whole call (`404 RECORD_NOT_FOUND`) before it starts. A throw is one outcome for the selection; a return value's top-level `succeeded` or `failed` is read as a `BulkActionResult` (`@objectstack/spec/ui`), and in any other form (counts, one list) reported as unreadable. ```typescript @@ -74,7 +74,7 @@ export const ReassignLeadAction = defineAction({ submitText: 'Reassign', undoable: true, successMessage: 'Lead {{ record.name }} reassigned.', - errorMessage: "Couldn't reassign this lead — try again.", + errorMessage: "Couldn't reassign this lead.", }); ``` @@ -96,8 +96,8 @@ export const ConvertLeadAction = defineAction({ target: 'crm_lead_conversion', locations: ['record_header', 'list_item'], visible: P`record.status == "qualified" && record.is_converted == false`, - confirmText: 'Are you sure you want to convert this lead?', - successMessage: 'Lead converted successfully!', + confirmText: 'Convert this lead?', + successMessage: 'Lead converted.', onSuccess: { navigate: '/apps/crm_enterprise/opportunity/record/${result.output.opportunity_id}' }, refreshAfter: true, }); @@ -113,9 +113,7 @@ export const AddToCampaignAction = defineAction({ objectName: 'lead', type: 'script', execution: 'perRecord', - params: [ - { field: 'campaign_id', objectOverride: 'campaign', required: true }, - ], + params: [{ field: 'campaign_id', objectOverride: 'campaign', required: true }], body: { language: 'js', source: ` @@ -131,7 +129,7 @@ export const AddToCampaignAction = defineAction({ ### Action body context (`ctx`) -A server-side `body` (or a registered `handler`) receives `ctx` with `input` (the dialog params), `record` (the target row, when a +A server-side `body` or registered `handler` receives `ctx` with `input` (the dialog params), `record` (the target row when a `recordId` is in scope), `api` (scoped cross-object CRUD) and the caller. Read the active organization as `ctx.user?.organizationId ?? ctx.session?.organizationId` (as in hooks, objectstack-data). @@ -143,11 +141,13 @@ Bodies execute **trusted** (`ctx.api` / `throw new Error('…')` answers every caller in the author's language. A `type: 'script'` action with a `js` body (an inline `target` function is lowered to one; any other action is refused the -key) declares `refusals` and throws the code, as `crm_add_invoice_line` below does: the catalogue, +key) declares `refusals` and throws the code, as `crm_add_invoice_line` below: the catalogue, throws and checks are a hook's (objectstack-data → Lifecycle Hooks → Declared refusals). The sentence is answered as `userMessage`, translated at `objects.._actions..refusals..message` (objectstack-i18n); the console's -failure toast shows it unless the action authors `errorMessage`. +failure toast shows it unless the action sets `errorMessage`. For several reasons throw +`reasons: [{ reason, params? }, …]`, not `reason`: `userMessage` is one line per reason, closed +by the code's `message` (rules there). ### Writing in the organization's language (`texts`) @@ -165,7 +165,7 @@ rejects. An undeclared key is refused at save when named literally, else at run. A **static** `target` URL on a `type: 'url'` action: `openIn: 'self'` forces in-place navigation; omitted, absolute URLs open in a new tab and relative ones -navigate in place. +in place. ```typescript @@ -173,7 +173,7 @@ import { defineAction } from '@objectstack/spec/ui'; export const PrintA3Action = defineAction({ name: 'crm_print_a3', - label: 'Print Summary Sheet (A3)', + label: 'Print A3', objectName: 'lead', type: 'url', target: '/print/a3?id=${ctx.recordId}', // interpolated at click @@ -188,7 +188,7 @@ A redirect URL **computed after a fetch**: `opensInNewTab: true` pre-opens the tab synchronously on click (no popup blocker), then navigates it to the handler's `redirectUrl`. `newTabUrl` skips the round-trip — a backend path starting with `/` (an external URL is refused, use -`openIn`), valid only with `opensInNewTab: true`; the endpoint enforces its own +`openIn`), only with `opensInNewTab: true`; the endpoint enforces its own auth (the tab carries no in-app session). @@ -261,7 +261,7 @@ export const AddInvoiceLineAction = defineAction({ Lines also written past the action (API, an agent, an import — one with automations off skips hooks) get the price from a `beforeInsert` hook on the -line instead (objectstack-data → Lifecycle Hooks), `runAs: 'system'` when the +line (objectstack-data → Lifecycle Hooks), `runAs: 'system'` when the writer cannot read it. -> Set `refreshAfter: true` whenever the action mutates the current record. +> Set `refreshAfter: true` when the action mutates the current record.