From f4ce7b5007173e208f498bec98afdbd3f84a682e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:22:01 +0000 Subject: [PATCH] feat(lint): data-model advisories carry a localized user sentence The five data-model advisory ids the publish door returns gain a user-facing sentence in all 11 platform locales, in catalogs beside their rules: autonumber-unrecognized-token and autonumber-references-optional-field (lint-autonumber-formats), sort-field-unprovisioned, searchable-field-unprovisioned, and object-reference-unregistered-platform at the dataset base-object site. Each push site sets userTextParams; the lintAutonumberFormats registry adapter now passes them through. Rule ids, message and hint are unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzvBVSWuwHDeSGbNmG --- .changeset/32838-advisory-user-text.md | 10 + packages/lint/src/authoring-rules.ts | 1 + .../src/finding-user-text.data-model.test.ts | 322 ++++++++++++++++++ packages/lint/src/finding-user-text.ts | 8 + packages/lint/src/lint-autonumber-formats.ts | 14 + .../src/lint-autonumber-formats.user-text.ts | 174 ++++++++++ .../lint/src/validate-object-references.ts | 19 +- .../validate-object-references.user-text.ts | 90 +++++ .../lint/src/validate-searchable-fields.ts | 9 + .../validate-searchable-fields.user-text.ts | 136 ++++++++ packages/lint/src/validate-sortable-fields.ts | 10 + .../src/validate-sortable-fields.user-text.ts | 94 +++++ 12 files changed, 886 insertions(+), 1 deletion(-) create mode 100644 .changeset/32838-advisory-user-text.md create mode 100644 packages/lint/src/finding-user-text.data-model.test.ts create mode 100644 packages/lint/src/lint-autonumber-formats.user-text.ts create mode 100644 packages/lint/src/validate-object-references.user-text.ts create mode 100644 packages/lint/src/validate-searchable-fields.user-text.ts create mode 100644 packages/lint/src/validate-sortable-fields.user-text.ts diff --git a/.changeset/32838-advisory-user-text.md b/.changeset/32838-advisory-user-text.md new file mode 100644 index 00000000000..d5760787ae2 --- /dev/null +++ b/.changeset/32838-advisory-user-text.md @@ -0,0 +1,10 @@ +--- +'@objectstack/lint': patch +--- + +Clause-②: no +Metadata-protocol: none + +The data-model advisories the save door returns now carry a user-facing sentence in all 11 platform locales, for the save door's `userMessage` (the pattern the security-posture advisories already follow). Five advisory rule ids gain one: the autonumber-format rule's `autonumber-unrecognized-token` and `autonumber-references-optional-field` (object writes), `sort-field-unprovisioned` and `searchable-field-unprovisioned` on an external object's list view or searchable fields (object and view writes), and `object-reference-unregistered-platform` on a dataset's base object (dataset writes). Their findings carry the names the sentence interpolates as `userTextParams`, and `findingUserMessage` renders the sentence in the request's locale, else the workspace default, else English. + +Rule ids, `message` and `hint` are unchanged, so `os validate`, `os lint` and every save response read exactly as before. The other data-model advisories have no sentence because the publish door never returns them: `unique/double-declaration`, `unique/legacy-organization-composite` and `title-unresolvable` run only on the CLI, and `field/select-missing-options`, `relationship/master-detail-required` and `relationship/association-inline-edit` belong to the `os lint` best-practice sweep. They stay on the English `message`. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index c3e485679c4..09a53557f93 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2221,6 +2221,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ path: f.where, message: f.message, hint: f.hint, + ...(f.userTextParams ? { userTextParams: f.userTextParams } : {}), })), }, // #2554 — a `type:'form'` action target naming a missing or LIST view opens a diff --git a/packages/lint/src/finding-user-text.data-model.test.ts b/packages/lint/src/finding-user-text.data-model.test.ts new file mode 100644 index 00000000000..5d9d06729e3 --- /dev/null +++ b/packages/lint/src/finding-user-text.data-model.test.ts @@ -0,0 +1,322 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The data-model advisories' user-facing sentences in the request's language + * (ruling record 6819749037, the pattern `finding-user-text.test.ts` pins for + * the security-posture rule): the autonumber-format rule's catalog + * (`lint-autonumber-formats.user-text.ts`), the sort and search rules' + * (`validate-sortable-fields.user-text.ts`, `validate-searchable-fields.user-text.ts`) + * and the object-reference rule's (`validate-object-references.user-text.ts`), + * each rendered from the rule's REAL findings in every platform locale, and + * carried out of the publish door. + */ + +import { describe, it, expect } from 'vitest'; +import { RuntimeAuthoringIssueSchema } from '@objectstack/spec/api'; +import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; +import { FINDING_USER_TEXT_CATALOG, findingUserMessage } from './finding-user-text.js'; +import { AUTONUMBER_FORMATS_USER_TEXT } from './lint-autonumber-formats.user-text.js'; +import { SORTABLE_FIELDS_USER_TEXT } from './validate-sortable-fields.user-text.js'; +import { SEARCHABLE_FIELDS_USER_TEXT } from './validate-searchable-fields.user-text.js'; +import { OBJECT_REFERENCES_USER_TEXT } from './validate-object-references.user-text.js'; +import { + AUTONUMBER_LITERAL_TOKEN, + AUTONUMBER_OPTIONAL_FIELD, + AUTONUMBER_UNKNOWN_FIELD, + lintAutonumberFormats, +} from './lint-autonumber-formats.js'; +import { SORT_FIELD_UNPROVISIONED, validateSortableFields } from './validate-sortable-fields.js'; +import { SEARCHABLE_FIELD_UNPROVISIONED, validateSearchableFields } from './validate-searchable-fields.js'; +import { + OBJECT_REFERENCE_UNREGISTERED_PLATFORM, + validateObjectReferences, +} from './validate-object-references.js'; +import { PAGE_FIELD_UNPROVISIONED } from './validate-page-field-bindings.js'; +import { TITLE_UNRESOLVABLE } from './validate-record-title.js'; +import { + RELATIONSHIP_MASTER_DETAIL_REQUIRED, + UNIQUE_DOUBLE_DECLARATION, + UNIQUE_LEGACY_ORGANIZATION_COMPOSITE, +} from './data-model-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +type AnyRec = Record; + +/** The data-model advisory ids the publish door returns, one catalog each. */ +const CATALOGS = [ + { catalog: AUTONUMBER_FORMATS_USER_TEXT, rules: [AUTONUMBER_LITERAL_TOKEN, AUTONUMBER_OPTIONAL_FIELD] }, + { catalog: SORTABLE_FIELDS_USER_TEXT, rules: [SORT_FIELD_UNPROVISIONED] }, + { catalog: SEARCHABLE_FIELDS_USER_TEXT, rules: [SEARCHABLE_FIELD_UNPROVISIONED] }, + { catalog: OBJECT_REFERENCES_USER_TEXT, rules: [OBJECT_REFERENCE_UNREGISTERED_PLATFORM] }, +] as const; + +// ── Fixtures ──────────────────────────────────────────────────────────────── + +/** An object with one Auto Number field of the given format. */ +const autonumberStack = (format: string): AnyRec => ({ + objects: [{ + name: 'acme_invoice', + fields: { + name: { type: 'text', required: true }, + plan_no: { type: 'text' }, + invoice_no: { type: 'autonumber', autonumberFormat: format }, + }, + }], +}); + +/** An external object: its injected audit columns are addressable and not stored. */ +const EXT = { + name: 'acme_ext_customer', + datasource: 'acme_external', + external: { remoteName: 'customers' }, + fields: { name: { type: 'text' }, email: { type: 'text' } }, +}; +const extStack = (patch: AnyRec): AnyRec => ({ objects: [{ ...EXT, ...patch }] }); + +const datasetStack = (object: string): AnyRec => ({ + objects: [EXT], + datasets: [{ name: 'acme_customer_metrics', object, dimensions: [], measures: [] }], +}); + +type Case = { + label: string; + rule: string; + stack: AnyRec; + params: Record; + run: (stack: AnyRec) => ReadonlyArray<{ rule: string; severity: string; userTextParams?: Record }>; +}; + +/** + * One stack per advisory push site the publish door reaches, with the params + * each finding must carry: both arms of `autonumber-unrecognized-token`, the + * optional-field site, the list-view sort site (`checkSortDeclaration`), both + * roles of the search site (`checkSearchableFieldList`) and the dataset site + * of the object-reference rule. + */ +const CASES: readonly Case[] = [ + { + label: 'autonumber format with a token that is no counter, date or field', + rule: AUTONUMBER_LITERAL_TOKEN, + stack: autonumberStack('INV-{ YYYY }-{0000}'), + params: { object: 'acme_invoice', field: 'invoice_no', token: '{ YYYY }', kind: 'unknown-token' }, + run: (s) => lintAutonumberFormats(s), + }, + { + label: 'autonumber format with a second counter', + rule: AUTONUMBER_LITERAL_TOKEN, + stack: autonumberStack('INV-{0000}-{00}'), + params: { object: 'acme_invoice', field: 'invoice_no', token: '{00}', kind: 'second-counter' }, + run: (s) => lintAutonumberFormats(s), + }, + { + label: 'autonumber format interpolating an optional field', + rule: AUTONUMBER_OPTIONAL_FIELD, + stack: autonumberStack('{plan_no}-{0000}'), + params: { object: 'acme_invoice', field: 'invoice_no', ref: 'plan_no' }, + run: (s) => lintAutonumberFormats(s), + }, + { + label: 'list-view sort on an unprovisioned injected column', + rule: SORT_FIELD_UNPROVISIONED, + stack: extStack({ listViews: { recent: { type: 'grid', sort: [{ field: 'created_at', order: 'desc' }] } } }), + params: { object: 'acme_ext_customer', field: 'created_at' }, + run: (s) => validateSortableFields(s), + }, + { + label: 'object searchable fields naming an unprovisioned injected column', + rule: SEARCHABLE_FIELD_UNPROVISIONED, + stack: extStack({ searchableFields: ['name', 'created_at'] }), + params: { object: 'acme_ext_customer', field: 'created_at', role: 'canonical' }, + run: (s) => validateSearchableFields(s), + }, + { + label: 'list-view search fields naming an unprovisioned injected column', + rule: SEARCHABLE_FIELD_UNPROVISIONED, + stack: extStack({ listViews: { recent: { type: 'grid', searchableFields: ['updated_at'] } } }), + params: { object: 'acme_ext_customer', field: 'updated_at', role: 'narrowing' }, + run: (s) => validateSearchableFields(s), + }, + { + label: 'dataset based on a platform-shaped object no package provides', + rule: OBJECT_REFERENCE_UNREGISTERED_PLATFORM, + stack: datasetStack('sys_customer_score'), + params: { dataset: 'acme_customer_metrics', object: 'sys_customer_score' }, + run: (s) => validateObjectReferences(s), + }, +]; + +/** The one finding of `rule` the case's stack produces. */ +const findingOf = (c: Case) => { + const found = c.run(c.stack).filter((f) => f.rule === c.rule); + expect(found, `${c.label}: exactly one ${c.rule} finding`).toHaveLength(1); + return found[0]!; +}; + +/** The params that are NAMES the sentence must show (not the arm selectors). */ +const namesOf = (params: Record): string[] => + Object.entries(params).filter(([key]) => key !== 'kind' && key !== 'role').map(([, value]) => value); + +describe('data-model advisories user text · the catalogs', () => { + it.each(CATALOGS.map((c) => [c.rules.join(', '), c] as const))( + 'the catalog of %s holds a sentence for exactly its door-reaching ids, in every platform locale', + (_label, { catalog, rules }) => { + expect(Object.keys(catalog).sort()).toEqual([...rules].sort()); + for (const [rule, entry] of Object.entries(catalog)) { + expect(Object.keys(entry).sort(), rule).toEqual([...PLATFORM_LOCALE_TAGS].sort()); + } + }, + ); + + it('all four are merged into the one finding catalog the door renders from', () => { + for (const { catalog, rules } of CATALOGS) { + for (const rule of rules) expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(catalog[rule]); + } + }); + + it('keeps every rule id stable: the catalogs are keyed by the ids the findings already carry', () => { + expect(CATALOGS.flatMap((c) => c.rules)).toEqual([ + 'autonumber-unrecognized-token', + 'autonumber-references-optional-field', + 'sort-field-unprovisioned', + 'searchable-field-unprovisioned', + 'object-reference-unregistered-platform', + ]); + }); + + it('the advisory ids the door never returns have no sentence here, and stay on the English message', () => { + // CLI-only registry entries (`RUNTIME_OBJECT_ADVISORY_VOLUME`) and the + // `lintDataModel` sweep, which has no registry entry at all. + for (const rule of [ + UNIQUE_DOUBLE_DECLARATION, + UNIQUE_LEGACY_ORGANIZATION_COMPOSITE, + 'field/select-missing-options', + RELATIONSHIP_MASTER_DETAIL_REQUIRED, + 'relationship/association-inline-edit', + TITLE_UNRESOLVABLE, + ]) { + expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBeUndefined(); + } + }); +}); + +describe('data-model advisories user text · rendered from the rules\' 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).toBe('warning'); + 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 name of namesOf(c.params)) expect(text, `${c.rule} · ${tag} names ${name}`).toContain(name); + // A real translation, not the English floor standing in for it. + if (tag !== 'en') expect(text, `${c.rule} · ${tag}`).not.toBe(english); + } + }); + + it('renders the two autonumber token arms, and the two search roles, apart in every platform locale', () => { + for (const rule of [AUTONUMBER_LITERAL_TOKEN, SEARCHABLE_FIELD_UNPROVISIONED]) { + const findings = CASES.filter((c) => c.rule === rule).map(findingOf); + expect(findings, rule).toHaveLength(2); + for (const tag of PLATFORM_LOCALE_TAGS) { + // Same names, so only the arm selector tells the two apart. + const texts = findings.map((f) => + findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, token: '{x}', field: 'f' } }, [tag])); + expect(new Set(texts).size, `${rule} · ${tag}`).toBe(2); + } + } + }); + + it('renders the Auto Number sentence in zh-Hans and en with the object, field and optional field names', () => { + const finding = findingOf(CASES.find((c) => c.rule === AUTONUMBER_OPTIONAL_FIELD)!); + expect(findingUserMessage(finding, ['zh-CN'])).toContain('对象“acme_invoice”的自动编号字段“invoice_no”'); + expect(findingUserMessage(finding, ['zh-CN'])).toContain('请将“plan_no”设为必填字段'); + expect(findingUserMessage(finding, ['en-US'])).toContain( + 'Auto Number field "invoice_no" on object "acme_invoice" puts the value of "plan_no"', + ); + }); + + it('gives no sentence where the finding is not advice the door returns', () => { + // An autonumber error refuses the write: no params. + const unknown = lintAutonumberFormats(autonumberStack('{gone_field}-{0000}')).filter((f) => f.rule === AUTONUMBER_UNKNOWN_FIELD); + expect(unknown.map((f) => f.severity)).toEqual(['error']); + expect(unknown[0]!.userTextParams).toBeUndefined(); + // A page sort's unprovisioned warning is `validate-page-field-bindings.ts`'s + // id: this file's page-sort site carries no params of its own. + const pageSort = validateSortableFields({ + objects: [EXT], + pages: [{ + name: 'acme_customer_page', type: 'app', + regions: [{ name: 'main', components: [{ + type: 'object-grid', + properties: { objectName: 'acme_ext_customer', sort: [{ field: 'created_at', order: 'desc' }] }, + }] }], + }], + }).filter((f) => f.rule === PAGE_FIELD_UNPROVISIONED); + expect(pageSort.map((f) => f.severity)).toEqual(['warning']); + expect(pageSort[0]!.userTextParams).toBeUndefined(); + expect(FINDING_USER_TEXT_CATALOG[PAGE_FIELD_UNPROVISIONED]).toBeUndefined(); + // The object-reference sites a per-write snapshot never carries as the + // written item (here an object field's lookup target) carry none. + const fieldSite = validateObjectReferences({ + objects: [{ name: 'acme_note', fields: { score: { type: 'lookup', reference: 'sys_customer_score' } } }], + }).filter((f) => f.rule === OBJECT_REFERENCE_UNREGISTERED_PLATFORM); + expect(fieldSite.map((f) => f.severity)).toEqual(['warning']); + expect(fieldSite[0]!.userTextParams).toBeUndefined(); + }); +}); + +describe('data-model advisories user text · from the runtime gate to the wire field', () => { + /** The element the save door's `advisories[]` carries, with the sentence it renders. */ + const issueOf = (advisory: { rule: string; path: string; where: string; message: string; hint: string; severity: string; userTextParams?: Record }, locales: string[]) => + RuntimeAuthoringIssueSchema.parse({ + rule: advisory.rule, + path: advisory.path, + where: advisory.where, + message: advisory.message, + hint: advisory.hint, + severity: advisory.severity, + userMessage: findingUserMessage(advisory, locales), + }); + + it('an object write\'s autonumber advisory carries its params through the registry adapter', () => { + const stack = autonumberStack('{plan_no}-{0000}') as { objects: AnyRec[] }; + const result = runRuntimeAuthoringRules({ type: 'object', item: stack.objects[0], context: { objects: [] } }); + const advisory = result.advisories.find((f) => f.rule === AUTONUMBER_OPTIONAL_FIELD); + expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + expect(advisory!.userTextParams).toEqual({ object: 'acme_invoice', field: 'invoice_no', ref: 'plan_no' }); + + const issue = issueOf(advisory!, ['zh-CN', 'en']); + expect(issue.rule).toBe('autonumber-references-optional-field'); + expect(issue.userMessage).toContain('自动编号字段“invoice_no”'); + expect(issue.message).toBe(advisory!.message); + }); + + it('a view write\'s sort and search advisories render a valid userMessage', () => { + const view = { + name: 'acme_ext_recent', objectName: 'acme_ext_customer', viewKind: 'list', type: 'grid', + sort: [{ field: 'created_at', order: 'desc' }], searchableFields: ['created_at'], + }; + const result = runRuntimeAuthoringRules({ type: 'view', item: view, context: { objects: [EXT] } }); + for (const rule of [SORT_FIELD_UNPROVISIONED, SEARCHABLE_FIELD_UNPROVISIONED]) { + const advisory = result.advisories.find((f) => f.rule === rule); + expect(advisory, `${rule}: ${JSON.stringify(result.advisories)}`).toBeDefined(); + const issue = issueOf(advisory!, ['fr-FR', 'zh-CN']); + expect(issue.rule).toBe(rule); + expect(issue.userMessage).toContain('l’objet externe « acme_ext_customer »'); + } + }); + + it('a dataset write\'s object-reference advisory renders a valid userMessage', () => { + const stack = datasetStack('sys_customer_score') as { objects: unknown[]; datasets: AnyRec[] }; + const result = runRuntimeAuthoringRules({ type: 'dataset', item: stack.datasets[0], context: { objects: stack.objects } }); + const advisory = result.advisories.find((f) => f.rule === OBJECT_REFERENCE_UNREGISTERED_PLATFORM); + expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + expect(advisory!.userTextParams).toEqual({ dataset: 'acme_customer_metrics', object: 'sys_customer_score' }); + + const issue = issueOf(advisory!, ['ja-JP']); + expect(issue.userMessage).toContain('データセット「acme_customer_metrics」はオブジェクト「sys_customer_score」'); + }); +}); diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index cceabc0cb69..b7179a04781 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -56,6 +56,10 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s import { SECURITY_POSTURE_USER_TEXT } from './validate-security-posture.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'; +import { AUTONUMBER_FORMATS_USER_TEXT } from './lint-autonumber-formats.user-text.js'; +import { SORTABLE_FIELDS_USER_TEXT } from './validate-sortable-fields.user-text.js'; +import { SEARCHABLE_FIELDS_USER_TEXT } from './validate-searchable-fields.user-text.js'; +import { OBJECT_REFERENCES_USER_TEXT } from './validate-object-references.user-text.js'; /** * The names a finding's user sentence interpolates — object, field and @@ -159,6 +163,10 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( SECURITY_POSTURE_USER_TEXT, WIDGET_BINDINGS_USER_TEXT, CHART_BINDINGS_USER_TEXT, + AUTONUMBER_FORMATS_USER_TEXT, + SORTABLE_FIELDS_USER_TEXT, + SEARCHABLE_FIELDS_USER_TEXT, + OBJECT_REFERENCES_USER_TEXT, ); /** diff --git a/packages/lint/src/lint-autonumber-formats.ts b/packages/lint/src/lint-autonumber-formats.ts index e8589ab40eb..c5626403ff3 100644 --- a/packages/lint/src/lint-autonumber-formats.ts +++ b/packages/lint/src/lint-autonumber-formats.ts @@ -47,6 +47,7 @@ import { parseAutonumberFormat, referencedFields, resolveAutonumberFormat } from '@objectstack/spec/data'; import { objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; export interface AutonumberLintFinding { where: string; @@ -54,6 +55,12 @@ export interface AutonumberLintFinding { hint: string; rule: string; severity: 'error' | 'warning'; + /** + * The names the finding's user sentence interpolates + * (`lint-autonumber-formats.user-text.ts`), set on the two advisory ids the + * object publish door returns. The errors carry none. + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -115,6 +122,12 @@ export function lintAutonumberFormats(stack: AnyRec): AutonumberLintFinding[] { : `Date tokens are case-sensitive and exact: {YYYY} {YY} {MM} {DD} {YYYYMMDD} (no spaces/punctuation inside). For a field value use {field_name}.`, rule: AUTONUMBER_LITERAL_TOKEN, severity: 'warning', + userTextParams: { + object: objectName, + field: name, + token: tok, + kind: isExtraSeq ? 'second-counter' : 'unknown-token', + }, }); } } @@ -146,6 +159,7 @@ export function lintAutonumberFormats(stack: AnyRec): AutonumberLintFinding[] { hint: `Mark '${ref}' as \`required: true\` so it is always set before the record number is rendered.`, rule: AUTONUMBER_OPTIONAL_FIELD, severity: 'warning', + userTextParams: { object: objectName, field: name, ref }, }); } } diff --git a/packages/lint/src/lint-autonumber-formats.user-text.ts b/packages/lint/src/lint-autonumber-formats.user-text.ts new file mode 100644 index 00000000000..7f91511f96c --- /dev/null +++ b/packages/lint/src/lint-autonumber-formats.user-text.ts @@ -0,0 +1,174 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `lint-autonumber-formats.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 object in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from them. So each sentence says what the Auto Number field's record numbers + * will look like (or fail to get) and the one change that fixes it, in the + * object designer's words (object, field, Auto Number, record number, required); + * the developer-facing detail stays in the finding's `message`, `hint` and + * `os explain` entry. + * + * Both advisory ids reach the publish door: the rule runs there on an `object` + * write (`lintAutonumberFormats` in `authoring-rules.ts`, `runtimeTypes: + * ['object']`). The two errors (`autonumber-references-unknown-field`, + * `autonumber-references-self`) refuse the write and have no sentence here. + * + * Each entry reads the `userTextParams` its finding carries, set at the push + * site in `lint-autonumber-formats.ts`: + * + * | rule id | params | + * |---|---| + * | `autonumber-unrecognized-token` | `object`, `field`, `token` (the braced group as written), `kind` (`unknown-token` · `second-counter`) | + * | `autonumber-references-optional-field` | `object`, `field`, `ref` (the optional field the format interpolates) | + * + * `kind` is the rule's own split: its `message` tells a second `{0..0}` counter + * apart from any other unrecognized group, so the sentence has one arm per + * value. Names are the API names the rule saw, not labels, for the reason + * `validate-security-posture.user-text.ts` gives. + * + * `finding-user-text.data-model.test.ts` renders every entry from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { AUTONUMBER_LITERAL_TOKEN, AUTONUMBER_OPTIONAL_FIELD } from './lint-autonumber-formats.js'; + +/** `kind` of an `autonumber-unrecognized-token` finding: a second `{0..0}` counter. */ +const SECOND_COUNTER = 'second-counter'; + +export const AUTONUMBER_FORMATS_USER_TEXT: UserTextCatalog = Object.freeze({ + [AUTONUMBER_LITERAL_TOKEN]: { + en: (p) => + p.kind === SECOND_COUNTER + ? `The format of Auto Number field "${p.field}" on object "${p.object}" contains a second counter ` + + `${p.token}. Only the first counter counts, so this one appears as typed in every record number. Keep a ` + + `single counter, such as {0000}.` + : `The format of Auto Number field "${p.field}" on object "${p.object}" contains ${p.token}, which is not a ` + + `counter, date or field token, so it appears as typed in every record number. Correct its spelling (date ` + + `tokens are exact, such as {YYYY}) or remove it.`, + 'zh-Hans': (p) => + p.kind === SECOND_COUNTER + ? `对象“${p.object}”的自动编号字段“${p.field}”的格式中包含第二个计数器 ${p.token}。只有第一个计数器生效,` + + `因此这个会原样出现在每条记录的编号中。请只保留一个计数器,例如 {0000}。` + : `对象“${p.object}”的自动编号字段“${p.field}”的格式中包含 ${p.token},它不是计数器、日期或字段标记,` + + `因此会原样出现在每条记录的编号中。请更正其拼写(日期标记须完全一致,例如 {YYYY}),或将其删除。`, + 'zh-Hant': (p) => + p.kind === SECOND_COUNTER + ? `物件「${p.object}」的自動編號欄位「${p.field}」的格式中包含第二個計數器 ${p.token}。只有第一個計數器有效,` + + `因此這個會原樣出現在每筆記錄的編號中。請只保留一個計數器,例如 {0000}。` + : `物件「${p.object}」的自動編號欄位「${p.field}」的格式中包含 ${p.token},它不是計數器、日期或欄位標記,` + + `因此會原樣出現在每筆記錄的編號中。請更正其拼寫(日期標記須完全一致,例如 {YYYY}),或將其刪除。`, + es: (p) => + p.kind === SECOND_COUNTER + ? `El formato del campo de numeración automática "${p.field}" del objeto "${p.object}" contiene un segundo ` + + `contador ${p.token}. Solo cuenta el primero, así que este aparece tal cual en cada número de registro. ` + + `Deje un único contador, como {0000}.` + : `El formato del campo de numeración automática "${p.field}" del objeto "${p.object}" contiene ${p.token}, ` + + `que no es un contador, una fecha ni un campo, así que aparece tal cual en cada número de registro. ` + + `Corrija cómo está escrito (los tokens de fecha son exactos, como {YYYY}) o elimínelo.`, + ar: (p) => + p.kind === SECOND_COUNTER + ? `يحتوي تنسيق حقل الترقيم التلقائي "${p.field}" في الكائن "${p.object}" على عدّاد ثانٍ ${p.token}. ` + + `لا يُحتسب إلا العدّاد الأول، لذا يظهر هذا كما هو في كل رقم سجل. أبقِ عدّادًا واحدًا فقط، مثل {0000}.` + : `يحتوي تنسيق حقل الترقيم التلقائي "${p.field}" في الكائن "${p.object}" على ${p.token}، وهو ليس عدّادًا ` + + `ولا تاريخًا ولا حقلًا، لذا يظهر كما هو في كل رقم سجل. صحّح كتابته (رموز التاريخ دقيقة، مثل {YYYY}) أو احذفه.`, + fr: (p) => + p.kind === SECOND_COUNTER + ? `Le format du champ à numérotation automatique « ${p.field} » de l’objet « ${p.object} » contient un ` + + `second compteur ${p.token}. Seul le premier compte, donc celui-ci apparaît tel quel dans chaque numéro ` + + `d’enregistrement. Gardez un seul compteur, comme {0000}.` + : `Le format du champ à numérotation automatique « ${p.field} » de l’objet « ${p.object} » contient ` + + `${p.token}, qui n’est ni un compteur, ni une date, ni un champ : il apparaît tel quel dans chaque numéro ` + + `d’enregistrement. Corrigez son orthographe (les jetons de date sont exacts, comme {YYYY}) ou supprimez-le.`, + 'pt-BR': (p) => + p.kind === SECOND_COUNTER + ? `O formato do campo de numeração automática "${p.field}" do objeto "${p.object}" contém um segundo ` + + `contador ${p.token}. Só o primeiro conta, então este aparece literalmente em cada número de registro. ` + + `Mantenha um único contador, como {0000}.` + : `O formato do campo de numeração automática "${p.field}" do objeto "${p.object}" contém ${p.token}, que ` + + `não é um contador, uma data nem um campo, então aparece literalmente em cada número de registro. Corrija ` + + `a grafia (tokens de data são exatos, como {YYYY}) ou remova-o.`, + ru: (p) => + p.kind === SECOND_COUNTER + ? `Формат поля автонумерации «${p.field}» объекта «${p.object}» содержит второй счётчик ${p.token}. ` + + `Учитывается только первый, поэтому этот выводится как есть в каждом номере записи. Оставьте один ` + + `счётчик, например {0000}.` + : `Формат поля автонумерации «${p.field}» объекта «${p.object}» содержит ${p.token} — это не счётчик, не ` + + `дата и не поле, поэтому он выводится как есть в каждом номере записи. Исправьте написание (токены даты ` + + `точные, например {YYYY}) или удалите его.`, + de: (p) => + p.kind === SECOND_COUNTER + ? `Das Format des Autonummernfelds „${p.field}“ im Objekt „${p.object}“ enthält einen zweiten Zähler ` + + `${p.token}. Nur der erste Zähler zählt, daher erscheint dieser unverändert in jeder Datensatznummer. ` + + `Behalten Sie nur einen Zähler, etwa {0000}.` + : `Das Format des Autonummernfelds „${p.field}“ im Objekt „${p.object}“ enthält ${p.token}, das weder ein ` + + `Zähler noch ein Datum noch ein Feld ist, und erscheint daher unverändert in jeder Datensatznummer. ` + + `Korrigieren Sie die Schreibweise (Datumstoken sind exakt, etwa {YYYY}) oder entfernen Sie es.`, + ja: (p) => + p.kind === SECOND_COUNTER + ? `オブジェクト「${p.object}」の自動採番フィールド「${p.field}」の書式に 2 つ目のカウンター ${p.token} が` + + `含まれています。有効なのは最初のカウンターだけなので、これはすべてのレコード番号にそのまま表示されます。` + + `カウンターは {0000} のように 1 つだけにしてください。` + : `オブジェクト「${p.object}」の自動採番フィールド「${p.field}」の書式に ${p.token} が含まれています。` + + `これはカウンター、日付、フィールドのいずれのトークンでもないため、すべてのレコード番号にそのまま表示されます。` + + `綴りを修正する(日付トークンは {YYYY} のように完全に一致させます)か、削除してください。`, + ko: (p) => + p.kind === SECOND_COUNTER + ? `개체 "${p.object}"의 자동 번호 필드 "${p.field}" 형식에 두 번째 카운터 ${p.token}이(가) 들어 있습니다. ` + + `첫 번째 카운터만 적용되므로 이 카운터는 모든 레코드 번호에 그대로 표시됩니다. {0000}처럼 카운터를 ` + + `하나만 두세요.` + : `개체 "${p.object}"의 자동 번호 필드 "${p.field}" 형식에 ${p.token}이(가) 들어 있습니다. 이는 카운터, ` + + `날짜, 필드 토큰이 아니므로 모든 레코드 번호에 그대로 표시됩니다. 철자를 고치거나({YYYY}처럼 날짜 ` + + `토큰은 정확해야 합니다) 삭제하세요.`, + }, + [AUTONUMBER_OPTIONAL_FIELD]: { + en: (p) => + `Auto Number field "${p.field}" on object "${p.object}" puts the value of "${p.ref}" into each record ` + + `number, but "${p.ref}" is not required, so creating a record with "${p.ref}" left blank fails. Make ` + + `"${p.ref}" a required field.`, + 'zh-Hans': (p) => + `对象“${p.object}”的自动编号字段“${p.field}”会把“${p.ref}”的值放进每条记录的编号,但“${p.ref}”不是必填` + + `字段,因此创建记录时若“${p.ref}”留空就会失败。请将“${p.ref}”设为必填字段。`, + 'zh-Hant': (p) => + `物件「${p.object}」的自動編號欄位「${p.field}」會把「${p.ref}」的值放進每筆記錄的編號,但「${p.ref}」不是必填` + + `欄位,因此建立記錄時若「${p.ref}」留空就會失敗。請將「${p.ref}」設為必填欄位。`, + es: (p) => + `El campo de numeración automática "${p.field}" del objeto "${p.object}" pone el valor de "${p.ref}" en cada ` + + `número de registro, pero "${p.ref}" no es obligatorio, así que crear un registro con "${p.ref}" vacío ` + + `falla. Haga que "${p.ref}" sea un campo obligatorio.`, + ar: (p) => + `يضع حقل الترقيم التلقائي "${p.field}" في الكائن "${p.object}" قيمة "${p.ref}" في كل رقم سجل، لكن ` + + `"${p.ref}" ليس حقلًا مطلوبًا، لذا يفشل إنشاء سجل يُترك فيه "${p.ref}" فارغًا. اجعل "${p.ref}" حقلًا مطلوبًا.`, + fr: (p) => + `Le champ à numérotation automatique « ${p.field} » de l’objet « ${p.object} » insère la valeur de ` + + `« ${p.ref} » dans chaque numéro d’enregistrement, mais « ${p.ref} » n’est pas obligatoire : créer un ` + + `enregistrement où « ${p.ref} » est vide échoue. Rendez « ${p.ref} » obligatoire.`, + 'pt-BR': (p) => + `O campo de numeração automática "${p.field}" do objeto "${p.object}" coloca o valor de "${p.ref}" em cada ` + + `número de registro, mas "${p.ref}" não é obrigatório, então criar um registro com "${p.ref}" em branco ` + + `falha. Torne "${p.ref}" um campo obrigatório.`, + ru: (p) => + `Поле автонумерации «${p.field}» объекта «${p.object}» подставляет значение «${p.ref}» в каждый номер ` + + `записи, но поле «${p.ref}» не обязательное, поэтому создание записи с пустым «${p.ref}» завершается ` + + `ошибкой. Сделайте «${p.ref}» обязательным полем.`, + de: (p) => + `Das Autonummernfeld „${p.field}“ im Objekt „${p.object}“ setzt den Wert von „${p.ref}“ in jede ` + + `Datensatznummer ein, aber „${p.ref}“ ist kein Pflichtfeld. Daher schlägt das Anlegen eines Datensatzes ` + + `fehl, bei dem „${p.ref}“ leer bleibt. Machen Sie „${p.ref}“ zu einem Pflichtfeld.`, + ja: (p) => + `オブジェクト「${p.object}」の自動採番フィールド「${p.field}」は「${p.ref}」の値を各レコード番号に入れますが、` + + `「${p.ref}」は必須ではないため、「${p.ref}」を空のままにしたレコードの作成は失敗します。` + + `「${p.ref}」を必須フィールドにしてください。`, + ko: (p) => + `개체 "${p.object}"의 자동 번호 필드 "${p.field}"은(는) "${p.ref}" 값을 각 레코드 번호에 넣지만 ` + + `"${p.ref}"은(는) 필수 필드가 아니므로 "${p.ref}"을(를) 비워 둔 레코드는 만들 수 없습니다. ` + + `"${p.ref}"을(를) 필수 필드로 만드세요.`, + }, +}); diff --git a/packages/lint/src/validate-object-references.ts b/packages/lint/src/validate-object-references.ts index 38f25ec4798..34497a2c53f 100644 --- a/packages/lint/src/validate-object-references.ts +++ b/packages/lint/src/validate-object-references.ts @@ -87,6 +87,7 @@ import { import { referenceCarrierOf, referenceTargetOf } from '@objectstack/spec/data'; import { closureDependencyRemedy, packagesOf, recordsOf, suggestName } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; /** Materialized once for the repeated edit-distance scans in `suggestName`. */ const PLATFORM_NAMES: readonly string[] = [...PLATFORM_PROVIDED_OBJECT_NAMES]; @@ -122,6 +123,14 @@ export interface ObjectRefFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user sentence interpolates + * (`validate-object-references.user-text.ts`): set on + * `object-reference-unregistered-platform` at the one site the publish door + * returns it from, a dataset's base object (a `dataset` write). The other + * sites and the error carry none. + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -238,6 +247,9 @@ export function validateObjectReferences( * `subject` describes the reference for the message ("record-picker target"). * `remedy`, when a site has one sharper than the generic line (a view * container's namespace-prefixed spelling), is the whole `fix:` line. + * `userTextOf`, at a site the publish door reaches, names the site's own + * params for the advisory's user sentence; the resolved name joins them as + * `object`. * * [#22161] What a miss costs at each site used to close every hint; it is * the ids' `os explain` entries now (one paragraph, every site), so a hint is @@ -249,6 +261,7 @@ export function validateObjectReferences( path: string, subject: string, remedy = '', + userTextOf?: UserTextParams, ) => { const name = strName(target); if (!name) return; @@ -263,6 +276,7 @@ export function validateObjectReferences( rule: OBJECT_REFERENCE_UNREGISTERED_PLATFORM, where, path, + ...(userTextOf ? { userTextParams: { ...userTextOf, object: name } } : {}), // [#22161] One verdict sentence; the resolution ladder, where the // registry comes from and why this rung only advises is // `os explain object-reference-unregistered-platform`. @@ -518,11 +532,14 @@ export function validateObjectReferences( for (let dsi = 0; dsi < datasets.length; dsi++) { const ds = datasets[dsi]; if (!ds || typeof ds !== 'object') continue; + const dsName = strName(ds.name) ?? `#${dsi}`; check( strName(ds.object), - `dataset "${strName(ds.name) ?? `#${dsi}`}"`, + `dataset "${dsName}"`, `datasets[${dsi}].object`, 'dataset base object', + '', + { dataset: dsName }, ); } diff --git a/packages/lint/src/validate-object-references.user-text.ts b/packages/lint/src/validate-object-references.user-text.ts new file mode 100644 index 00000000000..d6be4a78bcd --- /dev/null +++ b/packages/lint/src/validate-object-references.user-text.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-object-references.ts`'s advisory, 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 dataset in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from it. So the sentence says what the dataset will show and the one change + * that fixes it, in the console's words (dataset, object, package); the + * developer-facing detail stays in the finding's `message`, `hint` and + * `os explain` entry. + * + * Only the site the publish door can actually return has a sentence. The rule + * is a reference-integrity member on `flow` and `dataset` writes, and of its + * sites only a dataset's base object (`datasets[].object`) is on the written + * item: a flow snapshot carries no object field, view, action, dashboard filter + * or app navigation entry of its own, and those sites' names arrive as context + * on both sides of the door's differential, so they cancel. Those sites carry + * no params and stay on the English `message`; `object-reference-unknown` is an + * error. + * + * The entry reads the `userTextParams` its finding carries, set at the dataset + * site in `validate-object-references.ts`: + * + * | rule id | params | + * |---|---| + * | `object-reference-unregistered-platform` | `dataset`, `object` (the platform-shaped base object name) | + * + * Names are the API names the rule saw, not labels, for the reason + * `validate-security-posture.user-text.ts` gives. + * + * `finding-user-text.data-model.test.ts` renders the entry from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { OBJECT_REFERENCE_UNREGISTERED_PLATFORM } from './validate-object-references.js'; + +export const OBJECT_REFERENCES_USER_TEXT: UserTextCatalog = Object.freeze({ + [OBJECT_REFERENCE_UNREGISTERED_PLATFORM]: { + en: (p) => + `Dataset "${p.dataset}" is based on object "${p.object}", which is named like a platform object, but no ` + + `installed package provides it, so the dataset will likely show no data. Check the object's name, or ignore ` + + `this if another package provides it.`, + 'zh-Hans': (p) => + `数据集“${p.dataset}”基于对象“${p.object}”,该名称看起来像平台对象,但没有任何已安装的包提供它,因此该数据集` + + `很可能不显示任何数据。请检查对象名称;如果它由其他包提供,可忽略此提示。`, + 'zh-Hant': (p) => + `資料集「${p.dataset}」以物件「${p.object}」為基礎,該名稱看起來像平台物件,但沒有任何已安裝的套件提供它,` + + `因此該資料集很可能不顯示任何資料。請檢查物件名稱;如果它由其他套件提供,可忽略此提示。`, + es: (p) => + `El conjunto de datos "${p.dataset}" se basa en el objeto "${p.object}", cuyo nombre parece de un objeto de ` + + `la plataforma, pero ningún paquete instalado lo proporciona, así que probablemente el conjunto de datos no ` + + `muestre datos. Revise el nombre del objeto, o ignore este aviso si otro paquete lo proporciona.`, + ar: (p) => + `تستند مجموعة البيانات "${p.dataset}" إلى الكائن "${p.object}"، واسمه يشبه اسم كائن من المنصة، لكن لا توفره ` + + `أي حزمة مثبّتة، لذا من المرجح ألا تعرض مجموعة البيانات أي بيانات. تحقّق من اسم الكائن، أو تجاهل هذا التنبيه ` + + `إذا كانت حزمة أخرى توفره.`, + fr: (p) => + `Le jeu de données « ${p.dataset} » repose sur l’objet « ${p.object} », dont le nom ressemble à celui d’un ` + + `objet de la plateforme, mais aucun package installé ne le fournit : le jeu de données n’affichera ` + + `probablement aucune donnée. Vérifiez le nom de l’objet, ou ignorez ce message si un autre package le fournit.`, + 'pt-BR': (p) => + `O conjunto de dados "${p.dataset}" se baseia no objeto "${p.object}", cujo nome parece o de um objeto da ` + + `plataforma, mas nenhum pacote instalado o fornece, então o conjunto de dados provavelmente não mostrará ` + + `dados. Verifique o nome do objeto, ou ignore este aviso se outro pacote o fornecer.`, + ru: (p) => + `Набор данных «${p.dataset}» основан на объекте «${p.object}», имя которого похоже на объект платформы, но ни ` + + `один установленный пакет его не предоставляет, поэтому набор данных, скорее всего, не покажет данных. ` + + `Проверьте имя объекта или не обращайте внимания на это сообщение, если объект предоставляет другой пакет.`, + de: (p) => + `Der Datensatz „${p.dataset}“ basiert auf dem Objekt „${p.object}“, dessen Name wie der eines ` + + `Plattformobjekts aussieht, aber kein installiertes Paket stellt es bereit. Der Datensatz zeigt daher ` + + `wahrscheinlich keine Daten. Prüfen Sie den Namen des Objekts, oder ignorieren Sie diesen Hinweis, wenn ein ` + + `anderes Paket es bereitstellt.`, + ja: (p) => + `データセット「${p.dataset}」はオブジェクト「${p.object}」に基づいていますが、この名前はプラットフォームの` + + `オブジェクトのように見えるものの、インストール済みのどのパッケージも提供していないため、データセットには` + + `データが表示されない可能性があります。オブジェクト名を確認してください。別のパッケージが提供している場合は、` + + `この通知を無視してかまいません。`, + ko: (p) => + `데이터 세트 "${p.dataset}"은(는) 개체 "${p.object}"을(를) 기반으로 하는데, 이 이름은 플랫폼 개체처럼 ` + + `보이지만 설치된 어떤 패키지도 이 개체를 제공하지 않으므로 데이터 세트에 데이터가 표시되지 않을 수 ` + + `있습니다. 개체 이름을 확인하고, 다른 패키지가 제공하는 경우에는 이 알림을 무시하세요.`, + }, +}); diff --git a/packages/lint/src/validate-searchable-fields.ts b/packages/lint/src/validate-searchable-fields.ts index e126e3803ff..b4c38201347 100644 --- a/packages/lint/src/validate-searchable-fields.ts +++ b/packages/lint/src/validate-searchable-fields.ts @@ -159,6 +159,7 @@ import { type SearchFieldMeta, } from '@objectstack/spec/data'; import { objectsAsServed, recordsOf, suggestName } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; import { SYSTEM_FIELDS, indexUnprovisionedAnchors, @@ -185,6 +186,13 @@ export interface SearchableFieldFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user sentence interpolates + * (`validate-searchable-fields.user-text.ts`): set on + * `searchable-field-unprovisioned`, the advisory the publish door returns. + * The errors carry none. + */ + userTextParams?: UserTextParams; } /** @@ -484,6 +492,7 @@ export function checkSearchableFieldList( rule: SEARCHABLE_FIELD_UNPROVISIONED, where, path: `${path}[${i}]`, + userTextParams: { object: objectName, field: name, role }, // [#22161] One verdict sentence: the shared short anchor clause and // the role's consequence. Why a narrowing reaches the runtime at all // (the `$searchFields` echo) is the id's `os explain` entry. diff --git a/packages/lint/src/validate-searchable-fields.user-text.ts b/packages/lint/src/validate-searchable-fields.user-text.ts new file mode 100644 index 00000000000..78eb8a6ccb6 --- /dev/null +++ b/packages/lint/src/validate-searchable-fields.user-text.ts @@ -0,0 +1,136 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-searchable-fields.ts`'s advisory, 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 an object, or a list view, in Studio, in + * their own language, once the save door composes + * `RuntimeAuthoringIssueSchema.userMessage` from it. So the sentence says what + * search does and the one change that fixes it, in the console's words + * (external object, searchable fields, list, search, fields, remote table); the + * developer-facing detail stays in the finding's `message`, `hint` and + * `os explain` entry. + * + * `searchable-field-unprovisioned` reaches the publish door on `object` and + * `view` writes (the reference-integrity suite member + * `validateSearchableFields`); the file's other ids are errors. + * + * The entry reads the `userTextParams` its finding carries, set at the push + * site in `checkSearchableFieldList` (so every caller of that core carries + * them, the page-component one in `validate-react-page-props.ts` included): + * + * | rule id | params | + * |---|---| + * | `searchable-field-unprovisioned` | `object` (the external object), `field` (the injected column), `role` (`canonical` · `narrowing`) | + * + * `role` is the rule's own split: the object's own `searchableFields` + * (`canonical`) against a list's narrowing of them (`narrowing`), whose + * `message` names a different consequence, so the sentence has one arm per + * value. Names are the API names the rule saw, not labels, for the reason + * `validate-security-posture.user-text.ts` gives. + * + * `finding-user-text.data-model.test.ts` renders the entry from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { SEARCHABLE_FIELD_UNPROVISIONED } from './validate-searchable-fields.js'; + +/** `role` of a finding on the object's own `searchableFields`. */ +const CANONICAL = 'canonical'; + +export const SEARCHABLE_FIELDS_USER_TEXT: UserTextCatalog = Object.freeze({ + [SEARCHABLE_FIELD_UNPROVISIONED]: { + en: (p) => + p.role === CANONICAL + ? `The searchable fields of external object "${p.object}" include "${p.field}", a column the platform adds ` + + `to the object without storing it, so search never matches it. If the remote table has "${p.field}", add ` + + `it to the fields of "${p.object}"; otherwise remove it from the searchable fields.` + : `A list of external object "${p.object}" searches "${p.field}", a column the platform adds to the object ` + + `without storing it, so the list's search finds nothing there. If the remote table has "${p.field}", add ` + + `it to the fields of "${p.object}"; otherwise remove it from the list's search fields.`, + 'zh-Hans': (p) => + p.role === CANONICAL + ? `外部对象“${p.object}”的可搜索字段包含“${p.field}”,这是平台为该对象添加但并不存储的列,因此搜索永远` + + `不会匹配到它。如果远程表中有“${p.field}”,请将其添加到“${p.object}”的字段中;否则请将其从可搜索字段中删除。` + : `外部对象“${p.object}”的列表会搜索“${p.field}”,这是平台为该对象添加但并不存储的列,因此列表搜索在其中` + + `找不到任何内容。如果远程表中有“${p.field}”,请将其添加到“${p.object}”的字段中;否则请将其从列表的搜索字段中删除。`, + 'zh-Hant': (p) => + p.role === CANONICAL + ? `外部物件「${p.object}」的可搜尋欄位包含「${p.field}」,這是平台為該物件新增但並不儲存的欄位,因此搜尋永遠` + + `不會比對到它。如果遠端資料表中有「${p.field}」,請將其加入「${p.object}」的欄位;否則請將其從可搜尋欄位中刪除。` + : `外部物件「${p.object}」的清單會搜尋「${p.field}」,這是平台為該物件新增但並不儲存的欄位,因此清單搜尋在其中` + + `找不到任何內容。如果遠端資料表中有「${p.field}」,請將其加入「${p.object}」的欄位;否則請將其從清單的搜尋欄位中刪除。`, + es: (p) => + p.role === CANONICAL + ? `Los campos de búsqueda del objeto externo "${p.object}" incluyen "${p.field}", una columna que la ` + + `plataforma añade al objeto sin almacenarla, así que la búsqueda nunca la encuentra. Si la tabla remota ` + + `tiene "${p.field}", agréguela a los campos de "${p.object}"; de lo contrario, quítela de los campos de búsqueda.` + : `Una lista del objeto externo "${p.object}" busca en "${p.field}", una columna que la plataforma añade al ` + + `objeto sin almacenarla, así que la búsqueda de la lista no encuentra nada ahí. Si la tabla remota tiene ` + + `"${p.field}", agréguela a los campos de "${p.object}"; de lo contrario, quítela de los campos de búsqueda ` + + `de la lista.`, + ar: (p) => + p.role === CANONICAL + ? `تتضمن حقول البحث للكائن الخارجي "${p.object}" الحقل "${p.field}"، وهو عمود تضيفه المنصة إلى الكائن دون ` + + `تخزينه، لذا لا يطابقه البحث أبدًا. إذا كان الجدول البعيد يحتوي على "${p.field}"، فأضفه إلى حقول ` + + `"${p.object}"؛ وإلا فأزله من حقول البحث.` + : `تبحث قائمة للكائن الخارجي "${p.object}" في "${p.field}"، وهو عمود تضيفه المنصة إلى الكائن دون تخزينه، ` + + `لذا لا يجد بحث القائمة فيه شيئًا. إذا كان الجدول البعيد يحتوي على "${p.field}"، فأضفه إلى حقول ` + + `"${p.object}"؛ وإلا فأزله من حقول البحث في القائمة.`, + fr: (p) => + p.role === CANONICAL + ? `Les champs de recherche de l’objet externe « ${p.object} » incluent « ${p.field} », une colonne que la ` + + `plateforme ajoute à l’objet sans la stocker : la recherche ne la trouve jamais. Si la table distante ` + + `contient « ${p.field} », ajoutez-la aux champs de « ${p.object} » ; sinon, retirez-la des champs de recherche.` + : `Une liste de l’objet externe « ${p.object} » recherche dans « ${p.field} », une colonne que la plateforme ` + + `ajoute à l’objet sans la stocker : la recherche de la liste n’y trouve rien. Si la table distante contient ` + + `« ${p.field} », ajoutez-la aux champs de « ${p.object} » ; sinon, retirez-la des champs de recherche de la liste.`, + 'pt-BR': (p) => + p.role === CANONICAL + ? `Os campos de pesquisa do objeto externo "${p.object}" incluem "${p.field}", uma coluna que a plataforma ` + + `adiciona ao objeto sem armazená-la, então a pesquisa nunca a encontra. Se a tabela remota tiver ` + + `"${p.field}", adicione-a aos campos de "${p.object}"; caso contrário, remova-a dos campos de pesquisa.` + : `Uma lista do objeto externo "${p.object}" pesquisa em "${p.field}", uma coluna que a plataforma adiciona ` + + `ao objeto sem armazená-la, então a pesquisa da lista não encontra nada ali. Se a tabela remota tiver ` + + `"${p.field}", adicione-a aos campos de "${p.object}"; caso contrário, remova-a dos campos de pesquisa da lista.`, + ru: (p) => + p.role === CANONICAL + ? `Поля поиска внешнего объекта «${p.object}» включают «${p.field}» — столбец, который платформа добавляет к ` + + `объекту, но не хранит, поэтому поиск никогда его не находит. Если в удалённой таблице есть «${p.field}», ` + + `добавьте его в поля «${p.object}»; иначе уберите его из полей поиска.` + : `Список внешнего объекта «${p.object}» ищет по «${p.field}» — столбцу, который платформа добавляет к ` + + `объекту, но не хранит, поэтому поиск в списке ничего в нём не находит. Если в удалённой таблице есть ` + + `«${p.field}», добавьте его в поля «${p.object}»; иначе уберите его из полей поиска списка.`, + de: (p) => + p.role === CANONICAL + ? `Die Suchfelder des externen Objekts „${p.object}“ enthalten „${p.field}“, eine Spalte, die die Plattform ` + + `dem Objekt hinzufügt, ohne sie zu speichern. Die Suche findet darin daher nie etwas. Wenn die entfernte ` + + `Tabelle „${p.field}“ enthält, fügen Sie die Spalte den Feldern von „${p.object}“ hinzu; andernfalls ` + + `entfernen Sie sie aus den Suchfeldern.` + : `Eine Liste des externen Objekts „${p.object}“ durchsucht „${p.field}“, eine Spalte, die die Plattform dem ` + + `Objekt hinzufügt, ohne sie zu speichern. Die Suche der Liste findet darin daher nichts. Wenn die entfernte ` + + `Tabelle „${p.field}“ enthält, fügen Sie die Spalte den Feldern von „${p.object}“ hinzu; andernfalls ` + + `entfernen Sie sie aus den Suchfeldern der Liste.`, + ja: (p) => + p.role === CANONICAL + ? `外部オブジェクト「${p.object}」の検索対象フィールドに「${p.field}」が含まれていますが、これはプラットフォームが` + + `オブジェクトに追加するだけで保存しない列のため、検索で一致することはありません。リモートテーブルに` + + `「${p.field}」がある場合は「${p.object}」のフィールドに追加し、ない場合は検索対象フィールドから削除してください。` + : `外部オブジェクト「${p.object}」のリストは「${p.field}」を検索しますが、これはプラットフォームがオブジェクトに` + + `追加するだけで保存しない列のため、リストの検索ではそこから何も見つかりません。リモートテーブルに` + + `「${p.field}」がある場合は「${p.object}」のフィールドに追加し、ない場合はリストの検索フィールドから削除してください。`, + ko: (p) => + p.role === CANONICAL + ? `외부 개체 "${p.object}"의 검색 필드에 "${p.field}"이(가) 포함되어 있는데, 이는 플랫폼이 개체에 추가하지만 ` + + `저장하지 않는 열이므로 검색에서 일치하는 항목이 없습니다. 원격 테이블에 "${p.field}"이(가) 있으면 ` + + `"${p.object}"의 필드에 추가하고, 없으면 검색 필드에서 제거하세요.` + : `외부 개체 "${p.object}"의 목록은 "${p.field}"을(를) 검색하는데, 이는 플랫폼이 개체에 추가하지만 저장하지 ` + + `않는 열이므로 목록 검색에서 아무것도 찾지 못합니다. 원격 테이블에 "${p.field}"이(가) 있으면 ` + + `"${p.object}"의 필드에 추가하고, 없으면 목록의 검색 필드에서 제거하세요.`, + }, +}); diff --git a/packages/lint/src/validate-sortable-fields.ts b/packages/lint/src/validate-sortable-fields.ts index 85b88bd84cc..8fe103790ea 100644 --- a/packages/lint/src/validate-sortable-fields.ts +++ b/packages/lint/src/validate-sortable-fields.ts @@ -294,6 +294,7 @@ import { import { walkPageComponents } from './page-walk.js'; import { LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, columnSummaryRefusal } from './validate-list-view-field-refs.js'; import { PAGE_FIELD_UNKNOWN, PAGE_FIELD_UNPROVISIONED } from './validate-page-field-bindings.js'; +import type { UserTextParams } from './finding-user-text.js'; import { SYSTEM_FIELDS, indexUnprovisionedAnchors, @@ -340,6 +341,14 @@ export interface SortableFieldFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user sentence interpolates + * (`validate-sortable-fields.user-text.ts`): set on `sort-field-unprovisioned`, + * the list-view advisory the publish door returns. The errors carry none, and + * so does the page-sort `page-field-unprovisioned` warning: that id's + * sentences belong to `validate-page-field-bindings.ts`, its owner. + */ + userTextParams?: UserTextParams; } type AnyRec = Record; @@ -487,6 +496,7 @@ export function checkSortDeclaration( rule: SORT_FIELD_UNPROVISIONED, where, path: `${path}${key.at}`, + userTextParams: { object: objectName, field: name }, // [#22161] One verdict sentence: the shared short anchor clause and // this axis' consequence. The measured byte-identical reading and why // no door refuses it are the id's `os explain` entry. diff --git a/packages/lint/src/validate-sortable-fields.user-text.ts b/packages/lint/src/validate-sortable-fields.user-text.ts new file mode 100644 index 00000000000..7b0faabe112 --- /dev/null +++ b/packages/lint/src/validate-sortable-fields.user-text.ts @@ -0,0 +1,94 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-sortable-fields.ts`'s list-view + * advisory, 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 an object's list view, or a standalone + * list view, in Studio, in their own language, once the save door composes + * `RuntimeAuthoringIssueSchema.userMessage` from it. So the sentence says what + * the list shows and the one change that fixes it, in the console's words + * (list view, external object, sort, fields, remote table); the developer-facing + * detail stays in the finding's `message`, `hint` and `os explain` entry. + * + * `sort-field-unprovisioned` reaches the publish door on `object` and `view` + * writes (the reference-integrity suite member `validateSortableFields`). Every + * other id this file emits is an `error`, except the page-sort warning + * `page-field-unprovisioned`: that id's constant, its other push site and its + * sentences belong to `validate-page-field-bindings.ts`, so its catalog is that + * file's (a rule id has one owner), and the page-sort push site here carries + * no params until that catalog sets them. + * + * The entry reads the `userTextParams` its finding carries, set at the push + * site in `checkSortDeclaration`: + * + * | rule id | params | + * |---|---| + * | `sort-field-unprovisioned` | `object` (the external object), `field` (the injected column the sort names) | + * + * Names are the API names the rule saw, not labels, for the reason + * `validate-security-posture.user-text.ts` gives. + * + * `finding-user-text.data-model.test.ts` renders the entry from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { SORT_FIELD_UNPROVISIONED } from './validate-sortable-fields.js'; + +export const SORTABLE_FIELDS_USER_TEXT: UserTextCatalog = Object.freeze({ + [SORT_FIELD_UNPROVISIONED]: { + en: (p) => + `A list view of external object "${p.object}" sorts by "${p.field}", a column the platform adds to the ` + + `object without storing it, so the sort is ignored and records come back in no particular order. If the ` + + `remote table has "${p.field}", add it to the fields of "${p.object}"; otherwise sort by another field.`, + 'zh-Hans': (p) => + `外部对象“${p.object}”的列表视图按“${p.field}”排序,这是平台为该对象添加但并不存储的列,因此该排序会被忽略,` + + `记录以任意顺序返回。如果远程表中有“${p.field}”,请将其添加到“${p.object}”的字段中;否则请改用其他字段排序。`, + 'zh-Hant': (p) => + `外部物件「${p.object}」的列表檢視依「${p.field}」排序,這是平台為該物件新增但並不儲存的欄位,因此該排序會被` + + `忽略,記錄以任意順序傳回。如果遠端資料表中有「${p.field}」,請將其加入「${p.object}」的欄位;否則請改用其他` + + `欄位排序。`, + es: (p) => + `Una vista de lista del objeto externo "${p.object}" ordena por "${p.field}", una columna que la plataforma ` + + `añade al objeto sin almacenarla, así que el orden se ignora y los registros llegan sin un orden concreto. Si ` + + `la tabla remota tiene "${p.field}", agréguela a los campos de "${p.object}"; de lo contrario, ordene por ` + + `otro campo.`, + ar: (p) => + `يرتّب عرض قائمة للكائن الخارجي "${p.object}" حسب "${p.field}"، وهو عمود تضيفه المنصة إلى الكائن دون ` + + `تخزينه، لذا يُتجاهل الترتيب وتُعاد السجلات بترتيب عشوائي. إذا كان الجدول البعيد يحتوي على "${p.field}"، ` + + `فأضفه إلى حقول "${p.object}"؛ وإلا فرتّب حسب حقل آخر.`, + fr: (p) => + `Une vue de liste de l’objet externe « ${p.object} » trie par « ${p.field} », une colonne que la plateforme ` + + `ajoute à l’objet sans la stocker : le tri est ignoré et les enregistrements arrivent dans un ordre ` + + `quelconque. Si la table distante contient « ${p.field} », ajoutez-la aux champs de « ${p.object} » ; sinon, ` + + `triez par un autre champ.`, + 'pt-BR': (p) => + `Uma visualização de lista do objeto externo "${p.object}" ordena por "${p.field}", uma coluna que a ` + + `plataforma adiciona ao objeto sem armazená-la, então a ordenação é ignorada e os registros vêm em ordem ` + + `aleatória. Se a tabela remota tiver "${p.field}", adicione-a aos campos de "${p.object}"; caso contrário, ` + + `ordene por outro campo.`, + ru: (p) => + `Представление списка внешнего объекта «${p.object}» сортирует по «${p.field}» — столбцу, который платформа ` + + `добавляет к объекту, но не хранит, поэтому сортировка игнорируется и записи приходят в произвольном ` + + `порядке. Если в удалённой таблице есть «${p.field}», добавьте его в поля «${p.object}»; иначе сортируйте ` + + `по другому полю.`, + de: (p) => + `Eine Listenansicht des externen Objekts „${p.object}“ sortiert nach „${p.field}“, einer Spalte, die die ` + + `Plattform dem Objekt hinzufügt, ohne sie zu speichern. Die Sortierung wird daher ignoriert, und die ` + + `Datensätze kommen in beliebiger Reihenfolge. Wenn die entfernte Tabelle „${p.field}“ enthält, fügen Sie die ` + + `Spalte den Feldern von „${p.object}“ hinzu; andernfalls sortieren Sie nach einem anderen Feld.`, + ja: (p) => + `外部オブジェクト「${p.object}」のリストビューは「${p.field}」で並べ替えますが、これはプラットフォームが` + + `オブジェクトに追加するだけで保存しない列のため、並べ替えは無視され、レコードは順不同で返されます。` + + `リモートテーブルに「${p.field}」がある場合は「${p.object}」のフィールドに追加し、ない場合は別のフィールドで` + + `並べ替えてください。`, + ko: (p) => + `외부 개체 "${p.object}"의 목록 보기는 "${p.field}"(으)로 정렬하는데, 이는 플랫폼이 개체에 추가하지만 ` + + `저장하지 않는 열이므로 정렬이 무시되고 레코드가 임의의 순서로 반환됩니다. 원격 테이블에 ` + + `"${p.field}"이(가) 있으면 "${p.object}"의 필드에 추가하고, 없으면 다른 필드로 정렬하세요.`, + }, +});