diff --git a/.changeset/32836-advisory-user-text.md b/.changeset/32836-advisory-user-text.md new file mode 100644 index 00000000000..6fce05ebaa4 --- /dev/null +++ b/.changeset/32836-advisory-user-text.md @@ -0,0 +1,17 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): the approval and flow advisories a flow save returns carry a user sentence in every platform locale + +Clause-②: no +Metadata-protocol: none + +Nineteen advisory rule ids that the save door returns on a flow write now carry `userTextParams` (the flow, node, object, field and input names their user sentence interpolates) and have a sentence in all eleven platform locales, each in a `*.user-text.ts` catalog beside its rule and merged into the one catalog `findingUserMessage` renders from: + +- approval approvers: `approval-approver-type-unknown`, `approval-expression-invalid` (its `info` arm, `resolveAs` on a non-expression approver), `approval-approver-not-membership-tier`, `approval-approver-type-deprecated`, `approval-approver-type-unsupported`, `approval-approvers-may-resolve-empty`, `approval-expression-no-empty-policy`, `approval-escalation-reassign-no-target`; +- flow trigger readiness: `flow-trigger-unknown-object` and `flow-input-unknown-object` (as advisories, with no package closure stated), `flow-input-object-less`, `flow-input-record-read-as-list`, `flow-draft-status-ambiguous`; +- flow template paths: `flow-template-unknown-field`, `flow-template-lookup-traversal`, `flow-template-field-unprovisioned`; +- `flow-node-write-unprovisioned-anchor`, `flow-update-readonly-when-field` and `flow-credential-literal`, whose sentence names where the credential sits and never its value. + +Rule ids, `message` and `hint` are unchanged, and the refusals that share an id with one of these advisories carry no params, so they render no user sentence. The `lintFlowCredentialLiterals` registry entry now keeps `userTextParams` when it re-maps its findings, so the publish gate's advisory carries them. Because the finding objects now carry `userTextParams`, `os validate --json` and `os build --json` show that key on these findings in `warnings`. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index c3e485679c4..fbc21007134 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2028,6 +2028,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ path: f.path, message: f.message, hint: f.hint, + // The user sentence's names ride through the re-map, so the save door + // can render this advisory in the request's language. + ...(f.userTextParams !== undefined ? { userTextParams: f.userTextParams } : {}), })), }, // [#29049] ADR-0031 region shape: a flow whose `loop` body, `parallel` diff --git a/packages/lint/src/finding-user-text.test.ts b/packages/lint/src/finding-user-text.test.ts index f718fd633f4..f1a00552570 100644 --- a/packages/lint/src/finding-user-text.test.ts +++ b/packages/lint/src/finding-user-text.test.ts @@ -17,6 +17,7 @@ import { mergeUserTextCatalogs, renderUserText, userTextLocaleOf, + type UserTextCatalog, type UserTextEntry, } from './finding-user-text.js'; import { SECURITY_POSTURE_USER_TEXT } from './validate-security-posture.user-text.js'; @@ -32,6 +33,40 @@ import { type SecurityFinding, } from './validate-security-posture.js'; import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { + APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER, + APPROVAL_APPROVER_TYPE_DEPRECATED, + APPROVAL_APPROVER_TYPE_UNKNOWN, + APPROVAL_APPROVER_TYPE_UNSUPPORTED, + APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + APPROVAL_ESCALATION_REASSIGN_NO_TARGET, + APPROVAL_EXPRESSION_INVALID, + APPROVAL_EXPRESSION_NO_EMPTY_POLICY, + validateApprovalApprovers, +} from './validate-approval-approvers.js'; +import { APPROVAL_APPROVERS_USER_TEXT } from './validate-approval-approvers.user-text.js'; +import { + FLOW_DRAFT_STATUS_AMBIGUOUS, + FLOW_INPUT_OBJECT_LESS, + FLOW_INPUT_RECORD_READ_AS_LIST, + FLOW_INPUT_UNKNOWN_OBJECT, + FLOW_TRIGGER_UNKNOWN_OBJECT, + validateFlowTriggerReadiness, +} from './validate-flow-trigger-readiness.js'; +import { FLOW_TRIGGER_READINESS_USER_TEXT } from './validate-flow-trigger-readiness.user-text.js'; +import { + FLOW_TEMPLATE_FIELD_UNPROVISIONED, + FLOW_TEMPLATE_LOOKUP_TRAVERSAL, + FLOW_TEMPLATE_UNKNOWN_FIELD, + validateFlowTemplatePaths, +} from './validate-flow-template-paths.js'; +import { FLOW_TEMPLATE_PATHS_USER_TEXT } from './validate-flow-template-paths.user-text.js'; +import { FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR, validateFlowNodeWrites } from './validate-flow-node-writes.js'; +import { FLOW_NODE_WRITES_USER_TEXT } from './validate-flow-node-writes.user-text.js'; +import { FLOW_UPDATE_READONLY_WHEN_FIELD, validateReadonlyFlowWrites } from './validate-readonly-flow-writes.js'; +import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; +import { FLOW_CREDENTIAL_LITERAL, lintFlowCredentialLiterals } from './lint-flow-credential-literals.js'; +import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; describe('finding user text · the locale ladder (request locale, then workspace default, then en)', () => { /** A synthetic entry with two sentences: English and Simplified Chinese. */ @@ -420,3 +455,558 @@ describe('security-posture user text · from the runtime gate to the wire field' expect(issue.message).toBe(advisory!.message); }); }); + +// ── The automation writes: approval, flow trigger and flow node advisories ── +// +// Six rule files' catalogs, pinned the way the security-posture catalog is +// above: exact coverage, every push site rendered from the rule's REAL +// findings in every platform locale, and each finding's flow written through +// the runtime gate so the advisory the save door returns carries its params. +// The ids pinned are the ones that reach the save door; the other advisory ids +// of the automation family's write-body rules are judged on no runtime write. + +/** A finding as every rule here returns it. */ +type AutomationFinding = { rule: string; severity: string; userTextParams?: Readonly> }; + +/** One advisory push site: a stack whose rule run draws exactly one finding of `rule`, with these params. */ +interface AdvisoryCase { + label: string; + rule: string; + stack: Record; + params: Record; +} + +/** Params that pick a sentence's arm rather than name something the sentence must show. */ +const ARM_PARAMS: ReadonlySet = new Set(['slate', 'locked', 'trigger', 'root', 'position']); + +const shownNamesOf = (params: Record): string[] => + Object.entries(params) + .filter(([key, value]) => !ARM_PARAMS.has(key) && value !== '') + .map(([, value]) => value); + +/** The catalog holds exactly `ids`, each in exactly the platform locales, and is the one the door renders from. */ +function pinCatalog(name: string, catalog: UserTextCatalog, ids: readonly string[]): void { + describe(`${name} user text · the catalog`, () => { + it('holds a sentence for exactly the rule\'s door-reaching advisory ids, in every platform locale and no other', () => { + expect(Object.keys(catalog).sort()).toEqual([...ids].sort()); + for (const [rule, entry] of Object.entries(catalog)) { + expect(Object.keys(entry).sort(), rule).toEqual([...PLATFORM_LOCALE_TAGS].sort()); + } + }); + + it('is merged into the one finding catalog the door renders from', () => { + for (const rule of ids) expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(catalog[rule]); + }); + }); +} + +/** + * Every case renders in every platform locale from the rule's real finding, + * and its flow, written through the runtime gate, returns that advisory with + * the same params and a `userMessage` the wire schema accepts. + */ +function pinCases( + name: string, + run: (stack: Record) => readonly AutomationFinding[], + cases: readonly AdvisoryCase[], +): void { + const findingOf = (c: AdvisoryCase): AutomationFinding => { + const found = run(c.stack).filter((f) => f.rule === c.rule); + expect(found, `${c.label}: exactly one ${c.rule} finding`).toHaveLength(1); + return found[0]!; + }; + + describe(`${name} user text · rendered from the rule's real findings`, () => { + it.each(cases.map((c) => [c.label, c] as const))('%s: carries its params and renders in every platform locale', (_label, c) => { + const finding = findingOf(c); + expect(finding.severity).not.toBe('error'); + expect(finding.userTextParams).toEqual(c.params); + + const english = findingUserMessage(finding, ['en'])!; + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding, [tag]); + expect(text, `${c.rule} · ${tag}`).toBeTruthy(); + expect(text, `${c.rule} · ${tag}`).not.toMatch(/undefined|\$\{/); + for (const shown of shownNamesOf(c.params)) expect(text, `${c.rule} · ${tag} names ${shown}`).toContain(shown); + // A real translation, not the English floor standing in for it. + if (tag !== 'en') expect(text, `${c.rule} · ${tag}`).not.toBe(english); + } + }); + + it('renders each rule\'s arms apart in every platform locale', () => { + const byRule = new Map(); + for (const c of cases) byRule.set(c.rule, [...(byRule.get(c.rule) ?? []), c]); + for (const [rule, armCases] of byRule) { + if (armCases.length < 2) continue; + for (const tag of PLATFORM_LOCALE_TAGS) { + const texts = armCases.map((c) => findingUserMessage(findingOf(c), [tag])!); + expect(new Set(texts).size, `${rule} · ${tag}`).toBe(armCases.length); + } + } + }); + }); + + describe(`${name} user text · from the runtime gate to the wire field`, () => { + it.each(cases.map((c) => [c.label, c] as const))('%s: the flow write returns the advisory with its params', (_label, c) => { + const flows = c.stack.flows as unknown[]; + expect(flows, c.label).toHaveLength(1); + const result = runRuntimeAuthoringRules({ + type: 'flow', + item: flows[0], + context: { objects: (c.stack.objects as unknown[] | undefined) ?? [] }, + }); + const advisory = result.advisories.find((f) => f.rule === c.rule); + expect(advisory, `${c.label}: the gate returns the ${c.rule} advisory`).toBeDefined(); + expect(advisory!.userTextParams).toEqual(c.params); + + // The element the save door's `advisories[]` carries, with the sentence + // the door renders for a zh-CN request beside the unchanged rule id. + const userMessage = findingUserMessage(advisory!, ['zh-CN', 'en']); + const issue = RuntimeAuthoringIssueSchema.parse({ + rule: advisory!.rule, + path: advisory!.path, + where: advisory!.where, + message: advisory!.message, + hint: advisory!.hint, + severity: advisory!.severity, + userMessage, + }); + expect(issue.rule).toBe(c.rule); + expect(issue.userMessage).toBe(findingUserMessage(advisory!, ['zh-Hans'])); + expect(issue.message).toBe(advisory!.message); + }); + }); +} + +// ── validate-approval-approvers ───────────────────────────────────────────── + +/** A one-node approval flow; `config` is merged into the approval node's. */ +const approvalStack = (approvers: unknown[], config: Record = {}) => ({ + flows: [{ + name: 'expense_approval', + nodes: [ + { id: 'start', type: 'start', config: {} }, + { id: 'manager_review', type: 'approval', config: { approvers, ...config } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'manager_review' }], + }], +}); +const AT = { flow: 'expense_approval', node: 'manager_review' }; + +const APPROVAL_CASES: readonly AdvisoryCase[] = [ + { + label: 'an off-spec approver type with a canonical fix', + rule: APPROVAL_APPROVER_TYPE_UNKNOWN, + stack: approvalStack([{ type: 'business_unit', value: 'sales' }]), + params: { ...AT, type: 'business_unit', suggested: 'department' }, + }, + { + label: 'an off-spec approver type with no fix', + rule: APPROVAL_APPROVER_TYPE_UNKNOWN, + stack: approvalStack([{ type: 'robot', value: 'r1' }]), + params: { ...AT, type: 'robot', suggested: '' }, + }, + { + label: 'resolveAs on a non-expression approver', + rule: APPROVAL_EXPRESSION_INVALID, + stack: approvalStack([{ type: 'user', value: 'u_finance_lead', resolveAs: 'users' }]), + params: { ...AT, type: 'user' }, + }, + { + label: 'a position name authored as a membership level', + rule: APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER, + stack: approvalStack([{ type: 'org_membership_level', value: 'sales_manager' }]), + params: { ...AT, value: 'sales_manager' }, + }, + { + label: 'the deprecated role spelling', + rule: APPROVAL_APPROVER_TYPE_DEPRECATED, + stack: approvalStack([{ type: 'role', value: 'admin' }]), + params: { ...AT, type: 'role', replacement: 'org_membership_level' }, + }, + { + label: 'an all-position slate on a locking node', + rule: APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + stack: approvalStack([{ type: 'position', value: 'finance_manager' }]), + params: { ...AT, slate: 'group', locked: 'yes' }, + }, + { + label: 'an all-position slate on a node that does not lock', + rule: APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + stack: approvalStack([{ type: 'position', value: 'finance_manager' }], { lockRecord: false }), + params: { ...AT, slate: 'group', locked: 'no' }, + }, + { + label: 'an all-manager slate', + rule: APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + stack: approvalStack([{ type: 'manager' }]), + params: { ...AT, slate: 'manager', locked: 'yes' }, + }, + { + label: 'an expression approver with no empty-slate policy', + rule: APPROVAL_EXPRESSION_NO_EMPTY_POLICY, + stack: approvalStack([{ type: 'expression', value: 'current.approvers_dynamic' }]), + params: { ...AT }, + }, + { + label: 'a reassign escalation with no target', + rule: APPROVAL_ESCALATION_REASSIGN_NO_TARGET, + stack: approvalStack([{ type: 'user', value: 'u_finance_lead' }], { escalation: { action: 'reassign' } }), + params: { ...AT }, + }, +]; + +pinCatalog('approval approvers', APPROVAL_APPROVERS_USER_TEXT, [ + APPROVAL_APPROVER_TYPE_UNKNOWN, + APPROVAL_EXPRESSION_INVALID, + APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER, + APPROVAL_APPROVER_TYPE_DEPRECATED, + APPROVAL_APPROVER_TYPE_UNSUPPORTED, + APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + APPROVAL_EXPRESSION_NO_EMPTY_POLICY, + APPROVAL_ESCALATION_REASSIGN_NO_TARGET, +]); +pinCases('approval approvers', validateApprovalApprovers, APPROVAL_CASES); + +describe('approval approvers user text · the arms say what the finding found', () => { + const en = (label: string) => findingUserMessage( + validateApprovalApprovers(APPROVAL_CASES.find((c) => c.label === label)!.stack) + .find((f) => f.rule === APPROVAL_CASES.find((c) => c.label === label)!.rule)!, + ['en'], + )!; + + it('offers the canonical type only where the rule has one', () => { + expect(en('an off-spec approver type with a canonical fix')).toContain('Change the type to "department"'); + expect(en('an off-spec approver type with no fix')).toContain('Choose one of the approver types'); + }); + + it('says the record stays locked only on a locking node, and names the cause of each slate', () => { + expect(en('an all-position slate on a locking node')).toContain('the record stays locked'); + expect(en('an all-position slate on a node that does not lock')).not.toContain('locked'); + expect(en('an all-manager slate')).toContain('has no manager set'); + }); + + it('an expression-invalid refusal carries no params, so it never renders the advisory\'s sentence', () => { + const refusal = validateApprovalApprovers(approvalStack([{ type: 'expression', value: '' }])) + .find((f) => f.rule === APPROVAL_EXPRESSION_INVALID)!; + expect(refusal.severity).toBe('error'); + expect(refusal.userTextParams).toBeUndefined(); + expect(findingUserMessage(refusal, ['zh-CN'])).toBeUndefined(); + }); +}); + +// ── validate-flow-trigger-readiness ───────────────────────────────────────── + +const CANDIDATE = { name: 'app_candidate', label: 'Candidate', fields: { name: { type: 'text', label: 'Name' } } }; + +/** A screen flow whose start input `variables` are declared; `nodes` follow its start node. */ +const inputFlowStack = (variables: unknown[], nodes: unknown[] = [], objects: unknown[] = [CANDIDATE]) => ({ + objects, + flows: [{ + name: 'review_candidates', + type: 'screen', + variables, + nodes: [{ id: 'start', type: 'start', config: {} }, ...nodes], + edges: [], + }], +}); + +const FLOW_TRIGGER_CASES: readonly AdvisoryCase[] = [ + { + label: 'a record trigger on an object the stack does not define', + rule: FLOW_TRIGGER_UNKNOWN_OBJECT, + stack: { + objects: [CANDIDATE], + flows: [{ + name: 'notify_on_hire', + type: 'record_change', + status: 'active', + nodes: [{ id: 'start', type: 'start', config: { triggerType: 'record-after-update', objectName: 'candidate' } }], + edges: [], + }], + }, + params: { flow: 'notify_on_hire', object: 'candidate', trigger: 'record' }, + }, + { + label: 'a time-relative sweep of an object the stack does not define', + rule: FLOW_TRIGGER_UNKNOWN_OBJECT, + stack: { + objects: [CANDIDATE], + flows: [{ + name: 'remind_before_interview', + type: 'schedule', + status: 'active', + nodes: [{ + id: 'start', + type: 'start', + config: { timeRelative: { object: 'interview', dateField: 'scheduled_at', offset: { value: -1, unit: 'days' } } }, + }], + edges: [], + }], + }, + params: { flow: 'remind_before_interview', object: 'interview', trigger: 'schedule' }, + }, + { + label: 'a start input declared a record of an undefined object', + rule: FLOW_INPUT_UNKNOWN_OBJECT, + stack: inputFlowStack([{ name: 'candidateId', type: 'text', isInput: true, objectName: 'app_candidat' }]), + params: { flow: 'review_candidates', input: 'candidateId', object: 'app_candidat' }, + }, + { + label: 'a start input declared a record of the object-less placeholder', + rule: FLOW_INPUT_OBJECT_LESS, + stack: inputFlowStack( + [{ name: 'recordId', type: 'text', isInput: true, objectName: 'global' }], + [], + [CANDIDATE, { name: 'global', label: 'Global', fields: {} }], + ), + params: { flow: 'review_candidates', input: 'recordId' }, + }, + { + label: 'one declared record id read as a list', + rule: FLOW_INPUT_RECORD_READ_AS_LIST, + stack: inputFlowStack( + [{ name: 'candidateIds', type: 'text', isInput: true, objectName: 'app_candidate' }], + [{ + id: 'load', + type: 'get_record', + label: 'Load candidates', + config: { objectName: 'app_candidate', filter: { id: { $in: { dialect: 'cel', source: 'candidateIds' } } } }, + }], + ), + params: { + flow: 'review_candidates', input: 'candidateIds', object: 'app_candidate', node: 'Load candidates', + listObject: 'app_candidate', + }, + }, + { + label: 'an auto-triggered flow left in draft', + rule: FLOW_DRAFT_STATUS_AMBIGUOUS, + stack: { + objects: [CANDIDATE], + flows: [{ + name: 'welcome_candidate', + type: 'record_change', + nodes: [{ id: 'start', type: 'start', config: { triggerType: 'record-after-create', objectName: 'app_candidate' } }], + edges: [], + }], + }, + params: { flow: 'welcome_candidate' }, + }, +]; + +pinCatalog('flow trigger readiness', FLOW_TRIGGER_READINESS_USER_TEXT, [ + FLOW_TRIGGER_UNKNOWN_OBJECT, + FLOW_INPUT_UNKNOWN_OBJECT, + FLOW_INPUT_OBJECT_LESS, + FLOW_INPUT_RECORD_READ_AS_LIST, + FLOW_DRAFT_STATUS_AMBIGUOUS, +]); +pinCases('flow trigger readiness', (stack) => validateFlowTriggerReadiness(stack), FLOW_TRIGGER_CASES); + +describe('flow trigger readiness user text · a refusal under a package closure renders no advisory sentence', () => { + it('the closure\'s unknown-object refusal carries no params', () => { + const refusal = validateFlowTriggerReadiness(FLOW_TRIGGER_CASES[0]!.stack, { + packageScope: { packageId: 'app_recruiting', dependencies: [] }, + }).find((f) => f.rule === FLOW_TRIGGER_UNKNOWN_OBJECT)!; + expect(refusal.severity).toBe('error'); + expect(refusal.userTextParams).toBeUndefined(); + expect(findingUserMessage(refusal, ['zh-CN'])).toBeUndefined(); + }); +}); + +// ── validate-flow-template-paths ──────────────────────────────────────────── + +const LEAD = { + name: 'crm_lead', + fields: { + company: { name: 'company', type: 'text' }, + crm_account: { name: 'crm_account', type: 'lookup', reference: 'crm_account' }, + }, +}; +const EXTERNAL_CUSTOMER = { + name: 'ext_customer', + external: { remoteName: 'customers' }, + fields: { email: { name: 'email', type: 'text' } }, +}; +/** A record-change flow on `object` with one notify node carrying `title`; `extra` nodes follow it. */ +const templateStack = (object: { name: string }, title: string, extra: unknown[] = []) => ({ + objects: [object, ...(object === LEAD ? [] : [LEAD])], + flows: [{ + name: 'notify_owner', + type: 'record_change', + status: 'active', + nodes: [ + { id: 'start', type: 'start', config: { objectName: object.name, triggerType: 'record-after-create' } }, + ...extra, + { id: 'n1', type: 'notify', notify: { title, body: 'x' } }, + ], + edges: [], + }], +}); + +const FLOW_TEMPLATE_CASES: readonly AdvisoryCase[] = [ + { + label: 'a placeholder naming no field', + rule: FLOW_TEMPLATE_UNKNOWN_FIELD, + stack: templateStack(LEAD, 'New lead: {{ record.compnay }}'), + params: { flow: 'notify_owner', reference: 'record.compnay', field: 'compnay', object: 'crm_lead' }, + }, + { + label: 'a hop through the trigger record\'s lookup', + rule: FLOW_TEMPLATE_LOOKUP_TRAVERSAL, + stack: templateStack(LEAD, 'From {{ record.crm_account.name }}'), + params: { + flow: 'notify_owner', reference: 'record.crm_account.name', field: 'crm_account', object: 'crm_lead', + root: 'trigger', + }, + }, + { + label: 'a hop through a bound variable\'s lookup', + rule: FLOW_TEMPLATE_LOOKUP_TRAVERSAL, + stack: templateStack(LEAD, 'Account {{ lead.crm_account.name }}', [{ + id: 'get_lead', + type: 'get_record', + config: { objectName: 'crm_lead', outputVariable: 'lead', filter: { id: { dialect: 'cel', source: 'record.id' } } }, + }]), + params: { + flow: 'notify_owner', reference: 'lead.crm_account.name', field: 'crm_account', object: 'crm_lead', + root: 'variable', + }, + }, + { + label: 'a placeholder over an external object\'s unprovisioned anchor', + rule: FLOW_TEMPLATE_FIELD_UNPROVISIONED, + stack: templateStack(EXTERNAL_CUSTOMER, 'Owned by {{ record.owner_id }}'), + params: { flow: 'notify_owner', reference: 'record.owner_id', field: 'owner_id', object: 'ext_customer' }, + }, +]; + +pinCatalog('flow template paths', FLOW_TEMPLATE_PATHS_USER_TEXT, [ + FLOW_TEMPLATE_UNKNOWN_FIELD, + FLOW_TEMPLATE_LOOKUP_TRAVERSAL, + FLOW_TEMPLATE_FIELD_UNPROVISIONED, +]); +pinCases('flow template paths', validateFlowTemplatePaths, FLOW_TEMPLATE_CASES); + +// ── validate-flow-node-writes · validate-readonly-flow-writes · lint-flow-credential-literals ── + +const WH_ORDER = { + name: 'wh_order', + datasource: 'warehouse', + external: { remoteName: 'fact_orders' }, + fields: { order_id: { type: 'text' }, amount: { type: 'currency' } }, +}; +const DEAL = { + name: 'crm_deal', + fields: { + stage: { type: 'text' }, + discount: { type: 'percent', readonlyWhen: "record.stage == 'closed_won'" }, + }, +}; +/** A record-change flow whose second node is `node`. */ +const oneNodeFlowStack = (name: string, objects: unknown[], node: Record) => ({ + objects, + flows: [{ + name, + type: 'record_change', + status: 'active', + runAs: 'user', + nodes: [{ id: 'start', type: 'start', config: {} }, node], + edges: [], + }], +}); + +const FLOW_NODE_WRITE_CASES: readonly AdvisoryCase[] = [ + { + label: 'an update writing an external object\'s unprovisioned anchor', + rule: FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR, + stack: oneNodeFlowStack('stamp_owner', [WH_ORDER], { + id: 'mark', + type: 'update_record', + label: 'Stamp', + config: { objectName: 'wh_order', filter: { id: { dialect: 'cel', source: 'recordId' } }, fields: { owner_id: '{user.id}' } }, + }), + params: { flow: 'stamp_owner', node: 'Stamp', field: 'owner_id', object: 'wh_order' }, + }, +]; + +const READONLY_FLOW_WRITE_CASES: readonly AdvisoryCase[] = [ + { + label: 'an update writing a readonlyWhen field', + rule: FLOW_UPDATE_READONLY_WHEN_FIELD, + stack: oneNodeFlowStack('apply_discount', [DEAL], { + id: 'set_discount', + type: 'update_record', + label: 'Set discount', + config: { objectName: 'crm_deal', filter: { id: { dialect: 'cel', source: 'recordId' } }, fields: { discount: 10 } }, + }), + params: { flow: 'apply_discount', node: 'Set discount', field: 'discount', object: 'crm_deal' }, + }, +]; + +/** A flow with one credential-shaped literal at `position`. */ +const credentialStack = (node: Record) => ({ + flows: [{ + name: 'sync_invoices', + type: 'autolaunched', + status: 'active', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, node], + edges: [], + }], +}); + +const FLOW_CREDENTIAL_CASES: readonly AdvisoryCase[] = [ + { + label: 'a credential in an http header', + rule: FLOW_CREDENTIAL_LITERAL, + stack: credentialStack({ + id: 'push_invoice', type: 'http', + config: { url: 'https://billing.invalid/invoices', method: 'POST', headers: { Authorization: 'Bearer user-text-probe-1' } }, + }), + params: { flow: 'sync_invoices', node: 'push_invoice', name: 'Authorization', position: 'header' }, + }, + { + label: 'a credential in a url query parameter', + rule: FLOW_CREDENTIAL_LITERAL, + stack: credentialStack({ + id: 'push_invoice', type: 'http', + config: { url: 'https://billing.invalid/invoices?api_key=user-text-probe-2', method: 'POST' }, + }), + params: { flow: 'sync_invoices', node: 'push_invoice', name: 'api_key', position: 'query' }, + }, + { + label: 'a credential in a connector input', + rule: FLOW_CREDENTIAL_LITERAL, + stack: credentialStack({ + id: 'push_invoice', type: 'connector_action', + connectorConfig: { connectorId: 'rest', actionId: 'request', input: { token: 'user-text-probe-3', path: '/p' } }, + }), + params: { flow: 'sync_invoices', node: 'push_invoice', name: 'token', position: 'input' }, + }, +]; + +pinCatalog('flow node writes', FLOW_NODE_WRITES_USER_TEXT, [FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR]); +pinCases('flow node writes', validateFlowNodeWrites, FLOW_NODE_WRITE_CASES); +pinCatalog('readonly flow writes', READONLY_FLOW_WRITES_USER_TEXT, [FLOW_UPDATE_READONLY_WHEN_FIELD]); +pinCases('readonly flow writes', validateReadonlyFlowWrites, READONLY_FLOW_WRITE_CASES); +pinCatalog('flow credential literals', FLOW_CREDENTIAL_LITERALS_USER_TEXT, [FLOW_CREDENTIAL_LITERAL]); +pinCases('flow credential literals', lintFlowCredentialLiterals, FLOW_CREDENTIAL_CASES); + +describe('flow credential literals user text · never the value', () => { + it('no sentence in any locale carries the credential, the save door\'s copy included', () => { + for (const c of FLOW_CREDENTIAL_CASES) { + const [finding] = lintFlowCredentialLiterals(c.stack); + for (const tag of PLATFORM_LOCALE_TAGS) { + expect(findingUserMessage(finding!, [tag]), `${c.label} · ${tag}`).not.toMatch(/user-text-probe/); + } + } + }); + + it('the registry entry\'s re-map keeps the params, so the door can render the sentence', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: (FLOW_CREDENTIAL_CASES[0]!.stack.flows as unknown[])[0] }); + const advisory = result.advisories.find((f) => f.rule === FLOW_CREDENTIAL_LITERAL)!; + expect(result.rulesRun).toContain('lintFlowCredentialLiterals'); + expect(findingUserMessage(advisory, ['ja-JP'])).toContain('ヘッダー「Authorization」'); + }); +}); diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index cceabc0cb69..c1ebb94add1 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -54,6 +54,12 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system'; import { SECURITY_POSTURE_USER_TEXT } from './validate-security-posture.user-text.js'; +import { APPROVAL_APPROVERS_USER_TEXT } from './validate-approval-approvers.user-text.js'; +import { FLOW_TRIGGER_READINESS_USER_TEXT } from './validate-flow-trigger-readiness.user-text.js'; +import { FLOW_TEMPLATE_PATHS_USER_TEXT } from './validate-flow-template-paths.user-text.js'; +import { FLOW_NODE_WRITES_USER_TEXT } from './validate-flow-node-writes.user-text.js'; +import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; +import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; import { CHART_BINDINGS_USER_TEXT } from './validate-chart-bindings.user-text.js'; @@ -157,6 +163,14 @@ export function mergeUserTextCatalogs(...catalogs: readonly UserTextCatalog[]): */ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( SECURITY_POSTURE_USER_TEXT, + // The automation writes: approval, flow trigger and flow node advisories. + APPROVAL_APPROVERS_USER_TEXT, + FLOW_TRIGGER_READINESS_USER_TEXT, + FLOW_TEMPLATE_PATHS_USER_TEXT, + FLOW_NODE_WRITES_USER_TEXT, + READONLY_FLOW_WRITES_USER_TEXT, + FLOW_CREDENTIAL_LITERALS_USER_TEXT, + // The dashboard writes: widget and chart binding advisories. WIDGET_BINDINGS_USER_TEXT, CHART_BINDINGS_USER_TEXT, ); diff --git a/packages/lint/src/lint-flow-credential-literals.ts b/packages/lint/src/lint-flow-credential-literals.ts index e9a20e77326..efcc58bedca 100644 --- a/packages/lint/src/lint-flow-credential-literals.ts +++ b/packages/lint/src/lint-flow-credential-literals.ts @@ -48,6 +48,7 @@ import { isCredentialShapedLiteral } from './credential-literal.js'; import { walkFlowNodes } from './flow-walk.js'; import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; type AnyRec = Record; @@ -66,6 +67,13 @@ export interface FlowCredentialLiteralFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates + * (`lint-flow-credential-literals.user-text.ts`): the flow, the node, the + * entry's NAME and its position. ⛔ Never the value, for the module note's + * reason; see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } /** @@ -157,7 +165,13 @@ export function lintFlowCredentialLiterals(stack: AnyRec): FlowCredentialLiteral const where = regionTrail ? `flow '${flowName}' · ${regionTrail} · node '${nodeId}' (${nodeType})` : `flow '${flowName}' · node '${nodeId}' (${nodeType})`; - const report = (entryPath: string, what: string, steer: string, route: string): void => { + const report = ( + entryPath: string, + what: string, + steer: string, + route: string, + entry: { name: string; position: 'header' | 'query' | 'input' }, + ): void => { findings.push({ severity: 'warning', rule: FLOW_CREDENTIAL_LITERAL, @@ -168,6 +182,7 @@ export function lintFlowCredentialLiterals(stack: AnyRec): FlowCredentialLiteral // `os explain flow-credential-literal`. message: `${what} holds a credential-shaped literal, ${SERVED}; ${steer}`, hint: route, + userTextParams: { flow: flowName, node: nodeId, name: entry.name, position: entry.position }, }); }; @@ -176,13 +191,19 @@ export function lintFlowCredentialLiterals(stack: AnyRec): FlowCredentialLiteral if (isRec(headers)) { for (const [name, value] of Object.entries(headers)) { if (!isCredentialShapedLiteral(name, value)) continue; - report(`${path}.config.headers${keySegment(name)}`, `header '${name}'`, STEER_CONNECTOR, HEADER_ROUTE); + report(`${path}.config.headers${keySegment(name)}`, `header '${name}'`, STEER_CONNECTOR, HEADER_ROUTE, { + name, + position: 'header', + }); } } if (typeof url === 'string') { for (const [name, value] of queryParameters(url)) { if (!isCredentialShapedLiteral(name, value)) continue; - report(`${path}.config.url`, `url query parameter '${name}'`, STEER_CONNECTOR, QUERY_ROUTE); + report(`${path}.config.url`, `url query parameter '${name}'`, STEER_CONNECTOR, QUERY_ROUTE, { + name, + position: 'query', + }); } } } @@ -202,7 +223,7 @@ export function lintFlowCredentialLiterals(stack: AnyRec): FlowCredentialLiteral return; } if (isCredentialShapedLiteral(name, value)) { - report(at, `connector input '${label}'`, STEER_INPUT, INPUT_ROUTE); + report(at, `connector input '${label}'`, STEER_INPUT, INPUT_ROUTE, { name: label, position: 'input' }); } }; walk(connectorConfig.input, '', `${path}.connectorConfig.input`, '', 0); diff --git a/packages/lint/src/lint-flow-credential-literals.user-text.ts b/packages/lint/src/lint-flow-credential-literals.user-text.ts new file mode 100644 index 00000000000..72a8b3a6a3b --- /dev/null +++ b/packages/lint/src/lint-flow-credential-literals.user-text.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `lint-flow-credential-literals.ts`'s advisory + * finding (`flow-credential-literal`), in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it, kept beside the rule so its wording and its translations + * change together. + * + * Who reads it: the person who saved a flow in Studio, in their own language, + * once the save door composes `RuntimeAuthoringIssueSchema.userMessage` from + * it. It says who can read the credential and where it belongs instead. + * + * Params, set at the push site in `lint-flow-credential-literals.ts`: `flow`, + * `node`, `name` (the header, query parameter or connector input the value + * sits under) and `position` (`header` · `query` · `input`). ⛔ Never the value + * itself, for the rule's module-note reason: the sentence travels into the + * save response too. + * + * `finding-user-text.test.ts` renders it from the rule's real + * findings in every platform locale, one per position. + */ + +import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; +import { FLOW_CREDENTIAL_LITERAL } from './lint-flow-credential-literals.js'; + +/** Where the credential sits, per locale: `header`, `query` or `input`, the entry named. */ +const POSITION = { + en: { header: 'header', query: 'URL query parameter', input: 'connector input' }, + 'zh-Hans': { header: '请求头', query: 'URL 查询参数', input: '连接器输入' }, + 'zh-Hant': { header: '請求標頭', query: 'URL 查詢參數', input: '連接器輸入' }, + es: { header: 'el encabezado', query: 'el parámetro de consulta de la URL', input: 'la entrada del conector' }, + ar: { header: 'الترويسة', query: 'معامل الاستعلام في عنوان URL', input: 'مُدخل الموصل' }, + fr: { header: 'l’en-tête', query: 'le paramètre de requête de l’URL', input: 'l’entrée du connecteur' }, + 'pt-BR': { header: 'o cabeçalho', query: 'o parâmetro de consulta da URL', input: 'a entrada do conector' }, + ru: { header: 'заголовок', query: 'параметр запроса URL', input: 'входной параметр коннектора' }, + de: { header: 'den Header', query: 'den URL-Abfrageparameter', input: 'die Connector-Eingabe' }, + ja: { header: 'ヘッダー', query: 'URL のクエリパラメーター', input: 'コネクタの入力' }, + ko: { header: '헤더', query: 'URL 쿼리 매개변수', input: '커넥터 입력' }, +} as const; + +const position = (locale: keyof typeof POSITION, p: UserTextParams): string => + POSITION[locale][p.position === 'query' ? 'query' : p.position === 'input' ? 'input' : 'header']; + +export const FLOW_CREDENTIAL_LITERALS_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_CREDENTIAL_LITERAL]: { + en: (p) => + `Node "${p.node}" in flow "${p.flow}" has a credential written directly into ${position('en', p)} ` + + `"${p.name}", so everyone who can view flows can read it. Store it in a connector's credentials and have ` + + `the flow call that connector instead.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的节点“${p.node}”在${position('zh-Hans', p)}“${p.name}”中直接写入了凭据,因此所有能查看流程的人都能读到它。` + + `请把它存放到连接器的凭据中,并改为让流程调用该连接器。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的節點「${p.node}」在${position('zh-Hant', p)}「${p.name}」中直接寫入了憑證,因此所有能檢視流程的人都能讀到它。` + + `請把它存放到連接器的憑證中,並改為讓流程呼叫該連接器。`, + es: (p) => + `El nodo "${p.node}" del flujo "${p.flow}" tiene una credencial escrita directamente en ` + + `${position('es', p)} "${p.name}", así que cualquiera que pueda ver los flujos puede leerla. Guárdela en ` + + `las credenciales de un conector y haga que el flujo llame a ese conector.`, + ar: (p) => + `تحتوي العقدة "${p.node}" في التدفق "${p.flow}" على بيانات اعتماد مكتوبة مباشرة في ${position('ar', p)} ` + + `"${p.name}"، لذلك يستطيع كل من يمكنه عرض التدفقات قراءتها. خزّنها في بيانات اعتماد موصل، واجعل التدفق ` + + `يستدعي ذلك الموصل بدلًا من ذلك.`, + fr: (p) => + `Le nœud « ${p.node} » du flux « ${p.flow} » contient un identifiant secret écrit directement dans ` + + `${position('fr', p)} « ${p.name} » : toute personne pouvant consulter les flux peut donc le lire. ` + + `Stockez-le dans les identifiants d’un connecteur et faites appeler ce connecteur par le flux.`, + 'pt-BR': (p) => + `O nó "${p.node}" do fluxo "${p.flow}" tem uma credencial escrita diretamente em ${position('pt-BR', p)} ` + + `"${p.name}", então qualquer pessoa que possa ver fluxos consegue lê-la. Guarde-a nas credenciais de um ` + + `conector e faça o fluxo chamar esse conector.`, + ru: (p) => + `В узле «${p.node}» потока «${p.flow}» учётные данные записаны прямо в ${position('ru', p)} «${p.name}», ` + + `поэтому их может прочитать любой, кто видит потоки. Сохраните их в учётных данных коннектора и вызывайте ` + + `этот коннектор из потока.`, + de: (p) => + `Der Knoten „${p.node}“ im Flow „${p.flow}“ enthält Zugangsdaten, die direkt in ${position('de', p)} ` + + `„${p.name}“ geschrieben sind. Jeder, der Flows sehen darf, kann sie daher lesen. Speichern Sie sie in den ` + + `Zugangsdaten eines Connectors, und lassen Sie den Flow stattdessen diesen Connector aufrufen.`, + ja: (p) => + `フロー「${p.flow}」のノード「${p.node}」で、${position('ja', p)}「${p.name}」に認証情報が直接書き込まれているため、` + + `フローを閲覧できる人なら誰でも読み取れます。認証情報はコネクタに保存し、フローからはそのコネクタを呼び出してください。`, + ko: (p) => + `플로우 "${p.flow}"의 노드 "${p.node}"에서 ${position('ko', p)} "${p.name}"에 자격 증명이 직접 작성되어 있어, ` + + `플로우를 볼 수 있는 사람은 누구나 읽을 수 있습니다. 자격 증명은 커넥터에 저장하고, 플로우가 그 커넥터를 ` + + `호출하도록 바꾸세요.`, + }, +}); diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 7ee40cce5e1..524647463d5 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -53,6 +53,7 @@ import { BUILTIN_MEMBERSHIP_ROLES } from '@objectstack/spec'; import { collectCelRootIdentifiers } from '@objectstack/formula'; import { walkFlowNodes } from './flow-walk.js'; import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; export const APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER = 'approval-approver-not-membership-tier'; export const APPROVAL_APPROVER_TYPE_DEPRECATED = 'approval-approver-type-deprecated'; @@ -267,6 +268,11 @@ export interface ApprovalApproverFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user sentence interpolates, on the advisory push + * sites only (``validate-approval-approvers.user-text.ts`` sibling catalog); see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -392,6 +398,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin hint: fix ? `Use the spec value: { type: '${fix}', value: '${value}' }.` : `Pick one of the spec values; unmapped types degrade to an inert '${type}:${value}' literal at runtime.`, + userTextParams: { flow: flowName, node: nodeId, type, suggested: fix ?? '' }, }); continue; } @@ -463,6 +470,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin path: `${path}.resolveAs`, message: `resolveAs has no effect on a '${type}' approver — it only applies to type 'expression'.`, hint: `Remove it, or switch this approver to { type: 'expression', value: '', resolveAs: '${String(a.resolveAs)}' }.`, + userTextParams: { flow: flowName, node: nodeId, type }, }); } @@ -488,6 +496,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin hint: `If it is an org position, author { type: 'position', value: '${value}' }; keep ` + `'org_membership_level' for the tiers the verdict lists`, + userTextParams: { flow: flowName, node: nodeId, value }, }); } else if (type in DEPRECATED_APPROVER_TYPES) { const fix = canonicalApproverType(type); @@ -500,6 +509,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin `approver type '${type}' is the deprecated spelling of '${fix}' (ADR-0090 D3) and ` + `is removed in the next major.`, hint: `Author { type: '${fix}', value: '${value}' }. It resolves identically today.`, + userTextParams: { flow: flowName, node: nodeId, type, replacement: fix }, }); } else if ( (APPROVER_VALUE_BINDINGS as Record)[canonical]?.source === 'unsupported' @@ -523,6 +533,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin hint: `Route to people the engine can expand: ` + `{ type: ${EXPANDABLE_GROUP_TYPES.map((t) => `'${t}'`).join(' | ')}, ... }.`, + userTextParams: { flow: flowName, node: nodeId, type, routes: EXPANDABLE_GROUP_TYPES.join(', ') }, }); } @@ -580,6 +591,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin `none is staffed the request opens on the organization's administrators` + (locks ? STAYS_LOCKED : ''), hint: GROUP_ONLY_FIX, + userTextParams: { flow: flowName, node: nodeId, slate: 'group', locked: locks ? 'yes' : 'no' }, }); } @@ -626,6 +638,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin `is unset the request opens on the organization's administrators` + (locks ? STAYS_LOCKED : ''), hint: MANAGER_ONLY_FIX, + userTextParams: { flow: flowName, node: nodeId, slate: 'manager', locked: locks ? 'yes' : 'no' }, }); } @@ -653,6 +666,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin hint: `Declare onEmptyApprovers on the node: 'admin_rescue', 'fail', 'auto_approve', or 'fallback' ` + `with a fallbackApprovers list`, + userTextParams: { flow: flowName, node: nodeId }, }); } @@ -694,6 +708,7 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin hint: `Set escalateTo to a position machine name (expanded via sys_user_position, ` + `ADR-0090 D3) or a specific user id, or change action to 'notify'.`, + userTextParams: { flow: flowName, node: nodeId }, }); } } diff --git a/packages/lint/src/validate-approval-approvers.unsupported-type.test.ts b/packages/lint/src/validate-approval-approvers.unsupported-type.test.ts index 5919b939cf7..9023d429e64 100644 --- a/packages/lint/src/validate-approval-approvers.unsupported-type.test.ts +++ b/packages/lint/src/validate-approval-approvers.unsupported-type.test.ts @@ -1,6 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, expect, it, vi } from 'vitest'; +import { RuntimeAuthoringIssueSchema } from '@objectstack/spec/api'; +import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; // No approver binding is `unsupported` today (ADR-0142 D6 implemented the // last one, `queue`), so the `approval-approver-type-unsupported` arm is @@ -42,3 +44,54 @@ describe('approval-approver-type-unsupported', () => { ); }); }); + +// The user sentence of the same arm, reachable only against this file's table. +describe('approval-approver-type-unsupported · user text', async () => { + const { findingUserMessage, FINDING_USER_TEXT_CATALOG } = await import('./finding-user-text.js'); + const { APPROVAL_APPROVERS_USER_TEXT } = await import('./validate-approval-approvers.user-text.js'); + const { runRuntimeAuthoringRules } = await import('./runtime-gate.js'); + const flow = { + name: 'expense_approval', + nodes: [{ id: 'step1', type: 'approval', config: { approvers: [{ type: 'team', value: 't1' }] } }], + edges: [], + }; + const [finding] = validateApprovalApprovers({ flows: [flow] }).filter((f) => f.rule === APPROVAL_APPROVER_TYPE_UNSUPPORTED); + + it('carries its params, the routes derived as the hint derives them', () => { + expect(finding!.userTextParams).toEqual({ + flow: 'expense_approval', node: 'step1', type: 'team', routes: 'position, department, queue', + }); + expect(FINDING_USER_TEXT_CATALOG[APPROVAL_APPROVER_TYPE_UNSUPPORTED]).toBe( + APPROVAL_APPROVERS_USER_TEXT[APPROVAL_APPROVER_TYPE_UNSUPPORTED], + ); + }); + + it('renders in every platform locale, naming the type and the routes, never the English floor', () => { + const english = findingUserMessage(finding!, ['en'])!; + expect(english).toContain('position, department, queue'); + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding!, [tag])!; + expect(text, tag).not.toMatch(/undefined|\$\{/); + for (const shown of ['expense_approval', 'step1', 'team', 'position, department, queue']) { + expect(text, `${tag} names ${shown}`).toContain(shown); + } + if (tag !== 'en') expect(text, tag).not.toBe(english); + } + }); + + it('the flow write returns the advisory, and its userMessage parses as the wire field', () => { + const advisory = runRuntimeAuthoringRules({ type: 'flow', item: flow }).advisories + .find((f) => f.rule === APPROVAL_APPROVER_TYPE_UNSUPPORTED)!; + expect(advisory.userTextParams).toEqual(finding!.userTextParams); + const issue = RuntimeAuthoringIssueSchema.parse({ + rule: advisory.rule, + path: advisory.path, + where: advisory.where, + message: advisory.message, + hint: advisory.hint, + severity: advisory.severity, + userMessage: findingUserMessage(advisory, ['ko-KR']), + }); + expect(issue.userMessage).toBe(findingUserMessage(advisory, ['ko'])); + }); +}); diff --git a/packages/lint/src/validate-approval-approvers.user-text.ts b/packages/lint/src/validate-approval-approvers.user-text.ts new file mode 100644 index 00000000000..09d4412f13c --- /dev/null +++ b/packages/lint/src/validate-approval-approvers.user-text.ts @@ -0,0 +1,460 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-approval-approvers.ts`'s advisory + * findings, in every platform locale (`PLATFORM_LOCALE_TAGS`, + * `@objectstack/spec/system`). The finding mechanism and the locale ladder are + * `finding-user-text.ts`'s; this file is the rule's own half of it, kept beside + * the rule so its wording and its translations change together. + * + * Who reads these: the person who saved an approval flow in Studio, in their + * own language, once the save door composes + * `RuntimeAuthoringIssueSchema.userMessage` from them. So each sentence says + * what the approver setting does to the request and the one change that fixes + * it, in the console's words for approvals (approver, position, request); the + * developer-facing detail stays in the finding's `message`, `hint` and + * `os explain` entry. + * + * Each entry reads the `userTextParams` its finding carries, set at the push + * site in `validate-approval-approvers.ts`. Every entry reads `flow` and `node` + * (the flow's and the approval node's names, as the rule's `where` shows them): + * + * | rule id | further params | + * |---|---| + * | `approval-approver-type-unknown` | `type`, `suggested` (the spec value an off-spec spelling maps to, `''` when none) | + * | `approval-expression-invalid` (the `info` arm only) | `type` | + * | `approval-approver-not-membership-tier` | `value` | + * | `approval-approver-type-deprecated` | `type`, `replacement` | + * | `approval-approver-type-unsupported` | `type`, `routes` (the expandable group types, comma-joined) | + * | `approval-approvers-may-resolve-empty` | `slate` (`group` · `manager`), `locked` (`yes` · `no`) | + * | `approval-expression-no-empty-policy` | — | + * | `approval-escalation-reassign-no-target` | — | + * + * `approval-expression-invalid` is also this rule's `error` id for an + * expression that cannot run; those push sites carry no params, so a refusal + * never renders the advisory's sentence. Like the rule's own `message`, no + * sentence names what an empty slate does beyond what the finding states. + * + * `finding-user-text.test.ts` renders every entry from the rule's real + * findings in every platform locale; the unsupported-type arm, which no + * shipped binding reaches, is rendered against a mocked binding table in + * `validate-approval-approvers.unsupported-type.test.ts`. + */ + +import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; +import { + APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER, + APPROVAL_APPROVER_TYPE_DEPRECATED, + APPROVAL_APPROVER_TYPE_UNKNOWN, + APPROVAL_APPROVER_TYPE_UNSUPPORTED, + APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, + APPROVAL_ESCALATION_REASSIGN_NO_TARGET, + APPROVAL_EXPRESSION_INVALID, + APPROVAL_EXPRESSION_NO_EMPTY_POLICY, +} from './validate-approval-approvers.js'; + +/** The `locked: 'yes'` clause of the empty-slate sentence, per locale. */ +const STAYS_LOCKED = { + en: ', and the record stays locked', + 'zh-Hans': ',且该记录会保持锁定', + 'zh-Hant': ',且該記錄會保持鎖定', + es: ', y el registro permanece bloqueado', + ar: '، ويظل السجل مقفلًا', + fr: ', et l’enregistrement reste verrouillé', + 'pt-BR': ', e o registro permanece bloqueado', + ru: ', а запись остаётся заблокированной', + de: ', und der Datensatz bleibt gesperrt', + ja: '。その間、レコードはロックされたままになります', + ko: ', 레코드는 잠긴 상태로 유지됩니다', +} as const; + +const locked = (locale: keyof typeof STAYS_LOCKED, p: UserTextParams): string => + p.locked === 'yes' ? STAYS_LOCKED[locale] : ''; + +export const APPROVAL_APPROVERS_USER_TEXT: UserTextCatalog = Object.freeze({ + [APPROVAL_APPROVER_TYPE_UNKNOWN]: { + en: (p) => + `Approval node "${p.node}" in flow "${p.flow}" has an approver of type "${p.type}", which is not an ` + + `approver type, so it reaches no one. ` + + (p.suggested ? `Change the type to "${p.suggested}".` : `Choose one of the approver types the editor offers.`), + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”中有一个类型为“${p.type}”的审批人,但这不是有效的审批人类型,因此不会分配给任何人。` + + (p.suggested ? `请将类型改为“${p.suggested}”。` : `请从编辑器提供的审批人类型中选择一种。`), + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」中有一個類型為「${p.type}」的審批人,但這不是有效的審批人類型,因此不會分派給任何人。` + + (p.suggested ? `請將類型改為「${p.suggested}」。` : `請從編輯器提供的審批人類型中選擇一種。`), + es: (p) => + `El nodo de aprobación "${p.node}" del flujo "${p.flow}" tiene un aprobador de tipo "${p.type}", que no es ` + + `un tipo de aprobador, así que no llega a nadie. ` + + (p.suggested ? `Cambie el tipo a "${p.suggested}".` : `Elija uno de los tipos de aprobador que ofrece el editor.`), + ar: (p) => + `تحتوي عقدة الموافقة "${p.node}" في التدفق "${p.flow}" على موافق من النوع "${p.type}"، وهو ليس نوع موافق ` + + `صالحًا، لذلك لا يصل إلى أي شخص. ` + + (p.suggested ? `غيّر النوع إلى "${p.suggested}".` : `اختر أحد أنواع الموافقين التي يعرضها المحرر.`), + fr: (p) => + `Le nœud d’approbation « ${p.node} » du flux « ${p.flow} » a un approbateur de type « ${p.type} », qui ` + + `n’est pas un type d’approbateur : il n’atteint donc personne. ` + + (p.suggested + ? `Remplacez le type par « ${p.suggested} ».` + : `Choisissez l’un des types d’approbateur proposés par l’éditeur.`), + 'pt-BR': (p) => + `O nó de aprovação "${p.node}" do fluxo "${p.flow}" tem um aprovador do tipo "${p.type}", que não é um ` + + `tipo de aprovador, então ele não chega a ninguém. ` + + (p.suggested ? `Altere o tipo para "${p.suggested}".` : `Escolha um dos tipos de aprovador que o editor oferece.`), + ru: (p) => + `В узле согласования «${p.node}» потока «${p.flow}» есть согласующий типа «${p.type}», но такого типа ` + + `согласующих не существует, поэтому он никому не назначается. ` + + (p.suggested ? `Измените тип на «${p.suggested}».` : `Выберите один из типов согласующих, которые предлагает редактор.`), + de: (p) => + `Der Genehmigungsknoten „${p.node}“ im Flow „${p.flow}“ hat einen Genehmiger vom Typ „${p.type}“. Das ist ` + + `kein Genehmigertyp, daher erreicht er niemanden. ` + + (p.suggested ? `Ändern Sie den Typ in „${p.suggested}“.` : `Wählen Sie einen der Genehmigertypen, die der Editor anbietet.`), + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」に、種類が「${p.type}」の承認者があります。これは承認者の種類ではないため、` + + `誰にも割り当てられません。` + + (p.suggested ? `種類を「${p.suggested}」に変更してください。` : `エディターに表示される承認者の種類から選んでください。`), + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"에 유형이 "${p.type}"인 승인자가 있습니다. 이는 승인자 유형이 아니므로 ` + + `아무에게도 배정되지 않습니다. ` + + (p.suggested ? `유형을 "${p.suggested}"(으)로 바꾸세요.` : `편집기에서 제공하는 승인자 유형 중 하나를 선택하세요.`), + }, + [APPROVAL_EXPRESSION_INVALID]: { + en: (p) => + `An approver of type "${p.type}" on approval node "${p.node}" in flow "${p.flow}" has a resolve-as ` + + `setting, which only expression approvers use, so it has no effect. Remove the setting, or make the ` + + `approver an expression approver.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”中,类型为“${p.type}”的审批人设置了解析方式(resolveAs),但只有表达式审批人会使用该设置,` + + `因此它不起作用。请删除该设置,或将该审批人改为表达式审批人。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」中,類型為「${p.type}」的審批人設定了解析方式(resolveAs),但只有運算式審批人會使用該設定,` + + `因此它不起作用。請刪除該設定,或將該審批人改為運算式審批人。`, + es: (p) => + `Un aprobador de tipo "${p.type}" del nodo de aprobación "${p.node}" del flujo "${p.flow}" tiene un ajuste ` + + `de resolución (resolveAs), que solo usan los aprobadores de expresión, así que no tiene efecto. Quite el ` + + `ajuste o convierta el aprobador en un aprobador de expresión.`, + ar: (p) => + `يحتوي موافق من النوع "${p.type}" في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" على إعداد طريقة الحل ` + + `(resolveAs)، ولا تستخدمه إلا موافقات التعبير، لذلك لا أثر له. أزل الإعداد، أو اجعل الموافق موافق تعبير.`, + fr: (p) => + `Un approbateur de type « ${p.type} » du nœud d’approbation « ${p.node} » du flux « ${p.flow} » a un ` + + `réglage de résolution (resolveAs), que seuls les approbateurs par expression utilisent : il n’a donc aucun ` + + `effet. Supprimez ce réglage ou faites de cet approbateur un approbateur par expression.`, + 'pt-BR': (p) => + `Um aprovador do tipo "${p.type}" no nó de aprovação "${p.node}" do fluxo "${p.flow}" tem uma configuração ` + + `de resolução (resolveAs), que só aprovadores de expressão usam, então ela não tem efeito. Remova a ` + + `configuração ou transforme o aprovador em um aprovador de expressão.`, + ru: (p) => + `У согласующего типа «${p.type}» в узле согласования «${p.node}» потока «${p.flow}» задан способ разрешения ` + + `(resolveAs), который используют только согласующие-выражения, поэтому он ни на что не влияет. Удалите эту ` + + `настройку или сделайте согласующего выражением.`, + de: (p) => + `Ein Genehmiger vom Typ „${p.type}“ im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ hat eine ` + + `Auflösungseinstellung (resolveAs), die nur Ausdrucksgenehmiger verwenden, daher bleibt sie wirkungslos. ` + + `Entfernen Sie die Einstellung, oder machen Sie den Genehmiger zu einem Ausdrucksgenehmiger.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」で、種類が「${p.type}」の承認者に解決方法(resolveAs)が設定されていますが、` + + `この設定を使うのは式の承認者だけなので効果はありません。設定を削除するか、この承認者を式の承認者にしてください。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"에서 유형이 "${p.type}"인 승인자에 확인 방식(resolveAs)이 설정되어 ` + + `있지만, 이 설정은 표현식 승인자만 사용하므로 효과가 없습니다. 설정을 제거하거나 이 승인자를 표현식 승인자로 바꾸세요.`, + }, + [APPROVAL_APPROVER_NOT_MEMBERSHIP_TIER]: { + en: (p) => + `An approver on approval node "${p.node}" in flow "${p.flow}" is set to membership level "${p.value}", ` + + `which is not a membership level, so it matches no one. If "${p.value}" is a position, change the ` + + `approver type to position.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”中,有一个审批人被设为成员级别“${p.value}”,但这不是成员级别,因此匹配不到任何人。` + + `如果“${p.value}”是一个岗位,请把审批人类型改为岗位。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」中,有一個審批人被設為成員級別「${p.value}」,但這不是成員級別,因此比對不到任何人。` + + `如果「${p.value}」是一個崗位,請把審批人類型改為崗位。`, + es: (p) => + `Un aprobador del nodo de aprobación "${p.node}" del flujo "${p.flow}" tiene el nivel de membresía ` + + `"${p.value}", que no es un nivel de membresía, así que no coincide con nadie. Si "${p.value}" es un ` + + `puesto, cambie el tipo de aprobador a puesto.`, + ar: (p) => + `تم تعيين موافق في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" على مستوى العضوية "${p.value}"، وهو ليس ` + + `مستوى عضوية، لذلك لا يطابق أي شخص. إذا كان "${p.value}" منصبًا، فغيّر نوع الموافق إلى منصب.`, + fr: (p) => + `Un approbateur du nœud d’approbation « ${p.node} » du flux « ${p.flow} » est défini sur le niveau ` + + `d’adhésion « ${p.value} », qui n’est pas un niveau d’adhésion : il ne correspond donc à personne. Si ` + + `« ${p.value} » est un poste, changez le type d’approbateur en poste.`, + 'pt-BR': (p) => + `Um aprovador no nó de aprovação "${p.node}" do fluxo "${p.flow}" está definido com o nível de associação ` + + `"${p.value}", que não é um nível de associação, então não corresponde a ninguém. Se "${p.value}" for um ` + + `cargo, altere o tipo de aprovador para cargo.`, + ru: (p) => + `Согласующему в узле согласования «${p.node}» потока «${p.flow}» задан уровень участника «${p.value}», но ` + + `такого уровня нет, поэтому он никому не соответствует. Если «${p.value}» — это должность, измените тип ` + + `согласующего на «должность».`, + de: (p) => + `Ein Genehmiger im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ ist auf die Mitgliedsstufe ` + + `„${p.value}“ gesetzt. Das ist keine Mitgliedsstufe, daher passt er auf niemanden. Wenn „${p.value}“ eine ` + + `Position ist, ändern Sie den Genehmigertyp in Position.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」で、承認者にメンバーシップレベル「${p.value}」が設定されていますが、` + + `これはメンバーシップレベルではないため、誰にも一致しません。「${p.value}」がポジションなら、承認者の種類をポジションに変更してください。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"에서 승인자가 멤버십 수준 "${p.value}"(으)로 설정되어 있지만, ` + + `이는 멤버십 수준이 아니므로 아무와도 일치하지 않습니다. "${p.value}"이(가) 직책이라면 승인자 유형을 직책으로 바꾸세요.`, + }, + [APPROVAL_APPROVER_TYPE_DEPRECATED]: { + en: (p) => + `An approver on approval node "${p.node}" in flow "${p.flow}" uses the old approver type "${p.type}". It ` + + `still works, but it will be removed in the next major version: change it to "${p.replacement}".`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”中,有一个审批人使用了旧的审批人类型“${p.type}”。它目前仍然可用,` + + `但会在下一个主版本中移除:请改为“${p.replacement}”。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」中,有一個審批人使用了舊的審批人類型「${p.type}」。它目前仍然可用,` + + `但會在下一個主版本中移除:請改為「${p.replacement}」。`, + es: (p) => + `Un aprobador del nodo de aprobación "${p.node}" del flujo "${p.flow}" usa el tipo de aprobador antiguo ` + + `"${p.type}". Todavía funciona, pero se eliminará en la próxima versión principal: cámbielo a ` + + `"${p.replacement}".`, + ar: (p) => + `يستخدم موافق في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" نوع الموافق القديم "${p.type}". لا يزال ` + + `يعمل، لكنه سيُزال في الإصدار الرئيسي التالي: غيّره إلى "${p.replacement}".`, + fr: (p) => + `Un approbateur du nœud d’approbation « ${p.node} » du flux « ${p.flow} » utilise l’ancien type ` + + `d’approbateur « ${p.type} ». Il fonctionne encore, mais il sera supprimé dans la prochaine version ` + + `majeure : remplacez-le par « ${p.replacement} ».`, + 'pt-BR': (p) => + `Um aprovador no nó de aprovação "${p.node}" do fluxo "${p.flow}" usa o tipo de aprovador antigo ` + + `"${p.type}". Ele ainda funciona, mas será removido na próxima versão principal: altere-o para ` + + `"${p.replacement}".`, + ru: (p) => + `Согласующий в узле согласования «${p.node}» потока «${p.flow}» использует устаревший тип «${p.type}». ` + + `Он пока работает, но будет удалён в следующей мажорной версии: замените его на «${p.replacement}».`, + de: (p) => + `Ein Genehmiger im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ verwendet den alten Genehmigertyp ` + + `„${p.type}“. Er funktioniert noch, wird aber in der nächsten Hauptversion entfernt: Ändern Sie ihn in ` + + `„${p.replacement}“.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」の承認者が、古い承認者の種類「${p.type}」を使っています。` + + `現在は動作しますが、次のメジャーバージョンで削除されます。「${p.replacement}」に変更してください。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"에 있는 승인자가 이전 승인자 유형 "${p.type}"을(를) 사용합니다. ` + + `지금은 동작하지만 다음 주 버전에서 제거됩니다. "${p.replacement}"(으)로 바꾸세요.`, + }, + [APPROVAL_APPROVER_TYPE_UNSUPPORTED]: { + en: (p) => + `An approver on approval node "${p.node}" in flow "${p.flow}" has type "${p.type}", which the platform ` + + `does not support, so it reaches no one. Change it to one of these approver types: ${p.routes}.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”中,有一个审批人的类型是“${p.type}”,平台不支持该类型,因此不会分配给任何人。` + + `请改为以下审批人类型之一:${p.routes}。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」中,有一個審批人的類型是「${p.type}」,平台不支援該類型,因此不會分派給任何人。` + + `請改為以下審批人類型之一:${p.routes}。`, + es: (p) => + `Un aprobador del nodo de aprobación "${p.node}" del flujo "${p.flow}" es de tipo "${p.type}", que la ` + + `plataforma no admite, así que no llega a nadie. Cámbielo a uno de estos tipos de aprobador: ${p.routes}.`, + ar: (p) => + `موافق في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" من النوع "${p.type}"، وهو نوع لا تدعمه المنصة، ` + + `لذلك لا يصل إلى أي شخص. غيّره إلى أحد أنواع الموافقين هذه: ${p.routes}.`, + fr: (p) => + `Un approbateur du nœud d’approbation « ${p.node} » du flux « ${p.flow} » est de type « ${p.type} », que ` + + `la plateforme ne prend pas en charge : il n’atteint donc personne. Remplacez-le par l’un de ces types ` + + `d’approbateur : ${p.routes}.`, + 'pt-BR': (p) => + `Um aprovador no nó de aprovação "${p.node}" do fluxo "${p.flow}" é do tipo "${p.type}", que a plataforma ` + + `não suporta, então ele não chega a ninguém. Altere-o para um destes tipos de aprovador: ${p.routes}.`, + ru: (p) => + `Согласующий в узле согласования «${p.node}» потока «${p.flow}» имеет тип «${p.type}», который платформа ` + + `не поддерживает, поэтому он никому не назначается. Выберите один из этих типов: ${p.routes}.`, + de: (p) => + `Ein Genehmiger im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ hat den Typ „${p.type}“, den die ` + + `Plattform nicht unterstützt, daher erreicht er niemanden. Ändern Sie ihn in einen dieser Genehmigertypen: ` + + `${p.routes}.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」の承認者の種類「${p.type}」はプラットフォームでサポートされていないため、` + + `誰にも割り当てられません。次の承認者の種類のいずれかに変更してください: ${p.routes}。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"에 있는 승인자의 유형 "${p.type}"은(는) 플랫폼에서 지원하지 않으므로 ` + + `아무에게도 배정되지 않습니다. 다음 승인자 유형 중 하나로 바꾸세요: ${p.routes}.`, + }, + [APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY]: { + en: (p) => + p.slate === 'manager' + ? `Every approver on approval node "${p.node}" in flow "${p.flow}" is a manager, so when the user it ` + + `looks up has no manager set, the request goes to the organization's administrators${locked('en', p)}. ` + + `Set the users' managers, or add an approver who is always there.` + : `Every approver on approval node "${p.node}" in flow "${p.flow}" is a position, team, department or ` + + `queue, so if none of them has anyone in it, the request goes to the organization's ` + + `administrators${locked('en', p)}. Add an approver who is always there, or name fallback approvers.`, + 'zh-Hans': (p) => + p.slate === 'manager' + ? `流程“${p.flow}”的审批节点“${p.node}”中的审批人全部是上级经理,因此当所查找的用户没有设置经理时,` + + `申请会转给组织的管理员${locked('zh-Hans', p)}。请为这些用户设置经理,或添加一个始终有人的审批人。` + : `流程“${p.flow}”的审批节点“${p.node}”中的审批人全部是岗位、团队、部门或队列,因此如果其中都没有人,` + + `申请会转给组织的管理员${locked('zh-Hans', p)}。请添加一个始终有人的审批人,或指定备用审批人。`, + 'zh-Hant': (p) => + p.slate === 'manager' + ? `流程「${p.flow}」的審批節點「${p.node}」中的審批人全部是上級經理,因此當所查找的使用者沒有設定經理時,` + + `申請會轉給組織的管理員${locked('zh-Hant', p)}。請為這些使用者設定經理,或新增一個始終有人的審批人。` + : `流程「${p.flow}」的審批節點「${p.node}」中的審批人全部是崗位、團隊、部門或佇列,因此如果其中都沒有人,` + + `申請會轉給組織的管理員${locked('zh-Hant', p)}。請新增一個始終有人的審批人,或指定備用審批人。`, + es: (p) => + p.slate === 'manager' + ? `Todos los aprobadores del nodo de aprobación "${p.node}" del flujo "${p.flow}" son gerentes, así que ` + + `cuando el usuario consultado no tiene gerente asignado, la solicitud pasa a los administradores de la ` + + `organización${locked('es', p)}. Asigne gerente a esos usuarios o añada un aprobador que siempre esté ` + + `disponible.` + : `Todos los aprobadores del nodo de aprobación "${p.node}" del flujo "${p.flow}" son puestos, equipos, ` + + `departamentos o colas, así que si ninguno tiene a nadie asignado, la solicitud pasa a los ` + + `administradores de la organización${locked('es', p)}. Añada un aprobador que siempre esté disponible ` + + `o indique aprobadores de respaldo.`, + ar: (p) => + p.slate === 'manager' + ? `كل الموافقين في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" مديرون، لذلك عندما لا يكون للمستخدم ` + + `الذي يُبحث عنه مدير محدد، ينتقل الطلب إلى مسؤولي المؤسسة${locked('ar', p)}. حدّد مديري المستخدمين، أو ` + + `أضف موافقًا متاحًا دائمًا.` + : `كل الموافقين في عقدة الموافقة "${p.node}" في التدفق "${p.flow}" مناصب أو فرق أو أقسام أو قوائم انتظار، ` + + `لذلك إذا لم يكن في أي منها أحد، ينتقل الطلب إلى مسؤولي المؤسسة${locked('ar', p)}. أضف موافقًا متاحًا ` + + `دائمًا، أو حدّد موافقين احتياطيين.`, + fr: (p) => + p.slate === 'manager' + ? `Tous les approbateurs du nœud d’approbation « ${p.node} » du flux « ${p.flow} » sont des managers : ` + + `quand l’utilisateur concerné n’a pas de manager défini, la demande va aux administrateurs de ` + + `l’organisation${locked('fr', p)}. Définissez le manager de ces utilisateurs ou ajoutez un approbateur ` + + `toujours disponible.` + : `Tous les approbateurs du nœud d’approbation « ${p.node} » du flux « ${p.flow} » sont des postes, des ` + + `équipes, des services ou des files d’attente : si aucun n’a de titulaire, la demande va aux ` + + `administrateurs de l’organisation${locked('fr', p)}. Ajoutez un approbateur toujours disponible ou ` + + `désignez des approbateurs de secours.`, + 'pt-BR': (p) => + p.slate === 'manager' + ? `Todos os aprovadores do nó de aprovação "${p.node}" do fluxo "${p.flow}" são gerentes, então quando o ` + + `usuário consultado não tem gerente definido, a solicitação vai para os administradores da ` + + `organização${locked('pt-BR', p)}. Defina o gerente desses usuários ou adicione um aprovador que esteja ` + + `sempre disponível.` + : `Todos os aprovadores do nó de aprovação "${p.node}" do fluxo "${p.flow}" são cargos, equipes, ` + + `departamentos ou filas, então se nenhum deles tiver alguém, a solicitação vai para os administradores ` + + `da organização${locked('pt-BR', p)}. Adicione um aprovador que esteja sempre disponível ou indique ` + + `aprovadores substitutos.`, + ru: (p) => + p.slate === 'manager' + ? `Все согласующие в узле согласования «${p.node}» потока «${p.flow}» — руководители, поэтому если у ` + + `найденного пользователя руководитель не указан, заявка переходит к администраторам ` + + `организации${locked('ru', p)}. Укажите пользователям руководителей или добавьте согласующего, который ` + + `доступен всегда.` + : `Все согласующие в узле согласования «${p.node}» потока «${p.flow}» — должности, команды, отделы или ` + + `очереди, поэтому если ни в одной из них никого нет, заявка переходит к администраторам ` + + `организации${locked('ru', p)}. Добавьте согласующего, который доступен всегда, или укажите резервных ` + + `согласующих.`, + de: (p) => + p.slate === 'manager' + ? `Alle Genehmiger im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ sind Vorgesetzte. Hat der ` + + `ermittelte Benutzer keinen Vorgesetzten, geht die Anfrage an die Administratoren der ` + + `Organisation${locked('de', p)}. Hinterlegen Sie die Vorgesetzten der Benutzer, oder fügen Sie einen ` + + `Genehmiger hinzu, der immer verfügbar ist.` + : `Alle Genehmiger im Genehmigungsknoten „${p.node}“ des Flows „${p.flow}“ sind Positionen, Teams, ` + + `Abteilungen oder Warteschlangen. Ist keine davon besetzt, geht die Anfrage an die Administratoren der ` + + `Organisation${locked('de', p)}. Fügen Sie einen Genehmiger hinzu, der immer verfügbar ist, oder ` + + `benennen Sie Ersatzgenehmiger.`, + ja: (p) => + p.slate === 'manager' + ? `フロー「${p.flow}」の承認ノード「${p.node}」の承認者はすべてマネージャーです。参照するユーザーにマネージャーが` + + `設定されていない場合、申請は組織の管理者に回されます${locked('ja', p)}。ユーザーのマネージャーを設定するか、` + + `常に対応できる承認者を追加してください。` + : `フロー「${p.flow}」の承認ノード「${p.node}」の承認者はすべてポジション、チーム、部門、またはキューです。` + + `どれにも担当者がいない場合、申請は組織の管理者に回されます${locked('ja', p)}。常に対応できる承認者を追加するか、` + + `代替の承認者を指定してください。`, + ko: (p) => + p.slate === 'manager' + ? `플로우 "${p.flow}"의 승인 노드 "${p.node}"에 있는 승인자가 모두 관리자이므로, 조회한 사용자에게 관리자가 ` + + `설정되어 있지 않으면 요청이 조직 관리자에게 넘어갑니다${locked('ko', p)}. 사용자의 관리자를 설정하거나 ` + + `항상 처리할 수 있는 승인자를 추가하세요.` + : `플로우 "${p.flow}"의 승인 노드 "${p.node}"에 있는 승인자가 모두 직책, 팀, 부서 또는 대기열이므로, 어디에도 ` + + `사람이 없으면 요청이 조직 관리자에게 넘어갑니다${locked('ko', p)}. 항상 처리할 수 있는 승인자를 추가하거나 ` + + `대체 승인자를 지정하세요.`, + }, + [APPROVAL_EXPRESSION_NO_EMPTY_POLICY]: { + en: (p) => + `Approval node "${p.node}" in flow "${p.flow}" finds its approvers with an expression but does not say ` + + `what happens when the expression finds no one, so an empty result goes to an administrator to decide. ` + + `Choose what the node does when it finds no approver.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”通过表达式查找审批人,但没有指定表达式找不到人时该怎么办,因此结果为空时会交由管理员处理。` + + `请选择该节点找不到审批人时的处理方式。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」透過運算式查找審批人,但沒有指定運算式找不到人時該怎麼辦,因此結果為空時會交由管理員處理。` + + `請選擇該節點找不到審批人時的處理方式。`, + es: (p) => + `El nodo de aprobación "${p.node}" del flujo "${p.flow}" busca sus aprobadores con una expresión, pero no ` + + `indica qué hacer cuando la expresión no encuentra a nadie, así que un resultado vacío pasa a un ` + + `administrador para que decida. Elija qué hace el nodo cuando no encuentra ningún aprobador.`, + ar: (p) => + `تبحث عقدة الموافقة "${p.node}" في التدفق "${p.flow}" عن موافقيها بتعبير، لكنها لا تحدد ما يحدث عندما لا ` + + `يجد التعبير أحدًا، لذلك تنتقل النتيجة الفارغة إلى مسؤول ليقرر. اختر ما تفعله العقدة عندما لا تجد موافقًا.`, + fr: (p) => + `Le nœud d’approbation « ${p.node} » du flux « ${p.flow} » trouve ses approbateurs par une expression, mais ` + + `n’indique pas ce qui se passe quand l’expression ne trouve personne : un résultat vide est alors confié à ` + + `un administrateur. Choisissez ce que fait le nœud quand il ne trouve aucun approbateur.`, + 'pt-BR': (p) => + `O nó de aprovação "${p.node}" do fluxo "${p.flow}" encontra seus aprovadores com uma expressão, mas não ` + + `diz o que acontece quando a expressão não encontra ninguém, então um resultado vazio vai para um ` + + `administrador decidir. Escolha o que o nó faz quando não encontra nenhum aprovador.`, + ru: (p) => + `Узел согласования «${p.node}» потока «${p.flow}» находит согласующих с помощью выражения, но не указывает, ` + + `что делать, если выражение никого не нашло, поэтому пустой результат передаётся на решение ` + + `администратору. Выберите, что делает узел, если согласующий не найден.`, + de: (p) => + `Der Genehmigungsknoten „${p.node}“ im Flow „${p.flow}“ ermittelt seine Genehmiger über einen Ausdruck, ` + + `legt aber nicht fest, was geschieht, wenn der Ausdruck niemanden findet. Ein leeres Ergebnis geht daher ` + + `zur Entscheidung an einen Administrator. Legen Sie fest, was der Knoten tut, wenn er keinen Genehmiger ` + + `findet.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」は式で承認者を探しますが、式が誰も見つけなかった場合の動作が指定されていないため、` + + `結果が空のときは管理者の判断に委ねられます。承認者が見つからないときのノードの動作を選んでください。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"는 표현식으로 승인자를 찾지만, 표현식이 아무도 찾지 못했을 때의 동작을 ` + + `지정하지 않았으므로 결과가 비면 관리자가 결정하게 됩니다. 승인자를 찾지 못했을 때 노드가 할 동작을 선택하세요.`, + }, + [APPROVAL_ESCALATION_REASSIGN_NO_TARGET]: { + en: (p) => + `Approval node "${p.node}" in flow "${p.flow}" escalates by reassigning the request but names no one to ` + + `reassign it to, so the escalation only sends a notification and the request stays with the original ` + + `approvers. Set who it escalates to, or change the escalation to a notification.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的审批节点“${p.node}”的升级方式是转交申请,但没有指定转交给谁,因此升级时只会发送通知,申请仍由原审批人处理。` + + `请指定升级对象,或将升级方式改为通知。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的審批節點「${p.node}」的升級方式是轉交申請,但沒有指定轉交給誰,因此升級時只會傳送通知,申請仍由原審批人處理。` + + `請指定升級對象,或將升級方式改為通知。`, + es: (p) => + `El nodo de aprobación "${p.node}" del flujo "${p.flow}" escala reasignando la solicitud, pero no indica a ` + + `quién, así que el escalado solo envía una notificación y la solicitud sigue con los aprobadores ` + + `originales. Indique a quién se escala o cambie el escalado a una notificación.`, + ar: (p) => + `تُصعّد عقدة الموافقة "${p.node}" في التدفق "${p.flow}" بإعادة تعيين الطلب لكنها لا تحدد لمن، لذلك يكتفي ` + + `التصعيد بإرسال إشعار ويبقى الطلب لدى الموافقين الأصليين. حدّد الجهة التي يُصعَّد إليها، أو غيّر التصعيد إلى إشعار.`, + fr: (p) => + `Le nœud d’approbation « ${p.node} » du flux « ${p.flow} » escalade en réattribuant la demande, mais ne ` + + `désigne personne à qui la réattribuer : l’escalade envoie donc seulement une notification et la demande ` + + `reste aux approbateurs d’origine. Indiquez vers qui escalader ou changez l’escalade en notification.`, + 'pt-BR': (p) => + `O nó de aprovação "${p.node}" do fluxo "${p.flow}" escalona reatribuindo a solicitação, mas não indica ` + + `para quem, então o escalonamento apenas envia uma notificação e a solicitação continua com os ` + + `aprovadores originais. Defina para quem escalonar ou mude o escalonamento para uma notificação.`, + ru: (p) => + `Узел согласования «${p.node}» потока «${p.flow}» эскалирует заявку переназначением, но не указывает, ` + + `кому её переназначить, поэтому эскалация лишь отправляет уведомление, а заявка остаётся у прежних ` + + `согласующих. Укажите, кому эскалировать, или замените эскалацию уведомлением.`, + de: (p) => + `Der Genehmigungsknoten „${p.node}“ im Flow „${p.flow}“ eskaliert durch Neuzuweisung der Anfrage, nennt ` + + `aber niemanden, dem sie zugewiesen wird. Die Eskalation sendet daher nur eine Benachrichtigung, und die ` + + `Anfrage bleibt bei den ursprünglichen Genehmigern. Legen Sie fest, an wen eskaliert wird, oder ändern Sie ` + + `die Eskalation in eine Benachrichtigung.`, + ja: (p) => + `フロー「${p.flow}」の承認ノード「${p.node}」は申請の再割り当てでエスカレーションしますが、再割り当て先が指定されていないため、` + + `エスカレーションでは通知が送られるだけで、申請は元の承認者に残ります。エスカレーション先を指定するか、エスカレーションを通知に変更してください。`, + ko: (p) => + `플로우 "${p.flow}"의 승인 노드 "${p.node}"는 요청을 재배정하는 방식으로 에스컬레이션하지만 재배정할 대상을 ` + + `지정하지 않았으므로, 에스컬레이션 시 알림만 보내고 요청은 원래 승인자에게 남습니다. 에스컬레이션 대상을 ` + + `지정하거나 에스컬레이션을 알림으로 바꾸세요.`, + }, +}); diff --git a/packages/lint/src/validate-flow-node-writes.ts b/packages/lint/src/validate-flow-node-writes.ts index 084b6a3acba..e7a80d82fae 100644 --- a/packages/lint/src/validate-flow-node-writes.ts +++ b/packages/lint/src/validate-flow-node-writes.ts @@ -98,6 +98,7 @@ import { import { indexUnprovisionedAnchors, unprovisionedAnchorFix } from './system-fields.js'; import { walkFlowNodes, flowNodeLabel } from './flow-walk.js'; import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; /** * `error` for the existence verdict — a literal key against a literal object is @@ -119,6 +120,11 @@ export interface FlowNodeWriteFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates, on the advisory push + * sites only (`validate-flow-node-writes.user-text.ts` sibling catalog); see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } // Rule id (registry entry). @@ -265,6 +271,7 @@ export function validateFlowNodeWrites(stack: AnyRec): FlowNodeWriteFinding[] { path: `${nodePath}.config.fields.${fieldName}`, message: unprovisionedAnchorWriteVerdict(objectName, fieldName, `this ${node.type} write`), hint: unprovisionedAnchorFix(objectName, fieldName), + userTextParams: { flow: flowName, node: nodeName, field: fieldName, object: objectName }, }); continue; } diff --git a/packages/lint/src/validate-flow-node-writes.user-text.ts b/packages/lint/src/validate-flow-node-writes.user-text.ts new file mode 100644 index 00000000000..62c30338176 --- /dev/null +++ b/packages/lint/src/validate-flow-node-writes.user-text.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-flow-node-writes.ts`'s advisory finding + * (`flow-node-write-unprovisioned-anchor`), in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it, kept beside the rule so its wording and its translations + * change together. + * + * Who reads it: the person who saved a flow in Studio, in their own language, + * once the save door composes `RuntimeAuthoringIssueSchema.userMessage` from + * it. The rule's other id, `flow-node-write-unknown-field`, refuses the write + * (`error`) and carries no params. + * + * Params, set at the push site in `validate-flow-node-writes.ts`: `flow`, + * `node` (the node's label, as the rule's `where` shows it), `field`, `object`. + * + * `finding-user-text.test.ts` renders it from the rule's real + * finding in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR } from './validate-flow-node-writes.js'; + +export const FLOW_NODE_WRITES_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_NODE_WRITE_UNPROVISIONED_ANCHOR]: { + en: (p) => + `Node "${p.node}" in flow "${p.flow}" writes "${p.field}", a system field that external object ` + + `"${p.object}" has no storage for, so the value is never saved. If the external table has this column, add ` + + `"${p.field}" to the object's fields; otherwise remove it from the node.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的节点“${p.node}”写入“${p.field}”,这是一个系统字段,而外部对象“${p.object}”没有为它提供存储,因此该值永远不会被保存。` + + `如果外部表中有这一列,请把“${p.field}”添加到该对象的字段中;否则请从该节点中删除它。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的節點「${p.node}」寫入「${p.field}」,這是一個系統欄位,而外部物件「${p.object}」沒有為它提供儲存,因此該值永遠不會被儲存。` + + `如果外部資料表中有這一欄,請把「${p.field}」新增到該物件的欄位中;否則請從該節點中刪除它。`, + es: (p) => + `El nodo "${p.node}" del flujo "${p.flow}" escribe "${p.field}", un campo del sistema para el que el objeto ` + + `externo "${p.object}" no tiene almacenamiento, así que el valor nunca se guarda. Si la tabla externa tiene ` + + `esa columna, añada "${p.field}" a los campos del objeto; si no, quítelo del nodo.`, + ar: (p) => + `تكتب العقدة "${p.node}" في التدفق "${p.flow}" الحقل "${p.field}"، وهو حقل نظام لا يملك الكائن الخارجي ` + + `"${p.object}" تخزينًا له، لذلك لا تُحفظ القيمة أبدًا. إذا كان الجدول الخارجي يحتوي على هذا العمود، فأضف ` + + `"${p.field}" إلى حقول الكائن؛ وإلا فأزله من العقدة.`, + fr: (p) => + `Le nœud « ${p.node} » du flux « ${p.flow} » écrit « ${p.field} », un champ système pour lequel l’objet ` + + `externe « ${p.object} » n’a pas de stockage : la valeur n’est donc jamais enregistrée. Si la table externe ` + + `possède cette colonne, ajoutez « ${p.field} » aux champs de l’objet ; sinon, retirez-le du nœud.`, + 'pt-BR': (p) => + `O nó "${p.node}" do fluxo "${p.flow}" grava "${p.field}", um campo do sistema para o qual o objeto externo ` + + `"${p.object}" não tem armazenamento, então o valor nunca é salvo. Se a tabela externa tiver essa coluna, ` + + `adicione "${p.field}" aos campos do objeto; caso contrário, remova-o do nó.`, + ru: (p) => + `Узел «${p.node}» потока «${p.flow}» записывает «${p.field}» — системное поле, для которого у внешнего объекта ` + + `«${p.object}» нет хранилища, поэтому значение никогда не сохраняется. Если во внешней таблице есть такой ` + + `столбец, добавьте «${p.field}» в поля объекта; иначе удалите его из узла.`, + de: (p) => + `Der Knoten „${p.node}“ im Flow „${p.flow}“ schreibt „${p.field}“, ein Systemfeld, für das das externe Objekt ` + + `„${p.object}“ keinen Speicher hat. Der Wert wird daher nie gespeichert. Hat die externe Tabelle diese ` + + `Spalte, fügen Sie „${p.field}“ zu den Feldern des Objekts hinzu; andernfalls entfernen Sie es aus dem Knoten.`, + ja: (p) => + `フロー「${p.flow}」のノード「${p.node}」はシステム項目「${p.field}」に書き込みますが、外部オブジェクト「${p.object}」には` + + `この項目の保存先がないため、値は保存されません。外部テーブルにこの列がある場合は「${p.field}」をオブジェクトの項目に追加し、` + + `ない場合はノードから削除してください。`, + ko: (p) => + `플로우 "${p.flow}"의 노드 "${p.node}"는 시스템 필드 "${p.field}"에 쓰지만, 외부 개체 "${p.object}"에는 이 필드의 ` + + `저장 공간이 없으므로 값이 저장되지 않습니다. 외부 테이블에 이 열이 있다면 "${p.field}"을(를) 개체의 필드에 ` + + `추가하고, 없다면 노드에서 제거하세요.`, + }, +}); diff --git a/packages/lint/src/validate-flow-template-paths.ts b/packages/lint/src/validate-flow-template-paths.ts index c4ff18d7ce5..a55fe874397 100644 --- a/packages/lint/src/validate-flow-template-paths.ts +++ b/packages/lint/src/validate-flow-template-paths.ts @@ -112,6 +112,7 @@ import { } from './system-fields.js'; import { walkFlowNodes, type WalkedFlowNode } from './flow-walk.js'; import { objectsAsServed, recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; export type FlowTemplatePathSeverity = 'error' | 'warning'; @@ -124,6 +125,11 @@ export interface FlowTemplatePathFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates, on the advisory push + * sites only (``validate-flow-template-paths.user-text.ts`` sibling catalog); see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } // Rule ids (registry entries). @@ -652,6 +658,7 @@ export function validateFlowTemplatePaths(stack: AnyRec): FlowTemplatePathFindin // [#22161] The shared one-line anchor fix; how to vouch for or // opt out of the anchor is `os explain flow-template-field-unprovisioned`. hint: unprovisionedAnchorFix(objectName, head), + userTextParams: { flow: flowName, reference: token, field: head, object: objectName }, }); } } @@ -673,6 +680,7 @@ export function validateFlowTemplatePaths(stack: AnyRec): FlowTemplatePathFindin : `Check the field name against object '${objectName}'s field definitions — '${rootName}' is ` + `bound to a '${objectName}' record by this flow. System columns like id/created_at/owner ` + `are also addressable.`, + userTextParams: { flow: flowName, reference: token, field: head, object: objectName }, }); continue; } @@ -702,6 +710,10 @@ export function validateFlowTemplatePaths(stack: AnyRec): FlowTemplatePathFindin `(the id) or a formula field on '${objectName}' instead.` : `Write '{{ ${rootName}.${head} }}' (the id) or a formula field on '${objectName}', or ` + `read the related record with a get_record node.`, + userTextParams: { + flow: flowName, reference: token, field: head, object: objectName, + root: root.isTrigger ? 'trigger' : 'variable', + }, }); } // STRUCTURED_TYPES + any other scalar `.sub` access is left alone: diff --git a/packages/lint/src/validate-flow-template-paths.user-text.ts b/packages/lint/src/validate-flow-template-paths.user-text.ts new file mode 100644 index 00000000000..e4fe51d4d3f --- /dev/null +++ b/packages/lint/src/validate-flow-template-paths.user-text.ts @@ -0,0 +1,190 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-flow-template-paths.ts`'s advisory + * findings, in every platform locale (`PLATFORM_LOCALE_TAGS`, + * `@objectstack/spec/system`). The finding mechanism and the locale ladder are + * `finding-user-text.ts`'s; this file is the rule's own half of it, kept beside + * the rule so its wording and its translations change together. + * + * Who reads these: the person who saved a flow in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from them. So each sentence names the placeholder, says it renders blank and + * gives the one change that fixes it; the developer-facing detail stays in the + * finding's `message`, `hint` and `os explain` entry. + * + * Each entry reads the `userTextParams` its finding carries, set at the push + * site in `validate-flow-template-paths.ts`: `flow`, `reference` (the + * placeholder's path as written, without its braces, e.g. + * `record.crm_account.name`), `field` (its first segment, the field it reads), + * `object` (the object the placeholder's root is bound to), and, on + * `flow-template-lookup-traversal` only, `root` (`trigger` · `variable`: the + * flow's own record, or a record a node bound to a variable), which decides + * the remedy as the rule's hint does. + * + * `finding-user-text.test.ts` renders every entry from + * the rule's real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { + FLOW_TEMPLATE_FIELD_UNPROVISIONED, + FLOW_TEMPLATE_LOOKUP_TRAVERSAL, + FLOW_TEMPLATE_UNKNOWN_FIELD, +} from './validate-flow-template-paths.js'; + +export const FLOW_TEMPLATE_PATHS_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_TEMPLATE_UNKNOWN_FIELD]: { + en: (p) => + `In flow "${p.flow}", the placeholder {{ ${p.reference} }} refers to "${p.field}", which is not a field of ` + + `object "${p.object}", so it is always blank. Check the field name against the object's fields.`, + 'zh-Hans': (p) => + `在流程“${p.flow}”中,占位符 {{ ${p.reference} }} 引用了“${p.field}”,但它不是对象“${p.object}”的字段,因此始终为空。` + + `请对照该对象的字段检查字段名称。`, + 'zh-Hant': (p) => + `在流程「${p.flow}」中,預留位置 {{ ${p.reference} }} 參照了「${p.field}」,但它不是物件「${p.object}」的欄位,因此始終為空。` + + `請對照該物件的欄位檢查欄位名稱。`, + es: (p) => + `En el flujo "${p.flow}", el marcador {{ ${p.reference} }} hace referencia a "${p.field}", que no es un ` + + `campo del objeto "${p.object}", así que siempre queda vacío. Compruebe el nombre del campo con los campos ` + + `del objeto.`, + ar: (p) => + `في التدفق "${p.flow}"، يشير العنصر النائب {{ ${p.reference} }} إلى "${p.field}"، وهو ليس حقلًا في الكائن ` + + `"${p.object}"، لذلك يظهر فارغًا دائمًا. تحقق من اسم الحقل مقارنةً بحقول الكائن.`, + fr: (p) => + `Dans le flux « ${p.flow} », l’espace réservé {{ ${p.reference} }} fait référence à « ${p.field} », qui ` + + `n’est pas un champ de l’objet « ${p.object} » : il reste donc toujours vide. Vérifiez le nom du champ par ` + + `rapport aux champs de l’objet.`, + 'pt-BR': (p) => + `No fluxo "${p.flow}", o marcador {{ ${p.reference} }} se refere a "${p.field}", que não é um campo do ` + + `objeto "${p.object}", então ele fica sempre em branco. Confira o nome do campo com os campos do objeto.`, + ru: (p) => + `В потоке «${p.flow}» заполнитель {{ ${p.reference} }} ссылается на «${p.field}», но это не поле объекта ` + + `«${p.object}», поэтому он всегда пуст. Сверьте имя поля с полями объекта.`, + de: (p) => + `Im Flow „${p.flow}“ verweist der Platzhalter {{ ${p.reference} }} auf „${p.field}“, das kein Feld des ` + + `Objekts „${p.object}“ ist. Er bleibt daher immer leer. Prüfen Sie den Feldnamen anhand der Felder des ` + + `Objekts.`, + ja: (p) => + `フロー「${p.flow}」で、プレースホルダー {{ ${p.reference} }} は「${p.field}」を参照していますが、これはオブジェクト` + + `「${p.object}」の項目ではないため、常に空になります。オブジェクトの項目と照らし合わせて項目名を確認してください。`, + ko: (p) => + `플로우 "${p.flow}"에서 자리 표시자 {{ ${p.reference} }}는 "${p.field}"을(를) 참조하지만, 이는 개체 ` + + `"${p.object}"의 필드가 아니므로 항상 비어 있습니다. 개체의 필드와 비교해 필드 이름을 확인하세요.`, + }, + [FLOW_TEMPLATE_LOOKUP_TRAVERSAL]: { + en: (p) => + `In flow "${p.flow}", the placeholder {{ ${p.reference} }} reads through relationship field "${p.field}", ` + + `but the record there holds only the related record's ID, so it is always blank. ` + + (p.root === 'variable' + ? `Read the related record with a get-record node, or use a formula field on "${p.object}".` + : `Expand "${p.field}" on the start node, or use a formula field on "${p.object}".`), + 'zh-Hans': (p) => + `在流程“${p.flow}”中,占位符 {{ ${p.reference} }} 通过关联字段“${p.field}”读取数据,但该记录中只保存了关联记录的 ID,因此始终为空。` + + (p.root === 'variable' + ? `请用“获取记录”节点读取关联记录,或在“${p.object}”上使用公式字段。` + : `请在开始节点中展开“${p.field}”,或在“${p.object}”上使用公式字段。`), + 'zh-Hant': (p) => + `在流程「${p.flow}」中,預留位置 {{ ${p.reference} }} 透過關聯欄位「${p.field}」讀取資料,但該記錄中只保存了關聯記錄的 ID,因此始終為空。` + + (p.root === 'variable' + ? `請用「取得記錄」節點讀取關聯記錄,或在「${p.object}」上使用公式欄位。` + : `請在開始節點中展開「${p.field}」,或在「${p.object}」上使用公式欄位。`), + es: (p) => + `En el flujo "${p.flow}", el marcador {{ ${p.reference} }} lee a través del campo de relación ` + + `"${p.field}", pero ese registro solo guarda el ID del registro relacionado, así que siempre queda vacío. ` + + (p.root === 'variable' + ? `Lea el registro relacionado con un nodo de obtener registro, o use un campo de fórmula en "${p.object}".` + : `Expanda "${p.field}" en el nodo de inicio, o use un campo de fórmula en "${p.object}".`), + ar: (p) => + `في التدفق "${p.flow}"، يقرأ العنصر النائب {{ ${p.reference} }} عبر حقل العلاقة "${p.field}"، لكن ذلك ` + + `السجل لا يحمل إلا معرّف السجل المرتبط، لذلك يظهر فارغًا دائمًا. ` + + (p.root === 'variable' + ? `اقرأ السجل المرتبط بعقدة جلب سجل، أو استخدم حقل صيغة في "${p.object}".` + : `وسّع "${p.field}" في عقدة البدء، أو استخدم حقل صيغة في "${p.object}".`), + fr: (p) => + `Dans le flux « ${p.flow} », l’espace réservé {{ ${p.reference} }} lit à travers le champ de relation ` + + `« ${p.field} », mais cet enregistrement ne contient que l’ID de l’enregistrement lié : il reste donc ` + + `toujours vide. ` + + (p.root === 'variable' + ? `Lisez l’enregistrement lié avec un nœud de lecture d’enregistrement, ou utilisez un champ formule sur ` + + `« ${p.object} ».` + : `Développez « ${p.field} » sur le nœud de départ, ou utilisez un champ formule sur « ${p.object} ».`), + 'pt-BR': (p) => + `No fluxo "${p.flow}", o marcador {{ ${p.reference} }} lê através do campo de relacionamento ` + + `"${p.field}", mas esse registro guarda apenas o ID do registro relacionado, então ele fica sempre em ` + + `branco. ` + + (p.root === 'variable' + ? `Leia o registro relacionado com um nó de obter registro, ou use um campo de fórmula em "${p.object}".` + : `Expanda "${p.field}" no nó inicial, ou use um campo de fórmula em "${p.object}".`), + ru: (p) => + `В потоке «${p.flow}» заполнитель {{ ${p.reference} }} читает данные через поле связи «${p.field}», но эта ` + + `запись хранит только ID связанной записи, поэтому он всегда пуст. ` + + (p.root === 'variable' + ? `Прочитайте связанную запись узлом получения записи или используйте поле-формулу в «${p.object}».` + : `Раскройте «${p.field}» в начальном узле или используйте поле-формулу в «${p.object}».`), + de: (p) => + `Im Flow „${p.flow}“ liest der Platzhalter {{ ${p.reference} }} über das Beziehungsfeld „${p.field}“, aber ` + + `dieser Datensatz enthält nur die ID des verknüpften Datensatzes. Er bleibt daher immer leer. ` + + (p.root === 'variable' + ? `Lesen Sie den verknüpften Datensatz mit einem Knoten zum Abrufen eines Datensatzes, oder verwenden Sie ` + + `ein Formelfeld auf „${p.object}“.` + : `Erweitern Sie „${p.field}“ im Startknoten, oder verwenden Sie ein Formelfeld auf „${p.object}“.`), + ja: (p) => + `フロー「${p.flow}」で、プレースホルダー {{ ${p.reference} }} は関連項目「${p.field}」を経由して読み取りますが、` + + `そのレコードには関連レコードの ID しかないため、常に空になります。` + + (p.root === 'variable' + ? `レコード取得ノードで関連レコードを読み取るか、「${p.object}」の数式項目を使用してください。` + : `開始ノードで「${p.field}」を展開するか、「${p.object}」の数式項目を使用してください。`), + ko: (p) => + `플로우 "${p.flow}"에서 자리 표시자 {{ ${p.reference} }}는 관계 필드 "${p.field}"을(를) 거쳐 읽지만, 그 레코드에는 ` + + `관련 레코드의 ID만 있으므로 항상 비어 있습니다. ` + + (p.root === 'variable' + ? `레코드 가져오기 노드로 관련 레코드를 읽거나 "${p.object}"의 수식 필드를 사용하세요.` + : `시작 노드에서 "${p.field}"을(를) 확장하거나 "${p.object}"의 수식 필드를 사용하세요.`), + }, + [FLOW_TEMPLATE_FIELD_UNPROVISIONED]: { + en: (p) => + `In flow "${p.flow}", the placeholder {{ ${p.reference} }} reads "${p.field}", a system field that ` + + `external object "${p.object}" has no storage for, so it is always blank. If the external table has this ` + + `column, add "${p.field}" to the object's fields; otherwise remove the placeholder.`, + 'zh-Hans': (p) => + `在流程“${p.flow}”中,占位符 {{ ${p.reference} }} 读取“${p.field}”,这是一个系统字段,而外部对象“${p.object}”没有为它提供存储,` + + `因此始终为空。如果外部表中有这一列,请把“${p.field}”添加到该对象的字段中;否则请删除该占位符。`, + 'zh-Hant': (p) => + `在流程「${p.flow}」中,預留位置 {{ ${p.reference} }} 讀取「${p.field}」,這是一個系統欄位,而外部物件「${p.object}」沒有為它提供儲存,` + + `因此始終為空。如果外部資料表中有這一欄,請把「${p.field}」新增到該物件的欄位中;否則請刪除該預留位置。`, + es: (p) => + `En el flujo "${p.flow}", el marcador {{ ${p.reference} }} lee "${p.field}", un campo del sistema para el ` + + `que el objeto externo "${p.object}" no tiene almacenamiento, así que siempre queda vacío. Si la tabla ` + + `externa tiene esa columna, añada "${p.field}" a los campos del objeto; si no, quite el marcador.`, + ar: (p) => + `في التدفق "${p.flow}"، يقرأ العنصر النائب {{ ${p.reference} }} الحقل "${p.field}"، وهو حقل نظام لا يملك ` + + `الكائن الخارجي "${p.object}" تخزينًا له، لذلك يظهر فارغًا دائمًا. إذا كان الجدول الخارجي يحتوي على هذا ` + + `العمود، فأضف "${p.field}" إلى حقول الكائن؛ وإلا فأزل العنصر النائب.`, + fr: (p) => + `Dans le flux « ${p.flow} », l’espace réservé {{ ${p.reference} }} lit « ${p.field} », un champ système ` + + `pour lequel l’objet externe « ${p.object} » n’a pas de stockage : il reste donc toujours vide. Si la table ` + + `externe possède cette colonne, ajoutez « ${p.field} » aux champs de l’objet ; sinon, supprimez l’espace ` + + `réservé.`, + 'pt-BR': (p) => + `No fluxo "${p.flow}", o marcador {{ ${p.reference} }} lê "${p.field}", um campo do sistema para o qual o ` + + `objeto externo "${p.object}" não tem armazenamento, então ele fica sempre em branco. Se a tabela externa ` + + `tiver essa coluna, adicione "${p.field}" aos campos do objeto; caso contrário, remova o marcador.`, + ru: (p) => + `В потоке «${p.flow}» заполнитель {{ ${p.reference} }} читает «${p.field}» — системное поле, для которого у ` + + `внешнего объекта «${p.object}» нет хранилища, поэтому он всегда пуст. Если во внешней таблице есть такой ` + + `столбец, добавьте «${p.field}» в поля объекта; иначе удалите заполнитель.`, + de: (p) => + `Im Flow „${p.flow}“ liest der Platzhalter {{ ${p.reference} }} „${p.field}“, ein Systemfeld, für das das ` + + `externe Objekt „${p.object}“ keinen Speicher hat. Er bleibt daher immer leer. Hat die externe Tabelle diese ` + + `Spalte, fügen Sie „${p.field}“ zu den Feldern des Objekts hinzu; andernfalls entfernen Sie den Platzhalter.`, + ja: (p) => + `フロー「${p.flow}」で、プレースホルダー {{ ${p.reference} }} はシステム項目「${p.field}」を読み取りますが、外部オブジェクト` + + `「${p.object}」にはこの項目の保存先がないため、常に空になります。外部テーブルにこの列がある場合は「${p.field}」を` + + `オブジェクトの項目に追加し、ない場合はプレースホルダーを削除してください。`, + ko: (p) => + `플로우 "${p.flow}"에서 자리 표시자 {{ ${p.reference} }}는 시스템 필드 "${p.field}"을(를) 읽지만, 외부 개체 ` + + `"${p.object}"에는 이 필드의 저장 공간이 없으므로 항상 비어 있습니다. 외부 테이블에 이 열이 있다면 ` + + `"${p.field}"을(를) 개체의 필드에 추가하고, 없다면 자리 표시자를 제거하세요.`, + }, +}); diff --git a/packages/lint/src/validate-flow-trigger-readiness.ts b/packages/lint/src/validate-flow-trigger-readiness.ts index 08c1cd7dfc5..41937700936 100644 --- a/packages/lint/src/validate-flow-trigger-readiness.ts +++ b/packages/lint/src/validate-flow-trigger-readiness.ts @@ -215,6 +215,7 @@ import { } from '@objectstack/spec/automation'; import { walkFlowNodes } from './flow-walk.js'; import { closureDependencyRemedy, recordsOf, suggestName } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; export type FlowTriggerReadinessSeverity = 'error' | 'warning'; @@ -227,6 +228,11 @@ export interface FlowTriggerReadinessFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates, on the advisory push + * sites only (``validate-flow-trigger-readiness.user-text.ts`` sibling catalog); see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } // Rule ids (registry entries). @@ -605,7 +611,7 @@ export function validateFlowTriggerReadiness( path: string, objectName: string, at: { verb: string; key: string }, - advisory: { message: string; hint: string }, + advisory: { message: string; hint: string; userTextParams: UserTextParams }, // [#29442] The start-input declaration shares this verdict under its own // id and position; the trigger's two halves take the defaults. position: { rule: string; where: string } = { rule: FLOW_TRIGGER_UNKNOWN_OBJECT, where: 'start node' }, @@ -678,6 +684,7 @@ export function validateFlowTriggerReadiness( hint: `Set config.objectName to the object's exact registered name (e.g. 'app_candidate', not ` + `'candidate'), or ignore this if another installed package declares it`, + userTextParams: { flow: flowName, object: objectName, trigger: 'record' }, }, ), ); @@ -731,6 +738,7 @@ export function validateFlowTriggerReadiness( hint: `Set config.timeRelative.object to the object's exact registered name, or ignore this if ` + `another installed package declares it`, + userTextParams: { flow: flowName, object: objectName, trigger: 'schedule' }, }, ), ); @@ -1123,6 +1131,7 @@ export function validateFlowTriggerReadiness( hint: `Set the input's objectName to the object's exact registered name, or ignore this if another ` + `installed package declares it`, + userTextParams: { flow: flowName, input: variableName, object: objectName }, }, { rule: FLOW_INPUT_UNKNOWN_OBJECT, where: `input "${variableName}"` }, ), @@ -1163,6 +1172,7 @@ export function validateFlowTriggerReadiness( hint: `Set the input's objectName to the object whose record id the input carries, or remove ` + `objectName if the input is not a record id`, + userTextParams: { flow: flowName, input: shown }, }); } if (variable.isInput === true && variableName && !declaredInputs.has(variableName)) { @@ -1202,6 +1212,9 @@ export function validateFlowTriggerReadiness( hint: `Remove the input's objectName if it carries a list of ids, or read it as one id with filter.id ` + `or filter.id.$eq`, + userTextParams: { + flow: flowName, input: listed, object: declaredObject ?? '', node: nodeLabel, listObject: readObject, + }, }); } } @@ -1218,6 +1231,7 @@ export function validateFlowTriggerReadiness( `has status 'draft' (the default when none is authored). Draft flows DO still fire their ` + `triggers (only 'obsolete'/'invalid' disable), so the intent is ambiguous.`, hint: `Declare status: 'active' to arm it deliberately, or status: 'obsolete' to disable it.`, + userTextParams: { flow: flowName }, }); } }); diff --git a/packages/lint/src/validate-flow-trigger-readiness.user-text.ts b/packages/lint/src/validate-flow-trigger-readiness.user-text.ts new file mode 100644 index 00000000000..374b0871e02 --- /dev/null +++ b/packages/lint/src/validate-flow-trigger-readiness.user-text.ts @@ -0,0 +1,297 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-flow-trigger-readiness.ts`'s advisory + * findings, in every platform locale (`PLATFORM_LOCALE_TAGS`, + * `@objectstack/spec/system`). The finding mechanism and the locale ladder are + * `finding-user-text.ts`'s; this file is the rule's own half of it, kept beside + * the rule so its wording and its translations change together. + * + * Who reads these: the person who saved a flow in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from them. So each sentence says what the trigger or input setting does to + * the flow's runs and the one change that fixes it; the developer-facing detail + * stays in the finding's `message`, `hint` and `os explain` entry. + * + * Each entry reads the `userTextParams` its finding carries, set at the push + * site in `validate-flow-trigger-readiness.ts`: + * + * | rule id | params | + * |---|---| + * | `flow-trigger-unknown-object` | `flow`, `object`, `trigger` (`record` · `schedule`: the record trigger's object, or the time-relative sweep's) | + * | `flow-input-unknown-object` | `flow`, `input`, `object` | + * | `flow-input-object-less` | `flow`, `input` | + * | `flow-input-record-read-as-list` | `flow`, `input`, `object` (the declared one), `node`, `listObject` (the one the node reads) | + * | `flow-draft-status-ambiguous` | `flow` | + * + * The two unknown-object ids are advisories only while no package closure is + * stated; under one the same position is refused, and that push site carries + * no params, so a refusal never renders these sentences. Status values are the + * API values (`active`, `obsolete`), as the flow's settings store them. + * + * `finding-user-text.test.ts` renders every entry from + * the rule's real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { + FLOW_DRAFT_STATUS_AMBIGUOUS, + FLOW_INPUT_OBJECT_LESS, + FLOW_INPUT_RECORD_READ_AS_LIST, + FLOW_INPUT_UNKNOWN_OBJECT, + FLOW_TRIGGER_UNKNOWN_OBJECT, +} from './validate-flow-trigger-readiness.js'; + +export const FLOW_TRIGGER_READINESS_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_TRIGGER_UNKNOWN_OBJECT]: { + en: (p) => + (p.trigger === 'schedule' + ? `Flow "${p.flow}" runs on a schedule over records of object "${p.object}", which this app does not ` + + `define, so if the name is wrong it never finds a record to run on. ` + : `Flow "${p.flow}" is triggered by changes to object "${p.object}", which this app does not define, so ` + + `if the name is wrong the flow never runs. `) + + `Use the object's exact API name, or ignore this if another installed package provides it.`, + 'zh-Hans': (p) => + (p.trigger === 'schedule' + ? `流程“${p.flow}”按计划扫描对象“${p.object}”的记录,但本应用没有定义该对象,因此如果名称写错,它将永远找不到可处理的记录。` + : `流程“${p.flow}”由对象“${p.object}”的变更触发,但本应用没有定义该对象,因此如果名称写错,该流程将永远不会运行。`) + + `请使用对象准确的 API 名称;如果该对象由另一个已安装的包提供,可以忽略此提示。`, + 'zh-Hant': (p) => + (p.trigger === 'schedule' + ? `流程「${p.flow}」依排程掃描物件「${p.object}」的記錄,但本應用程式沒有定義該物件,因此如果名稱寫錯,它將永遠找不到可處理的記錄。` + : `流程「${p.flow}」由物件「${p.object}」的變更觸發,但本應用程式沒有定義該物件,因此如果名稱寫錯,該流程將永遠不會執行。`) + + `請使用物件準確的 API 名稱;如果該物件由另一個已安裝的套件提供,可以忽略此提示。`, + es: (p) => + (p.trigger === 'schedule' + ? `El flujo "${p.flow}" se ejecuta según una programación sobre registros del objeto "${p.object}", que ` + + `esta aplicación no define, así que si el nombre es incorrecto nunca encontrará registros. ` + : `El flujo "${p.flow}" se activa con los cambios del objeto "${p.object}", que esta aplicación no define, ` + + `así que si el nombre es incorrecto el flujo nunca se ejecutará. `) + + `Use el nombre de API exacto del objeto, o ignore este aviso si otro paquete instalado lo proporciona.`, + ar: (p) => + (p.trigger === 'schedule' + ? `يعمل التدفق "${p.flow}" وفق جدول على سجلات الكائن "${p.object}"، الذي لا يعرّفه هذا التطبيق، لذلك إذا ` + + `كان الاسم خاطئًا فلن يجد أي سجل يعمل عليه. ` + : `يُشغَّل التدفق "${p.flow}" عند تغيّر الكائن "${p.object}"، الذي لا يعرّفه هذا التطبيق، لذلك إذا كان ` + + `الاسم خاطئًا فلن يعمل التدفق أبدًا. `) + + `استخدم اسم API الدقيق للكائن، أو تجاهل هذا إذا كانت حزمة مثبتة أخرى توفره.`, + fr: (p) => + (p.trigger === 'schedule' + ? `Le flux « ${p.flow} » s’exécute selon une planification sur les enregistrements de l’objet ` + + `« ${p.object} », que cette application ne définit pas : si le nom est erroné, il ne trouvera jamais ` + + `d’enregistrement. ` + : `Le flux « ${p.flow} » est déclenché par les modifications de l’objet « ${p.object} », que cette ` + + `application ne définit pas : si le nom est erroné, le flux ne s’exécutera jamais. `) + + `Utilisez le nom d’API exact de l’objet, ou ignorez ce message si un autre package installé le fournit.`, + 'pt-BR': (p) => + (p.trigger === 'schedule' + ? `O fluxo "${p.flow}" é executado por agendamento sobre registros do objeto "${p.object}", que este ` + + `aplicativo não define, então se o nome estiver errado ele nunca encontrará um registro. ` + : `O fluxo "${p.flow}" é acionado por alterações no objeto "${p.object}", que este aplicativo não define, ` + + `então se o nome estiver errado o fluxo nunca será executado. `) + + `Use o nome de API exato do objeto, ou ignore este aviso se outro pacote instalado o fornecer.`, + ru: (p) => + (p.trigger === 'schedule' + ? `Поток «${p.flow}» запускается по расписанию для записей объекта «${p.object}», который это приложение ` + + `не определяет, поэтому если имя указано неверно, он никогда не найдёт ни одной записи. ` + : `Поток «${p.flow}» запускается при изменениях объекта «${p.object}», который это приложение не ` + + `определяет, поэтому если имя указано неверно, поток никогда не запустится. `) + + `Укажите точное API-имя объекта или не обращайте внимания, если его предоставляет другой установленный пакет.`, + de: (p) => + (p.trigger === 'schedule' + ? `Der Flow „${p.flow}“ läuft nach Zeitplan über Datensätze des Objekts „${p.object}“, das diese App nicht ` + + `definiert. Ist der Name falsch, findet er nie einen Datensatz. ` + : `Der Flow „${p.flow}“ wird durch Änderungen am Objekt „${p.object}“ ausgelöst, das diese App nicht ` + + `definiert. Ist der Name falsch, läuft der Flow nie. `) + + `Verwenden Sie den genauen API-Namen des Objekts, oder ignorieren Sie dies, wenn ein anderes installiertes ` + + `Paket es bereitstellt.`, + ja: (p) => + (p.trigger === 'schedule' + ? `フロー「${p.flow}」はオブジェクト「${p.object}」のレコードをスケジュールで処理しますが、このアプリではこのオブジェクトが` + + `定義されていないため、名前が誤っている場合は処理するレコードが見つかりません。` + : `フロー「${p.flow}」はオブジェクト「${p.object}」の変更で起動しますが、このアプリではこのオブジェクトが定義されていないため、` + + `名前が誤っている場合はフローが実行されません。`) + + `オブジェクトの正確な API 名を使用してください。別のインストール済みパッケージが提供している場合は無視してかまいません。`, + ko: (p) => + (p.trigger === 'schedule' + ? `플로우 "${p.flow}"는 일정에 따라 개체 "${p.object}"의 레코드를 처리하지만, 이 앱은 해당 개체를 정의하지 ` + + `않으므로 이름이 잘못되었다면 처리할 레코드를 찾지 못합니다. ` + : `플로우 "${p.flow}"는 개체 "${p.object}"의 변경으로 실행되지만, 이 앱은 해당 개체를 정의하지 않으므로 ` + + `이름이 잘못되었다면 플로우가 실행되지 않습니다. `) + + `개체의 정확한 API 이름을 사용하세요. 설치된 다른 패키지가 제공하는 개체라면 무시해도 됩니다.`, + }, + [FLOW_INPUT_UNKNOWN_OBJECT]: { + en: (p) => + `Flow "${p.flow}" declares input "${p.input}" as a record of object "${p.object}", which this app does not ` + + `define, so if the name is wrong, every start that passes this input is refused. Use the object's exact ` + + `API name, or ignore this if another installed package provides it.`, + 'zh-Hans': (p) => + `流程“${p.flow}”将输入“${p.input}”声明为对象“${p.object}”的记录,但本应用没有定义该对象,因此如果名称写错,` + + `每次传入该输入的启动都会被拒绝。请使用对象准确的 API 名称;如果该对象由另一个已安装的包提供,可以忽略此提示。`, + 'zh-Hant': (p) => + `流程「${p.flow}」將輸入「${p.input}」宣告為物件「${p.object}」的記錄,但本應用程式沒有定義該物件,因此如果名稱寫錯,` + + `每次傳入該輸入的啟動都會被拒絕。請使用物件準確的 API 名稱;如果該物件由另一個已安裝的套件提供,可以忽略此提示。`, + es: (p) => + `El flujo "${p.flow}" declara la entrada "${p.input}" como un registro del objeto "${p.object}", que esta ` + + `aplicación no define, así que si el nombre es incorrecto se rechazará cada inicio que pase esta entrada. ` + + `Use el nombre de API exacto del objeto, o ignore este aviso si otro paquete instalado lo proporciona.`, + ar: (p) => + `يعرّف التدفق "${p.flow}" المُدخل "${p.input}" على أنه سجل من الكائن "${p.object}"، الذي لا يعرّفه هذا ` + + `التطبيق، لذلك إذا كان الاسم خاطئًا فسيُرفض كل تشغيل يمرّر هذا المُدخل. استخدم اسم API الدقيق للكائن، أو ` + + `تجاهل هذا إذا كانت حزمة مثبتة أخرى توفره.`, + fr: (p) => + `Le flux « ${p.flow} » déclare l’entrée « ${p.input} » comme un enregistrement de l’objet « ${p.object} », ` + + `que cette application ne définit pas : si le nom est erroné, chaque démarrage qui transmet cette entrée ` + + `sera refusé. Utilisez le nom d’API exact de l’objet, ou ignorez ce message si un autre package installé le ` + + `fournit.`, + 'pt-BR': (p) => + `O fluxo "${p.flow}" declara a entrada "${p.input}" como um registro do objeto "${p.object}", que este ` + + `aplicativo não define, então se o nome estiver errado toda inicialização que passar essa entrada será ` + + `recusada. Use o nome de API exato do objeto, ou ignore este aviso se outro pacote instalado o fornecer.`, + ru: (p) => + `Поток «${p.flow}» объявляет входной параметр «${p.input}» записью объекта «${p.object}», который это ` + + `приложение не определяет, поэтому если имя указано неверно, каждый запуск с этим параметром будет ` + + `отклонён. Укажите точное API-имя объекта или не обращайте внимания, если его предоставляет другой ` + + `установленный пакет.`, + de: (p) => + `Der Flow „${p.flow}“ deklariert die Eingabe „${p.input}“ als Datensatz des Objekts „${p.object}“, das ` + + `diese App nicht definiert. Ist der Name falsch, wird jeder Start abgelehnt, der diese Eingabe übergibt. ` + + `Verwenden Sie den genauen API-Namen des Objekts, oder ignorieren Sie dies, wenn ein anderes installiertes ` + + `Paket es bereitstellt.`, + ja: (p) => + `フロー「${p.flow}」は入力「${p.input}」をオブジェクト「${p.object}」のレコードとして宣言していますが、このアプリでは` + + `このオブジェクトが定義されていないため、名前が誤っている場合はこの入力を渡す起動がすべて拒否されます。` + + `オブジェクトの正確な API 名を使用してください。別のインストール済みパッケージが提供している場合は無視してかまいません。`, + ko: (p) => + `플로우 "${p.flow}"는 입력 "${p.input}"을(를) 개체 "${p.object}"의 레코드로 선언하지만, 이 앱은 해당 개체를 ` + + `정의하지 않으므로 이름이 잘못되었다면 이 입력을 전달하는 모든 시작이 거부됩니다. 개체의 정확한 API 이름을 ` + + `사용하세요. 설치된 다른 패키지가 제공하는 개체라면 무시해도 됩니다.`, + }, + [FLOW_INPUT_OBJECT_LESS]: { + en: (p) => + `Flow "${p.flow}" declares input "${p.input}" as a record without naming a real object, so no start loads ` + + `the record and the input's value is used unchecked. Set the object whose record ID the input carries, or ` + + `remove the object if the input is not a record ID.`, + 'zh-Hans': (p) => + `流程“${p.flow}”将输入“${p.input}”声明为记录,却没有指定真实的对象,因此任何启动都不会加载该记录,输入值会未经检查就被使用。` + + `请设置该输入所携带记录 ID 对应的对象;如果该输入不是记录 ID,请删除对象设置。`, + 'zh-Hant': (p) => + `流程「${p.flow}」將輸入「${p.input}」宣告為記錄,卻沒有指定真實的物件,因此任何啟動都不會載入該記錄,輸入值會未經檢查就被使用。` + + `請設定該輸入所攜帶記錄 ID 對應的物件;如果該輸入不是記錄 ID,請刪除物件設定。`, + es: (p) => + `El flujo "${p.flow}" declara la entrada "${p.input}" como un registro sin indicar un objeto real, así que ` + + `ningún inicio carga el registro y el valor de la entrada se usa sin comprobar. Indique el objeto cuyo ID de ` + + `registro lleva la entrada, o quite el objeto si la entrada no es un ID de registro.`, + ar: (p) => + `يعرّف التدفق "${p.flow}" المُدخل "${p.input}" على أنه سجل دون تحديد كائن حقيقي، لذلك لا يحمّل أي تشغيل ` + + `السجل وتُستخدم قيمة المُدخل دون تحقق. حدّد الكائن الذي يحمل المُدخل معرّف سجله، أو أزل الكائن إذا لم يكن ` + + `المُدخل معرّف سجل.`, + fr: (p) => + `Le flux « ${p.flow} » déclare l’entrée « ${p.input} » comme un enregistrement sans nommer d’objet réel : ` + + `aucun démarrage ne charge donc l’enregistrement et la valeur de l’entrée est utilisée sans contrôle. ` + + `Indiquez l’objet dont l’entrée porte l’ID d’enregistrement, ou supprimez l’objet si l’entrée n’est pas un ` + + `ID d’enregistrement.`, + 'pt-BR': (p) => + `O fluxo "${p.flow}" declara a entrada "${p.input}" como um registro sem indicar um objeto real, então ` + + `nenhuma inicialização carrega o registro e o valor da entrada é usado sem verificação. Defina o objeto cujo ` + + `ID de registro a entrada carrega, ou remova o objeto se a entrada não for um ID de registro.`, + ru: (p) => + `Поток «${p.flow}» объявляет входной параметр «${p.input}» записью, не указывая реальный объект, поэтому ни ` + + `один запуск не загружает запись, а значение параметра используется без проверки. Укажите объект, ID записи ` + + `которого передаёт параметр, или удалите объект, если параметр не является ID записи.`, + de: (p) => + `Der Flow „${p.flow}“ deklariert die Eingabe „${p.input}“ als Datensatz, ohne ein echtes Objekt zu nennen. ` + + `Daher lädt kein Start den Datensatz, und der Wert der Eingabe wird ungeprüft verwendet. Legen Sie das ` + + `Objekt fest, dessen Datensatz-ID die Eingabe trägt, oder entfernen Sie das Objekt, wenn die Eingabe keine ` + + `Datensatz-ID ist.`, + ja: (p) => + `フロー「${p.flow}」は入力「${p.input}」をレコードとして宣言していますが、実際のオブジェクトを指定していないため、` + + `どの起動でもレコードが読み込まれず、入力値は確認されないまま使われます。入力が持つレコード ID のオブジェクトを設定するか、` + + `入力がレコード ID でない場合はオブジェクトの指定を削除してください。`, + ko: (p) => + `플로우 "${p.flow}"는 입력 "${p.input}"을(를) 실제 개체를 지정하지 않은 레코드로 선언하므로, 어떤 시작에서도 ` + + `레코드를 불러오지 않고 입력 값이 검사 없이 사용됩니다. 입력이 담는 레코드 ID의 개체를 지정하거나, 입력이 ` + + `레코드 ID가 아니라면 개체 지정을 제거하세요.`, + }, + [FLOW_INPUT_RECORD_READ_AS_LIST]: { + en: (p) => + `Flow "${p.flow}" declares input "${p.input}" as one "${p.object}" record ID, but node "${p.node}" reads it ` + + `as a list of "${p.listObject}" IDs, so every start that passes this input is refused. If the input ` + + `carries a list of IDs, remove its object; otherwise read it as a single ID.`, + 'zh-Hans': (p) => + `流程“${p.flow}”将输入“${p.input}”声明为一个“${p.object}”记录 ID,但节点“${p.node}”把它当作“${p.listObject}”的 ID 列表读取,` + + `因此每次传入该输入的启动都会被拒绝。如果该输入携带的是 ID 列表,请删除它的对象设置;否则请按单个 ID 读取它。`, + 'zh-Hant': (p) => + `流程「${p.flow}」將輸入「${p.input}」宣告為一個「${p.object}」記錄 ID,但節點「${p.node}」把它當作「${p.listObject}」的 ID 清單讀取,` + + `因此每次傳入該輸入的啟動都會被拒絕。如果該輸入攜帶的是 ID 清單,請刪除它的物件設定;否則請按單一 ID 讀取它。`, + es: (p) => + `El flujo "${p.flow}" declara la entrada "${p.input}" como un único ID de registro de "${p.object}", pero el ` + + `nodo "${p.node}" la lee como una lista de IDs de "${p.listObject}", así que se rechazará cada inicio que ` + + `pase esta entrada. Si la entrada lleva una lista de IDs, quite su objeto; si no, léala como un único ID.`, + ar: (p) => + `يعرّف التدفق "${p.flow}" المُدخل "${p.input}" على أنه معرّف سجل واحد من "${p.object}"، لكن العقدة ` + + `"${p.node}" تقرؤه كقائمة معرّفات من "${p.listObject}"، لذلك سيُرفض كل تشغيل يمرّر هذا المُدخل. إذا كان ` + + `المُدخل يحمل قائمة معرّفات، فأزل كائنه؛ وإلا فاقرأه كمعرّف واحد.`, + fr: (p) => + `Le flux « ${p.flow} » déclare l’entrée « ${p.input} » comme un seul ID d’enregistrement de « ${p.object} », ` + + `mais le nœud « ${p.node} » la lit comme une liste d’ID de « ${p.listObject} » : chaque démarrage qui ` + + `transmet cette entrée sera donc refusé. Si l’entrée porte une liste d’ID, supprimez son objet ; sinon, ` + + `lisez-la comme un seul ID.`, + 'pt-BR': (p) => + `O fluxo "${p.flow}" declara a entrada "${p.input}" como um único ID de registro de "${p.object}", mas o nó ` + + `"${p.node}" a lê como uma lista de IDs de "${p.listObject}", então toda inicialização que passar essa ` + + `entrada será recusada. Se a entrada carrega uma lista de IDs, remova o objeto dela; caso contrário, leia-a ` + + `como um único ID.`, + ru: (p) => + `Поток «${p.flow}» объявляет входной параметр «${p.input}» одним ID записи «${p.object}», но узел ` + + `«${p.node}» читает его как список ID «${p.listObject}», поэтому каждый запуск с этим параметром будет ` + + `отклонён. Если параметр передаёт список ID, удалите у него объект; иначе читайте его как один ID.`, + de: (p) => + `Der Flow „${p.flow}“ deklariert die Eingabe „${p.input}“ als eine einzelne Datensatz-ID von „${p.object}“, ` + + `aber der Knoten „${p.node}“ liest sie als Liste von „${p.listObject}“-IDs. Daher wird jeder Start ` + + `abgelehnt, der diese Eingabe übergibt. Trägt die Eingabe eine Liste von IDs, entfernen Sie ihr Objekt; ` + + `andernfalls lesen Sie sie als einzelne ID.`, + ja: (p) => + `フロー「${p.flow}」は入力「${p.input}」を「${p.object}」のレコード ID 1 件として宣言していますが、ノード「${p.node}」は` + + `これを「${p.listObject}」の ID のリストとして読み取るため、この入力を渡す起動はすべて拒否されます。入力が ID のリストなら` + + `オブジェクトの指定を削除し、そうでなければ 1 件の ID として読み取ってください。`, + ko: (p) => + `플로우 "${p.flow}"는 입력 "${p.input}"을(를) "${p.object}" 레코드 ID 하나로 선언하지만, 노드 "${p.node}"는 이를 ` + + `"${p.listObject}" ID 목록으로 읽으므로 이 입력을 전달하는 모든 시작이 거부됩니다. 입력이 ID 목록이라면 개체 ` + + `지정을 제거하고, 아니라면 하나의 ID로 읽으세요.`, + }, + [FLOW_DRAFT_STATUS_AMBIGUOUS]: { + en: (p) => + `Flow "${p.flow}" is a draft, and a draft flow still runs when its trigger fires. Set its status to ` + + `"active" to run it on purpose, or to "obsolete" to turn it off.`, + 'zh-Hans': (p) => + `流程“${p.flow}”是草稿,而草稿流程在触发条件满足时仍会运行。如果有意让它运行,请将状态设为“active”;如果要停用,请设为“obsolete”。`, + 'zh-Hant': (p) => + `流程「${p.flow}」是草稿,而草稿流程在觸發條件滿足時仍會執行。如果有意讓它執行,請將狀態設為「active」;如果要停用,請設為「obsolete」。`, + es: (p) => + `El flujo "${p.flow}" es un borrador, y un flujo en borrador se ejecuta igualmente cuando se activa su ` + + `disparador. Ponga su estado en "active" para ejecutarlo a propósito, o en "obsolete" para desactivarlo.`, + ar: (p) => + `التدفق "${p.flow}" مسودة، والتدفق المسودة يعمل مع ذلك عند تنشيط مشغّله. اضبط حالته على "active" لتشغيله ` + + `عن قصد، أو على "obsolete" لإيقافه.`, + fr: (p) => + `Le flux « ${p.flow} » est un brouillon, et un flux en brouillon s’exécute quand même lorsque son ` + + `déclencheur se produit. Passez son statut à « active » pour l’exécuter délibérément, ou à « obsolete » pour ` + + `le désactiver.`, + 'pt-BR': (p) => + `O fluxo "${p.flow}" é um rascunho, e um fluxo em rascunho ainda é executado quando seu gatilho dispara. ` + + `Defina o status como "active" para executá-lo de propósito, ou como "obsolete" para desativá-lo.`, + ru: (p) => + `Поток «${p.flow}» — черновик, а черновик всё равно запускается при срабатывании триггера. Задайте статус ` + + `«active», чтобы запускать его осознанно, или «obsolete», чтобы отключить.`, + de: (p) => + `Der Flow „${p.flow}“ ist ein Entwurf, und ein Entwurf läuft trotzdem, wenn sein Auslöser eintritt. Setzen ` + + `Sie den Status auf „active“, um ihn bewusst auszuführen, oder auf „obsolete“, um ihn abzuschalten.`, + ja: (p) => + `フロー「${p.flow}」は下書きですが、下書きのフローもトリガーが発生すると実行されます。意図して実行する場合は` + + `ステータスを「active」に、無効にする場合は「obsolete」に設定してください。`, + ko: (p) => + `플로우 "${p.flow}"는 초안이지만, 초안 플로우도 트리거가 발생하면 실행됩니다. 의도적으로 실행하려면 상태를 ` + + `"active"로, 끄려면 "obsolete"로 설정하세요.`, + }, +}); diff --git a/packages/lint/src/validate-readonly-flow-writes.ts b/packages/lint/src/validate-readonly-flow-writes.ts index 2e522d9f1e1..ab54fd47bb9 100644 --- a/packages/lint/src/validate-readonly-flow-writes.ts +++ b/packages/lint/src/validate-readonly-flow-writes.ts @@ -65,6 +65,7 @@ import { walkFlowNodes, flowNodeLabel } from './flow-walk.js'; import { objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; export type ReadonlyFlowWriteSeverity = 'error' | 'warning'; @@ -77,6 +78,11 @@ export interface ReadonlyFlowWriteFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates, on the advisory push + * sites only (`validate-readonly-flow-writes.user-text.ts` sibling catalog); see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } // Rule ids (registry entries). One id per SHAPE, not per verb: since #15394 @@ -412,6 +418,7 @@ export function validateReadonlyFlowWrites(stack: AnyRec): ReadonlyFlowWriteFind hint: `Derive '${fieldName}' in a beforeUpdate hook on '${objectName}', or target only records whose ` + `readonlyWhen predicate is FALSE; the lock is NOT waived by a system context`, + userTextParams: { flow: flowName, node: nodeName, field: fieldName, object: objectName }, }); } } diff --git a/packages/lint/src/validate-readonly-flow-writes.user-text.ts b/packages/lint/src/validate-readonly-flow-writes.user-text.ts new file mode 100644 index 00000000000..65ada4ec59e --- /dev/null +++ b/packages/lint/src/validate-readonly-flow-writes.user-text.ts @@ -0,0 +1,79 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-readonly-flow-writes.ts`'s advisory + * finding (`flow-update-readonly-when-field`), in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it, kept beside the rule so its wording and its translations + * change together. + * + * Who reads it: the person who saved the flow in Studio, or the object whose + * field gained the condition while a live flow writes it (the rule also judges + * carried flows on an object write), in their own language, once the save door + * composes `RuntimeAuthoringIssueSchema.userMessage` from it. The condition is + * named by the field designer's own label ("Read-only when"). The rule's other + * id, `flow-update-readonly-field`, refuses the write (`error`) and carries no + * params. + * + * Params, set at the push site in `validate-readonly-flow-writes.ts`: `flow`, + * `node` (the node's label, as the rule's `where` shows it), `field`, `object`. + * + * `finding-user-text.test.ts` renders it from the rule's real + * finding in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { FLOW_UPDATE_READONLY_WHEN_FIELD } from './validate-readonly-flow-writes.js'; + +export const READONLY_FLOW_WRITES_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_UPDATE_READONLY_WHEN_FIELD]: { + en: (p) => + `Node "${p.node}" in flow "${p.flow}" updates field "${p.field}" of "${p.object}", which has a "Read-only ` + + `when" condition, so the change is silently dropped on records where that condition is true. Set the value ` + + `in a before-update hook on "${p.object}", or update only records where the condition is false.`, + 'zh-Hans': (p) => + `流程“${p.flow}”的节点“${p.node}”更新“${p.object}”的字段“${p.field}”,而该字段设置了“只读条件”,因此在满足该条件的记录上,` + + `这次更改会被静默丢弃。请在“${p.object}”的更新前钩子中设置该值,或只更新不满足该条件的记录。`, + 'zh-Hant': (p) => + `流程「${p.flow}」的節點「${p.node}」更新「${p.object}」的欄位「${p.field}」,而該欄位設定了「唯讀條件」,因此在符合該條件的記錄上,` + + `這次變更會被靜默捨棄。請在「${p.object}」的更新前鉤子中設定該值,或只更新不符合該條件的記錄。`, + es: (p) => + `El nodo "${p.node}" del flujo "${p.flow}" actualiza el campo "${p.field}" de "${p.object}", que tiene una ` + + `condición "Solo lectura cuando", así que el cambio se descarta sin aviso en los registros donde esa ` + + `condición se cumple. Asigne el valor en un hook previo a la actualización de "${p.object}", o actualice ` + + `solo registros donde la condición no se cumpla.`, + ar: (p) => + `تحدّث العقدة "${p.node}" في التدفق "${p.flow}" الحقل "${p.field}" في "${p.object}"، وله شرط "للقراءة فقط ` + + `عندما"، لذلك يُتجاهل التغيير بصمت في السجلات التي يتحقق فيها هذا الشرط. اضبط القيمة في خطاف قبل التحديث ` + + `على "${p.object}"، أو حدّث فقط السجلات التي لا يتحقق فيها الشرط.`, + fr: (p) => + `Le nœud « ${p.node} » du flux « ${p.flow} » met à jour le champ « ${p.field} » de « ${p.object} », qui a ` + + `une condition « Lecture seule si » : la modification est donc ignorée sans avertissement sur les ` + + `enregistrements où cette condition est vraie. Définissez la valeur dans un hook avant mise à jour sur ` + + `« ${p.object} », ou ne mettez à jour que les enregistrements où la condition est fausse.`, + 'pt-BR': (p) => + `O nó "${p.node}" do fluxo "${p.flow}" atualiza o campo "${p.field}" de "${p.object}", que tem uma condição ` + + `"Somente leitura quando", então a alteração é descartada silenciosamente nos registros em que essa ` + + `condição é verdadeira. Defina o valor em um hook antes da atualização em "${p.object}", ou atualize apenas ` + + `registros em que a condição seja falsa.`, + ru: (p) => + `Узел «${p.node}» потока «${p.flow}» обновляет поле «${p.field}» объекта «${p.object}», у которого есть ` + + `условие «Только для чтения, если», поэтому изменение молча отбрасывается в записях, где это условие ` + + `выполняется. Задайте значение в хуке перед обновлением «${p.object}» или обновляйте только записи, где ` + + `условие не выполняется.`, + de: (p) => + `Der Knoten „${p.node}“ im Flow „${p.flow}“ aktualisiert das Feld „${p.field}“ von „${p.object}“, das eine ` + + `Bedingung „Schreibgeschützt, wenn“ hat. Die Änderung wird daher bei Datensätzen, für die diese Bedingung ` + + `zutrifft, stillschweigend verworfen. Setzen Sie den Wert in einem Hook vor der Aktualisierung von ` + + `„${p.object}“, oder aktualisieren Sie nur Datensätze, für die die Bedingung nicht zutrifft.`, + ja: (p) => + `フロー「${p.flow}」のノード「${p.node}」は「${p.object}」の項目「${p.field}」を更新しますが、この項目には読み取り専用の条件が` + + `設定されているため、その条件を満たすレコードでは変更が通知なく破棄されます。「${p.object}」の更新前フックで値を設定するか、` + + `条件を満たさないレコードだけを更新してください。`, + ko: (p) => + `플로우 "${p.flow}"의 노드 "${p.node}"는 "${p.object}"의 필드 "${p.field}"을(를) 업데이트하지만, 이 필드에는 ` + + `읽기 전용 조건이 있으므로 조건이 참인 레코드에서는 변경이 알림 없이 버려집니다. "${p.object}"의 업데이트 전 ` + + `후크에서 값을 설정하거나, 조건이 거짓인 레코드만 업데이트하세요.`, + }, +});