diff --git a/.changeset/34374-action-texts-org-locale.md b/.changeset/34374-action-texts-org-locale.md new file mode 100644 index 00000000000..8b74aed6686 --- /dev/null +++ b/.changeset/34374-action-texts-org-locale.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': minor +'@objectstack/lint': minor +'@object-ui/core': patch +--- + +feat(actions): an action writes the sentences it declares in the organization's language + +Clause-②: yes (widening: a new optional authorable key `ActionSchema.texts`, and new translation keys) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-i18n/SKILL.md + +A `script` action's `js` body can now write a sentence into a record in the organization's language, the way a hook does: declare it under `texts`, keyed by a snake_case key, and ask for it by key — `texts: { email_subject: { message: 'Email: {{ subject }}', params: ['subject'] } }`, then `await ctx.text('email_subject', { subject })` where the body used to write `'Email: ' + subject`. The answer is in the organization's language, because everyone in the organization reads the record: the Localization setting (`localization.locale`) when somebody set it, else the app's declared `i18n.defaultLocale`. It is never the language of the person who ran the action. The translation is picked first, then its `{{ }}` holes are filled from `params`. The entry is the hook text's, built by the same shared factory. + +- The translation sits beside the action's other copy: `objects.._actions..texts..message` for an action bound to an object, `globalActions..texts..message` for an object-less one. `os i18n extract` scaffolds the keys and the existing coverage check counts them; `objectstack validate` refuses a translation over a key the action does not declare. +- A missing translation, or no language to pick, answers the declared sentence, and the action goes on. A Localization setting that cannot be read rejects the call. +- Only declared text is translated: a string the body builds itself is written as it is. A key `texts` does not declare is refused when the action is saved if the body asks for it literally (`ctx.text('key')`), otherwise when it runs, as a fault naming the action and the key. +- `texts` is read only for a `type: 'script'` action with a `js` body (an inline `target` function is lowered to one by `os build`); on any other action, or with no body, it is refused at save. A `flow` action's record writes are the flow's own, marked and translated there (`flows..records.…`). +- A text with `params` is compiled like a hook's: a hole over another name is refused when the action is saved, and `objectstack validate`, `compile` and the publish gate refuse a hole holding logic, an unknown formatter, an empty hole and `{{ amount | currency }}` with no code. A translation whose holes do not render at run time is dropped for the declared sentence, filled. +- Text is picked when it is written. Records already written are not changed. An action without `texts` runs exactly as before. + +`@object-ui/core` lists `texts` among the spec's declared action keys, so an action carrying them is not reported as having an unknown key; the console reads nothing new, because the body stores the sentence already picked. + +New exports: `@objectstack/spec` adds `ActionTextSchema` and the `ActionText` type (`ui`), `actionTextMessageKey` (`system`), and `ACTION_TEXT_MESSAGE_HOLE_REFUSED`, `actionTextsWithoutRunnableCode`, `undeclaredActionTextKeyAtSave` and `undeclaredActionTextAtRun` (`data`); `@objectstack/runtime` adds none. Nothing that was accepted before is refused. diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 13a22c957d2..eb9f583fe7d 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -103,7 +103,7 @@ The script sees only what the surrounding `ctx` object exposes: | `ctx.api.object(name).insert\|update\|delete` | Cross-object writes. | `api.write` | | `ctx.title()` | This record's title — the object's `nameField`, **including when it is a `formula`** (evaluated server-side against the record already in hand: no extra read over the record's own columns, one read per lookup a title such as `record.book.title + ' · ' + record.reader.name` reads through). | none | | `ctx.title('')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne` (plus the lookups that record's own title reads through). | `api.read` | -| `ctx.text('', params?)` | A sentence the hook declared under `texts`, in the **organization's** language (translated, holes filled from `params`), for a value it writes into a record. Hook bodies only. See [Writing a sentence people read](/docs/automation/hooks#writing-a-sentence-people-read--texts). | none | +| `ctx.text('', params?)` | A sentence the hook — or the `script` action — declared under `texts`, in the **organization's** language (translated, holes filled from `params`), for a value it writes into a record. Hook and action bodies; a job body has no `texts`. See [Writing a sentence people read](/docs/automation/hooks#writing-a-sentence-people-read--texts) and [Write in the organization's language](/docs/ui/actions#write-in-the-organizations-language--texts). | none | | `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` | | `ctx.log.{info,warn,error}` | Structured logging. | `log` | | `ctx.email.send({ to, subject, text })` | Sends mail through the mail service, from the configured sender, as the calling user and under the caller's organization. An action or a job body only: a hook body cannot send mail, because a message cannot be taken back if the write that runs the hook rolls back. A hook whose body is granted `email.send` is refused when it is saved, validated, built or bound, and the Console does not offer the grant on a hook. Send mail on a record change from an action, a job or a flow. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | `email.send` | diff --git a/content/docs/protocol/objectui/actions.mdx b/content/docs/protocol/objectui/actions.mdx index f52deff7279..efc5299bdf2 100644 --- a/content/docs/protocol/objectui/actions.mdx +++ b/content/docs/protocol/objectui/actions.mdx @@ -230,6 +230,7 @@ interface Action { patch?: Record; // Static field values for operation: 'update', merged under params body?: HookBody; // Inline logic for type: 'script' refusals?: Record; // Codes the js body may throw, answered with a declared sentence in the caller's locale + texts?: Record; // Sentences the js body writes into records (ctx.text), in the organization's language params?: ActionParam[]; // Inputs collected before execution submitText?: I18nLabel; // The param dialog's submit button verb (default "Confirm") cancelText?: I18nLabel; // The confirm or param dialog's dismiss button label (default "Cancel") diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 449d8e7a499..e05806f2f96 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -502,6 +502,7 @@ const result = ApiMethod.parse(data); | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | +| **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index e8e0464e67d..8a6f4058679 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1674 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1675 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 16 | 179 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1674** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **218** | **1675** | 14 protocol modules | --- @@ -385,13 +385,13 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 179 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 180 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | File | Schemas | | :--- | :--- | -| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionType`, `InlineAction` | +| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionText`, `ActionType`, `InlineAction` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | | [`bulk-action.zod.ts`](/docs/references/ui/bulk-action) | `BulkActionDef`, `BulkActionExecution`, `BulkActionOperation`, `BulkActionParam`, `BulkActionResult` | diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index f17a715bf92..e47f4742954 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -332,6 +332,7 @@ const result = MetadataBulkResultSchema.parse(data); | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | +| **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index a798e21c4e9..51ade2bcd9a 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -140,6 +140,7 @@ Translation data for a single field | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the action's `texts` declares | ### Nested Shape: `ObjectTranslationData._sections[string]` @@ -247,6 +248,7 @@ Translation data for a single object | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the action's `texts` declares | ### Nested Shape: `PlatformTranslationData.dashboards[string]` @@ -435,6 +437,7 @@ Translation data for a single object | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the action's `texts` declares | ### Nested Shape: `ServedTranslationData.dashboards[string]` @@ -686,6 +689,7 @@ Translation data for a single object | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the action's `texts` declares | ### Nested Shape: `TranslationData.dashboards[string]` @@ -906,6 +910,7 @@ Translation data for a single object | **resultDialog** | `{ title?: string; description?: string; acknowledge?: string; fields?: Record; … }` | optional | Translations for the action result dialog | | **preflight** | `{ fields?: Record; columns?: Record> }` | optional | Translations for the action preflight panel | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the action's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the action's `texts` declares | ### Nested Shape: `TranslationItem.dashboards[string]` diff --git a/content/docs/references/ui/action.mdx b/content/docs/references/ui/action.mdx index dec614aeb08..96fa5ec9c6f 100644 --- a/content/docs/references/ui/action.mdx +++ b/content/docs/references/ui/action.mdx @@ -1,7 +1,7 @@ --- title: Action schema — UI Protocol property reference navTitle: Action -description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, ActionLocation and 4 more — each property with its type, default and a TypeScript example." +description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, ActionLocation and 5 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Action schemas of the ObjectStack UI Protocol: Action, ActionAi, A ## TypeScript Usage ```typescript -import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionRefusalSchema, ActionType, InlineActionSchema } from '@objectstack/spec/ui'; -import type { Action, ActionAi, ActionLocation, ActionParam, ActionRefusal, ActionType, InlineAction } from '@objectstack/spec/ui'; +import { ActionSchema, ActionAiSchema, ActionLocationSchema, ActionParamSchema, ActionRefusalSchema, ActionTextSchema, ActionType, InlineActionSchema } from '@objectstack/spec/ui'; +import type { Action, ActionAi, ActionLocation, ActionParam, ActionRefusal, ActionText, ActionType, InlineAction } from '@objectstack/spec/ui'; // Validate data const result = ActionSchema.parse(data); @@ -40,6 +40,7 @@ const result = ActionSchema.parse(data); | **openIn** | `Enum<'self' \| 'new-tab'>` | optional | For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only). | | **body** | `{ language: 'expression'; source: string } \| { language: 'js'; source: string; capabilities?: Enum<'api.read' \| 'api.write' \| 'api.transaction' \| 'crypto.uuid' \| 'log' \| …>[]; timeoutMs?: integer; … }` | optional | Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`. An action body runs as system, and its update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. | | **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the action's js body throws: `{ message, status?, reasons?, params? }`. The body refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through objects.``._actions.``.refusals.``.message, or globalActions.``.refusals.``.message for an object-less action, ….reasons.``.message for a reason, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the body throws it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | +| **texts** | `Record` | optional | Texts the action's js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: 'script' action with a js body declares one | | **operation** | `Enum<'update'>` | optional | The declarative single-record field write, mirroring a list view's `bulkActionDefs`: `'update'` applies `patch` (merged under the collected `params`) to the current record on the data plane AS THE CALLER — never system-elevated — so the caller's permissions, the object's hooks and its validations fire as for a user edit. `type` stays at its default `'script'` (the platform action route the write is performed on); `target`/`body`/`method`/`bodyExtra` are refused beside it. `'delete'` and `'custom'` have no row-level form. | | **patch** | `Record` | optional | For `operation: 'update'` — static field values written to the current record, merged UNDER the user-supplied `params` so a fixed value can be declared without exposing it in the dialog. Written on the data plane as the caller: object permissions, hooks and validations fire as for a user edit. Refused on an action without `operation: 'update'` (it would be silently dropped). | | **execution** | `Enum<'perRecord' \| 'aggregate'>` | optional | The bulk dispatch contract this action's BODY is written for, in `bulkActionDefs`' own vocabulary: 'perRecord' = one dispatch per selected row carrying that row's `recordId` (the view's `bulkActions: ['']` bare-string form); 'aggregate' = ONE dispatch for the whole selection carrying every id in `params._selectedIds` (a `bulkActionDefs` entry with `execution: 'aggregate'`). Optional with NO default — omit it only when the body genuinely serves both. A list view wiring a declared action under the other contract is refused by `@objectstack/lint` (`action-dispatch-contract-mismatch`). | @@ -146,6 +147,13 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **reasons** | `Record` | optional | Further sentences under this same code, keyed by the snake_case reason the action throws beside the code (`{ code, reason }`): `{ message }`. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read | | **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the action throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | +### Nested Shape: `Action.texts[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the action's body writes into a record — in the source locale, translated whole through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) in the organization's language when the body asks for it (ctx.text). With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter | +| **params** | `string[]` | optional | The names this text may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the action's body passes in ctx.text(KEY, `{ NAME: value }`). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a `{{ }}` hole is refused | + ### Nested Shape: `Action.params[number]` | Property | Type | Required | Description | @@ -372,6 +380,18 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **message** | `string` | ✅ | The sentence the user reads when the action throws this reason under its code — in the source locale, translated through objects.``._actions.``.refusals.``.reasons.``.message (globalActions.``.… for an object-less action) in the caller's locale; its `{{ }}` holes follow the entry's message rule | +--- + +## ActionText + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the action's body writes into a record — in the source locale, translated whole through objects.``._actions.``.texts.``.message (globalActions.``.texts.``.message for an object-less action) in the organization's language when the body asks for it (ctx.text). With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter | +| **params** | `string[]` | optional | The names this text may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the action's body passes in ctx.text(KEY, `{ NAME: value }`). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a `{{ }}` hole is refused | + + --- ## ActionType diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index f731f2229fb..91cfda209fe 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -185,6 +185,52 @@ passes through as before, and so does a crash. `refusals` is read only for a `type: 'script'` action with a `js` body (an inline `target` function is lowered to one by `os build`); on any other action it is refused. +#### Write in the organization's language — `texts` + +A body that writes a sentence into a record — the subject of the email +activity it logs — writes it in the language the author typed, whoever reads +the record. To write it in the organization's language, declare the sentence +under `texts`, keyed by a snake_case key, and ask for it with `ctx.text` +instead of building the string — the same `texts` a +[hook declares](/docs/automation/hooks): + +```typescript +export const SendEmail = defineAction({ + name: 'send_email', + label: 'Send email', + objectName: 'crm_contact', + type: 'script', + texts: { + email_subject: { message: 'Email: {{ subject }}', params: ['subject'] }, + }, + body: { + language: 'js', + source: + "const subject = await ctx.text('email_subject', { subject: input.subject });" + + "await ctx.api.object('crm_activity').insert({ subject, contact: ctx.recordId });" + + "return { ok: true };", + capabilities: ['api.write'], + }, +}); +``` + +`ctx.text(key, params)` answers the sentence in the **organization's** +language — the Localization setting when somebody set it, else the app's +`i18n.defaultLocale` — never the language of the person who pressed the +button: the record is read by the whole organization. It picks the translation +first, then fills its `{{ }}` holes from `params`. With no translation the +declared sentence is written and the action goes on; a Localization setting +that cannot be read rejects the call. Translate it beside the action's other +copy — `objects.._actions..texts..message`, or +`globalActions..texts..message` for an action with no +`objectName`; `os i18n extract` scaffolds the keys. + +A key the action does not declare is refused: at save when the body asks for +it literally, otherwise when it runs, as a fault naming the action and the +key. A string the body builds itself is written as it is. `texts` is read only +for a `type: 'script'` action with a `js` body; on any other action it is +refused. + ### Path B: a registered handler (full TypeScript) For logic that belongs in real source files, point `target` at a handler name diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 342877ff272..c6c7e893a50 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -95,6 +95,7 @@ export default defineStack({ | Hook refusal messages | `hooks..refusals..message` — one per entry of the hook's `refusals` catalogue — and `hooks..refusals..reasons..message`, one per reason an entry declares. A hook (a `js` body or a TypeScript `handler`) refuses by code, optionally with a declared reason, and the server answers the refusal with this sentence in the caller's locale, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Hook texts | `hooks..texts..message` — one per entry of the hook's `texts`. A hook asks for the sentence with `ctx.text(key, params)` when it writes it into a record, and the server answers it in the **organization's** language (the Localization setting somebody set, else the app's `i18n.defaultLocale`), never the caller's, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Action refusal messages | `objects.._actions..refusals..message` — one per entry of the action's `refusals` catalogue — and `….refusals..reasons..message`, one per reason an entry declares; `globalActions..refusals.…` for an action with no `objectName`. A `script` action's `js` body refuses by code, and the server answers the refusal with this sentence in the caller's locale, else the declared one, on the refusal's `userMessage`. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | +| Action texts | `objects.._actions..texts..message` — one per entry of the action's `texts`; `globalActions..texts..message` for an action with no `objectName`. A `script` action's `js` body asks for the sentence with `ctx.text(key, params)` when it writes it into a record, and the server answers it in the **organization's** language (the Localization setting somebody set, else the app's `i18n.defaultLocale`), never the caller's, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Position label / description | `positions..label` / `description` — keyed by the position's `name`; overlaid on every served position, which is the list the console's position picker draws | | Permission-set label / description | `permissions..label` / `description` — the group is spelled as the stack spells the collection (`permissions[]`), keyed by the set's `name` | | Doc book title, description and section titles | `books..label` / `description` / `groups..label` — keyed by the book's `name` and each group's `key`; overlaid on every served book and on the book tree, which is what the docs sidebar draws. A doc's own title and body localize through `doc.translations` instead | diff --git a/packages/lint/src/i18n-walk.test.ts b/packages/lint/src/i18n-walk.test.ts index dfe788a4561..7350581b471 100644 --- a/packages/lint/src/i18n-walk.test.ts +++ b/packages/lint/src/i18n-walk.test.ts @@ -244,6 +244,39 @@ describe('collectExpectedEntries — answer table column labels', () => { }); }); +describe('collectExpectedEntries — an action\'s declared texts (#34374 PR2)', () => { + const texts = { email_subject: { message: 'Email: {{ subject }}', params: ['subject'] } }; + const body = { language: 'js', source: "await ctx.text('email_subject', { subject: input.subject });" }; + const entries = collectExpectedEntries({ + objects: [{ + name: 'crm_contact', + fields: {}, + actions: [{ name: 'send_email', label: 'Send email', type: 'script', body, texts }], + }], + actions: [ + { name: 'send_digest', label: 'Send digest', type: 'script', body, texts }, + { name: 'log_call', label: 'Log call', objectName: 'crm_contact', type: 'script', body, texts }, + ], + }, { warnedGroups: new Set() }); + const at = (path: string) => entries.find((e) => e.path.join('.') === path); + + it('yields objects.._actions..texts..message with the declared sentence, for an inline action', () => { + expect(at('objects.crm_contact._actions.send_email.texts.email_subject.message')).toMatchObject({ + sourceValue: 'Email: {{ subject }}', source: 'action', objectName: 'crm_contact', + }); + }); + + it('yields a top-level bound action\'s texts under its object', () => { + expect(at('objects.crm_contact._actions.log_call.texts.email_subject.message')?.sourceValue).toBe('Email: {{ subject }}'); + }); + + it('yields an object-less action\'s texts under globalActions', () => { + expect(at('globalActions.send_digest.texts.email_subject.message')).toMatchObject({ + sourceValue: 'Email: {{ subject }}', source: 'globalAction', + }); + }); +}); + describe('collectExpectedEntries — an action\'s refusal catalogue (#34273)', () => { const refusals = { NOT_DRAFT: { message: 'Only a draft invoice can be signed off.' }, diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 9063fd3a3d3..763afc1909c 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -146,6 +146,8 @@ * hooks..texts..message (#34374) * objects.._actions..refusals..message (#34273; and * globalActions..refusals..message, with `.reasons..message` under each) + * objects.._actions..texts..message (#34374 PR2; and + * globalActions..texts..message) * positions..label / .description * permissions..label / .description * books..label / .description @@ -838,6 +840,29 @@ function pushActionRefusals( } } +/** + * [#34374 PR2] Emit `.texts..message` for every text an + * action declares (`ActionSchema.texts`), seeded with the declared message, as + * {@link walkHookTexts} seeds a hook's. The action body runner reads exactly + * that key (`actionTextMessageKey`) in the organization's language when the + * body asks for the text (`ctx.text`), so each declared text is one demand, + * under the action's own root: `objects.._actions.` or + * `globalActions.`. + */ +function pushActionTexts( + out: ExpectedEntry[], + actionRoot: string[], + action: any, + kind: ExpectedEntry['source'], + objectName?: string, +): void { + const texts = action?.texts; + if (!texts || typeof texts !== 'object' || Array.isArray(texts)) return; + for (const [key, entry] of Object.entries(texts)) { + pushOptional(out, [...actionRoot, 'texts', key, 'message'], inlineText(entry?.message), kind, { objectName }); + } +} + function pushActionResultDialog( out: ExpectedEntry[], actionRoot: string[], @@ -1594,6 +1619,7 @@ export function collectExpectedEntries( pushActionResultDialog(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionPreflight(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); pushActionRefusals(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); + pushActionTexts(out, ['objects', objectName, '_actions', aname], action, 'action', objectName); } } @@ -1695,6 +1721,7 @@ export function collectExpectedEntries( pushActionResultDialog(out, root, action, kind, objectName); pushActionPreflight(out, root, action, kind, objectName); pushActionRefusals(out, root, action, kind, objectName); + pushActionTexts(out, root, action, kind, objectName); } // ── Apps + navigation ──────────────────────────────────────────── diff --git a/packages/lint/src/validate-hook-refusal-templates.test.ts b/packages/lint/src/validate-hook-refusal-templates.test.ts index 00d6d6c20bb..d959ccdcf1f 100644 --- a/packages/lint/src/validate-hook-refusal-templates.test.ts +++ b/packages/lint/src/validate-hook-refusal-templates.test.ts @@ -231,3 +231,81 @@ describe('action refusal templates over declared params (#34273)', () => { expect(gate('Paid {{ amount | currency:EUR }}.')).toEqual([]); }); }); + +describe('action text templates over declared params (#34374 PR2)', () => { + const action = (texts: Record, extra: Record = {}) => ({ + name: 'send_email', + label: 'Send email', + type: 'script', + body: { language: 'js', source: "return ctx.text('email_subject', { subject: input.subject });" }, + texts, + ...extra, + }); + const text = (message: string, params: string[] | undefined = ['subject']) => ({ + email_subject: params ? { message, params } : { message }, + }); + const stackWith = (message: string, params?: string[] | undefined) => ({ + objects: [{ name: 'crm_contact', actions: [action(text(message, params))] }], + }); + const actionIssues = (message: string, params?: string[]) => + actionRefusalTemplateIssues(stackWith(message, params), { actions: true, objects: true }); + + it.each([ + 'Email: {{ subject }}', + 'Email: {{ subject | upper }}', + 'Paid {{ subject | currency:EUR }}', + ])('CONTROL: accepts %j', (message) => { + expect(actionIssues(message)).toEqual([]); + }); + + it.each([ + ['an unknown formatter', 'Email: {{ subject | shout }}'], + ['logic', 'Email: {{ subject + 1 }}'], + ['an empty hole', 'Email: {{ }}'], + ])('refuses %s as an error at texts..message, naming the object and the action', (_label, message) => { + const issues = actionIssues(message); + expect(issues.length).toBeGreaterThan(0); + expect(issues.every((i) => i.severity === 'error')).toBe(true); + expect(issues[0]!.where).toBe("object 'crm_contact' · action 'send_email' texts.email_subject.message"); + }); + + it('refuses a currency formatter with no code, naming the code spelling', () => { + const issues = actionIssues('Paid {{ subject | currency }}'); + expect(issues).toHaveLength(1); + expect(issues[0]!.message).toContain('{{ subject | currency:EUR }}'); + }); + + it('a text with no params is not read here (the parse refuses every hole in it)', () => { + const issues = actionRefusalTemplateIssues( + { actions: [action({ email_subject: { message: 'Email {{ subject | shout }}' } })] }, + { actions: true, objects: true }, + ); + expect(issues).toEqual([]); + }); + + it('judges a text and a refusal on one action, each at its own path', () => { + const both = action(text('Email: {{ subject | shout }}'), { + refusals: { NOT_SENT: { message: 'Not sent {{ reason | shout }}.', params: ['reason'] } }, + }); + const issues = actionRefusalTemplateIssues({ actions: [both] }, { actions: true, objects: true }); + expect(issues.map((i) => i.where).sort()).toEqual([ + "stack · action 'send_email' refusals.NOT_SENT.message", + "stack · action 'send_email' texts.email_subject.message", + ]); + }); + + it('is part of the stack expression pass `objectstack validate` and `compile` run', () => { + const issues = validateStackExpressions(stackWith('Email: {{ subject | shout }}') as never); + expect(issues.some((i) => i.where.endsWith("action 'send_email' texts.email_subject.message") && i.severity === 'error')) + .toBe(true); + }); + + it('refuses an `action` write at the publish gate, and passes the CONTROL', () => { + const gate = (message: string) => + runRuntimeAuthoringRules({ type: 'action', item: action(text(message)), context: { objects: [] } }) + .errors.filter((e) => String(e.where ?? '').includes('texts.')); + const refused = gate('Paid {{ subject | currency }}'); + expect(refused.some((e) => String(e.message).includes('{{ subject | currency:EUR }}')), JSON.stringify(refused)).toBe(true); + expect(gate('Paid {{ subject | currency:EUR }}')).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index cbd5bb21828..1e40c1642ca 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -35,7 +35,9 @@ * * [#34273] An action's refusal catalogue (`ActionSchema.refusals`) is the same * entry, so {@link actionRefusalTemplateIssues} judges it by the same rules, - * on the action collections the action copy pass reads. + * on the action collections the action copy pass reads; [#34374 PR2] and an + * action's declared texts (`ActionSchema.texts`) beside it, at + * `texts..message`, as a hook's are. */ import { validateExpression } from '@objectstack/formula'; @@ -141,7 +143,8 @@ export interface ActionRefusalTemplateScope { /** * [#34273] The same findings for an action's refusal catalogue - * (`ActionSchema.refusals`, the hook catalogue's twin), across the + * (`ActionSchema.refusals`, the hook catalogue's twin) and, #34374 PR2, its + * declared texts (`ActionSchema.texts`), across the * collections `scope` names. An action declared both top-level and on its * object is judged once, at the first place it is met — the de-duplication * the action copy pass applies. @@ -155,7 +158,12 @@ export function actionRefusalTemplateIssues(stack: AnyRec, scope: ActionRefusalT const key = `${bound}:${name}`; if (seen.has(key)) return; seen.add(key); - judgeSentences(issues, `${owner} · action '${name}'`, refusalSentences(action.refusals), 'action'); + judgeSentences( + issues, + `${owner} · action '${name}'`, + [...refusalSentences(action.refusals), ...textSentences(action.texts)], + 'action', + ); }; if (scope.actions) { for (const action of recordsOf(stack.actions)) judge('stack', action); diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index f5778376d4f..0c2ca1addec 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -4312,7 +4312,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# }; type Address = 'bound' | 'global'; - type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight' | 'noRefusals'; + type Host = 'outcome' | 'dialog' | 'noDialog' | 'noParams' | 'noPreRunDialog' | 'preflight' | 'noRefusals' | 'noTexts'; /** * Which declared action a ghost is written under, per address. `noDialog` * names an action that declares no `resultDialog`: the dialog's leaves @@ -4334,6 +4334,9 @@ describe('validateTranslationReferences — keyed children of an action entry (# // [#34273] An action that declares no `refusals`, so a refusal key under // it is read by nothing (`coverageStack` gives the outcome hosts one). noRefusals: { bound: 'plain_env', global: 'mint_token' }, + // [#34374 PR2] An action that declares no `texts`, so a text key under + // it is read by nothing (`coverageStack` gives the outcome hosts some). + noTexts: { bound: 'plain_env', global: 'mint_token' }, }; type Coverage = | { kind: 'reference-checked'; host: Host; ghost: Record; suffix: string; rule: string } @@ -4447,6 +4450,13 @@ describe('validateTranslationReferences — keyed children of an action entry (# suffix: '.refusals.GHOST_CODE', rule: TRANSLATION_TARGET_UNKNOWN, }, + texts: { + kind: 'reference-checked', + host: 'noTexts', + ghost: { texts: { ghost_key: { message: 'x' } } }, + suffix: '.texts.ghost_key', + rule: TRANSLATION_TARGET_UNKNOWN, + }, }; // The global action needs a param with inline options for the options ghost. @@ -4459,6 +4469,10 @@ describe('validateTranslationReferences — keyed children of an action entry (# (stack.actions.find((a) => a.name === name) as Record).refusals = { NOT_READY: { message: 'Not ready.', reasons: { stale: { message: 'Stale.' } } }, }; + // [#34374 PR2] …and declared texts. + (stack.actions.find((a) => a.name === name) as Record).texts = { + audit_line: { message: 'Done.' }, + }; } return stack; }; @@ -4504,6 +4518,7 @@ describe('validateTranslationReferences — keyed children of an action entry (# outcomeMessages: address === 'bound' ? { archived: 'x' } : { up_to_date: 'x' }, params: { mode: { label: 'x', helpText: 'x', placeholder: 'x', options: { soft: 'x' } } }, refusals: { NOT_READY: { message: 'x', reasons: { stale: { message: 'x' } } } }, + texts: { audit_line: { message: 'x' } }, }, [dialog]: { resultDialog: { title: 'x', description: 'x', acknowledge: 'x', fields: { token: 'x' }, columns: { rows: { id: 'x' } } }, @@ -5347,3 +5362,47 @@ describe('validateTranslationReferences — action refusals (#34273)', () => { expect(findings[1].message).toContain('declares no `reasons` under that code'); }); }); + +describe('validateTranslationReferences — action texts (#34374 PR2)', () => { + const texts = { email_subject: { message: 'Email: {{ subject }}', params: ['subject'] } }; + const body = { language: 'js', source: "await ctx.text('email_subject', { subject: input.subject });" }; + const textStack = (bundle: Record) => ({ + objects: [{ name: 'crm_contact', label: 'Contact', fields: { name: { type: 'text', label: 'Name' } } }], + actions: [ + { name: 'send_email', label: 'Send email', objectName: 'crm_contact', type: 'script', body, texts }, + { name: 'send_digest', label: 'Send digest', type: 'script', body, texts }, + { name: 'plain_contact', label: 'Plain', objectName: 'crm_contact', type: 'script', target: 'plainContact' }, + ], + translations: [{ 'zh-CN': bundle }], + }); + const ON = 'translations[0]["zh-CN"].objects.crm_contact._actions'; + const GLOBAL = 'translations[0]["zh-CN"].globalActions'; + + it('CONTROL: reports nothing for declared text keys, bound and object-less', () => { + expect(validateTranslationReferences(textStack({ + objects: { crm_contact: { _actions: { send_email: { texts: { email_subject: { message: '邮件:{{ subject }}' } } } } } }, + globalActions: { send_digest: { texts: { email_subject: { message: '邮件:{{ subject }}' } } } }, + }))).toEqual([]); + }); + + it('refuses a key the action does not declare, with the nearest declared key offered, at both addresses', () => { + const findings = validateTranslationReferences(textStack({ + objects: { crm_contact: { _actions: { send_email: { texts: { email_subjct: { message: 'x' } } } } } }, + globalActions: { send_digest: { texts: { email_subjct: { message: 'x' } } } }, + })); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [TRANSLATION_TARGET_UNKNOWN, 'error', `${ON}.send_email.texts.email_subjct`], + [TRANSLATION_TARGET_UNKNOWN, 'error', `${GLOBAL}.send_digest.texts.email_subjct`], + ]); + expect(findings[0].message).toContain('a key action "send_email" does not declare under `texts`'); + expect(findings[0].message).toContain('Did you mean "email_subject"?'); + }); + + it('refuses a text key on an action that declares no `texts`', () => { + const findings = validateTranslationReferences(textStack({ + objects: { crm_contact: { _actions: { plain_contact: { texts: { any: { message: 'x' } } } } } }, + })); + expect(findings.map((f) => f.path)).toEqual([`${ON}.plain_contact.texts.any`]); + expect(findings[0].message).toContain('action "plain_contact" declares no `texts`'); + }); +}); diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index 6e0b751a24a..bed72caf306 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -2754,6 +2754,7 @@ interface ActionEntryContext { * | `submitText` | a non-empty `params` (the param dialog) | `translateAction` | * | `cancelText` | `confirmText` or a non-empty `params` (either dialog) | `translateAction` | * | `refusals.[.reasons.]` | the action's `refusals` codes (and each code's `reasons`) | `resolveActionRefusal` (#34273) | + * | `texts.` | the action's `texts` keys | `buildActionTextSurface` (#34374 PR2) | * * A dialog leaf under a DECLARED dialog is read whether or not the dialog * authors that leaf itself — the resolver overlays a translated `title` onto a @@ -2786,6 +2787,39 @@ function checkActionEntry(findings: TranslationRefFinding[], ctx: ActionEntryCon checkActionSubmitText(findings, ctx); checkActionCancelText(findings, ctx); checkActionRefusals(findings, ctx); + checkActionTexts(findings, ctx); +} + +/** + * [#34374 PR2] `texts.` — the translations of the action's declared + * texts (`ActionSchema.texts`). The action body runner + * (`buildActionTextSurface`, `@objectstack/runtime`) reads them only for a key + * the action declares, so any other key is read by nothing: the bundle cannot + * add a text, only translate one — the hook texts' rule + * (`hooks..texts.*`), in the action vocabulary. + */ +function checkActionTexts(findings: TranslationRefFinding[], ctx: ActionEntryContext): void { + const rawTexts = asRecord(isRec(ctx.rawAction) ? ctx.rawAction.texts : undefined); + if (Object.keys(rawTexts).length === 0) return; + const keys = new Set(Object.keys(asRecord(ctx.action.texts))); + for (const key of Object.keys(rawTexts)) { + if (keys.has(key)) continue; + findings.push({ + severity: TRANSLATION_TARGET_UNKNOWN_SEVERITY, + rule: TRANSLATION_TARGET_UNKNOWN, + where: `${ctx.where} · text "${key}"`, + path: `${ctx.path}.texts.${key}`, + message: + keys.size > 0 + ? `Translations are keyed to text "${key}", a key ${ctx.subject} does not declare under ` + + `\`texts\`, so nothing resolves this key.` + suggest(key, keys) + : `Translations are keyed to text "${key}", but ${ctx.subject} declares no \`texts\`, ` + + `so nothing resolves this key.`, + hint: + `Text translations are keyed by a key the action's \`texts\` declares; declare it there, ` + + `or drop the key.`, + }); + } } /** diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 1230dacc584..9964d662f26 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -274,10 +274,13 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // shows before submit) joined the accepted set, and the sample names it. // [#34273] 53 → 54: `refusals` (the action body's declared refusal // catalogue) joined the accepted set, and the sample names it. - expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(54); + // [#34374, action half] 54 → 55: `texts` (the sentences the action's + // body writes into records, in the organization's language) joined + // the accepted set, and the sample names it. + expect(Object.keys(properties).length + retiredTopLevelCount('action')).toBe(55); // A sample an author would actually address, and the one #17500's // repeater titles need a node to sit on. - for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight', 'refusals']) { + for (const key of ['name', 'label', 'objectName', 'type', 'params', 'locations', 'outcomeMessages', 'requiresMembershipReach', 'disabledReason', 'pressed', 'submitText', 'cancelText', 'overrides', 'preflight', 'refusals', 'texts']) { expect(Object.keys(properties)).toContain(key); } }); diff --git a/packages/runtime/src/sandbox/action-text.integration.test.ts b/packages/runtime/src/sandbox/action-text.integration.test.ts new file mode 100644 index 00000000000..d8092d8147c --- /dev/null +++ b/packages/runtime/src/sandbox/action-text.integration.test.ts @@ -0,0 +1,276 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34374 PR2, ruling 6913660232 option B, parameter 7] A sentence an ACTION + * writes into a record for people to read is written in the ORGANIZATION's + * language — the action half of what `hook-text.integration.test.ts` pins for + * hooks. + * + * The action declares it (`ActionSchema.texts`) and its sandboxed body asks + * for it by key — `await ctx.text('email_subject', { subject })` — and the + * runtime answers the translation at the action's own address + * (`objects.._actions..texts..message`, or + * `globalActions..texts..message` for an object-less action) in + * the organization's language (the Localization setting somebody set, else the + * app's `i18n.defaultLocale`; never the caller's), the declared sentence on a + * miss, its holes filled after. + * + * The HotCRM shape the release record names: a `send_email` script action + * that logs an activity titled `'Email: ' + subject`, here written + * `ctx.text('email_subject', { subject })`. Same wiring as the hook pin: the + * REAL `ObjectQL` + REAL `SqlDriver` (better-sqlite3) + REAL + * `QuickJSScriptRunner` behind `actionBodyRunnerFactory`, the handler + * registered and dispatched through the engine's own `registerAction` / + * `executeAction`, with the REAL in-memory `i18n` service. Every assertion + * lands on the activity row the action stored. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { createMemoryI18n } from '@objectstack/core'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { actionBodyRunnerFactory } from './body-runner.js'; +import { hookRefusalI18nReader } from './hook-refusal-catalogue.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; + +const CONTACT = { name: 'probe_text_contact', fields: { name: { type: 'text' } } }; +const ACTIVITY = { name: 'probe_text_activity', fields: { subject: { type: 'text' }, related_id: { type: 'text' } } }; + +const ACTION_NAME = 'send_email'; +const GLOBAL_KEY = 'global'; +const EN = 'Email: {{ subject }}'; +const ZH = '邮件:{{ subject }}'; +const JA = 'メール:{{ subject }}'; + +/** The HotCRM body, its `'Email: ' + subject` written as a declared text asked for by key. */ +const BODY_SOURCE = ` + var key = input.key || 'email_subject'; + var line = await ctx.text(key, { subject: input.subject }); + await ctx.api.object('${ACTIVITY.name}').insert({ subject: line, related_id: input.recordId || null }); + return { subject: line }; +`; + +const TEXTS = { email_subject: { message: EN, params: ['subject'] } }; + +const SYSTEM_READ: EngineQueryOptions = { context: { isSystem: true } }; + +/** What the `settings` service answers for `localization.locale`. */ +type SettingsAnswer = { value?: unknown; source?: string } | (() => never); + +interface StackOptions { + /** The app's declared `i18n.defaultLocale`. */ + defaultLocale?: string; + /** Translation bundles by locale. */ + bundles?: Record>; + /** What the settings service answers; absent ⇒ the host has no settings service. */ + settings?: SettingsAnswer; + /** Per-organization Localization answers, as a real settings store scopes them: an unscoped or other-organization read gets the `source: 'default'` placeholder. */ + orgSettings?: Record; + /** The action is object-less (`globalActions`) rather than bound to the contact object. */ + objectLess?: boolean; + /** The action's declared texts; absent ⇒ {@link TEXTS}, `null` ⇒ none declared. */ + texts?: Record | null; + /** Collects every `logger.warn` line the runtime writes. */ + warnings?: string[]; +} + +/** A bundle carrying `sentence` at the bound address and `globalSentence` at the object-less one. */ +function bundle(sentence: string | undefined, globalSentence?: string) { + return { + ...(sentence !== undefined + ? { objects: { [CONTACT.name]: { _actions: { [ACTION_NAME]: { texts: { email_subject: { message: sentence } } } } } } } + : {}), + ...(globalSentence !== undefined + ? { globalActions: { [ACTION_NAME]: { texts: { email_subject: { message: globalSentence } } } } } + : {}), + }; +} + +describe('#34374 PR2 — a script action writes its declared text in the organization\'s language (ctx.text)', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function reset(): Promise { + await engine?.destroy(); + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + } + + async function makeStack(options: StackOptions = {}) { + dir = mkdtempSync(join(tmpdir(), 'os-34374-action-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([CONTACT, ACTIVITY]); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(CONTACT as any, 'probe'); + engine.registry.registerObject(ACTIVITY as any, 'probe'); + + const i18n = createMemoryI18n(); + if (options.defaultLocale) i18n.setDefaultLocale(options.defaultLocale); + for (const [locale, data] of Object.entries(options.bundles ?? {})) i18n.loadTranslations(locale, data); + const asked: Array<{ tenantId?: string } | undefined> = []; + const settings = options.settings === undefined && options.orgSettings === undefined ? undefined : { + async get(_ns: string, _key: string, ctx?: { tenantId?: string }) { + asked.push(ctx); + if (options.orgSettings) { + const scoped = ctx?.tenantId ? options.orgSettings[ctx.tenantId] : undefined; + return scoped ?? { value: 'en-US', source: 'default' }; + } + const answer = options.settings!; + if (typeof answer === 'function') answer(); + return answer as { value?: unknown; source?: string }; + }, + }; + const services: Record = { i18n, ...(settings ? { settings } : {}) }; + const getService = (name: string): unknown => { + if (name in services) return services[name]; + throw new Error(`service '${name}' not registered`); + }; + const logger = { + debug: () => {}, info: () => {}, error: () => {}, + warn: (...args: unknown[]) => { options.warnings?.push(args.map(String).join(' ')); }, + }; + + const texts = options.texts === undefined ? TEXTS : options.texts ?? undefined; + const action = { + name: ACTION_NAME, + type: 'script', + ...(options.objectLess ? {} : { objectName: CONTACT.name, object: CONTACT.name }), + body: { language: 'js', source: BODY_SOURCE, capabilities: ['api.read', 'api.write'] }, + ...(texts ? { texts } : {}), + }; + const handler = actionBodyRunnerFactory(new QuickJSScriptRunner(), { + ql: engine, appId: 'probe', logger, i18n: hookRefusalI18nReader({ getService: getService as never }), getService, + })(action); + expect(handler, 'the action body must bind').toBeTypeOf('function'); + const objectKey = options.objectLess ? GLOBAL_KEY : CONTACT.name; + engine.registerAction(objectKey, ACTION_NAME, handler!, 'probe'); + return { engine, asked, objectKey }; + } + + /** + * Run the action as a caller whose own language is en-US, in organization + * `org_a` — the context the REST and MCP action doors hand a handler + * (`buildActionSession`: `session.organizationId` from the caller's + * `tenantId`) — and answer the stored activity subjects. The + * `ObjectRepository.execute` door, which passes no `session`, has its own case. + */ + async function sendEmail( + stack: { engine: ObjectQL; objectKey: string }, + params: { subject: string; key?: string }, + ): Promise { + const executionContext = { userId: 'u_probe', tenantId: 'org_a', locale: 'en-US' }; + await stack.engine.executeAction(stack.objectKey, ACTION_NAME, { + params: { ...params, recordId: 'c1' }, + session: { userId: 'u_probe', organizationId: 'org_a' }, + executionContext, + }); + const rows: any[] = await stack.engine.find(ACTIVITY.name, SYSTEM_READ); + return rows.map((r) => r.subject); + } + + it('writes the app default language\'s translation at the bound address for an en-US caller, holes filled; CONTROL: the globalActions sentence is not read', async () => { + const stack = await makeStack({ + defaultLocale: 'zh-CN', + bundles: { 'zh-CN': bundle(ZH, '(全局)邮件:{{ subject }}'), 'en-US': bundle('EN-US VARIANT {{ subject }}') }, + }); + expect(await sendEmail(stack, { subject: 'Q3 renewal' })).toEqual(['邮件:Q3 renewal']); + }, 30000); + + it('an object-less action reads `globalActions..texts..message`; CONTROL: an object\'s sentence is not read', async () => { + const stack = await makeStack({ + objectLess: true, + defaultLocale: 'zh-CN', + bundles: { 'zh-CN': bundle('(对象)邮件:{{ subject }}', ZH) }, + }); + expect(await sendEmail(stack, { subject: 'Q3 renewal' })).toEqual(['邮件:Q3 renewal']); + }, 30000); + + it('writes the language somebody SET in Localization, asked for the caller\'s organization; CONTROL: the default placeholder does not count', async () => { + const bundles = { 'zh-CN': bundle(ZH), 'ja-JP': bundle(JA) }; + const set = await makeStack({ defaultLocale: 'zh-CN', bundles, settings: { value: 'ja-JP', source: 'organization' } }); + expect(await sendEmail(set, { subject: 'Q3 renewal' })).toEqual(['メール:Q3 renewal']); + expect(set.asked).toContainEqual({ tenantId: 'org_a' }); + await reset(); + + const placeholder = await makeStack({ defaultLocale: 'zh-CN', bundles, settings: { value: 'en-US', source: 'default' } }); + expect(await sendEmail(placeholder, { subject: 'Q3 renewal' })).toEqual(['邮件:Q3 renewal']); + }, 30000); + + it('through repo.execute (tenantId, no session) writes the language SET in Localization for the caller\'s organization', async () => { + // `ObjectRepository.execute` hands the handler the caller's `tenantId` and + // an elevated `executionContext`, but no `session`: the organization is read + // off the body's own door caller (`executionContext.tenantId` first). + const stack = await makeStack({ + defaultLocale: 'zh-CN', + bundles: { 'zh-CN': bundle(ZH), 'ja-JP': bundle(JA) }, + orgSettings: { org_a: { value: 'ja-JP', source: 'organization' } }, + }); + await stack.engine + .createContext({ userId: 'u_probe', tenantId: 'org_a' }) + .object(CONTACT.name) + .execute(ACTION_NAME, { params: { subject: 'Q3 renewal', recordId: 'c1' } }); + const rows: any[] = await stack.engine.find(ACTIVITY.name, SYSTEM_READ); + expect(rows.map((r) => r.subject)).toEqual(['メール:Q3 renewal']); + expect(stack.asked).toContainEqual({ tenantId: 'org_a' }); + }, 30000); + + it('writes the declared sentence, holes filled, when the organization\'s language has no translation — and the action goes on', async () => { + const stack = await makeStack({ defaultLocale: 'fr-FR', bundles: { 'zh-CN': bundle(ZH) } }); + expect(await sendEmail(stack, { subject: 'Q3 renewal' })).toEqual(['Email: Q3 renewal']); + }, 30000); + + it('writes the declared sentence, filled, when the translation\'s holes do not render — never the braces; CONTROL: a translation that renders is written', async () => { + const warnings: string[] = []; + const broken = await makeStack({ defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle('邮件:{{ subject | shout }}') }, warnings }); + expect(await sendEmail(broken, { subject: 'Q3 renewal' })).toEqual(['Email: Q3 renewal']); + expect(warnings.some((w) => w.includes(`action '${ACTION_NAME}': the zh-CN translation of its text 'email_subject' did not render`) + && w.includes('so the declared text is written'))).toBe(true); + await reset(); + + const control = await makeStack({ defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle('邮件:{{ subject | upper }}') } }); + expect(await sendEmail(control, { subject: 'Q3 renewal' })).toEqual(['邮件:Q3 RENEWAL']); + }, 30000); + + it('answers an unregistered Localization setting as not set (the app default writes); any other settings failure refuses the action with nothing written', async () => { + const unregistered = await makeStack({ + defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) }, + settings: () => { throw Object.assign(new Error('unknown key'), { code: 'SETTINGS_UNKNOWN_KEY' }); }, + }); + expect(await sendEmail(unregistered, { subject: 'Q3 renewal' })).toEqual(['邮件:Q3 renewal']); + await reset(); + + const broken = await makeStack({ + defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) }, + settings: () => { throw Object.assign(new Error('settings store unavailable'), { code: 'SETTINGS_STORE_UNAVAILABLE' }); }, + }); + await expect(sendEmail(broken, { subject: 'Q3 renewal' })).rejects.toThrow(/settings store unavailable/); + expect(await broken.engine.find(ACTIVITY.name, SYSTEM_READ)).toEqual([]); + }, 30000); + + it('refuses a key the action does not declare, naming the action and the key, with nothing written', async () => { + const stack = await makeStack({ defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) } }); + await expect(sendEmail(stack, { subject: 'Q3 renewal', key: 'email_body' })).rejects.toThrow( + /action 'send_email' asked for text 'email_body'.*declared: 'email_subject'/, + ); + expect(await stack.engine.find(ACTIVITY.name, SYSTEM_READ)).toEqual([]); + }, 30000); + + it('refuses ctx.text on an action that declares no texts, naming none declared', async () => { + const stack = await makeStack({ defaultLocale: 'zh-CN', texts: null }); + await expect(sendEmail(stack, { subject: 'Q3 renewal' })).rejects.toThrow( + /action 'send_email' asked for text 'email_subject'.*declared: none/, + ); + }, 30000); +}); diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index c8d38918869..e659821e3d3 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -83,7 +83,7 @@ import { type HookRefusalI18nSource, } from './hook-refusal-catalogue.js'; import { isRelayedSandboxRefusal } from './quickjs-runner.js'; -import { buildHookTextSurface } from './hook-text.js'; +import { buildActionTextSurface, buildHookTextSurface } from './hook-text.js'; import { buildBodyDoors, callerScopeOf, type BodyDoorCaller } from './body-doors.js'; import { deriveHookApi, openTransactionKind, seedHookUnreadMembership, seedHookUserGrants } from '@objectstack/objectql'; @@ -608,7 +608,16 @@ export function hookBodyRunnerFactory( export function actionBodyRunnerFactory( runner: ScriptRunner, opts: FactoryOptions, -): (action: { name: string; body?: unknown; object?: string; type?: string; timeoutMs?: number; refusals?: unknown }) => +): (action: { + name: string; + body?: unknown; + object?: string; + objectName?: string; + type?: string; + timeoutMs?: number; + refusals?: unknown; + texts?: unknown; +}) => | ((actionCtx: any) => Promise) | undefined { return (action) => { @@ -669,16 +678,23 @@ export function actionBodyRunnerFactory( // the body runs and before its sandbox context is built. const subjectRefusal = actionSubjectRecordRefusal(actionCtx, action); if (subjectRefusal) throw subjectRefusal; + const doorCaller = actionDoorCaller(actionCtx); const sandboxCtx = buildActionSandboxContext( actionCtx, opts.ql, buildBodyLogSurface(opts, { kind: 'action', name: action.name }), + // [#34374 PR2] The action's declared texts, in the organization's + // language — the hook body's `ctx.text`, built by the same core — for + // the door caller's organization, so every action door answers alike. + buildActionTextSurface(action, doorCaller.organizationId, { + i18n: opts.i18n, getService: opts.getService, logger: opts.logger, + }), ); installBodyDoors( sandboxCtx, opts, { kind: 'action', name: action.name }, - actionDoorCaller(actionCtx), + doorCaller, actionCtx?.executionContext?.transaction, ); try { @@ -1565,7 +1581,8 @@ function buildSandboxContext( // sites; widening the accessor to it is a separate capability call and is // deliberately not taken here — the ruling names hook bodies. title, - // [#34374] Hook face only: the hook's declared texts, answered in the + // [#34374] The hook's declared texts (the action face carries its own, + // #34374 PR2, `buildActionSandboxContext`), answered in the // organization's language (`hook-text.ts`). ...(text ? { text } : {}), // [#11552] Hook face only, both of them: an action is never one of N @@ -1615,6 +1632,7 @@ function buildActionSandboxContext( actionCtx: any, ql: any, log: ScriptContext['log'], + text?: ScriptContext['text'], ): ScriptContext { // Action ctx convention (mirrors http-dispatcher.ts): // { record, params, recordId, user, session, engine, services, ... } @@ -1659,6 +1677,9 @@ function buildActionSandboxContext( // [#7448] Same removal as the hook face: neither action-context assembly // site (`../domains/actions.ts`, `../action-execution.ts`) writes `logger`. log, + // [#34374 PR2] The action's declared texts, answered in the + // organization's language (`hook-text.ts` `buildActionTextSurface`). + ...(text ? { text } : {}), crypto: globalThis.crypto, }; } diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index b4af045aa5f..3bf0e07986d 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -170,12 +170,20 @@ export interface ActionRefusalDeclaration { refusals?: unknown; } +/** + * The action's OWN object — `undefined` for an object-less action — read by + * the one owner-key ladder (`objectName`, then `object`, else object-less), + * never re-spelled here. Shared with an action's declared texts (#34374 PR2, + * `hook-text.ts`), so a refusal and a text of one action read one address. + */ +export function actionOwnObject(action: Pick): string | undefined { + const ownerKey = standaloneActionOwnerKey(action); + return isObjectLessActionKey(ownerKey) ? undefined : ownerKey; +} + function actionOwner(action: ActionRefusalDeclaration): RefusalOwner { const name = String(action.name); - // The action's OWN object, read by the one owner-key ladder - // (`objectName`, then `object`, else object-less) — never re-spelled here. - const ownerKey = standaloneActionOwnerKey(action); - const object = isObjectLessActionKey(ownerKey) ? undefined : ownerKey; + const object = actionOwnObject(action); return { label: `action '${name}'`, messageKey: (code, reason) => actionRefusalMessageKey(object, name, code, reason), diff --git a/packages/runtime/src/sandbox/hook-text.ts b/packages/runtime/src/sandbox/hook-text.ts index 89cdddac024..5ee3dc81585 100644 --- a/packages/runtime/src/sandbox/hook-text.ts +++ b/packages/runtime/src/sandbox/hook-text.ts @@ -33,13 +33,27 @@ * One answer on every path a hook runs on: the sandboxed body (installed on the * VM's `ctx.text` by `installCtx`) and the in-process seam a `handler` runs * through (`withInProcessHookTitle`). + * + * [#34374 PR2] And one answer for an ACTION's declared texts + * (`ActionSchema.texts`), through {@link buildActionTextSurface}: the same + * language, pick, fill and fallback, the translation read at the action's own + * address (`actionTextMessageKey` — `objects.._actions..texts..message`, + * or `globalActions..…` for an object-less action, the object read by + * the one owner-key ladder the action's refusals read), the organization the + * body's door caller's (`executionContext.tenantId`, else `session.organizationId`), + * and an undeclared key refused as + * a fault naming the action (`undeclaredActionTextAtRun`). Only a `script` + * action's sandboxed `js` body runs code of its own (`actionBodyRunnerFactory`), + * so that is the one path it is installed on. Both are one function, + * {@link buildDeclaredTextSurface}, parameterised by the owner. */ import type { Hook } from '@objectstack/spec/data'; -import { undeclaredHookTextAtRun } from '@objectstack/spec/data'; -import { hookTextMessageKey } from '@objectstack/spec/system'; +import { undeclaredActionTextAtRun, undeclaredHookTextAtRun } from '@objectstack/spec/data'; +import { actionTextMessageKey, hookTextMessageKey } from '@objectstack/spec/system'; import { readOrganizationTextLocale } from '@objectstack/core'; import { + actionOwnObject, negotiatedLocale, renderHookTemplate, type HookRefusalI18nService, @@ -47,7 +61,7 @@ import { } from './hook-refusal-catalogue.js'; import { SandboxError } from './quickjs-runner.js'; -/** One declared text, as the hook holds it. */ +/** One declared text, as the declaration holds it. */ interface DeclaredText { message: string; params?: string[]; @@ -56,7 +70,7 @@ interface DeclaredText { /** What `ctx.text(key, params?)` is answered with. */ export type HookTextSurface = (key: string, params?: Record) => Promise; -/** What {@link buildHookTextSurface} reads its services through. */ +/** What {@link buildHookTextSurface} and {@link buildActionTextSurface} read their services through. */ export interface HookTextOptions { /** The `i18n` service a declared text is translated through, read at call time. */ i18n?: HookRefusalI18nSource; @@ -65,15 +79,27 @@ export interface HookTextOptions { logger?: { warn?: (...args: any[]) => void }; } -/** The hook's declared texts, or `undefined` when it declares none. */ -function textsOf(hook: Pick): Record | undefined { - const texts = (hook as { texts?: unknown }).texts; +/** + * [#34374 PR2] The declaration a text catalogue sits on — a hook, or an + * action — as the shared answer needs it: its label for the log lines, the + * key its translations are read at, and the run-time fault sentence. + */ +interface TextOwner { + /** `hook 'NAME'` / `action 'NAME'`, for the log lines. */ + label: string; + messageKey(key: string): string; + undeclaredAtRun(key: string, declared: readonly string[]): string; +} + +/** The declaration's declared texts, or `undefined` when it declares none. */ +function textsOf(declaration: { texts?: unknown }): Record | undefined { + const texts = declaration.texts; return texts && typeof texts === 'object' ? (texts as Record) : undefined; } /** The translation of a declared text in `locale`, or `undefined` when none is picked. */ function pickTranslatedText( - hookName: string, + owner: TextOwner, key: string, locale: string, i18n: HookRefusalI18nSource | undefined, @@ -86,14 +112,14 @@ function pickTranslatedText( return undefined; } if (!service || typeof service.t !== 'function') return undefined; - const translationKey = hookTextMessageKey(hookName, key); + const translationKey = owner.messageKey(key); try { const translated = service.t(translationKey, negotiatedLocale(service, locale)); // II18nService echoes the key back on a miss. if (typeof translated === 'string' && translated.trim().length > 0 && translated !== translationKey) return translated; } catch (err: unknown) { logger?.warn?.( - `[BodyRunner] hook '${hookName}': the i18n service threw reading '${translationKey}' ` + `[BodyRunner] ${owner.label}: the i18n service threw reading '${translationKey}' ` + `(${err instanceof Error ? err.message : String(err)}), so the text is written as declared.`, ); } @@ -101,28 +127,25 @@ function pickTranslatedText( } /** - * Build `ctx.text(key, params?)` for one hook invocation. The organization is - * the hook context's `session.organizationId`; a write with none asks the - * settings service with no scope (its own reach), as the flow record write does. + * Build `ctx.text(key, params?)` for one invocation of a declaration that + * holds `texts`, in `organizationId`'s language — each face resolves its own + * organization; a call with none asks the settings service with no scope (its + * own reach), as the flow record write does. */ -export function buildHookTextSurface( - hook: Pick, - engineCtx: { session?: { organizationId?: unknown } } | undefined, - opts: HookTextOptions = {}, +function buildDeclaredTextSurface( + owner: TextOwner, + declaration: { texts?: unknown }, + organizationId: string | undefined, + opts: HookTextOptions, ): HookTextSurface { - const hookName = String(hook.name); return async (key: string, params?: Record): Promise => { - const texts = textsOf(hook); + const texts = textsOf(declaration); const entry = texts && Object.prototype.hasOwnProperty.call(texts, key) ? texts[key] : undefined; if (!entry || typeof entry.message !== 'string') { - throw new SandboxError(undeclaredHookTextAtRun(hookName, String(key), Object.keys(texts ?? {}))); + throw new SandboxError(owner.undeclaredAtRun(String(key), Object.keys(texts ?? {}))); } - const organizationId = engineCtx?.session?.organizationId; - const locale = await readOrganizationTextLocale( - opts.getService, - typeof organizationId === 'string' && organizationId.length > 0 ? organizationId : undefined, - ); - const translated = locale ? pickTranslatedText(hookName, key, locale, opts.i18n, opts.logger) : undefined; + const locale = await readOrganizationTextLocale(opts.getService, organizationId); + const translated = locale ? pickTranslatedText(owner, key, locale, opts.i18n, opts.logger) : undefined; const declared = Array.isArray(entry.params) ? entry.params : []; if (declared.length === 0) return translated ?? entry.message; // A translation whose holes do not render falls back to the declared @@ -131,18 +154,79 @@ export function buildHookTextSurface( const filled = renderHookTemplate(translated, declared, params); if (filled.ok) return filled.value; opts.logger?.warn?.( - `[BodyRunner] hook '${hookName}': the ${locale} translation of its text '${key}' did not render ` + `[BodyRunner] ${owner.label}: the ${locale} translation of its text '${key}' did not render ` + `(${filled.error}), so the declared text is written.`, ); } const filled = renderHookTemplate(entry.message, declared, params); if (filled.ok) return filled.value; - // Only reachable for a hook that skipped the compile check (`objectstack - // validate`, `compile`, the publish gate refuse such a sentence). + // Only reachable for a declaration that skipped the compile check + // (`objectstack validate`, `compile`, the publish gate refuse such a sentence). opts.logger?.warn?.( - `[BodyRunner] hook '${hookName}': its declared text '${key}' did not render (${filled.error}), ` + `[BodyRunner] ${owner.label}: its declared text '${key}' did not render (${filled.error}), ` + 'so it is written unfilled, holes and all.', ); return entry.message; }; } + +/** + * Build `ctx.text(key, params?)` for one hook invocation. The organization is + * the hook context's `session.organizationId`; a write with none asks the + * settings service with no scope (its own reach), as the flow record write does. + */ +export function buildHookTextSurface( + hook: Pick, + engineCtx: { session?: { organizationId?: unknown } } | undefined, + opts: HookTextOptions = {}, +): HookTextSurface { + const hookName = String(hook.name); + const owner: TextOwner = { + label: `hook '${hookName}'`, + messageKey: (key) => hookTextMessageKey(hookName, key), + undeclaredAtRun: (key, declared) => undeclaredHookTextAtRun(hookName, key, declared), + }; + const organizationId = engineCtx?.session?.organizationId; + return buildDeclaredTextSurface( + owner, + hook, + typeof organizationId === 'string' && organizationId.length > 0 ? organizationId : undefined, + opts, + ); +} + +/** [#34374 PR2] An action as its declared texts read it: its name, its OWN object (absent: object-less), its texts. */ +export interface ActionTextDeclaration { + name: string; + /** The object the action is declared on (`ActionSchema.objectName`). */ + objectName?: string; + /** The object that declares it inline, as the bundle collector stamps it. */ + object?: string; + texts?: unknown; +} + +/** + * [#34374 PR2] Build `ctx.text(key, params?)` for one invocation of an + * action's sandboxed body, in `organizationId`'s language. The caller passes + * the body's own door caller's organization (`actionDoorCaller` in + * `body-runner.ts`: `executionContext.tenantId`, else `session.organizationId`) + * — the one reading every action door answers, `ObjectRepository.execute` + * included, which hands the handler a `tenantId` and no `session`. The + * translation is read at the action's own address, never the object a caller + * routed it under, so a bound action never reads `globalActions` and an + * object-less one never reads an object's group. + */ +export function buildActionTextSurface( + action: ActionTextDeclaration, + organizationId: string | undefined, + opts: HookTextOptions = {}, +): HookTextSurface { + const actionName = String(action.name); + const object = actionOwnObject(action); + const owner: TextOwner = { + label: `action '${actionName}'`, + messageKey: (key) => actionTextMessageKey(object, actionName, key), + undeclaredAtRun: (key, declared) => undeclaredActionTextAtRun(actionName, key, declared), + }; + return buildDeclaredTextSurface(owner, action, organizationId, opts); +} diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index 571aa67e747..d6969cd443d 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -1045,7 +1045,8 @@ export class QuickJSScriptRunner implements ScriptRunner { // ── [#34374] `ctx.text(key, params?)` — a declared text, in the // organization's language ──────────────────────────────────────────────── // - // Installed when the host built the seam (hook bodies, `hook-text.ts`). The + // Installed when the host built the seam (hook bodies and, #34374 PR2, + // action bodies — `hook-text.ts`). The // same deferred-promise pump as `title`, never `newAsyncifiedFunction`, for // the same reason: a body awaits it beside `ctx.api` calls. No capability: // it reads no record, and the language it reads is the platform's. diff --git a/packages/runtime/src/sandbox/script-runner.ts b/packages/runtime/src/sandbox/script-runner.ts index 452958aff6c..404db3f8b56 100644 --- a/packages/runtime/src/sandbox/script-runner.ts +++ b/packages/runtime/src/sandbox/script-runner.ts @@ -422,7 +422,10 @@ export interface ScriptContext { title?: (field: string | undefined, api: unknown) => Promise; /** * [#34374, ruling 6913660232 parameter 7] `ctx.text(key, params?)` for the - * HOOK face — a sentence the hook declared under `HookSchema.texts`, answered + * HOOK face and (#34374 PR2) the ACTION face — a sentence the hook declared + * under `HookSchema.texts` (or the action under `ActionSchema.texts`, read at + * `objects.._actions..texts..message` / + * `globalActions..texts..message`), answered * in the ORGANIZATION's language (translated `hooks..texts..message` * first, the declared message on a miss, its `{{ }}` holes filled from * `params` after). Built per invocation by `buildHookTextSurface` diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 0097b3131e6..845847c81c9 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -5,6 +5,7 @@ "ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", + "ACTION_TEXT_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES (const)", "AGGREGATION_ROWS (const)", @@ -913,6 +914,7 @@ "ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody (function)", + "actionTextsWithoutRunnableCode (function)", "aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason (function)", @@ -1126,6 +1128,8 @@ "undeclaredActionRefusalCodeAtSave (function)", "undeclaredActionRefusalReasonAtRun (function)", "undeclaredActionRefusalReasonAtSave (function)", + "undeclaredActionTextAtRun (function)", + "undeclaredActionTextKeyAtSave (function)", "undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun (function)", diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index fb331ccc315..be3cbbeaa1b 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -853,6 +853,7 @@ "WorkerStats (type)", "WorkerStatsSchema (const)", "actionRefusalMessageKey (function)", + "actionTextMessageKey (function)", "audienceAllows (function)", "audiencePermitsSelfRegistration (function)", "authorisesIrreversibleAction (function)", diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index d9d95241a60..fb48dd45051 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -45,6 +45,8 @@ "ActionSchema (const)", "ActionSession (type)", "ActionSessionSchema (const)", + "ActionText (type)", + "ActionTextSchema (const)", "ActionType (const)", "ActionType (type)", "AddRecordConfig (type)", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 084e7bae6b9..4778370ac4b 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -52,6 +52,7 @@ "ui/Action:submitText", "ui/Action:successMessage", "ui/Action:target", + "ui/Action:texts", "ui/Action:type", "ui/Action:undoable", "ui/Action:variant", @@ -169,6 +170,8 @@ "ui/ActionSession:positions", "ui/ActionSession:roles", "ui/ActionSession:userId", + "ui/ActionText:message", + "ui/ActionText:params", "ui/AddRecordConfig:enabled", "ui/AddRecordConfig:formView [RETIRED]", "ui/AddRecordConfig:mode [RETIRED]", diff --git a/packages/spec/declaration-map/ui.json b/packages/spec/declaration-map/ui.json index cd76aad6299..930815ee0f9 100644 --- a/packages/spec/declaration-map/ui.json +++ b/packages/spec/declaration-map/ui.json @@ -24,6 +24,8 @@ "ActionSchema": "ui/Action", "ActionSession": "ui/ActionSession", "ActionSessionSchema": "ui/ActionSession", + "ActionText": "ui/ActionText", + "ActionTextSchema": "ui/ActionText", "ActionType": "ui/ActionType", "AddRecordConfig": "ui/AddRecordConfig", "AddRecordConfigSchema": "ui/AddRecordConfig", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 828622a8aae..0f4c8408979 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 270, - "droppedRefinementSites": 1135, + "publishedSchemasWithDroppedRefinements": 271, + "droppedRefinementSites": 1148, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -108,6 +108,7 @@ "manifest.actions.element.in.preflight.fields.element", "manifest.actions.element.in.refusals.valueType", "manifest.actions.element.in.resultDialog.fields.element", + "manifest.actions.element.in.texts.valueType", "manifest.agents.element.memory", "manifest.agents.element.structuredOutput.schema", "manifest.analyticsCubes.element.measures.valueType", @@ -294,6 +295,7 @@ "data.options[1].manifest.actions.element.in.preflight.fields.element", "data.options[1].manifest.actions.element.in.refusals.valueType", "data.options[1].manifest.actions.element.in.resultDialog.fields.element", + "data.options[1].manifest.actions.element.in.texts.valueType", "data.options[1].manifest.agents.element.memory", "data.options[1].manifest.agents.element.structuredOutput.schema", "data.options[1].manifest.analyticsCubes.element.measures.valueType", @@ -448,6 +450,7 @@ "options[1].manifest.actions.element.in.preflight.fields.element", "options[1].manifest.actions.element.in.refusals.valueType", "options[1].manifest.actions.element.in.resultDialog.fields.element", + "options[1].manifest.actions.element.in.texts.valueType", "options[1].manifest.agents.element.memory", "options[1].manifest.agents.element.structuredOutput.schema", "options[1].manifest.analyticsCubes.element.measures.valueType", @@ -541,6 +544,7 @@ "data.packages.element.options[1].manifest.actions.element.in.preflight.fields.element", "data.packages.element.options[1].manifest.actions.element.in.refusals.valueType", "data.packages.element.options[1].manifest.actions.element.in.resultDialog.fields.element", + "data.packages.element.options[1].manifest.actions.element.in.texts.valueType", "data.packages.element.options[1].manifest.agents.element.memory", "data.packages.element.options[1].manifest.agents.element.structuredOutput.schema", "data.packages.element.options[1].manifest.analyticsCubes.element.measures.valueType", @@ -631,7 +635,8 @@ "data.actions.element.in.params.element.in", "data.actions.element.in.preflight.fields.element", "data.actions.element.in.refusals.valueType", - "data.actions.element.in.resultDialog.fields.element" + "data.actions.element.in.resultDialog.fields.element", + "data.actions.element.in.texts.valueType" ] }, "api/ObjectDefinitionResponse": { @@ -644,6 +649,7 @@ "data.actions.element.in.preflight.fields.element", "data.actions.element.in.refusals.valueType", "data.actions.element.in.resultDialog.fields.element", + "data.actions.element.in.texts.valueType", "data.defaultRowScope", "data.fieldGroups", "data.fields.out.valueType", @@ -1156,6 +1162,7 @@ "actions.element.in.preflight.fields.element", "actions.element.in.refusals.valueType", "actions.element.in.resultDialog.fields.element", + "actions.element.in.texts.valueType", "defaultRowScope", "fieldGroups", "fields.out.valueType", @@ -1398,7 +1405,8 @@ "actions.element.in.params.element.in", "actions.element.in.preflight.fields.element", "actions.element.in.refusals.valueType", - "actions.element.in.resultDialog.fields.element" + "actions.element.in.resultDialog.fields.element", + "actions.element.in.texts.valueType" ] }, "kernel/OpsDomainModule": { @@ -1525,6 +1533,7 @@ "operations.element.options[3].object.actions.element.in.preflight.fields.element", "operations.element.options[3].object.actions.element.in.refusals.valueType", "operations.element.options[3].object.actions.element.in.resultDialog.fields.element", + "operations.element.options[3].object.actions.element.in.texts.valueType", "operations.element.options[3].object.defaultRowScope", "operations.element.options[3].object.fieldGroups", "operations.element.options[3].object.fields.out.valueType", @@ -1552,6 +1561,7 @@ "object.actions.element.in.preflight.fields.element", "object.actions.element.in.refusals.valueType", "object.actions.element.in.resultDialog.fields.element", + "object.actions.element.in.texts.valueType", "object.defaultRowScope", "object.fieldGroups", "object.fields.out.valueType", @@ -1611,6 +1621,7 @@ "options[3].object.actions.element.in.preflight.fields.element", "options[3].object.actions.element.in.refusals.valueType", "options[3].object.actions.element.in.resultDialog.fields.element", + "options[3].object.actions.element.in.texts.valueType", "options[3].object.defaultRowScope", "options[3].object.fieldGroups", "options[3].object.fields.out.valueType", @@ -1749,7 +1760,8 @@ "in.params.element.in", "in.preflight.fields.element", "in.refusals.valueType", - "in.resultDialog.fields.element" + "in.resultDialog.fields.element", + "in.texts.valueType" ] }, "ui/ActionAi": { @@ -2222,6 +2234,11 @@ "sites": [ "" ] + }, + "ui/ActionText": { + "sites": [ + "" + ] } } } diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index b57563a62af..bf1675ef00f 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -5,6 +5,7 @@ "ACCEPTED_FILTER_COMPARAND_TYPES": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", + "ACTION_TEXT_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#ACTION_TEXT_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY": "src/data/aggregate-field-type-compatibility.ts#AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES": "src/data/aggregation-conformance.ts#AGGREGATION_CASES (const)", "AGGREGATION_ROWS": "src/data/aggregation-conformance.ts#AGGREGATION_ROWS (const)", @@ -899,6 +900,7 @@ "ValueShapeFieldDef": "src/data/field-value.zod.ts#ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase": "src/data/pagination-conformance.ts#ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#actionRefusalsWithoutSandboxedBody (function)", + "actionTextsWithoutRunnableCode": "src/data/hook-refusal-codes.ts#actionTextsWithoutRunnableCode (function)", "aiReadExposureRefusal": "src/data/ai-read-exposure.ts#aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage": "src/data/analytics.zod.ts#analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason": "src/data/api-derivation.ts#apiExposureDenialReason (function)", @@ -1112,6 +1114,8 @@ "undeclaredActionRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalCodeAtSave (function)", "undeclaredActionRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtRun (function)", "undeclaredActionRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtSave (function)", + "undeclaredActionTextAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionTextAtRun (function)", + "undeclaredActionTextKeyAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionTextKeyAtSave (function)", "undeclaredHookRefusalAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtRun (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index c1295d32e16..a4d22ecc43a 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -813,6 +813,7 @@ "WorkerStats": "src/system/worker.zod.ts#WorkerStats (type)", "WorkerStatsSchema": "src/system/worker.zod.ts#WorkerStatsSchema (const)", "actionRefusalMessageKey": "src/system/i18n-resolver.ts#actionRefusalMessageKey (function)", + "actionTextMessageKey": "src/system/i18n-resolver.ts#actionTextMessageKey (function)", "audienceAllows": "src/system/book.zod.ts#audienceAllows (function)", "audiencePermitsSelfRegistration": "src/system/auth-config.zod.ts#audiencePermitsSelfRegistration (function)", "authorisesIrreversibleAction": "src/system/migration.zod.ts#authorisesIrreversibleAction (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 1e5d15a72c3..2c17987d2ac 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -44,6 +44,8 @@ "ActionSchema": "src/ui/action.zod.ts#ActionSchema (const)", "ActionSession": "src/ui/action-params.zod.ts#ActionSession (type)", "ActionSessionSchema": "src/ui/action-params.zod.ts#ActionSessionSchema (const)", + "ActionText": "src/ui/action.zod.ts#ActionText (type)", + "ActionTextSchema": "src/ui/action.zod.ts#ActionTextSchema (const)", "ActionType": "src/ui/action.zod.ts#ActionType (type)", "AddRecordConfig": "src/ui/view.zod.ts#AddRecordConfig (type)", "AddRecordConfigParsed": "src/ui/view.zod.ts#AddRecordConfigParsed (type)", diff --git a/packages/spec/json-schema.manifest/ui.json b/packages/spec/json-schema.manifest/ui.json index 2a8ec8ea85d..af83edb6c59 100644 --- a/packages/spec/json-schema.manifest/ui.json +++ b/packages/spec/json-schema.manifest/ui.json @@ -13,6 +13,7 @@ "ui/ActionParam", "ui/ActionRefusal", "ui/ActionSession", + "ui/ActionText", "ui/ActionType", "ui/AddRecordConfig", "ui/App", diff --git a/packages/spec/liveness/action.json b/packages/spec/liveness/action.json index 3a800d610d3..e8cc93ab71e 100644 --- a/packages/spec/liveness/action.json +++ b/packages/spec/liveness/action.json @@ -134,6 +134,29 @@ } } }, + "texts": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildActionTextSurface (the one reader: `ctx.text(key, params)` on a script action's sandboxed body answers a declared text in the organization's language, and a key the action does not declare as a fault naming the action and the key); packages/runtime/src/sandbox/body-runner.ts#actionBodyRunnerFactory (builds it for every action body invocation and hands it to the body's sandbox context); packages/runtime/src/sandbox/quickjs-runner.ts#installCtx (wires it onto the VM's `ctx.text`)", + "producer": "packages/runtime/src/app-plugin.ts#collectBundleActions and packages/runtime/src/app-artifact-handlers.ts#bindAppArtifactHandlers (hand the AUTHORED action, `texts` included, to the body runner factory); packages/spec/src/ui/action.zod.ts#refuseUndeclaredLiteralActionTextKey (refuses at save `texts` on an action that runs no js body, and a key the body asks for literally that `texts` does not declare)", + "note": "[#34374, action half; ruling 6913660232 parameter 7] The hook texts' twin (`HookSchema.texts`), seeded `live` with its reader in one change (Prime Directive 10): the key, the action body runner that answers it, the translation address (`objects.._actions..texts..message` / `globalActions..texts..message`), `objectstack validate`'s key check and the i18n coverage walk. One entry shape for both (`data/declared-entry.zod.ts`) and one run-time answer (`hook-text.ts`). Never the caller's language (parameter 2); a missing translation writes the declared sentence (parameter 5); an unreadable Localization setting rejects the call. Only a `type: 'script'` action's js body runs code of its own, so that is the one path it is served on. DRILLED to the entry's two keys: the entry face is closed.", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildActionTextSurface (the sentence `ctx.text` answers: `actionTextMessageKey` — `objects.._actions..texts..message`, or `globalActions..texts..message` for an object-less action — picked through the `i18n` service in the organization's language, `readOrganizationTextLocale`, negotiated by `resolveBundleLocale`, else the declared `message`)" + }, + "params": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#renderHookTemplate (fills the picked sentence's `{{ NAME }}` holes from the call's `params` through the formula template engine, the declared names alone in scope); packages/runtime/src/sandbox/hook-text.ts#buildActionTextSurface (fills an entry that declares `params`; one that declares none stays plain text)", + "producer": "packages/spec/src/data/declared-entry.zod.ts#declaredTextEntrySchema (judges the message's holes against the declared names at save)" + } + } + }, "params": { "status": "live", "verifiedAt": "2026-09-15", diff --git a/packages/spec/liveness/state-counts/action.md b/packages/spec/liveness/state-counts/action.md index be97fdd5c8b..f329b814cef 100644 --- a/packages/spec/liveness/state-counts/action.md +++ b/packages/spec/liveness/state-counts/action.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `action` | 86 | 0 | 0 | 1 | 2 | 89 | +| `action` | 88 | 0 | 0 | 1 | 2 | 91 | diff --git a/packages/spec/src/data/declared-entry.zod.ts b/packages/spec/src/data/declared-entry.zod.ts index 67f4dfc14f7..eec8092e3bd 100644 --- a/packages/spec/src/data/declared-entry.zod.ts +++ b/packages/spec/src/data/declared-entry.zod.ts @@ -10,8 +10,9 @@ * (#34273), keyed by code: `{ message, status?, reasons?, params? }`, read * in the CALLER's locale when the code is thrown; * - a **text** entry — `HookSchema.texts` (#34374, ruling 6913660232 - * parameter 7), keyed by snake_case key: `{ message, params? }`, read in - * the ORGANIZATION's language when the code asks for it (`ctx.text`). + * parameter 7) and `ActionSchema.texts` (#34374 PR2), keyed by snake_case + * key: `{ message, params? }`, read in the ORGANIZATION's language when the + * code asks for it (`ctx.text`). * * Both are built from the same core so they cannot drift: `message` (a * trimmed, non-empty sentence), `params` (identifiers, each declared once), @@ -30,7 +31,8 @@ * * Not on any barrel: each entry schema is published by the declaration that * carries it — {@link HookSchema}'s module exports `HookRefusalSchema` and - * `HookTextSchema`, `ui/action.zod.ts` exports `ActionRefusalSchema`. + * `HookTextSchema`, `ui/action.zod.ts` exports `ActionRefusalSchema` and + * `ActionTextSchema`. */ import { z } from 'zod'; @@ -38,6 +40,7 @@ import { lazySchema } from '../shared/lazy-schema'; import { strictObject } from '../shared/strict-object'; import { ACTION_REFUSAL_MESSAGE_HOLE_REFUSED, + ACTION_TEXT_MESSAGE_HOLE_REFUSED, HOOK_REFUSAL_MESSAGE_HOLE_REFUSED, HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, HOOK_REFUSAL_PARAM_PATTERN, @@ -271,10 +274,10 @@ export function declaredRefusalEntrySchema(subject: DeclaredRefusalSubject) { // ── Text entries ───────────────────────────────────────────────────────────── /** - * The declarations a text catalogue sits on. `hook` today (#34374 PR1); the - * action half of #34374 adds its row to {@link TEXT_WORDS}. + * The declarations a text catalogue sits on: `hook` (#34374 PR1) and `action` + * (#34374 PR2), one row each in {@link TEXT_WORDS}. */ -export type DeclaredTextSubject = 'hook'; +export type DeclaredTextSubject = 'hook' | 'action'; /** What a text entry's text says about its subject — each a whole sentence, so a row reads as it publishes. */ interface TextWords { @@ -311,6 +314,26 @@ const TEXT_WORDS: Record = { + '(os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused', rule: { slot: 'A hook text `message`', holeRefused: HOOK_TEXT_MESSAGE_HOLE_REFUSED }, }, + action: { + surface: 'this action text', + localeGuidance: + 'An action text has no language of its own — the runtime picks the organization\'s language. Write the sentence ' + + 'in the source locale in `message` and translate it through `objects.OBJ._actions.ACT.texts.KEY.message` ' + + '(`globalActions.ACT.texts.KEY.message` for an object-less action).', + messageDescribe: + 'The sentence the action\'s body writes into a record — in the source locale, translated whole through ' + + 'objects.._actions..texts..message (globalActions..texts..message for an ' + + 'object-less action) in the organization\'s language when the body asks for it (ctx.text). With no params ' + + 'every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter', + paramPatternMessage: 'A text param is an identifier (e.g. subject) — the root a {{ }} hole names', + paramsDescribe: + 'The names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the action\'s body ' + + 'passes in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding ' + + 'logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text ' + + 'is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is ' + + 'refused', + rule: { slot: 'An action text `message`', holeRefused: ACTION_TEXT_MESSAGE_HOLE_REFUSED }, + }, }; /** diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 2159752116c..9b643d96b2e 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -457,18 +457,33 @@ export function undeclaredHookTextKeyAtSave( declared: readonly string[], at: 'body.source' | 'handler' = 'body.source', ): string { + return undeclaredTextKeyAtSave('hook', key, declared, at); +} + +// [#34374 PR2] One subject-parameterised core per text sentence, as the +// refusal sentences above are: the hook exports keep their bytes, and the +// action twins below name the action. +function undeclaredTextKeyAtSave(subject: RefusalSubject, key: string, declared: readonly string[], at: string): string { return ( - `\`${at}\` asks for text '${key}' (\`ctx.text('${key}')\`), and this hook's \`texts\` declares no such key ` + `\`${at}\` asks for text '${key}' (\`ctx.text('${key}')\`), and this ${subject}'s \`texts\` declares no such key ` + `(declared: ${declaredList(declared)}). Declare it under \`texts.${key}\` with the sentence the record keeps, ` + 'or ask for one of the declared keys.' ); } /** The save-time refusal for a `{{ … }}` hole in a text `message` whose entry declares no `params`. */ -export const HOOK_TEXT_MESSAGE_HOLE_REFUSED = - 'A hook text `message` whose entry declares no `params` is plain text, and nothing fills a `{{ }}` hole: the ' - + 'record would keep the braces as written. Declare the name under the entry\'s `params` (`params: [\'lead\']`) ' - + 'and pass it to `ctx.text` (`ctx.text(\'KEY\', { lead })`), or write the sentence without the hole.'; +export const HOOK_TEXT_MESSAGE_HOLE_REFUSED = textMessageHoleRefused('hook', 'lead'); + +/** [#34374 PR2] The action twin of {@link HOOK_TEXT_MESSAGE_HOLE_REFUSED}. */ +export const ACTION_TEXT_MESSAGE_HOLE_REFUSED = textMessageHoleRefused('action', 'subject'); + +function textMessageHoleRefused(subject: RefusalSubject, param: string): string { + return ( + `${capArticle(subject)} text \`message\` whose entry declares no \`params\` is plain text, and nothing fills a \`{{ }}\` hole: the ` + + `record would keep the braces as written. Declare the name under the entry's \`params\` (\`params: ['${param}']\`) ` + + `and pass it to \`ctx.text\` (\`ctx.text('KEY', { ${param} })\`), or write the sentence without the hole.` + ); +} /** * The save-time refusal for `texts` on a hook whose code cannot ask for one: @@ -489,8 +504,12 @@ export function hookTextsWithoutRunnableCode(language: string | undefined): stri * and the key and says how to fix it. */ export function undeclaredHookTextAtRun(hookName: string, key: string, declared: readonly string[]): string { + return undeclaredTextAtRun('hook', hookName, key, declared); +} + +function undeclaredTextAtRun(subject: RefusalSubject, name: string, key: string, declared: readonly string[]): string { return ( - `hook '${hookName}' asked for text '${key}' (ctx.text), and its \`texts\` declares no such key ` + `${subject} '${name}' asked for text '${key}' (ctx.text), and its \`texts\` declares no such key ` + `(declared: ${declaredList(declared)}). Only a declared text is written in the organization's language: ` + 'declare it under `texts` with the sentence the record keeps, or ask for one of the declared keys.' ); @@ -548,11 +567,7 @@ export function undeclaredActionRefusalReasonAtRun( * serve them. */ export function actionRefusalsWithoutSandboxedBody(type: string, language: string | undefined): string { - const has = type !== 'script' - ? `\`type: '${type}'\`, which runs no code of the action's own` - : language !== undefined - ? `a \`${language}\` body` - : 'no `body` (an inline `target` function `os build` could not lower leaves none)'; + const has = actionCodeCarrier(type, language); return ( "`refusals` is answered for a `type: 'script'` action's sandboxed `body` (`language: 'js'`) and for its inline " + `\`target\` function (which \`os build\` lowers to a \`js\` body), and this action has ${has}: nothing it runs ` @@ -560,3 +575,54 @@ export function actionRefusalsWithoutSandboxedBody(type: string, language: strin + 'throws the declared codes, or drop `refusals`.' ); } + +/** How an action that runs no `js` body of its own names what it has, for the two sentences that refuse it. */ +function actionCodeCarrier(type: string, language: string | undefined): string { + return type !== 'script' + ? `\`type: '${type}'\`, which runs no code of the action's own` + : language !== undefined + ? `a \`${language}\` body` + : 'no `body` (an inline `target` function `os build` could not lower leaves none)'; +} + +/* + * ── An action's declared texts (#34374 PR2, ruling 6913660232 parameter 7) ── + * + * `ActionSchema.texts` is the hook texts' twin on an action: a sentence a + * `script` action's `js` body writes into a record for people to read — the + * subject of the email activity it logs — declared under `texts: { : { + * message, params? } }` and asked for by key, `await ctx.text('email_subject', + * { subject })`. The runtime answers it in the ORGANIZATION's language through + * the action's own translation address (`actionTextMessageKey`: + * `objects.._actions..texts..message`, or + * `globalActions..texts..message` for an object-less action). + * The same two halves as a hook text: a key the body asks for literally and + * `texts` does not declare is refused at save (the key reading is + * {@link hookTextKeysAskedIn}, one reading for both); any other key is refused + * when the action runs. The sentences are the hook ones with the action named. + */ + +/** The save-time refusal for a key an action's body asks for literally that its `texts` does not declare. */ +export function undeclaredActionTextKeyAtSave(key: string, declared: readonly string[]): string { + return undeclaredTextKeyAtSave('action', key, declared, 'body.source'); +} + +/** The run-time fault for `ctx.text(key)` with a key the action's `texts` does not declare (or none at all). */ +export function undeclaredActionTextAtRun(actionName: string, key: string, declared: readonly string[]): string { + return undeclaredTextAtRun('action', actionName, key, declared); +} + +/** + * The save-time refusal for `texts` on an action whose code cannot ask for + * one: a type other than `script`, an `expression` body, or a `script` action + * with no body. `os i18n` would demand its translations and nothing would + * serve them. + */ +export function actionTextsWithoutRunnableCode(type: string, language: string | undefined): string { + return ( + "`texts` is served to a `type: 'script'` action's sandboxed `body` (`language: 'js'`) and to its inline " + + `\`target\` function (which \`os build\` lowers to a \`js\` body) through \`ctx.text\`, and this action has ` + + `${actionCodeCarrier(type, language)}: nothing it runs can ask for a declared text, while \`os i18n\` still ` + + 'demanded its translations. Give the action a `js` body that writes the texts, or drop `texts`.' + ); +} diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index e88a00354ff..f1a66a17c2d 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4677,14 +4677,37 @@ export function actionRefusalMessageKey( code: string, reason?: string, ): string { - const node = typeof objectName === 'string' && objectName.length > 0 - ? `objects.${objectName}._actions.${actionName}` - : `globalActions.${actionName}`; + const node = actionTranslationNodeKey(objectName, actionName); return reason === undefined ? `${node}.refusals.${code}.message` : `${node}.refusals.${code}.reasons.${reason}.message`; } +/** + * Dot-notation i18n key for an action's declared text (#34374 PR2, ruling + * 6913660232 parameter 7, `ActionSchema.texts`) — the action twin of + * {@link hookTextMessageKey}, at the address every action translation is read + * at, beside the action's refusals: + * + * - a bound action: `objects.._actions..texts..message`; + * - an object-less action: `globalActions..texts..message`. + * + * Used by the action body runner, which answers `ctx.text(key, params)` with + * this translation in the ORGANIZATION's language (never the caller's), the + * declared sentence on a miss, and fills its holes after. `objectName` is the + * action's OWN object, as for {@link actionRefusalMessageKey}. + */ +export function actionTextMessageKey(objectName: string | undefined, actionName: string, key: string): string { + return `${actionTranslationNodeKey(objectName, actionName)}.texts.${key}.message`; +} + +/** The translation node of an action: `objects.._actions.`, or `globalActions.` with no object. */ +function actionTranslationNodeKey(objectName: string | undefined, actionName: string): string { + return typeof objectName === 'string' && objectName.length > 0 + ? `objects.${objectName}._actions.${actionName}` + : `globalActions.${actionName}`; +} + /** * Dot-notation i18n key for a screen's heading or body text — * `flows..screens..title` / `.description` (#22507). diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index bffceb2a176..02bd67dffc3 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -486,6 +486,18 @@ const LEDGER: ReadonlyArray = [ key: 'refusals', why: "live, not yet offered in the Studio — the refusals a `script` action's `js` body throws by code (answered with the declared sentence in the caller's locale) are validated at parse (SCREAMING_SNAKE codes, the hook entry's closed-scope holes over declared `params`, a literal code or reason the catalogue does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body that throws them. The Studio row, a key-only record, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then an action authored in the Studio declares `refusals` through the metadata API or its package source", }, + // #34374 (action half) — an action's declared texts land in the action's + // source first, as its refusal catalogue (#34273) and a hook's declared + // texts did. The Studio row (a key-only record, with its help text in the + // eleven metadata-forms bundles) is a follow-up, so this row records why the + // key is not offered. + { + kind: 'omit', + type: 'action', + path: ROOT_PATH, + key: 'texts', + why: "live, not yet offered in the Studio — the sentences a `script` action's `js` body writes into records (`ctx.text`, answered in the organization's language) are validated at parse (snake_case keys, closed-scope holes over declared `params`, a literal `ctx.text` key the action does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body that asks for them. The Studio row, a key-only record beside `refusals`, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then an action authored in the Studio declares `texts` through the metadata API or its package source", + }, // #27946 — an action's pressed-state predicate lands spec-first the same // way: `planned` in the liveness ledger, drawn by no action surface until // the console card that draws `aria-pressed` on the header buttons. diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index 40a7c3b6509..02e25507a60 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -388,6 +388,28 @@ const refusalTranslationsSchema = (noun: 'hook' | 'action') => z.record(z.string })).optional().describe("Reason translations keyed by the reason the code's `reasons` declares"), })).optional().describe(`Refusal translations keyed by the code the ${noun}'s \`refusals\` declares`); +/** + * The translations of a declared text catalogue, keyed by text key — one shape + * for `hooks..texts` (#34374) and an action's `….texts` (#34374 PR2, + * under `objects.._actions.` or `globalActions.`), + * built by one factory so the two cannot drift. Every sentence it produces for + * `hook` is the one the hook group carried before. + */ +const textTranslationsSchema = (noun: 'hook' | 'action') => z.record(z.string(), strictObject({ + surface: `this ${noun} text translation`, + history: TRANSLATION_HISTORY, + // The spellings the text entry schema renames onto its own `message`. + aliases: { text: 'message', template: 'message', value: 'message', description: 'message' }, +}, { + // The declared message's own form — plain text, or a template over the + // entry's declared `params`; an empty string is the untranslated + // skeleton slot `os i18n extract` writes (the declared message is served). + message: z.string().optional().describe( + `Translated sentence of ${noun === 'action' ? 'an action' : 'a hook'}'s declared text — written into the record in the organization's language in ` + + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', + ), +})).optional().describe(`Text translations keyed by the key the ${noun}'s \`texts\` declares`); + /** * Action translations — one shape, used at two addresses: an object's * `_actions.` and the top-level `globalActions.` (the same split @@ -412,6 +434,7 @@ const actionTranslationSchema = (surface: string) => strictObject({ parameters: 'params', args: 'params', inputs: 'params', result: 'resultDialog', dialog: 'resultDialog', refusal: 'refusals', + text: 'texts', }, }, { label: z.string().optional().describe('Translated action label'), @@ -472,6 +495,12 @@ const actionTranslationSchema = (surface: string) => strictObject({ // declared sentence on a miss. Server-rendered like a hook refusal, so no // client overlay reads it. refusals: refusalTranslationsSchema('action'), + // [#34374 PR2] `ActionSchema.texts` — one translated sentence per declared + // text key, picked by the action body runner in the ORGANIZATION's language + // through `actionTextMessageKey` (`system/i18n-resolver.ts`) when the body + // asks for it (`ctx.text`), the declared sentence on a miss. Written into a + // record server-side like a hook text, so no client overlay reads it. + texts: textTranslationsSchema('action'), }); /** @@ -751,6 +780,7 @@ export const ObjectTranslationDataSchema = lazySchema(() => strictObject({ * objects.._actions..preflight.columns.. * objects.._actions..refusals..message (#34273, `ActionSchema.refusals`) * objects.._actions..refusals..reasons..message + * objects.._actions..texts..message (#34374 PR2, `ActionSchema.texts`) */ _actions: z.record(z.string(), actionTranslationSchema('this object action translation')) .optional().describe('Action translations keyed by action name'), @@ -1283,6 +1313,7 @@ const appTranslationDataShape = () => ({ * globalActions..preflight.columns.. * globalActions..refusals..message (#34273, `ActionSchema.refusals`) * globalActions..refusals..reasons..message + * globalActions..texts..message (#34374 PR2, `ActionSchema.texts`) */ globalActions: z.record(z.string(), actionTranslationSchema('this global action translation')) .optional().describe('Global action translations keyed by action name'), @@ -2226,20 +2257,7 @@ const appTranslationDataShape = () => ({ }, { refusals: refusalTranslationsSchema('hook'), // [#34374] A declared text's sentence, picked in the organization's language. - texts: z.record(z.string(), strictObject({ - surface: 'this hook text translation', - history: TRANSLATION_HISTORY, - // The spellings `HookTextSchema` renames onto its own `message`. - aliases: { text: 'message', template: 'message', value: 'message', description: 'message' }, - }, { - // The declared message's own form — plain text, or a template over the - // entry's declared `params`; an empty string is the untranslated - // skeleton slot `os i18n extract` writes (the declared message is served). - message: z.string().optional().describe( - "Translated sentence of a hook's declared text — written into the record in the organization's language in " - + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', - ), - })).optional().describe("Text translations keyed by the key the hook's `texts` declares"), + texts: textTranslationsSchema('hook'), })).optional().describe('Hook translations keyed by hook name'), /** diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 189646066fe..894979f28c6 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -304,7 +304,7 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // --------------------------------------------------------------------------- -// 862 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 863 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -1578,6 +1578,7 @@ export type Iso_ui_actionParams__ActionSessionSchema = Assert, z.infer< typeof M155.ActionLocationSchema > >>; export type Iso_ui_action__ActionRefusalSchema = Assert, z.infer< typeof M155.ActionRefusalSchema > >>; +export type Iso_ui_action__ActionTextSchema = Assert, z.infer< typeof M155.ActionTextSchema > >>; export type Iso_ui_action__ActionType = Assert, z.infer< typeof M155.ActionType > >>; // ui/app.zod.ts @@ -1837,7 +1838,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 862 isomorphic pins', () => { + it('still declares all 863 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2937,7 +2938,12 @@ describe('ADR-0122 type-alias convention', () => { // `TimesheetConfigSchema` (`ui/view.zod.ts`), a closed object of a string // array and two strings with no default or transform // (Iso_ui_view__TimesheetConfigSchema). +1 added. - expect(pins).toHaveLength(862); + // 862 -> 863 is the action half of #34374: an action's declared text + // entry, `ActionTextSchema` (`ui/action.zod.ts`), built by the same + // declared-entry factory as `HookTextSchema` and closed at the same two + // keys with no default or transform, pinned here + // (Iso_ui_action__ActionTextSchema). +1 added. + expect(pins).toHaveLength(863); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either diff --git a/packages/spec/src/ui/action-texts.test.ts b/packages/spec/src/ui/action-texts.test.ts new file mode 100644 index 00000000000..0b430117784 --- /dev/null +++ b/packages/spec/src/ui/action-texts.test.ts @@ -0,0 +1,201 @@ +import { describe, it, expect } from 'vitest'; +import { ActionSchema, ActionTextSchema } from './action.zod'; +import { HookTextSchema } from '../data/hook.zod'; +import { + ACTION_TEXT_MESSAGE_HOLE_REFUSED, + HOOK_TEXT_MESSAGE_HOLE_REFUSED, + actionTextsWithoutRunnableCode, + hookTextsWithoutRunnableCode, + undeclaredActionTextAtRun, + undeclaredActionTextKeyAtSave, + undeclaredHookTextAtRun, + undeclaredHookTextKeyAtSave, +} from '../data/hook-refusal-codes'; +import { actionTextMessageKey } from '../system/i18n-resolver'; +import { TranslationDataSchema } from '../system/translation.zod'; + +// #34374 PR2 (ruling 6913660232 option B, parameter 7): an action declares the +// sentences its body writes into records, `texts: { : { message, params? } }` +// — the hook texts' twin — and its sandboxed body asks for one by key with +// `ctx.text(key, params)`; the runtime answers it in the organization's language. + +const base = { name: 'send_email', label: 'Send email', objectName: 'crm_contact', type: 'script' as const }; +const body = (source: string) => ({ language: 'js' as const, source }); +/** HotCRM's `send_email` action wrote `'Email: ' + subject`; the declared text is the same sentence, asked for by key. */ +const ASKS = "const line = await ctx.text('email_subject', { subject: input.subject });"; +const TEXTS = { email_subject: { message: 'Email: {{ subject }}', params: ['subject'] } }; + +const issuesOf = (r: { success: boolean; error?: { issues: Array<{ path: PropertyKey[]; message: string }> } }) => + r.success ? [] : r.error!.issues; + +describe('Action.texts — the declared texts', () => { + it('accepts snake_case keys with a message and the params its holes name (the HotCRM send_email sentence)', () => { + const parsed = ActionSchema.parse({ ...base, body: body(ASKS), texts: TEXTS }); + expect(parsed.texts?.email_subject).toEqual({ message: 'Email: {{ subject }}', params: ['subject'] }); + }); + + it('CONTROL: is optional — an action that declares no texts parses as before', () => { + expect(ActionSchema.parse({ ...base, body: body('return;') }).texts).toBeUndefined(); + }); + + it('refuses a key that is not snake_case, at `texts`', () => { + const r = ActionSchema.safeParse({ ...base, body: body('return;'), texts: { EmailSubject: { message: 'x' } } }); + expect(r.success).toBe(false); + expect(issuesOf(r).some((i) => i.path[0] === 'texts')).toBe(true); + }); + + it('is a closed entry — a key the text entry does not hold (a refusal\'s `status`) is refused', () => { + expect(ActionTextSchema.safeParse({ message: 'x', status: 400 }).success).toBe(false); + expect(ActionTextSchema.safeParse({ message: 'x', reasons: {} }).success).toBe(false); + }); + + it('refuses an empty message', () => { + expect(ActionTextSchema.safeParse({ message: ' ' }).success).toBe(false); + }); + + it('refuses a param that is not an identifier, and a param declared twice', () => { + const bad = ActionTextSchema.safeParse({ message: 'Email: {{ subject }}', params: ['the subject'] }); + expect(bad.success).toBe(false); + expect(issuesOf(bad).some((i) => i.path.join('.') === 'params.0')).toBe(true); + const twice = ActionTextSchema.safeParse({ message: 'Email: {{ subject }}', params: ['subject', 'subject'] }); + expect(twice.success).toBe(false); + expect(issuesOf(twice).some((i) => i.path.join('.') === 'params.1')).toBe(true); + }); + + it('refuses a {{ }} hole in a message whose entry declares no params, in the action\'s words; CONTROL: declared params allow it', () => { + const r = ActionTextSchema.safeParse({ message: 'Email: {{ subject }}' }); + expect(r.success).toBe(false); + expect(issuesOf(r).find((i) => i.path.join('.') === 'message')!.message).toBe(ACTION_TEXT_MESSAGE_HOLE_REFUSED); + expect(ACTION_TEXT_MESSAGE_HOLE_REFUSED).toMatch(/^An action text `message`/); + expect(ActionTextSchema.safeParse(TEXTS.email_subject).success).toBe(true); + }); + + it('refuses a hole over a name the entry does not declare, naming the action text slot', () => { + const r = ActionTextSchema.safeParse({ message: 'Email: {{ body }}', params: ['subject'] }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'message')!; + expect(issue.message).toContain('An action text `message`'); + expect(issue.message).toContain('body'); + }); + + it('renames a near-miss spelling of message and params onto the declared keys, loudly', () => { + for (const doc of [{ text: 'Email' }, { template: 'Email' }, { message: 'Email', parameters: ['subject'] }]) { + const r = ActionTextSchema.safeParse(doc); + expect(r.success).toBe(false); + expect(JSON.stringify(issuesOf(r))).toMatch(/message|params/); + } + }); + + it.each([ + ['no body', { type: 'script' }, 'no `body`'], + ['an expression body', { type: 'script', body: { language: 'expression', source: 'record.amount > 0' } }, 'a `expression` body'], + ['a url action', { type: 'url', target: 'https://example.com' }, "`type: 'url'`"], + ['a flow action', { type: 'flow', target: 'send_email_flow' }, "`type: 'flow'`"], + ['an api action', { type: 'api', target: '/api/v1/email' }, "`type: 'api'`"], + ])('refuses texts on an action that runs no js body of its own — %s', (_label, shape, says) => { + const r = ActionSchema.safeParse({ ...base, ...shape, texts: TEXTS }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'texts'); + expect(issue?.message).toContain(says); + expect(issue?.message).toContain('drop `texts`'); + }); + + it('accepts texts on an action whose `type` is omitted (the schema default is `script`)', () => { + const { type: _omit, ...untyped } = base; + expect(ActionSchema.safeParse({ ...untyped, body: body(ASKS), texts: TEXTS }).success).toBe(true); + }); + + it('accepts texts on an object-less action', () => { + const { objectName: _omit, ...objectLess } = base; + expect(ActionSchema.safeParse({ ...objectLess, body: body(ASKS), texts: TEXTS }).success).toBe(true); + }); +}); + +describe('Action.texts — a key the body asks for literally is refused at save when undeclared', () => { + it('refuses a literal ctx.text key that texts does not declare, at body.source, naming the declared keys', () => { + const r = ActionSchema.safeParse({ ...base, body: body("await ctx.text('email_body');"), texts: TEXTS }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source')!; + expect(issue.message).toBe(undeclaredActionTextKeyAtSave('email_body', ['email_subject'])); + expect(issue.message).toContain("this action's `texts`"); + }); + + it('CONTROL: a declared key, a key in a comment or a longer string, and a computed key all pass the save', () => { + const source = [ + ASKS, + "// await ctx.text('not_declared')", + "const note = \"ctx.text('not_declared') is how\";", + 'const k = pick(); await ctx.text(k);', + ].join('\n'); + expect(ActionSchema.safeParse({ ...base, body: body(source), texts: TEXTS }).success).toBe(true); + }); + + it('CONTROL: an action that declares no texts is not read for ctx.text calls (the run-time fault names it)', () => { + expect(ActionSchema.safeParse({ ...base, body: body("await ctx.text('anything');") }).success).toBe(true); + expect(undeclaredActionTextAtRun('send_email', 'anything', [])).toMatch(/^action 'send_email' asked for text 'anything'.*declared: none/); + }); +}); + +describe('the shared declared-entry factory — one text entry, the words per subject', () => { + it('the hook and action text entries accept and refuse the same documents', () => { + const docs = [ + { message: 'Email: {{ subject }}', params: ['subject'] }, + { message: 'Plain sentence' }, + { message: 'Email: {{ subject }}' }, + { message: 'Email: {{ other }}', params: ['subject'] }, + { message: 'x', status: 400 }, + { message: '' }, + ]; + for (const doc of docs) { + expect(ActionTextSchema.safeParse(doc).success, JSON.stringify(doc)).toBe(HookTextSchema.safeParse(doc).success); + } + }); + + it('each subject keeps its own words — the hook sentences are unchanged', () => { + expect(HOOK_TEXT_MESSAGE_HOLE_REFUSED).toMatch(/^A hook text `message`.*params: \['lead'\].*ctx\.text\('KEY', \{ lead \}\)/); + expect(ACTION_TEXT_MESSAGE_HOLE_REFUSED).toMatch(/params: \['subject'\].*ctx\.text\('KEY', \{ subject \}\)/); + expect(undeclaredHookTextKeyAtSave('a', ['b'])).toContain("this hook's `texts`"); + expect(undeclaredHookTextAtRun('h', 'a', [])).toMatch(/^hook 'h' asked for text 'a'/); + expect(hookTextsWithoutRunnableCode(undefined)).toContain('no `body` and no `handler`'); + expect(actionTextsWithoutRunnableCode('url', undefined)).toContain("`type: 'url'`, which runs no code of the action's own"); + }); + + it('the action text guidance names both translation addresses, with no tracker number', () => { + const r = ActionTextSchema.safeParse({ message: 'x', locale: 'en' }); + expect(r.success).toBe(false); + const said = issuesOf(r).map((i) => i.message).join(' '); + expect(said).toContain('objects.OBJ._actions.ACT.texts.KEY.message'); + expect(said).toContain('globalActions.ACT.texts.KEY.message'); + expect(said).not.toMatch(/#\d/); + }); +}); + +describe('the translation address — beside the action\'s other copy', () => { + it('a bound action: `objects.._actions..texts..message`', () => { + expect(actionTextMessageKey('crm_contact', 'send_email', 'email_subject')) + .toBe('objects.crm_contact._actions.send_email.texts.email_subject.message'); + }); + + it('an object-less action: `globalActions..texts..message`', () => { + expect(actionTextMessageKey(undefined, 'send_email', 'email_subject')).toBe('globalActions.send_email.texts.email_subject.message'); + expect(actionTextMessageKey('', 'send_email', 'email_subject')).toBe('globalActions.send_email.texts.email_subject.message'); + }); + + it('is a path a translation bundle can write, at both addresses', () => { + expect(TranslationDataSchema.safeParse({ + objects: { crm_contact: { _actions: { send_email: { texts: { email_subject: { message: '邮件:{{ subject }}' } } } } } }, + globalActions: { send_email: { texts: { email_subject: { message: '邮件:{{ subject }}' } } } }, + }).success).toBe(true); + }); + + it('refuses a key an action text translation does not hold, and names `text` as the rename onto `texts` it is', () => { + expect(TranslationDataSchema.safeParse({ + globalActions: { send_email: { texts: { email_subject: { message: 'x', status: 400 } } } }, + }).success).toBe(false); + const renamed = TranslationDataSchema.safeParse({ + globalActions: { send_email: { text: { email_subject: { message: 'x' } } } }, + }); + expect(renamed.success).toBe(false); + expect(JSON.stringify(renamed.error!.issues)).toMatch(/texts/); + }); +}); diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 64d28c68b9c..dd22398cf60 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -38,14 +38,20 @@ import { templateExpressionInput } from '../shared/typed-expression-input'; import { HookBodySchema } from '../data/hook-body.zod'; // [#34273] An action's refusal catalogue: the hook catalogue's entry shape, // code spelling, literal-throw reading and sentences — import-free leaves. -import { declaredRefusalEntrySchema } from '../data/declared-entry.zod'; +// [#34374 PR2] …and its declared texts: the hook texts' entry shape, key +// spelling, literal `ctx.text` reading and sentences, from the same leaves. +import { declaredRefusalEntrySchema, declaredTextEntrySchema } from '../data/declared-entry.zod'; import { HOOK_REFUSAL_CODE_PATTERN, + HOOK_TEXT_KEY_PATTERN, actionRefusalsWithoutSandboxedBody, + actionTextsWithoutRunnableCode, hookRefusalCodesThrownIn, hookRefusalReasonsThrownIn, + hookTextKeysAskedIn, undeclaredActionRefusalCodeAtSave, undeclaredActionRefusalReasonAtSave, + undeclaredActionTextKeyAtSave, } from '../data/hook-refusal-codes'; // [#25653] Import-free leaf, shared with `HookSchema`: the identity-assignment // set, the body-source reading and the refusal text. @@ -1524,6 +1530,55 @@ const actionObject = () => strictObject({ + 'run time. Only a type: \'script\' action with a js body declares one', ), + /** + * The action's declared texts (#34374 PR2, ruling 6913660232 parameter 7) — + * the twin of `HookSchema.texts`: every sentence the action's body writes + * into a record for people to read, keyed by a snake_case key the body asks + * for. + * + * texts: { + * email_subject: { message: 'Email: {{ subject }}', params: ['subject'] }, + * } + * + * await ctx.api.object('crm_activity').insert({ subject: await ctx.text('email_subject', { subject }) }); + * + * `ctx.text(key, params?)` answers the sentence in the ORGANIZATION's + * language, never the caller's (parameter 2): the Localization setting when + * somebody set it, else the app's `i18n.defaultLocale` (parameter 3, the + * one shared reader a hook text and the flow record write read). It picks + * the translation beside the action's other copy first — + * `objects.._actions..texts..message`, or + * `globalActions..texts..message` for an object-less action — + * and fills the `{{ }}` holes from `params` after (parameter 1). With no + * translation, or no language, the declared sentence is answered and the + * action goes on (parameter 5). A Localization setting that cannot be READ + * rejects the call. A string the body builds itself is written as it is + * (parameter 4). + * + * A key the body asks for literally that `texts` does not declare is + * refused at save; any other undeclared key is refused when the action + * runs, as a fault naming the action and the key. Served where an action + * runs code of its own: a `type: 'script'` action's sandboxed `js` body — + * which is also what `os build` lowers an inline `target` function to. + * Refused on every other action: another `type` (its `target` is a URL, + * page, flow or endpoint), an `expression` body, or no body. Absent: + * `ctx.text` has nothing to answer. + */ + texts: z.record( + z.string().regex(HOOK_TEXT_KEY_PATTERN, { + message: 'A text key is snake_case (e.g. email_subject) — the key the action\'s body asks for with ctx.text', + }), + ActionTextSchema, + ).optional().describe( + 'Texts the action\'s js body writes into records, keyed by the snake_case key it asks for with ctx.text(KEY, ' + + 'params): { message, params? }. ctx.text answers the sentence in the organization\'s language (the Localization ' + + 'setting when somebody set it, else the app\'s i18n.defaultLocale), translated through ' + + 'objects.._actions..texts..message (globalActions..texts..message for an ' + + 'object-less action) with the declared message as the fallback, its holes filled from params. A key not declared ' + + 'here is refused — at save when the body asks for it literally, otherwise at run time. Only a type: \'script\' ' + + 'action with a js body declares one', + ), + /** * The declarative single-record field write — the row-level counterpart of * a list view's `bulkActionDefs` `{ operation: 'update', patch }` (#14092, @@ -2566,6 +2621,53 @@ export const ActionRefusalSchema = declaredRefusalEntrySchema('action'); export type ActionRefusal = z.input; +/** + * [#34374 PR2] One declared text of an action (`ActionSchema.texts`): a + * sentence the action's body writes into a record for people to read, picked + * in the ORGANIZATION's language when the body asks for it + * (`ctx.text(key, params)`). The same entry a hook's texts hold + * (`HookTextSchema`), built by the one factory so the two cannot drift; only + * its words name the action and its translation address. With `params`, a + * hole over an undeclared name is refused at parse; a hole holding logic, an + * unknown formatter, an empty hole and a `currency` formatter with no code + * are refused where the text is compiled (`@objectstack/lint` + * `validate-hook-refusal-templates.ts`). + */ +export const ActionTextSchema = declaredTextEntrySchema('action'); + +export type ActionText = z.input; + +/** + * [#34374 PR2] The object-level check on an action's `texts`, the twin of + * `HookSchema`'s: `texts` nothing the action runs could ask for is refused at + * `texts`, and a key the body's source asks for literally + * (`ctx.text('key')`) that `texts` does not declare is refused at + * `body.source`, one issue each. A key that arrives any other way is the + * run-time refusal's. + */ +function refuseUndeclaredLiteralActionTextKey( + data: { + type?: string; + body?: { language?: string; source?: unknown }; + texts?: Record; + }, + ctx: z.core.$RefinementCtx, +): void { + if (!data.texts) return; + const type = data.type ?? 'script'; + if (type !== 'script' || data.body?.language !== 'js') { + ctx.addIssue({ code: 'custom', path: ['texts'], message: actionTextsWithoutRunnableCode(type, data.body?.language) }); + return; + } + const source = data.body.source; + if (typeof source !== 'string') return; + const declared = Object.keys(data.texts); + for (const key of hookTextKeysAskedIn(source)) { + if (Object.prototype.hasOwnProperty.call(data.texts, key)) continue; + ctx.addIssue({ code: 'custom', path: ['body', 'source'], message: undeclaredActionTextKeyAtSave(key, declared) }); + } +} + /** * [#34273] The object-level check on an action's `refusals`, the twin of * `HookSchema`'s: a catalogue nothing the action runs could answer is @@ -3125,6 +3227,7 @@ export const ActionSchema = lazySchema(() => actionObject().refine((data) => { .superRefine(refuseInertOutcomeMessages) .superRefine(refuseIdentityAssignmentBodyWrite) .superRefine(refuseUndeclaredLiteralActionRefusalCode) + .superRefine(refuseUndeclaredLiteralActionTextKey) .superRefine(refusePreflightContradictions) // Grade gate first, feature gate last: `requiresFeature` composes onto // whatever `visible` it finds, so this order keeps `features.*` the final diff --git a/ui/packages/core/src/actions/actionKeys.ts b/ui/packages/core/src/actions/actionKeys.ts index 784f82f21e2..d983648deb9 100644 --- a/ui/packages/core/src/actions/actionKeys.ts +++ b/ui/packages/core/src/actions/actionKeys.ts @@ -365,6 +365,14 @@ export const SPEC_ACTION_KEYS = [ 'submitText', 'successMessage', 'target', + // Added to `ActionSchema` by the action half of objectstack#34374: the + // sentences a `script` action's `js` body writes into records (`ctx.text`). + // The SERVER answers it — the body stores the sentence already picked in the + // organization's language — so it is listed for the reason `refusals` is: + // this array restates the spec's declared keys, so an action carrying it is + // not reported as having an unknown key. `ActionDef` does NOT declare it and + // the runner does not read it. + 'texts', 'type', 'undoable', 'variant',