Skip to content

Commit 82de298

Browse files
committed
wip(lint): field-name indexes read the objects as served
Claude-Session: https://claude.ai/code/session_01WGufzft7TrxiryiTZm4o9p Co-authored-by: Claude <noreply@anthropic.com>
1 parent a1d0b1e commit 82de298

7 files changed

Lines changed: 236 additions & 76 deletions

‎packages/lint/src/object-graph.test.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ import { RLS_PREDICATE_UNKNOWN_FIELD, validateRlsPredicateEnforceability } from
3434
import { SHARING_RULE_UNLOWERABLE_CONDITION, validateSharingRuleEnforceability } from './validate-sharing-rule-enforceability.js';
3535
import { THANK_YOU_RECORD_FIELD, validateThankYouRecordFields } from './validate-thank-you-record-fields.js';
3636
import { MEASURE_AGGREGATE_INCOHERENT, WIDGET_FILTER_FIELD_UNKNOWN, validateWidgetBindings } from './validate-widget-bindings.js';
37+
import { validateStackExpressions } from './validate-expressions.js';
38+
import { FLOW_NODE_WRITE_UNKNOWN_FIELD, validateFlowNodeWrites } from './validate-flow-node-writes.js';
39+
import { ACTION_BODY_WRITE_UNKNOWN_FIELD, validateActionBodyWrites } from './validate-action-body-writes.js';
40+
import { HOOK_BODY_WRITE_UNKNOWN_FIELD, validateHookBodyWrites } from './validate-hook-body-writes.js';
41+
import { validateReactPageProps } from './validate-react-page-props.js';
42+
import { TRANSLATION_TARGET_UNKNOWN, validateTranslationReferences } from './validate-translation-references.js';
3743
// [#16340] Read back the registry's OWN definition table to assert the graph
3844
// derives its injected types rather than carrying a second copy of them.
3945
import { injectedSystemColumnDefs } from '@objectstack/spec/data';
@@ -805,3 +811,136 @@ describe('[#30383] the field-path rules read the objects as served', () => {
805811
});
806812
});
807813
});
814+
815+
// [#30471] The field-NAME indexes outside the graph read the same fold: the
816+
// `record.FIELD` index of the expression passes (validations, formulas, flows,
817+
// hooks, sharing-rule conditions), the write rules' index (flow nodes, action
818+
// and hook bodies), a react page's field props and the translation universe.
819+
// The #30383 artifact, plus one extension rule for the translation rung.
820+
describe('[#30471] the field-name indexes read the objects as served', () => {
821+
type Rec = Record<string, unknown>;
822+
type Finding = { rule: string; severity?: unknown; where?: unknown; path?: unknown; message?: unknown };
823+
type Run = (stack: Rec) => ReadonlyArray<Finding>;
824+
const deal = { name: 'xs_deal', label: 'Deal', fields: { name: { type: 'text' }, amount: { type: 'number' } } };
825+
const account = { name: 'xs_account', label: 'Account', fields: { name: { type: 'text' } } };
826+
const added = { region: { type: 'text' }, score: { type: 'number' } };
827+
const extensions = [{
828+
extend: 'xs_deal',
829+
fields: added,
830+
validations: [{ name: 'region_set', type: 'script', condition: 'record.region == null', message: 'Set a region' }],
831+
}];
832+
const artifact = (extra: Rec, objectExtensions: unknown[] = extensions, objects: unknown[] = [deal, account]): Rec => ({
833+
objects,
834+
packages: [
835+
{ manifest: { id: 'app', objects } },
836+
{ manifest: { id: 'mod', objectExtensions } },
837+
],
838+
...extra,
839+
});
840+
// The per-package leg of `os build` (`packageBodyAsStack` in the cli).
841+
const perPackage = (extra: Rec, objectExtensions: unknown[] = extensions): Rec => {
842+
const body = { id: 'app', objects: [deal, account], ...extra };
843+
return { ...body, manifest: body, packages: [{ manifest: body }, { manifest: { id: 'mod', objectExtensions } }] };
844+
};
845+
const ids = (run: Run, stack: Rec) => run(stack).map((f) => f.rule);
846+
// The expression passes carry no rule id: every issue they raise on these
847+
// stacks is about the one expression each names, read as `expression`.
848+
const expressions: Run = (stack) => validateStackExpressions(stack).map((issue) => ({ ...issue, rule: 'expression' }));
849+
const validationOn = (condition: string): Rec => ({
850+
objects: [{ ...deal, validations: [{ name: 'v', type: 'script', condition, message: 'M' }] }, account],
851+
});
852+
853+
// rule · its unknown-field id · the stack naming FIELD
854+
const existence: Array<[string, string, Run, (field: string) => Rec]> = [
855+
['validate-expressions (a validation condition)', 'expression', expressions, (f) => validationOn(`record.${f} == 'x'`)],
856+
['validate-expressions (a sharing-rule condition)', 'expression', expressions, (f) => ({
857+
sharingRules: [{ name: 'sr', object: 'xs_deal', condition: `record.${f} == 'x'`, sharedWith: { type: 'role', value: 'r' }, accessLevel: 'read' }],
858+
})],
859+
['validate-flow-node-writes', FLOW_NODE_WRITE_UNKNOWN_FIELD, validateFlowNodeWrites, (f) => ({
860+
flows: [{ name: 'fl', nodes: [{ id: 'n', type: 'update_record', config: { objectName: 'xs_deal', fields: { [f]: 'x' } } }] }],
861+
})],
862+
['validate-action-body-writes', ACTION_BODY_WRITE_UNKNOWN_FIELD, validateActionBodyWrites, (f) => ({
863+
actions: [{ name: 'act', label: 'Act', body: { language: 'js', source: `await ctx.api.object('xs_deal').updateById(id, { ${f}: 'x' });` } }],
864+
})],
865+
['validate-hook-body-writes', HOOK_BODY_WRITE_UNKNOWN_FIELD, (stack) => validateHookBodyWrites(stack), (f) => ({
866+
hooks: [{ name: 'h', object: 'xs_deal', events: ['beforeInsert'], body: { language: 'js', source: `ctx.input.${f} = 'x';` } }],
867+
})],
868+
['validate-react-page-props', PAGE_FIELD_UNKNOWN, validateReactPageProps, (f) => ({
869+
pages: [{
870+
name: 'p', kind: 'react',
871+
source: `function Page(){ return <ListView data={{ provider: 'object', object: 'xs_deal' }} columns={['name', '${f}']} />; }`,
872+
}],
873+
})],
874+
['validate-translation-references', TRANSLATION_TARGET_UNKNOWN, validateTranslationReferences, (f) => ({
875+
translations: [{ 'zh-CN': { objects: { xs_deal: { fields: { [f]: { label: 'L' } } } } } }],
876+
})],
877+
];
878+
879+
it.each(existence)('%s: an extension-added field passes; a field nothing adds is still refused', (_rule, id, run, naming) => {
880+
expect(ids(run, artifact(naming('region')))).not.toContain(id);
881+
expect(ids(run, artifact(naming('region'), []))).toContain(id);
882+
expect(ids(run, artifact(naming('nowhere')))).toContain(id);
883+
});
884+
885+
it.each(existence)('%s, on the per-package leg: the same verdicts', (_rule, id, run, naming) => {
886+
expect(ids(run, perPackage(naming('region')))).not.toContain(id);
887+
expect(ids(run, perPackage(naming('region'), []))).toContain(id);
888+
expect(ids(run, perPackage(naming('nowhere')))).toContain(id);
889+
});
890+
891+
it.each(existence)('%s: a field nothing adds is refused byte-for-byte as on the declared objects alone', (_rule, id, run, naming) => {
892+
const refusal = (stack: Rec) => run(stack)
893+
.filter((f) => f.rule === id)
894+
.map(({ severity, where, path, message }) => ({ severity, where, path, message }));
895+
const served = refusal(artifact(naming('zq_absent')));
896+
expect(served).toHaveLength(1);
897+
expect(served).toEqual(refusal(artifact(naming('zq_absent'), [])));
898+
});
899+
900+
it('validate-translation-references: a `_validations` key for a rule an extension adds resolves', () => {
901+
const bundle = (rule: string) => ({ translations: [{ 'zh-CN': { objects: { xs_deal: { _validations: { [rule]: { message: 'M' } } } } } }] });
902+
expect(ids(validateTranslationReferences, artifact(bundle('region_set')))).toEqual([]);
903+
expect(ids(validateTranslationReferences, artifact(bundle('region_set'), []))).toEqual([TRANSLATION_TARGET_UNKNOWN]);
904+
expect(ids(validateTranslationReferences, artifact(bundle('nowhere')))).toEqual([TRANSLATION_TARGET_UNKNOWN]);
905+
});
906+
907+
// The retired private reader kept every entry; the fold keeps one per
908+
// package per target, so a later entry of the same package replaces an
909+
// earlier one whole, its rules with its fields.
910+
it('validate-translation-references: a key only a replaced entry adds is an orphan, as the registry serves it', () => {
911+
const replaced = [...extensions, { extend: 'xs_deal', fields: { mood: { type: 'text' } } }];
912+
const keys = (fields: Rec, rules: Rec = {}) => ({ translations: [{ 'zh-CN': { objects: { xs_deal: { fields, _validations: rules } } } }] });
913+
expect(ids(validateTranslationReferences, artifact(keys({ mood: { label: 'M' } }), replaced))).toEqual([]);
914+
expect(ids(validateTranslationReferences, artifact(keys({ region: { label: 'R' } }), replaced))).toEqual([TRANSLATION_TARGET_UNKNOWN]);
915+
expect(ids(validateTranslationReferences, artifact(keys({}, { region_set: { message: 'M' } }), replaced))).toEqual([TRANSLATION_TARGET_UNKNOWN]);
916+
});
917+
918+
// The write rules leave an object that declares no field unjudged (an
919+
// external, introspected schema): an extension adding to it does not make
920+
// its other fields knowable.
921+
it('the write rules keep an object that declares no field unjudged, extended or not', () => {
922+
const bare = { name: 'xs_deal', label: 'Deal', fields: {} };
923+
const write = { flows: [{ name: 'fl', nodes: [{ id: 'n', type: 'update_record', config: { objectName: 'xs_deal', fields: { remote_col: 'x' } } }] }] };
924+
expect(ids(validateFlowNodeWrites, artifact(write, extensions, [bare, account]))).toEqual([]);
925+
expect(ids(validateFlowNodeWrites, artifact(write, [], [bare, account]))).toEqual([]);
926+
});
927+
928+
// A field two packages write at the deciding priority: its name is served,
929+
// its definition is registration order. The expression type check leaves it
930+
// untyped; each pair lists last the definition the check would refuse.
931+
it('validate-expressions: a field two packages tie on is a served name with no type', () => {
932+
const tie = (a: Rec, b: Rec, extra: Rec): Rec => ({
933+
objects: [deal, account],
934+
packages: [
935+
{ manifest: { id: 'app', objects: [deal, account] } },
936+
{ manifest: { id: 'mod', objectExtensions: [{ extend: 'xs_deal', fields: a }] } },
937+
{ manifest: { id: 'mod2', objectExtensions: [{ extend: 'xs_deal', fields: b }] } },
938+
],
939+
...extra,
940+
});
941+
const sum = validationOn('record.score + 1 > 2');
942+
expect(ids(expressions, tie({ score: { type: 'number' } }, { score: { type: 'text' } }, sum))).toEqual([]);
943+
expect(ids(expressions, tie({ score: { type: 'text' } }, {}, sum))).toEqual(['expression']);
944+
expect(ids(expressions, tie({ score: { type: 'number' } }, {}, sum))).toEqual([]);
945+
});
946+
});

