Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/34575-hook-texts-studio-row.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/spec': minor
'@objectstack/platform-objects': patch
---

feat(spec): the Studio hook form offers a hook's declared `texts`, and `HookContext` declares `ctx.text`

Clause-②: yes (widening)
Metadata-protocol: added

The added key is the type member `HookContext.text` (the authorable-surface record lists `HookContext` members); nothing a stack writes changes.

- **Studio hook form.** `hookForm` gains a `texts` row beside `refusals`: a key-only record keyed by the snake_case key the hook's code asks for with `ctx.text`, each entry editing its `message` and `params`. An author editing a hook in the Studio can now write the `texts` the schema has accepted since 18.6.0, instead of going through the metadata API or the package source. The row's label and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. Nothing about what a hook may declare changes.
- **`HookContext.text`.** `HookContext` now declares `text?: (key: string, params?: Record<string, unknown>) => Promise<string>` (named `HookTextReader`), the call the runtime already binds on every path a hook runs on, declared the way `api` and `notice` are: `z.unknown()` at parse, a static cast for the type, optional because a context parsed without the runtime carries none. A typed handler no longer needs a local type to call `ctx.text`. `HookContextSchema.parse` now keeps a bound `text` instead of stripping it.
1 change: 1 addition & 0 deletions content/docs/references/data/hook.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
| **ql** | `any` | ✅ | ObjectQL Engine Reference |
| **api** | `any` | optional | Cross-object data access (IScopedContext — `object(name)` + `transaction(cb)`) |
| **notice** | `any` | optional | Tell the person who made THIS insert/update what the save set in motion: `ctx.notice(message)` hands one non-empty string to the write's own `onNotice` listener, answered as the create/update `notice`. Bound by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete |
| **text** | `any` | optional | Answer one of the hook's declared texts: `await ctx.text(KEY, params?)` returns the sentence in the organization's language (translated through hooks.`<hook>`.texts.`<key>`.message, the declared message as the fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does not declare rejects the call |
| **user** | `{ id?: string; name?: string; email?: string; organizationId?: string }` | optional | Current user info shortcut |

### Nested Shape: `HookContext.dispatch`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -705,9 +705,11 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms,
// 9 since #26835: the hook form offers the `refusals` record, whose two
// entry fields (`message`, `status`) are enumerated the same way. 12 since
// #33657: the entry also offers `reasons` (a record of `{ message }`) and
// `params`, three more enumerated children.
// `params`, three more enumerated children. 14 since #34575: the form
// offers the `texts` record, whose entry fields (`message`, `params`) are
// enumerated the same way.
expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0);
expect(HOOK_ENUMERATED.skipped.length).toBe(12);
expect(HOOK_ENUMERATED.skipped.length).toBe(14);
for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`);
expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries');
expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs');
Expand All @@ -716,6 +718,8 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms,
expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons');
expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons.message');
expect(HOOK_ENUMERATED.skipped).toContain('refusals.params');
expect(HOOK_ENUMERATED.skipped).toContain('texts.message');
expect(HOOK_ENUMERATED.skipped).toContain('texts.params');
//
// ⇒ one composite, two forms, two different greens: a lit control that
// passes on a sibling repeater, and a dark control that is right about
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const arMetadataForms: NonNullable<TranslationData['metadataForms']> = {
label: "المعاملات",
helpText: "الأسماء التي يمكن للجمل ملؤها (مثل state): يرمي المتن { code, params: { state } } ويعرض العنصر النائب {{ state }} قيمتها. عند الغياب: الجمل نص عادي"
},
texts: {
label: "النصوص",
helpText: "الجمل التي يكتبها الخطاف في السجلات، مفهرسة بالمفتاح بصيغة snake_case الذي تطلبه شيفرته عبر ctx.text (مثل follow_up_subject). يتلقى الخطاف الرسالة المُعلنة بلغة المؤسسة، مترجمة، مع الرسالة المُعلنة بديلًا عند غياب الترجمة. لمتن JavaScript ‏(L2) أو معالج؛ ويُرفض في متن التعبير"
},
"texts.message": {
label: "الرسالة",
helpText: "الجملة التي يكتبها الخطاف عندما تطلب شيفرته هذا المفتاح. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا"
},
"texts.params": {
label: "المعاملات",
helpText: "الأسماء التي يمكن للجملة ملؤها (مثل lead): تطلب الشيفرة ctx.text(key, { lead }) ويعرض العنصر النائب {{ lead }} قيمتها. عند الغياب: الجملة نص عادي"
},
handler: {
label: "المعالج",
helpText: "اسم دالة المعالج (مُهمَل — يُفضَّل `body`)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const deMetadataForms: NonNullable<TranslationData['metadataForms']> = {
label: "Parameter",
helpText: "Namen, die die Sätze füllen dürfen (z. B. state): Der Rumpf wirft { code, params: { state } }, und ein Platzhalter {{ state }} zeigt den Wert. Fehlt er: Die Sätze sind einfacher Text"
},
texts: {
label: "Texte",
helpText: "Sätze, die der Hook in Datensätze schreibt, nach dem snake_case-Schlüssel, den sein Code mit ctx.text anfragt (z. B. follow_up_subject). Der Hook erhält die deklarierte Meldung in der Sprache der Organisation, übersetzt, mit der deklarierten Meldung als Rückfall. Für einen JavaScript-Rumpf (L2) oder einen Handler; bei einem Ausdrucksrumpf abgelehnt"
},
"texts.message": {
label: "Meldung",
helpText: "Der Satz, den der Hook schreibt, wenn sein Code diesen Schlüssel anfragt. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter"
},
"texts.params": {
label: "Parameter",
helpText: "Namen, die der Satz füllen darf (z. B. lead): Der Code fragt ctx.text(key, { lead }) an, und ein Platzhalter {{ lead }} zeigt den Wert. Fehlt er: Der Satz ist einfacher Text"
},
handler: {
label: "Handler",
helpText: "Name der Handler-Funktion (veraltet – besser `body`)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const enMetadataForms: NonNullable<TranslationData['metadataForms']> = {
label: "Params",
helpText: "Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text"
},
texts: {
label: "Texts",
helpText: "Sentences the hook writes into records, keyed by the snake_case key its code asks for with ctx.text (e.g. follow_up_subject). The hook gets the declared message in the organization's language, translated, with the declared message as the fallback. For a JavaScript (L2) body or a handler; refused on an expression body"
},
"texts.message": {
label: "Message",
helpText: "The sentence the hook writes when its code asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param"
},
"texts.params": {
label: "Params",
helpText: "Names the sentence may fill (e.g. lead): the code asks for ctx.text(key, { lead }), and a {{ lead }} hole renders it. Absent: the sentence is plain text"
},
handler: {
label: "Handler",
helpText: "Handler function name (deprecated — prefer `body`)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const esESMetadataForms: NonNullable<TranslationData['metadataForms']> =
label: "Parámetros",
helpText: "Nombres que las frases pueden rellenar (p. ej. state): el cuerpo lanza { code, params: { state } } y un marcador {{ state }} muestra su valor. Si se omite: las frases son texto plano"
},
texts: {
label: "Textos",
helpText: "Frases que el gancho escribe en los registros, indexadas por la clave snake_case que su código pide con ctx.text (p. ej. follow_up_subject). El gancho recibe el mensaje declarado en el idioma de la organización, traducido, con el mensaje declarado como respaldo. Para un cuerpo JavaScript (L2) o un manejador; se rechaza en un cuerpo de expresión"
},
"texts.message": {
label: "Mensaje",
helpText: "La frase que escribe el gancho cuando su código pide esta clave. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado"
},
"texts.params": {
label: "Parámetros",
helpText: "Nombres que la frase puede rellenar (p. ej. lead): el código pide ctx.text(key, { lead }) y un marcador {{ lead }} muestra su valor. Si se omite: la frase es texto plano"
},
handler: {
label: "Manejador",
helpText: "Nombre de función manejadora (obsoleto — preferir `body`)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const frMetadataForms: NonNullable<TranslationData['metadataForms']> = {
label: "Paramètres",
helpText: "Les noms que les phrases peuvent remplir (par ex. state) : le corps lève { code, params: { state } }, et un espace réservé {{ state }} en affiche la valeur. Absent : les phrases sont du texte brut"
},
texts: {
label: "Textes",
helpText: "Les phrases que le hook écrit dans les enregistrements, indexées par la clé snake_case que son code demande avec ctx.text (par ex. follow_up_subject). Le hook reçoit le message déclaré dans la langue de l’organisation, traduit, avec le message déclaré comme repli. Pour un corps JavaScript (L2) ou un gestionnaire ; refusé sur un corps expression"
},
"texts.message": {
label: "Message",
helpText: "La phrase que le hook écrit lorsque son code demande cette clé. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré"
},
"texts.params": {
label: "Paramètres",
helpText: "Les noms que la phrase peut remplir (par ex. lead) : le code demande ctx.text(key, { lead }), et un espace réservé {{ lead }} en affiche la valeur. Absent : la phrase est du texte brut"
},
handler: {
label: "Gestionnaire",
helpText: "Nom de la fonction de gestion (obsolète — préférez `body`)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const frGeneratedSourceHashes: Readonly<Record<string, string>> = {
"metadataForms.hook.fields.description.label": "779a4342c8eb6707",
"metadataForms.hook.fields.refusals.message.label": "2af15199795c25b9",
"metadataForms.hook.fields.refusals.reasons.message.label": "2af15199795c25b9",
"metadataForms.hook.fields.texts.message.label": "2af15199795c25b9",
"metadataForms.hook.label": "248bb1cdc692252d",
"metadataForms.object.fields.description.label": "779a4342c8eb6707",
"metadataForms.object.fields.fields.description.label": "779a4342c8eb6707",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -785,9 +785,10 @@ describe('#19403 round 6 — the composite blind spot, hook side, CLOSED', () =>
// round 5 wrote down. Seven children sit enumerated and outside it — 9
// since #26835, when the `refusals` record's `message` / `status` joined,
// and 12 since #33657, when its `reasons` (with `reasons.message`) and
// `params` joined.
// `params` joined, and 14 since #34575, when the `texts` record's
// `message` / `params` joined.
expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0);
expect(HOOK_ENUMERATED.skipped.length).toBe(12);
expect(HOOK_ENUMERATED.skipped.length).toBe(14);
for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`);
expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries');
expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const jaJPMetadataForms: NonNullable<TranslationData['metadataForms']> =
label: "パラメーター",
helpText: "文に埋め込める名前(例: state)。本体が { code, params: { state } } をスローすると、{{ state }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです"
},
texts: {
label: "テキスト",
helpText: "フックがレコードに書き込む文。コードが ctx.text で要求する snake_case のキー(例: follow_up_subject)をキーとします。フックには宣言したメッセージが組織の言語に翻訳されて返り、翻訳がない場合は宣言したメッセージが返ります。JavaScript(L2)本体またはハンドラーで使用可能。expression 本体では拒否されます"
},
"texts.message": {
label: "メッセージ",
helpText: "コードがこのキーを要求したときにフックが書き込む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります"
},
"texts.params": {
label: "パラメーター",
helpText: "文に埋め込める名前(例: lead)。コードが ctx.text(key, { lead }) を要求すると、{{ lead }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです"
},
handler: {
label: "ハンドラー",
helpText: "ハンドラー関数名(非推奨 — `body` を推奨)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const koMetadataForms: NonNullable<TranslationData['metadataForms']> = {
label: "매개변수",
helpText: "문장에 채울 수 있는 이름(예: state)입니다. 본문이 { code, params: { state } }를 던지면 {{ state }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다"
},
texts: {
label: "텍스트",
helpText: "훅이 레코드에 쓰는 문장으로, 코드가 ctx.text로 요청하는 snake_case 키(예: follow_up_subject)를 키로 합니다. 훅은 선언된 메시지를 조직의 언어로 번역해 받으며, 번역이 없으면 선언된 메시지를 받습니다. JavaScript(L2) 본문 또는 핸들러용이며, expression 본문에서는 거부됩니다"
},
"texts.message": {
label: "메시지",
helpText: "코드가 이 키를 요청할 때 훅이 쓰는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다"
},
"texts.params": {
label: "매개변수",
helpText: "문장에 채울 수 있는 이름(예: lead)입니다. 코드가 ctx.text(key, { lead })를 요청하면 {{ lead }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다"
},
handler: {
label: "핸들러",
helpText: "핸들러 함수 이름(사용 중단, `body` 권장)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => {
// 741 since #33657: the hook form's refusal entry offers `reasons` (with
// its `message`) and `params` — three row labels, authored in all three
// locales.
expect(translated.length, `${locale} positive control`).toBe(741);
// 744 since #34575: the hook form offers the `texts` record and its
// `message` / `params` entry fields — three row labels, authored in all
// three locales.
expect(translated.length, `${locale} positive control`).toBe(744);
}
// ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the
// all-three predicate returns 0 while the per-locale one returns 1, so the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ export const ptBRMetadataForms: NonNullable<TranslationData['metadataForms']> =
label: "Parâmetros",
helpText: "Nomes que as frases podem preencher (por exemplo state): o corpo lança { code, params: { state } } e um marcador {{ state }} mostra o valor. Ausente: as frases são texto simples"
},
texts: {
label: "Textos",
helpText: "Frases que o hook escreve nos registros, indexadas pela chave snake_case que o código dele pede com ctx.text (por exemplo follow_up_subject). O hook recebe a mensagem declarada no idioma da organização, traduzida, com a mensagem declarada como alternativa. Para um corpo JavaScript (L2) ou um handler; recusado em um corpo de expressão"
},
"texts.message": {
label: "Mensagem",
helpText: "A frase que o hook escreve quando o código dele pede esta chave. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado"
},
"texts.params": {
label: "Parâmetros",
helpText: "Nomes que a frase pode preencher (por exemplo lead): o código pede ctx.text(key, { lead }) e um marcador {{ lead }} mostra o valor. Ausente: a frase é texto simples"
},
handler: {
label: "Handler",
helpText: "Nome da função handler (obsoleto — prefira `body`)"
Expand Down
Loading
Loading