Skip to content

Latest commit

 

History

History
203 lines (156 loc) · 23.2 KB

hook.mdx

File metadata and controls

203 lines (156 loc) · 23.2 KB
title Hook schema — Data Protocol property reference
navTitle Hook
description Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent, HookRefusal — 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/. */}

**Source:** `packages/spec/src/data/hook.zod.ts`

TypeScript Usage

import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema } from '@objectstack/spec/data';
import type { Hook, HookContext, HookRefusal } from '@objectstack/spec/data';

// Validate data
const result = HookSchema.parse(data);

Hook

Properties

Property Type Required Description
name string ✅ Hook unique name (snake_case)
label string optional Description of what this hook does
object string | string[] ✅ Target object(s)
events Enum<'beforeFind' | 'afterFind' | 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeDelete' | 'afterDelete'>[] ✅ Lifecycle events
handler string optional Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer body
body { language: 'expression'; source: string } | { language: 'js'; source: string; capabilities?: Enum<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | …>[]; timeoutMs?: integer; … } optional Hook body — expression (L1) or sandboxed JS (L2). A hook body cannot send mail: a js body granted email.send is refused, because a message cannot be taken back if the write that runs the hook rolls back; send mail on a record change from an action, a job or a flow. A hook body may add a timeline entry (activity.append), which commits or rolls back with the write.
priority number optional (default: 100) Execution priority
async boolean optional (default: false) Run specifically as fire-and-forget
condition string | { dialect: Enum<'cel' | 'cron' | 'template'>; source: string; ast?: any; meta?: object } optional Predicate (CEL); hook runs only when TRUE. e.g. Precord.status == "closed" && record.amount != null && record.amount > 1000
description string optional Human-readable description of what this hook does
retryPolicy { maxRetries?: number; backoffMs?: number } optional Retry policy for failed hook executions
timeoutMs number optional Maximum execution time in milliseconds before the hook is aborted
timeout never optional [REMOVED] hook.timeout was removed in @objectstack/spec 17 — its unit (milliseconds) lived only in the description, beside a body-level timeoutMs and a retryPolicy.backoffMs that spell theirs, so the same number read as two conventions on one surface. Rename the key to timeoutMs; the value (milliseconds) is unchanged. Run os migrate meta --from 17 to list the mechanical edits for existing sources; --write applies the ones it can prove, and you apply the rest by hand.
onError Enum<'abort' | 'log'> optional (default: "abort") Error handling strategy. abort: refuse the operation; a blocking hook's abort rolls the write back inside a unit of work, which the write door opens for an after* hook on an object on the default datasource whose driver declares transactions (elsewhere the caller is refused and the row stays stored). log: log the error and continue
refusals Record<string, { message: string; status?: integer; reasons?: Record<string, object>; params?: string[] }> optional Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: { message, status?, reasons?, params? }. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.<hook>.refusals.<CODE>.message, or ….<CODE>.reasons.<REASON>.message, 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 hook throws it literally, otherwise at run time; under a code with no reasons a thrown reason is not read
runAs Enum<'system' | 'user' | 'inherit'> optional (default: "inherit") Execution identity for the hook's ctx.api data operations: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting), inherit = the context of the write that fired the hook (the pre-runAs behaviour; the default). A hook with no trigger user has no identity to scope to, so under user its ctx.api data operations are REFUSED — declare system to make the elevation explicit. This covers any hook fired by a write that carried no user (an isSystem plugin/service write; a system-elevated flow node). Elevation does not reach identity assignment: a system hook's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED, and a system hook whose body names such a write is refused at save; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the hook acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system hook body's 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. Scope: ctx.api only — condition evaluation, the readonly strip on ctx.input, ctx.session and async are unchanged.
_lock Enum<'none' | 'no-overlay' | 'no-delete' | 'full'> optional Item-level lock — controls overlay & delete (ADR-0010).
_lockReason string optional Human-readable reason shown when a write is refused by _lock.
_lockSource Enum<'artifact' | 'package' | 'env-forced'> optional Layer that set _lock (artifact | package | env-forced).
_provenance Enum<'package' | 'org' | 'env-forced'> optional Origin of the item (package | org | env-forced).
_packageId string optional Owning package machine id.
_packageVersion string optional Owning package version.
_lockDocsUrl string optional Optional documentation link surfaced next to _lockReason.

Nested Shape: Hook.body[language='expression']

L1 expression body — pure formula, no IO

Property Type Required Description
language 'expression' ✅
source string ✅ Formula expression source

Nested Shape: Hook.body[language='js']

L2 sandboxed JS body — runs inside an isolated VM with declared capabilities