‎packages/lint/src/object-graph.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,14 @@ export interface VisibleObjectExtension {
378378
priority: number;
379379
/** Its field records, name folded in ({@link recordsOf}). */
380380
fields: AnyRec[];
381+
/**
382+
* [#30471] Its validation rule records ({@link recordsOf}), carried for the
383+
* one reader that addresses an object's rules by name
384+
* (`validate-translation-references.ts`, `_validations.RULE`). Carrying them
385+
* changes nothing about which entries survive: a replaced entry's rules go
386+
* with it, as its fields do.
387+
*/
388+
validations: AnyRec[];
381389
}
382390

383391
/**
@@ -430,6 +438,7 @@ export function objectExtensionsByTarget(stack: unknown): Map<string, VisibleObj
430438
path: `${at}objectExtensions[${i}]`,
431439
priority: typeof ext.priority === 'number' ? ext.priority : 200,
432440
fields: recordsOf(ext.fields),
441+
validations: recordsOf(ext.validations),
433442
});
434443
byTarget.set(ext.extend, kept);
435444
});

‎packages/lint/src/validate-expressions.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ import type { FlowCelEntrance } from './flow-cel-root-scope.js';
153153
import { injectedColumnDefsFor, injectedColumnsFor, unprovisionedInjectedColumnsFor } from './system-fields.js';
154154
import { findUnguardedNullableOperands, nullGuardMessage, provenNonNullKeys } from './validate-null-guards.js';
155155
import type { NullGuardOptions, NullGuardOutcome } from './validate-null-guards.js';
156-
import { recordsOf } from './object-graph.js';
156+
import { objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js';
157157
export interface ExprIssue {
158158
where: string;
159159
message: string;
@@ -198,6 +198,9 @@ type AnyRec = Record<string, unknown>;
198198
* `owner_id`, so `record.owner_id` there stays the error it should be. A blanket
199199
* union would have traded a false positive for a false negative and called it
200200
* fixed.
201+
*
202+
* [#30471] Built over the objects as served ({@link objectsAsServed}), so the
203+
* authored half includes every field an `objectExtensions` entry adds.
201204
*/
202205
function buildFieldIndex(objects: AnyRec[]): Map<string, string[]> {
203206
const idx = new Map<string, string[]>();
@@ -2228,10 +2231,23 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
22282231
return actionCopyTemplateIssues(stack, { actions: false, objects: false, pages: true });
22292232
}
22302233
const objects = recordsOf(stack.objects);
2231-
const fieldIndex = buildFieldIndex(objects);
2234+
// [#30471] The field indexes read the objects as the registry SERVES them,
2235+
// every `objectExtensions` field of any body folded in (`objectsAsServed`,
2236+
// the package's one fold): a `record.FIELD` read of a field a sibling
2237+
// package adds resolves as it does at runtime, and a field no body declares
2238+
// or extends is still unknown. The walk below stays on the declared
2239+
// `objects`, so every finding keeps its declared path. The two indexes that
2240+
// judge a field's DEFINITION (its type, whether it is nullable) leave out a
2241+
// field two packages tie on (`objectsWithoutTiedFields`): which definition
2242+
// the registry serves is registration order, which the stack does not state,
2243+
// so such a field is a known name with no type and no null-guard verdict.
2244+
// The read-attachment index is object-level and an extension carries none.
2245+
const served = objectsAsServed(stack);
2246+
const typedObjects = objectsWithoutTiedFields(served);
2247+
const fieldIndex = buildFieldIndex(served.objects);
22322248
const attachedOnReadIndex = buildAttachedOnReadIndex(objects);
2233-
const fieldTypeIndex = buildFieldTypeIndex(objects);
2234-
const nullableIndex = buildNullableFieldIndex(objects);
2249+
const fieldTypeIndex = buildFieldTypeIndex(typedObjects);
2250+
const nullableIndex = buildNullableFieldIndex(typedObjects);
22352251
// [#24316] object name → its references into a stored-metadata-body table,
22362252
// read the first time a site of that object serves a hop, or (#24677) when
22372253
// the walk reaches the object's fields, whichever comes first — never before
@@ -3450,7 +3466,10 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
34503466
// The type is read from the field-type index, never off the field again:
34513467
// the #5017 receiver meta-test pins the keys this walk reads off `f`. The
34523468
// collector admits only a field whose `type` is a string, and the index
3453-
// records every such field, so each collected field has its type here.
3469+
// records every such field, so each collected field has its type here,
3470+
// save one two packages tie on (#30471): the index leaves its definition
3471+
// out, so it is skipped rather than judged on a definition the registry
3472+
// may not serve.
34543473
if (objectName) {
34553474
const familyRefs = storedMetadataBodyReferencesFor(objectName);
34563475
const ownFieldTypes = fieldTypeIndex.get(objectName);

‎packages/lint/src/validate-hook-body-writes.ts‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ import {
103103
unprovisionedAnchorFix,
104104
unprovisionedAnchorVerdict,
105105
} from './system-fields.js';
106-
import { recordsOf } from './object-graph.js';
106+
import { objectsAsServed, recordsOf } from './object-graph.js';
107107

108108
// The TypeScript compiler must NOT be imported at module top level: it is
109109
// ~9 MB of CJS, and @objectstack/lint sits on the kernel boot path — while
@@ -497,22 +497,43 @@ export function hookBodyFindingLocation(
497497
}
498498

499499
/**
500-
* object name → its declared field names (both `fields` authoring shapes).
500+
* object name → its field names as the registry SERVES the object (both
501+
* `fields` authoring shapes).
501502
*
502-
* Exported for `validate-action-body-writes.ts` only (see
503-
* {@link IMPLICIT_FIELDS} for why the two rules share rather than copy).
503+
* Exported for `validate-action-body-writes.ts` and
504+
* `validate-flow-node-writes.ts` (see {@link IMPLICIT_FIELDS} for why the
505+
* rules share rather than copy).
506+
*
507+
* [#30471] Read through the package's one extension fold
508+
* ({@link objectsAsServed}): a write naming a field a sibling package adds
509+
* through `objectExtensions` lands, as it does at runtime, and a field no body
510+
* declares or extends is still unknown. A tied field is a served name, so it
511+
* is kept: these rules ask whether the name exists, never its definition.
512+
* Whether the column is WRITABLE (`readonly`) is the readonly rules' question,
513+
* not this index's.
514+
*
515+
* Judgeability stays the declaration's ({@link judgeableFieldsOf}): an object
516+
* that declares no field at all (external, datasource-introspected) keeps an
517+
* empty set even when an extension adds to it, because the fields it does
518+
* serve are still unknown here.
504519
*/
505520
export function indexObjectFields(stack: AnyRec): Map<string, Set<string>> {
506521
const out = new Map<string, Set<string>>();
507-
for (const obj of recordsOf(stack.objects)) {
508-
const name = typeof obj.name === 'string' ? obj.name : undefined;
509-
if (!name) continue;
522+
const namesOf = (obj: AnyRec | undefined): Set<string> => {
510523
const names = new Set<string>();
511-
for (const f of recordsOf(obj.fields)) {
524+
for (const f of recordsOf(obj?.fields)) {
512525
if (typeof f.name === 'string' && f.name) names.add(f.name);
513526
}
514-
out.set(name, names);
515-
}
527+
return names;
528+
};
529+
const declared = recordsOf(stack.objects);
530+
// `objectsAsServed` returns the declared objects in order, one per entry.
531+
objectsAsServed(stack).objects.forEach((obj, i) => {
532+
const name = typeof obj.name === 'string' ? obj.name : undefined;
533+
if (!name) return;
534+
const own = namesOf(declared[i]);
535+
out.set(name, own.size > 0 ? namesOf(obj) : own);
536+
});
516537
return out;
517538
}
518539

‎packages/lint/src/validate-react-page-props.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ import {
6969
// #5020's zod-rejection renderer, shared with the SDUI component-props gate
7070
// since #5068 — see `zod-issue-format.ts` for why one copy matters here.
7171
import { describeIssue, type LintZodIssue } from './zod-issue-format.js';
72+
import { objectsAsServed } from './object-graph.js';
7273
import { createSourceFileChecked, describeParseFailure, PARSE_FAILURE_FIX } from './checked-parse.js';
7374
// [#22161] The verdict half of a forwarded `@objectstack/spec` refusal — one
7475
// cut for every rule that forwards the same producer's words.
@@ -1136,7 +1137,11 @@ function localComponentNames(tsc: typeof ts, sf: ts.SourceFile): Set<string> {
11361137

11371138
export function validateReactPageProps(stack: AnyRec): ReactPropFinding[] {
11381139
const findings: ReactPropFinding[] = [];
1139-
const objectFields = indexObjectFields(stack);
1140+
// [#30471] Over the objects as served, every `objectExtensions` field
1141+
// folded in, as `validatePageFieldBindings` reads them: a prop naming a
1142+
// field a sibling package adds is served, and one no body declares or
1143+
// extends is still unknown.
1144+
const objectFields = indexObjectFields({ objects: objectsAsServed(stack).objects });
11401145
// [#8340] The provenance index alongside the existence one — same keying,
11411146
// asked on the path where the existence check stays silent.
11421147
const unprovisionedAnchors = indexUnprovisionedAnchors(stack);

‎packages/lint/src/validate-security-posture.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1910,7 +1910,7 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s
19101910
},
19111911
{
19121912
receiver: 'ext',
1913-
expected: ['extend', 'fields', 'priority'],
1913+
expected: ['extend', 'fields', 'priority', 'validations'],
19141914
declaredBy: 'ObjectStackSchema.objectExtensions[]',
19151915
keys: () => shapeKeysOf(ObjectStackSchema.shape.objectExtensions),
19161916
},

0 commit comments

Comments
 (0)