diff --git a/.changeset/34824-action-refusals-skill.md b/.changeset/34824-action-refusals-skill.md new file mode 100644 index 00000000000..2115a303e51 --- /dev/null +++ b/.changeset/34824-action-refusals-skill.md @@ -0,0 +1,15 @@ +--- +'@objectstack/skills': patch +'@objectstack/spec': patch +--- + +docs(skills, spec): the ui and i18n skills teach an action's `refusals` catalogue and its translation keys; `action.zod.ts` gains a module description + +Clause-②: no — skill teaching text, evals and two comment-only edits in packages/spec; no schema, export or accept set moves +Metadata-protocol: none — no metadata key is touched + +objectstack-ui's `rules/actions.md` gains a short section, "Refusing by code (`refusals`)": a `type: 'script'` action with a `js` body declares the refusals it may throw and throws the code instead of a sentence, the catalogue, the throws and the checks are the ones a hook has (taught in objectstack-data's `references/data-hooks.md` § Declared refusals), the sentence is answered as `userMessage` and translated at `objects.._actions..refusals..message`, and an authored `errorMessage` replaces it in the console's failure toast. The file's Add Line example now declares `refusals: { PRODUCT_NOT_FOUND: … }` and throws `{ code: 'PRODUCT_NOT_FOUND' }` where it threw `new Error('Product not found.')`. + +objectstack-i18n's SKILL.md lists the keys in the object key table — `_actions.{action_name}.refusals.{CODE}` holds `message` and `reasons.{reason}.message`, the same under `globalActions.{action_name}`, and a key for a code or reason the action does not declare is `translation-target-unknown` — and the server-composed text section names an action's refusal beside a hook's. Each skill's eval file gains one case that grades the rule. + +`@objectstack/spec`: comments only. `src/ui/action.zod.ts` opens with a module doc block, so the generated reference page and the two skill reference indexes describe the module ("Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from.") where they listed its first five exports, and the jsdoc above `actionRefusalsWithoutSandboxedBody` names the third case as the function judges it: a `script` action with no `body`. diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index 96fa5ec9c6f..0d7a61d3e37 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -1,11 +1,26 @@ --- title: Action schema — UI Protocol property reference navTitle: Action -description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, ActionLocation and 5 more — each property with its type, default and a TypeScript example." +description: "Action protocol schemas — ActionSchema, the action metadata type, and the parts it is built from." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} +Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from. + +An action is a command a user or an AI agent runs: a button on a record +header, a list row or a list toolbar, or on a page. Its `type` names the +dispatch route — a `script` body or handler, a `url`, a `flow`, an `api` +endpoint, a `modal` or a `form` — and `locations` names the surfaces that +draw it. Declare one with `defineAction`. + +Beside `ActionSchema`: `ActionParamSchema` (one input of the +param dialog), `ActionLocationSchema` (the surfaces), +`ActionAiSchema` (how an agent is offered the action), +`ActionRefusalSchema` (one entry of the `refusals` catalogue a +`script` body refuses through) and `InlineActionSchema` (an action +declared inline on a page element instead of registered by name). + **Source:** `packages/spec/src/ui/action.zod.ts` diff --git a/packages/spec/scripts/file-description.test.ts b/packages/spec/scripts/file-description.test.ts index 61e12aeae5d..4bf99ba91da 100644 --- a/packages/spec/scripts/file-description.test.ts +++ b/packages/spec/scripts/file-description.test.ts @@ -1796,13 +1796,17 @@ describe('corpus — no reference source donates a symbol comment to its page', expect(openingOf('shared/mapping.zod.ts')).toBe('@module shared/mapping'); }); - it('publishes no description for the eight modules whose opening was one schema\'s doc (#13334)', () => { + it('publishes no description for seven of the eight modules whose opening was one schema\'s doc (#13334)', () => { // The corpus half of route ② — each of the eight had a symbol's comment // wedged into its import list by the lazify codemod, published as the // page's opening and as the module's skill-index pointer row. The comments // moved back to the declarations they document (or to the family they // head), so no block sits in the header zone documenting nothing: the page // honestly prints no description. 宁可缺,不要错. + // + // The eighth, `ui/action.zod.ts`, has since been given a module header + // written on purpose (#34824 N4) — the case below pins it, so it leaves + // this list rather than being exempted from it. const openingOf = (rel: string) => opening(findModuleDocBlock(fs.readFileSync(path.join(SRC_DIR, rel), 'utf-8'))); for (const rel of [ @@ -1810,7 +1814,6 @@ describe('corpus — no reference source donates a symbol comment to its page', 'data/datasource.zod.ts', 'data/hook.zod.ts', 'security/permission.zod.ts', - 'ui/action.zod.ts', 'ui/app.zod.ts', 'ui/component.zod.ts', 'ui/page.zod.ts', @@ -1818,6 +1821,34 @@ describe('corpus — no reference source donates a symbol comment to its page', expect(openingOf(rel), rel).toBeNull(); } }); + + it('opens `ui/action` with the module header written above its imports (#34824 N4)', () => { + // The one #13334 module that regained a description, and how: not a + // symbol's comment back in the import list, but a block in the header zone + // — after the licence line, before the first import — that describes the + // module. Pinned on three facts so neither a re-wedged symbol comment nor a + // header glued to a declaration can pass for it. + const rel = 'ui/action.zod.ts'; + const source = fs.readFileSync(path.join(SRC_DIR, rel), 'utf-8'); + const block = findModuleDocBlock(source); + + // ① the opening, exactly — the page's first line and the skill-index row. + expect(opening(block)).toBe( + 'Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from.', + ); + + // ② the selected block is the header zone's: nothing but the licence line + // and blanks precede it, and no import does. + const at = source.indexOf(`/**${block}*/`); + expect(at).toBeGreaterThan(-1); + const before = source.slice(0, at).split('\n').filter(l => l.trim() !== ''); + expect(before).toEqual(['// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.']); + + // ③ what follows it is the import list, not a declaration it could be + // documenting. + const after = source.slice(at + `/**${block}*/`.length).split('\n').find(l => l.trim() !== ''); + expect(after).toMatch(/^import\b/); + }); }); /** diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 9b643d96b2e..0c2d935587f 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -559,12 +559,13 @@ export function undeclaredActionRefusalReasonAtRun( } /** - * The save-time refusal for a catalogue on an action whose code cannot throw a - * code: a type other than `script` (its `target` is a URL, page, flow or - * endpoint — a refused flow answers through its own `end` refusal), an - * `expression` body, or a `script` action with neither a body nor an inline - * `target` function. `os i18n` would demand its translations and nothing would - * serve them. + * The save-time refusal for a catalogue on an action that runs no sandboxed + * `js` body, so nothing it runs can throw a declared code: a type other than + * `script` (its `target` is a URL, page, flow or endpoint — a refused flow + * answers through its own `end` refusal), an `expression` body, or a `script` + * action with no `body` — which is what a string `target` naming a host + * handler, or an inline `target` function `os build` could not lower, leaves. + * `os i18n` would demand its translations and nothing would serve them. */ export function actionRefusalsWithoutSandboxedBody(type: string, language: string | undefined): string { const has = actionCodeCarrier(type, language); diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index dd22398cf60..bd2687980dc 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -1,5 +1,22 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +/** + * Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from. + * + * An action is a command a user or an AI agent runs: a button on a record + * header, a list row or a list toolbar, or on a page. Its `type` names the + * dispatch route — a `script` body or handler, a `url`, a `flow`, an `api` + * endpoint, a `modal` or a `form` — and `locations` names the surfaces that + * draw it. Declare one with `defineAction`. + * + * Beside {@link ActionSchema}: {@link ActionParamSchema} (one input of the + * param dialog), {@link ActionLocationSchema} (the surfaces), + * {@link ActionAiSchema} (how an agent is offered the action), + * {@link ActionRefusalSchema} (one entry of the `refusals` catalogue a + * `script` body refuses through) and {@link InlineActionSchema} (an action + * declared inline on a page element instead of registered by name). + */ + import { z } from 'zod'; import { retiredKey } from '../shared/retired-key'; import { FieldType } from '../data/field.zod'; diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 9adc35fc5f9..afb5f3bf832 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1391,7 +1391,31 @@ export const CEILINGS = new Map([ // 「A:先削重复,余额按实测提高」 (record 6513306068). The seven hand-authored // objectstack-ui files net -149 bytes across the move (100990 -> 100841). // ceil($(wc -c < skills/objectstack-ui/rules/actions.md) / 4) == ceil(12123 / 4) - ['skills/objectstack-ui/rules/actions.md', 3031], + // 3031 -> 3180 (#34824): an action body refuses by code. One paragraph under the `ctx` section (which + // action may declare `refusals`; that the catalogue, the throws and the checks are a hook's, + // taught in objectstack-data and only pointed at here; the bundle key the sentence is translated + // at; that an authored `errorMessage` replaces the sentence in the console's toast), and the + // Add Line example declares one entry and throws its code where it threw a sentence. PAID DOWN + // FIRST by 124 bytes of true restatement in this file, five cuts: the label line + // "**Script-typed action**:" above the Add to Campaign example (26; the block's own + // `type: 'script'` says it, under the H2 "Examples"); the label "**Flow-typed action**" and the + // parentheses it held the `onSuccess` note in (19 net, the note now says "the flow run"; the + // block's own `type: 'flow'` says it); "`openIn: 'new-tab'` opens it in a new tab," (35 net, + // `'self'` now spelled `openIn: 'self'`; the H3 "`openIn: 'new-tab'`" under the H2 "Opening in + // a New Tab" and the example's `openIn: 'new-tab'` line say it); " on success / failure" on + // the `successMessage` / `errorMessage` bullet (21; the two key names, that bullet's + // "Action completed" half and the refusals paragraph's "failure toast … `errorMessage`" say + // it); "(`{ field: 'email' }`)" beside "field-backed params" (23; the `{ field: … }` params of + // the Reassign Lead, Add to Campaign and Add Line examples show the shape). The same ruling's + // second half carries the rest. Arithmetic: the text adds 721 bytes, the cuts remove 124, so + // the file is 12123 -> 12720 bytes -> 3180 tokens, zero headroom before, ceiling +149, the + // measured remainder only, pinned AT the measurement. RE-MEASURED on the merge with main after + // the #34770 row above landed first (this entry was written as 2808 -> 2957 over 11231 -> + // 11828 bytes; the delta is the same +597 bytes, +149 tokens, and none of the five cuts falls + // in the text that row moved in). Same ruling as the lines above (2026-10-27, tap A): + // 「A:先削重复,余额按实测提高」 (ruling record 6513306068). + // ceil($(wc -c < skills/objectstack-ui/rules/actions.md) / 4) == ceil(12720 / 4) + ['skills/objectstack-ui/rules/actions.md', 3180], // 6090 -> 6252 (#19715, card item 4): a 5-line table of contents at the top, // anchors to the file's existing headings, nothing else changed. +162 tokens, // zero headroom to absorb any of it, ceiling +162. Maintainer ruling diff --git a/skills/objectstack-data/references/_index.md b/skills/objectstack-data/references/_index.md index 70456ad9993..ec47ecb6743 100644 --- a/skills/objectstack-data/references/_index.md +++ b/skills/objectstack-data/references/_index.md @@ -59,7 +59,7 @@ from `node_modules` — there is no local copy in the skill bundle. - `node_modules/@objectstack/spec/src/system/deploy-bundle.zod.ts` — Deploy Bundle Protocol - `node_modules/@objectstack/spec/src/system/translation.zod.ts` — Exports: LocaleSchema, FieldTranslationSchema, ActionResultDialogTranslationSchema, ObjectTranslationDataSchema, TranslationDataSchema - `node_modules/@objectstack/spec/src/ui/action-params.zod.ts` — The action DISPATCH contract: what the platform validates on the way in, and -- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionRefusalSchema +- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from. - `node_modules/@objectstack/spec/src/ui/bulk-action.zod.ts` — Bulk Action Schemas - `node_modules/@objectstack/spec/src/ui/chart.zod.ts` — Unified Chart Type Taxonomy - `node_modules/@objectstack/spec/src/ui/i18n.zod.ts` — Display-label and ARIA-label primitives shared by every `ui/` shape. diff --git a/skills/objectstack-i18n/SKILL.md b/skills/objectstack-i18n/SKILL.md index 18628b28f88..6625e0bde0a 100644 --- a/skills/objectstack-i18n/SKILL.md +++ b/skills/objectstack-i18n/SKILL.md @@ -168,6 +168,7 @@ All translatable content for a single object is aggregated under | `_sections.{section_name}` | Form section `label`, `description`; `fields.{field_name}` — the `label`, `placeholder`, `helpText` an entry overrides for that form alone (`helpText` here, `help` under `fields.{field_name}` above: each spells what its source does) | | `_tabs.{tab_name}` | Filter-preset tab `label` (`ViewTabSchema.name`) | | `_validations.{rule_name}` | `message` only — the sentence a rejected write returns (replaces the retired `validationMessages`) | +| `_actions.{action_name}.refusals.{CODE}` | `message`, and `reasons.{reason}.message` per declared reason — the sentences of the action's `refusals` catalogue (**objectstack-ui** → Actions), for a code and reason it declares (any other is `translation-target-unknown`); the same under `globalActions.{action_name}` | Top-level groups alongside `objects`: `apps` (label, description, navigation), `messages`, `globalActions` (actions with no `objectName` — a key naming a bound action is @@ -340,9 +341,8 @@ The spec models coverage results for tooling — the return shapes of the option (totals, `coveragePercent`, per-group `breakdown`) and `TranslationDiffItem` — `key` (dot path), `status` (`missing | redundant | stale`), `locale`, optional `objectName`, optional `sourceHash` for stale detection, and AI-enrichment -fields (`aiSuggested`, `aiConfidence`). Full Zod shape: -`node_modules/@objectstack/spec/src/system/translation.zod.ts` — -`TranslationCoverageResultSchema`, `TranslationDiffItemSchema`. +fields (`aiSuggested`, `aiConfidence`). Full Zod shape: `TranslationCoverageResultSchema`, +`TranslationDiffItemSchema` (`translation.zod.ts`). --- @@ -403,7 +403,8 @@ produced; a client renders it as received. code is never handed Simplified text. - **App-authored** refusal text is not on this ladder: a hook's catalogued refusal is served through `hooks..refusals..message` (a declared reason's through - `hooks..refusals..reasons..message`) in the caller's locale, negotiated over + `…..reasons..message`), an action's through its `_actions.{action_name}.refusals` + keys (table above), each in the caller's locale, negotiated over whatever locales the app's translations hold, and otherwise as declared, in the app's own source language. No `en` floor is supplied for it. Under an entry declaring `params`, a translation keeps its `{{ name }}` holes; the runtime fills them after picking it. @@ -474,8 +475,8 @@ every plugin contributes its own `objects.*` slice. ## Shipped examples -`examples/app-crm` — the bundled layout (one `crm.translation.ts`, `en` + `zh-CN`). -`examples/app-todo` — the per-locale layout (`{en,zh-CN,ja-JP}.ts` + `index.ts`). +`examples/app-crm` — the bundled layout (`en` + `zh-CN`). +`examples/app-todo` — the per-locale layout. --- diff --git a/skills/objectstack-i18n/evals/bundles-locales-coverage.json b/skills/objectstack-i18n/evals/bundles-locales-coverage.json index 627e5123c0c..5e229184997 100644 --- a/skills/objectstack-i18n/evals/bundles-locales-coverage.json +++ b/skills/objectstack-i18n/evals/bundles-locales-coverage.json @@ -91,6 +91,16 @@ "must_not_contain": ["pages.crm_manual", "sections.getting_started"] } }, + { + "id": 13, + "prompt": "The `submit_signoff` action on `crm_invoice` declares `refusals: { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 }, STAGE_LOCKED: { message: 'This stage change is not allowed.', params: ['stage'], reasons: { closed: { message: 'A {{ stage }} invoice can no longer change.' } } } }`, and its body throws those codes. zh-CN users still read the English sentences. Which bundle keys translate them, and what does a caller get in a locale no bundle covers?", + "expected_output": "`objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message` and `….refusals.STAGE_LOCKED.message`, and the reason's sentence at `objects.crm_invoice._actions.submit_signoff.refusals.STAGE_LOCKED.reasons.closed.message`; an action with no `objectName` takes the same keys under `globalActions.submit_signoff`. The reason's translation keeps its `{{ stage }}` hole, which the server fills after picking the translation. The server answers the sentence in the caller's locale, negotiated over the locales the app's bundles hold, on the refusal's `userMessage`; a locale no bundle covers gets the declared sentence as written, with no `en` floor. A key for a code or reason the action does not declare is `translation-target-unknown`. Not a hook's refusal key, and not a `messages` entry the body looks up itself.", + "files": [], + "assertions": { + "must_contain": ["_actions", "submit_signoff", "refusals", "NOT_DRAFT", "reasons", "closed"], + "must_not_contain": ["hooks.submit_signoff"] + } + }, { "id": 10, "prompt": "In zh-CN the `crm_renew` action on `crm_opportunity` opens its param dialog with the rows of its pre-submit read still in English. Its `preflight.fields` declares the paths `amount` and `verdict.summary`.", diff --git a/skills/objectstack-ui/evals/views-apps-actions-pages.json b/skills/objectstack-ui/evals/views-apps-actions-pages.json index e03630631ee..acd3596f15e 100644 --- a/skills/objectstack-ui/evals/views-apps-actions-pages.json +++ b/skills/objectstack-ui/evals/views-apps-actions-pages.json @@ -190,6 +190,16 @@ "must_contain": ["type: 'simple'", "modalSize"], "must_not_contain": ["type: 'tabbed'"] } + }, + { + "id": 20, + "prompt": "The `submit_signoff` script action on `crm_invoice` refuses a non-draft invoice with `throw new Error('Only a draft invoice can be signed off.')` in its `js` body, so zh-CN users read that English sentence in the failure toast. Make it refuse in the caller's language, with the code `NOT_DRAFT` and a 409.", + "expected_output": "The action declares `refusals: { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 } }` and the body throws the code instead of the sentence: `throw { code: 'NOT_DRAFT' }`. The server answers the declared sentence on the refusal's `userMessage` with status 409, in the caller's locale once the zh-CN bundle carries `objects.crm_invoice._actions.submit_signoff.refusals.NOT_DRAFT.message`, else as declared, and the console's failure toast shows it. The action authors no failure copy of its own, which would replace that sentence in the toast. A code the body throws literally and `refusals` does not declare is refused at save. Not a locale branch in the body, and not a second sentence per language in the throw.", + "files": [], + "assertions": { + "must_contain": ["refusals", "NOT_DRAFT", "409", "_actions"], + "must_not_contain": ["hooks.submit_signoff"] + } } ] } diff --git a/skills/objectstack-ui/references/_index.md b/skills/objectstack-ui/references/_index.md index 4b1612be625..625b677159c 100644 --- a/skills/objectstack-ui/references/_index.md +++ b/skills/objectstack-ui/references/_index.md @@ -9,7 +9,7 @@ from `node_modules` — there is no local copy in the skill bundle. ## Core schemas -- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Exports: ActionParamSchema, ActionType, ActionLocationSchema, ActionAiSchema, ActionRefusalSchema +- `node_modules/@objectstack/spec/src/ui/action.zod.ts` — Action protocol schemas — `ActionSchema`, the `action` metadata type, and the parts it is built from. - `node_modules/@objectstack/spec/src/ui/app.zod.ts` — Exports: ObjectNavItemSchema, DashboardNavItemSchema, PageNavItemSchema, UrlNavItemSchema, ReportNavItemSchema - `node_modules/@objectstack/spec/src/ui/chart.zod.ts` — Unified Chart Type Taxonomy - `node_modules/@objectstack/spec/src/ui/component.zod.ts` — Exports: PageContainerProps, PageHeaderProps, PageTabsProps, PageCardProps, RecordDetailsProps diff --git a/skills/objectstack-ui/rules/actions.md b/skills/objectstack-ui/rules/actions.md index 6da87a0d9fc..8d9776350bc 100644 --- a/skills/objectstack-ui/rules/actions.md +++ b/skills/objectstack-ui/rules/actions.md @@ -35,7 +35,7 @@ it. - `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`' `{ path, label?, format? }` (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. -- `successMessage` / `errorMessage` — toast copy on success / failure; without `successMessage` the UI shows a generic "Action completed" toast. +- `successMessage` / `errorMessage` — toast copy; without `successMessage` the UI shows a generic "Action completed" toast. - Copy holes are `{{ }}`: `confirmText`, `description` (`'Choose the new owner of {{ record.name }}.'`) and a param's `helpText` read `record`; `successMessage` and each `outcomeMessages` entry (`resent: 'Invitation resent to {{ result.email }}'`) read `result` (the handler's answer) 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. @@ -64,7 +64,7 @@ export const ReassignLeadAction = defineAction({ ## Examples -**Flow-typed action** (`onSuccess` hops once the run completes, not when it pauses at a screen; its URL template reads an `isOutput` variable as `${result.output.NAME}`): +`onSuccess` hops once the flow run completes, not when it pauses at a screen; its URL template reads an `isOutput` variable as `${result.output.NAME}`: ```typescript @@ -87,8 +87,6 @@ export const ConvertLeadAction = defineAction({ }); ``` -**Script-typed action**: - ```typescript import { defineAction } from '@objectstack/spec/ui'; @@ -133,13 +131,23 @@ Bodies execute **trusted** (`ctx.api` / `ctx.engine` bypass RLS/FLS). `ctx.session.positions` (absent when the caller holds none) is **not an authorization input** — ask the security service for privilege (ADR-0095). +### Refusing by code (`refusals`) + +`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, +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`. + ## Opening in a New Tab ### `openIn: 'new-tab'` -A **static** `target` URL on a `type: 'url'` action: `openIn: 'new-tab'` opens -it in a new tab, `'self'` forces in-place navigation; omitted, absolute URLs open -in a new tab and relative ones navigate in place. +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. ```typescript @@ -188,8 +196,8 @@ export const OpenInvoicePdfAction = defineAction({ ## Action Parameter Patterns -Prefer **field-backed** params (`{ field: 'email' }`): label (i18n), type, -validation, options, placeholder and widget come from the object metadata +Prefer **field-backed** params: label (i18n), type, validation, options, +placeholder and widget come from the object metadata (`widget` only while the param keeps or restates the field's `type`; a param that overrides `type` names its own `widget`); `objectOverride` borrows a field of another object, and `defaultFromRow: true` @@ -215,11 +223,12 @@ export const AddInvoiceLineAction = defineAction({ { field: 'product', objectOverride: 'invoice_line', required: true }, { field: 'quantity', objectOverride: 'invoice_line', required: true }, ], + refusals: { PRODUCT_NOT_FOUND: { message: 'Product not found.', status: 404 } }, body: { language: 'js', source: ` const product = await ctx.api.object('product').findOne({ where: { id: input.product } }); - if (!product) throw new Error('Product not found.'); + if (!product) throw { code: 'PRODUCT_NOT_FOUND' }; await ctx.api.object('invoice_line').insert({ invoice: ctx.recordId, product: input.product, quantity: input.quantity, unit_price: product.list_price,