Property Type Required Description
language 'js' ✅
source string ✅ Function body source
capabilities Enum<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | …>[] optional (default: []) Granted capability tokens
timeoutMs integer optional Per-invocation timeout (ms)
memoryMb integer optional Per-invocation memory cap (MB)

Nested Shape: Hook.retryPolicy

Property Type Required Description
maxRetries number optional (default: 3) Maximum retry attempts on failure
backoffMs number optional (default: 1000) Backoff delay between retries in milliseconds

Nested Shape: Hook.refusals[string]

Property Type Required Description
message string ✅ The sentence the user reads when the hook throws this code — in the source locale, translated whole through hooks.<hook>.refusals.<CODE>.message in the caller's locale. With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused
status integer optional HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides
reasons Record<string, { message: string }> optional Further sentences under this same code, keyed by the snake_case reason the hook 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 hook 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

HookContext

Properties

Property Type Required Description
id string optional Unique execution ID for tracing
object string ✅
event Enum<'beforeFind' | 'afterFind' | 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeDelete' | 'afterDelete'> ✅
input Record<string, any> ✅ Mutable input parameters
result any optional Operation result (After hooks only)
previous Record<string, any> optional Record state before operation
submitted Record<string, any> optional What the caller submitted, as sent (update only) — diagnostics only, never the persist image
dispatch { mode: Enum<'record' | 'per-row'>; index: integer; scope: Record<string, any> } optional How this hook call relates to the caller's write (engine-produced)
session { userId?: string; actor?: string; organizationId?: string; accessToken?: string; … } optional Current session context
provenance { flowRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; … } optional Server-stamped write provenance (never client-supplied, never an authorization input)
referentialFieldClear boolean optional Engine-produced marker: true exactly when this write is the engine's own referential cleanup (the set_null cascade UPDATE clearing — or, for multiple: true, removing the deleted member from — a lookup, tree or user field that references a record being deleted, where a user field takes part only when it declares its deleteBehavior). Absent on every other write, including a user hand-clearing the same field; read as ctx.referentialFieldClear === true. The declared projection of the operation-private __referentialFieldClear, carried across the sandbox boundary by contract; server-derived and never client-supplied.
referentialCascadeDelete boolean optional Engine-produced marker: true exactly when this delete is one the engine's cascade issued (the child delete removing a row that references a record being deleted through a relation whose deleteBehavior resolves to cascade, at any depth), in both phases of that delete. Absent on every other delete, including a user hand-deleting the same child and a delete a hook issues through ctx.api; read as ctx.referentialCascadeDelete === true. The delete twin of referentialFieldClear, carried across the sandbox boundary by contract; server-derived, never client-supplied, and with no operation-private spelling to read instead.
transaction any optional Database transaction handle
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
user { id?: string; name?: string; email?: string; organizationId?: string } optional Current user info shortcut

Nested Shape: HookContext.dispatch

Property Type Required Description
mode Enum<'record' | 'per-row'> ✅ 'record' = this call is the caller's whole write; 'per-row' = one of N dispatches for one write
index integer ✅ 0-based position in the per-row fan-out; always 0 when mode is "record"
scope Record<string, any> ✅ Scratch shared by every dispatch of one caller write, across both phases (same object identity)

Nested Shape: HookContext.session

Property Type Required Description
userId string optional
actor string optional Service-principal label for audit attribution when the caller is not a real user (e.g. svc:flow:<flowName>)
organizationId string optional Active organization ID (blessed developer-facing name)
accessToken string optional
isSystem boolean optional True when the call was made with an elevated system context (engine self-writes)
skipTriggers boolean optional True when record-change automation (flow triggers) must be suppressed for this write — e.g. package seed replay. Lifecycle hooks still run.
skipAutomations boolean optional True when metadata-bound automation hooks must be suppressed for this write — e.g. a data import the system principal runs with "run automations" unchecked, or the system principal's import undo. Implies skipTriggers; code-registered system hooks (audit, security) still run. Only the system principal may take an app's declared controls off a write, and the import undo door is not an exception: an undo by any other caller runs under the object's hooks, record-change triggers and state machine.
positions string[] optional Position names held by the caller (ADR-0090 D3; formerly roles), copied from ExecutionContext.positions. For hook READS only — e.g. tailoring a message, or branching a business rule the hook runs through its own ctx.api channel. Authorization is decided by the security service on the ExecutionContext (permissions / positions / derived posture); this is NOT an authorization input and a hook must not gate a write by testing it. A hook context carries no services key, so the sharing service cannot be called from one either — the sharing gates already ran inside the engine before the hook chain.
preserveAudit boolean optional True when this write is a historical import that must KEEP its caller-supplied updated_at/updated_by (and the readonly audit family) instead of being stamped with the import instant. Server-set, opt-in, absent on normal writes; read by the built-in audit hook. A stamping policy, not an authorization input.
locale string optional The caller's locale (BCP-47), copied from ExecutionContext.locale: the request's Accept-Language, else the localization setting; absent on a write no person asked for. The body runner answers a declared refusal (HookSchema.refusals) in it. Descriptive only — not an authorization input.
principalKind Enum<'human' | 'agent' | 'service' | 'guest' | 'system'> optional What kind of principal is calling (ADR-0090 D10, ADR-0151 D5), copied verbatim from ExecutionContext.principalKind. A person reads human through every door; an agent reads agent — an OAuth client acting for the person in userId (with provenance.performedByClientId set) and an AI service account acting as itself (userId is the account, no performedByClientId) alike. Absent when the envelope carries no kind, which the envelope reads as human. Descriptive only — not an authorization input.
roles never optional [REMOVED] HookContext.session.roles was removed in @objectstack/spec 17.0.0 (ADR-0049 D2) — it was declared, read by two dead exemption branches, and never produced: ObjectQL's buildSession() builds the session field by field and has never written roles, so every read resolved undefined and a guard keyed on it was dead code that merely LOOKED like an authorization decision. Delete the key. To gate a hook on the caller, read ctx.session.userId / ctx.session.isSystem; to judge PRIVILEGE, ask the security service, which evaluates the ADR-0095 vocabulary on the execution context — capability grants (permissions), placements (positions) and the derived posture — never a role-name string comparison (ADR-0090 D3 bans the role spelling outright). Nothing to migrate: a HookContext is built per operation by the engine and never stored, so no metadata source carries this key. NOTE an ACTION body's ctx.session is a different object and still carries its own roles array today; that surface is tracked separately and is not what this key was.

Nested Shape: HookContext.provenance

Property Type Required Description
flowRunId string optional Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request.
attributedUserId string optional The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth update-member-role call the identity adapter executes as isSystem. ATTRIBUTION ONLY: the audit writer records it as sys_audit_log.user_id; no security middleware reads it, and it never becomes the subject the write is authorized as.
performedByClientId string optional [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (azp, a registered sys_oauth_application id) the access token was issued to, when an AI client acted on behalf of the human in session.userId. Copied from ExecutionContext.performedBy.clientId, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like attributedUserId: the audit writer records it in sys_audit_log.metadata as performed_by beside on_behalf_of; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork.
performedByAgentId string optional The in-product AI agent that performed this write for the signed-in person in session.userId, whose write it runs as: the agent the chat runs as. Copied from ExecutionContext.performedBy.agentId, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like performedByClientId: carried for the audit writer, which does not record it yet; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves.
performedByConversationId string optional The AI conversation an in-product AI write was performed in. Copied from ExecutionContext.performedBy.conversationId, set beside performedByAgentId. ATTRIBUTION ONLY: no security middleware reads it.
performedByConfirmationId string optional The confirmation the person gave before an AI-performed write ran: the id of the pending item their approval decided. Copied from ExecutionContext.performedBy.confirmationId; absent when the write needed no confirmation. ATTRIBUTION ONLY: no security middleware reads it, and it is never the authorization for the write, which runs as the person with every gate re-checked.
impersonatedBy string optional The ADMINISTRATOR (a sys_user id) who made this write from an impersonation session, while session.userId is the impersonated user the write is authorized as. Copied from ExecutionContext.impersonatedBy, which the shared request-identity resolution sets from the session read. ATTRIBUTION ONLY, exactly like performedByClientId: the audit writer records it as sys_audit_log.metadata.impersonated_by and on the sys_activity row; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the user made themselves.

Nested Shape: HookContext.user

Property Type Required Description
id string optional
name string optional
email string optional
organizationId string optional Active organization ID of the acting user (equals session.organizationId)

HookEvent

Allowed Values

  • beforeFind
  • afterFind
  • beforeInsert
  • afterInsert
  • beforeUpdate
  • afterUpdate
  • beforeDelete
  • afterDelete

HookRefusal

Properties

Property Type Required Description
message string ✅ The sentence the user reads when the hook throws this code — in the source locale, translated whole through hooks.<hook>.refusals.<CODE>.message in the caller's locale. With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused
status integer optional HTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides
reasons Record<string, { message: string }> optional Further sentences under this same code, keyed by the snake_case reason the hook 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 hook 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: HookRefusal.reasons[string]

Property Type Required Description
message string ✅ The sentence the user reads when the hook throws this reason under its code — in the source locale, translated through hooks.<hook>.refusals.<CODE>.reasons.<REASON>.message in the caller's locale; its {{ }} holes follow the entry's message rule