Skip to content

Commit bdd897e

Browse files
committed
feat(spec)!: key an object extension's fields by the field map's own key grammar
ObjectExtensionSchema.fields was keyed by a bare string, so an extension could add a field under a key (`Region Code`, `region-code`) the target's own field map refuses. It now reads FieldNameKeySchema, with an invalid_key prescription at fields.KEY, an ADR-0087 semantic entry, and a REFUSED_STORED_SHAPES detector that lists such a stored row. Claude-Session: https://claude.ai/code/session_01WGufzf5kvTFdbWYDbe8bHE Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 1c1a5d4 commit bdd897e

6 files changed

Lines changed: 262 additions & 13 deletions

File tree

‎content/docs/data-modeling/object-extensions.mdx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,11 @@ reason.
160160

161161
## Naming the fields you add
162162

163+
Each key of an extension's `fields` is a field name of the target, so it follows the
164+
grammar of the target's own `fields` keys: lowercase snake_case, such as `region_code`
165+
(`region_code__c` in a `.custom` package). A key outside it (`Region Code`,
166+
`region-code`, a label) is refused when the extension parses, at `fields.<key>`.
167+
163168
Field names in an extension are **not** namespace-prefixed by the platform. The
164169
namespace rule (`<namespace>_<name>`) governs the names of objects a package *defines*;
165170
it does not walk `objectExtensions`, and it could not — the target's name belongs to

‎packages/spec/src/conversions/refused-shapes.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ describe('the refused-shape list — registered against the migration chain', ()
7474
'object-duplicate-action-name-refused',
7575
'ui-dashboard-global-filter-duplicate-name-refused',
7676
'object-extension-field-patch-key-grammar-refused',
77+
'object-extension-field-key-grammar-refused',
7778
]);
7879
});
7980

@@ -909,3 +910,61 @@ describe('#29554 — a stored object extension whose fieldPatches key cannot be
909910
expect(patchKeyIssues(row)).toEqual([]);
910911
});
911912
});
913+
914+
// ── #29523 (the extension `fields` key grammar) ───────────────────────────
915+
916+
const fieldRow = (fields: Record<string, unknown>) => ({ extend: 'crm_account', fields });
917+
/** The `invalid_key` issues the extension parse locates at `fields.KEY`, as `[path, message]`. */
918+
const fieldKeyIssues = (row: unknown) => {
919+
const parsed = ObjectExtensionSchema.safeParse(row);
920+
return parsed.success
921+
? []
922+
: parsed.error.issues
923+
.filter((i) => i.code === 'invalid_key' && i.path[0] === 'fields')
924+
.map((i) => [i.path.join('.'), i.message]);
925+
};
926+
927+
describe('#29523 — a stored object extension whose fields key cannot be a field name is listed by extension', () => {
928+
it('one TODO per refused key, at fields.KEY, naming the target; the row is not rewritten', () => {
929+
const row = fieldRow({
930+
'Region Code': { type: 'text', label: 'Region' },
931+
'region-tier': { type: 'number', label: 'Tier' },
932+
region_owner: { type: 'text', label: 'Owner' },
933+
});
934+
const { item, todos } = storedTodos('object_extension', row);
935+
expect(item).toEqual(row);
936+
expect(todos.map((t) => [t.code, t.conversionId, t.path])).toEqual([
937+
[CONVERSION_TODO_CODE, 'object-extension-field-key-grammar-refused', 'objectExtensions[0].fields.Region Code'],
938+
[CONVERSION_TODO_CODE, 'object-extension-field-key-grammar-refused', 'objectExtensions[0].fields.region-tier'],
939+
]);
940+
const todo = todos[0]!;
941+
expect(todo.reason).toMatch(/^The extension of `crm_account` adds a field under `Region Code`\. No lossless rewrite:/);
942+
expect(todo.reason).not.toMatch(/#\d{3,}/);
943+
expect(JSON.parse(todo.from)).toEqual({ 'Region Code': { type: 'text' } });
944+
});
945+
946+
it('agrees with the refusing door: each listed key is one the extension parse refuses as a key, and no other', () => {
947+
const row = fieldRow({ RegionCode: { type: 'text', label: 'R' }, '2nd_phone': { type: 'phone', label: 'P' }, region: { type: 'text', label: 'R' } });
948+
const { todos } = storedTodos('object_extension', row);
949+
const issues = fieldKeyIssues(row);
950+
expect(issues.map(([path]) => path)).toEqual(['fields.RegionCode', 'fields.2nd_phone']);
951+
expect(todos.map((t) => t.path)).toEqual(issues.map(([path]) => `objectExtensions[0].${path}`));
952+
// The door's own message closes each reason, so the listing says what the parse says.
953+
todos.forEach((t, i) => expect(t.reason.endsWith(issues[i]![1]!)).toBe(true));
954+
});
955+
956+
it('snake_case keys, `__c` ones included, are not listed, and the parse accepts them', () => {
957+
const row = fieldRow({ region_code: { type: 'text', label: 'Region' }, region_code__c: { type: 'text', label: 'Region' } });
958+
expect(storedTodos('object_extension', row).todos).toEqual([]);
959+
expect(ObjectExtensionSchema.safeParse(row).success).toBe(true);
960+
});
961+
962+
it('each record is listed by its own detector: a refused fieldPatches key is not listed as a field, nor the reverse', () => {
963+
const row = { extend: 'crm_account', fields: { 'Region Code': { type: 'text', label: 'R' } }, fieldPatches: { Industry: { label: 'Sector' } } };
964+
const { todos } = storedTodos('object_extension', row);
965+
expect(todos.map((t) => [t.conversionId, t.path])).toEqual([
966+
['object-extension-field-patch-key-grammar-refused', 'objectExtensions[0].fieldPatches.Industry'],
967+
['object-extension-field-key-grammar-refused', 'objectExtensions[0].fields.Region Code'],
968+
]);
969+
});
970+
});

‎packages/spec/src/conversions/refused-shapes.ts‎

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,9 @@
4545
* ({@link externalBindingDatasourceRefusal}), and the one-name-per-action
4646
* judge of the object refinement ({@link duplicateActionNames}), and the
4747
* one-key-per-global-filter judge of the dashboard refinement
48-
* ({@link duplicateGlobalFilterNames}), and the `fieldPatches` key
49-
* grammar of `ObjectExtensionSchema`'s own parse
50-
* ({@link refusedFieldPatchKeys}). A site is listed here exactly
48+
* ({@link duplicateGlobalFilterNames}), and the `fieldPatches` and
49+
* `fields` key grammar of `ObjectExtensionSchema`'s own parse
50+
* ({@link refusedFieldPatchKeys}, {@link refusedExtensionFieldKeys}). A site is listed here exactly
5151
* when that door refuses it. One door lives outside this package: the
5252
* page/view `visibleWhen` rule in `@objectstack/lint` judges a `has()`
5353
* argument on the engine's AST, which this package cannot parse, so its
@@ -597,12 +597,25 @@ const dashboardDuplicateGlobalFilterName: RefusedStoredShape = {
597597
* a key is listed here exactly when that parse refuses it as a key.
598598
*/
599599
function refusedFieldPatchKeys(extension: Dict): Array<{ key: string; message: string }> {
600-
if (!isDict(extension.fieldPatches)) return [];
600+
return refusedExtensionRecordKeys(extension, 'fieldPatches');
601+
}
602+
603+
/**
604+
* The keys of one field-name-keyed record of an object extension (`fields` or
605+
* `fieldPatches`) that `ObjectExtensionSchema` refuses as no field name: each
606+
* `invalid_key` issue the extension's own parse locates at `SLOT.KEY`, with
607+
* that issue's message.
608+
*/
609+
function refusedExtensionRecordKeys(
610+
extension: Dict,
611+
slot: 'fields' | 'fieldPatches',
612+
): Array<{ key: string; message: string }> {
613+
if (!isDict(extension[slot])) return [];
601614
const parsed = ObjectExtensionSchema.safeParse(extension);
602615
if (parsed.success) return [];
603616
const refused: Array<{ key: string; message: string }> = [];
604617
for (const issue of parsed.error.issues) {
605-
if (issue.code !== 'invalid_key' || issue.path.length !== 2 || issue.path[0] !== 'fieldPatches') continue;
618+
if (issue.code !== 'invalid_key' || issue.path.length !== 2 || issue.path[0] !== slot) continue;
606619
const key = issue.path[1];
607620
if (typeof key === 'string') refused.push({ key, message: issue.message });
608621
}
@@ -634,6 +647,45 @@ const objectExtensionFieldPatchKeyGrammar: RefusedStoredShape = {
634647
},
635648
};
636649

650+
// ── #29523: an object extension whose `fields` key cannot be a field name ──
651+
652+
/**
653+
* The `fields` keys `ObjectExtensionSchema` refuses as no field name, read as
654+
* {@link refusedFieldPatchKeys} reads `fieldPatches`: the extension's own
655+
* parse, the one the save door and the sync that registers stored extensions
656+
* run, so a key is listed here exactly when that parse refuses it as a key.
657+
*/
658+
function refusedExtensionFieldKeys(extension: Dict): Array<{ key: string; message: string }> {
659+
return refusedExtensionRecordKeys(extension, 'fields');
660+
}
661+
662+
const objectExtensionFieldKeyGrammar: RefusedStoredShape = {
663+
id: 'object-extension-field-key-grammar-refused',
664+
toMajor: 18,
665+
surface: 'objectExtensions[].fields — a key outside the snake_case grammar of an object\'s `fields` keys',
666+
detect(stack, report) {
667+
mapCollection(stack, 'objectExtensions', (extension, path) => {
668+
const target = typeof extension.extend === 'string' ? `\`${extension.extend}\`` : 'its target';
669+
for (const { key, message } of refusedExtensionFieldKeys(extension)) {
670+
report({
671+
path: `${path}.fields.${key}`,
672+
// The key and the field's type only: the body is the author's, the key is what is refused.
673+
from: JSON.stringify({ [key]: { type: ((extension.fields as Dict)[key] as Dict | undefined)?.type } }),
674+
reason: `The extension of ${target} adds a field under \`${key}\`. `
675+
+ 'No lossless rewrite: the key is the name the field is stored and read under, and re-spelling it '
676+
+ '(lower-casing it, turning `-` or a space into `_`) names a different column than the one rows, '
677+
+ 'views and formulas may already read, or lands on a field the object already declares, so the '
678+
+ 'name is the author\'s to choose. Left as stored, the row no longer parses: the sync that registers '
679+
+ 'stored extensions names it (INVALID_METADATA) and registers none of it, its `fieldPatches` '
680+
+ 'included, and its next save is refused until the field is renamed. '
681+
+ message,
682+
});
683+
}
684+
return extension;
685+
});
686+
},
687+
};
688+
637689
/**
638690
* Every refused stored shape, in report order. A new entry is a reviewed edit:
639691
* `refused-shapes.test.ts` pins each one.
@@ -648,6 +700,7 @@ export const REFUSED_STORED_SHAPES: readonly RefusedStoredShape[] = [
648700
objectDuplicateActionName,
649701
dashboardDuplicateGlobalFilterName,
650702
objectExtensionFieldPatchKeyGrammar,
703+
objectExtensionFieldKeyGrammar,
651704
];
652705

653706
/**

‎packages/spec/src/data/field-customization.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,3 +411,67 @@ describe('`fieldPatches` keys — the field map\'s own key grammar', () => {
411411
}
412412
});
413413
});
414+
415+
/** Parse an extension whose `fields` is `fields`; return the issues. */
416+
function extensionFieldsIssues(fields: Record<string, unknown>): Issue[] {
417+
const r = ObjectExtensionSchema.safeParse({ extend: 'crm_account', fields });
418+
return r.success ? [] : (r.error.issues as unknown as Issue[]);
419+
}
420+
421+
describe('extension `fields` keys — the field map\'s own key grammar', () => {
422+
it.each([['Region Code'], ['RegionCode'], ['region-code'], ['2nd_phone'], ['Region Code__c']])(
423+
'refuses `%s`, which no field name can be: one `invalid_key` at its key, naming the grammar and an example',
424+
(key) => {
425+
const issues = extensionFieldsIssues({ [key]: { type: 'text', label: 'Region' } });
426+
expect(issues).toHaveLength(1);
427+
expect(issues[0]!.code).toBe('invalid_key');
428+
expect(issues[0]!.path).toEqual(['fields', key]);
429+
expect(issues[0]!.message.startsWith(`\`${key}\` cannot be a field name`)).toBe(true);
430+
expect(issues[0]!.message).toContain('lowercase snake_case such as `region_code`');
431+
expect(issues[0]!.message).not.toMatch(/#\d{3,}/);
432+
},
433+
);
434+
435+
it('control: a snake_case key parses, and so does one spelled `__c` (the suffix is judged at the doors)', () => {
436+
expect(extensionFieldsIssues({ region_code: { type: 'text', label: 'Region' } })).toEqual([]);
437+
expect(extensionFieldsIssues({ region_code__c: { type: 'text', label: 'Region' } })).toEqual([]);
438+
});
439+
440+
it('control: the authored examples of the object-extension guide still parse whole', () => {
441+
// `content/docs/data-modeling/object-extensions.mdx`, the declaration and the worked example.
442+
const declared = ObjectExtensionSchema.parse({
443+
extend: 'showcase_account',
444+
fields: {
445+
loyalty_tier: { type: 'select', label: 'Loyalty Tier', options: [{ label: 'Gold', value: 'gold' }] },
446+
csat_score: { type: 'number', label: 'CSAT Score', min: 0, max: 100 },
447+
},
448+
priority: 210,
449+
});
450+
expect(Object.keys(declared.fields ?? {})).toEqual(['loyalty_tier', 'csat_score']);
451+
const worked = ObjectExtensionSchema.parse({
452+
extend: 'crm_account',
453+
fields: {
454+
cs_health_score: { type: 'number', label: 'Health Score', min: 0, max: 100 },
455+
cs_renewal_date: { type: 'date', label: 'Renewal Date' },
456+
cs_owner: { type: 'text', label: 'Success Manager' },
457+
},
458+
indexes: [{ name: 'idx_crm_account_cs_renewal', fields: ['cs_renewal_date'] }],
459+
priority: 300,
460+
});
461+
expect(Object.keys(worked.fields ?? {})).toEqual(['cs_health_score', 'cs_renewal_date', 'cs_owner']);
462+
});
463+
464+
it('the key schema IS the one `ObjectSchema.fields` reads: both admit exactly the same grammar', () => {
465+
// `constructor` / `prototype` are left out: `ObjectSchema.fields` refuses them by record refines, outside the key schema.
466+
const keys = ['region', 'region_code', '_internal', 'region__c', 'a1', 'Region', 'Region Code', 'region-code', '2nd_phone', 'regionCode', ''];
467+
const admitted = keys.filter((key) => objectFieldsAdmit(key));
468+
// Guard against a vacuous agreement: the sample holds keys on both sides of the grammar.
469+
expect(admitted.length).toBeGreaterThan(0);
470+
expect(admitted.length).toBeLessThan(keys.length);
471+
for (const key of keys) {
472+
const refusedAtKey = extensionFieldsIssues({ [key]: { type: 'text', label: 'L' } })
473+
.some((i) => i.code === 'invalid_key' && i.path.join('.') === `fields.${key}`);
474+
expect(refusedAtKey, key).toBe(!admitted.includes(key));
475+
}
476+
});
477+
});

‎packages/spec/src/data/object.zod.ts‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2777,10 +2777,12 @@ function refuseDuplicateActionNames(objectName: unknown, actions: unknown, ctx:
27772777
/**
27782778
* The key grammar of an object's field map: a field name is lowercase
27792779
* snake_case. ONE schema, read by every record keyed by a field name of an
2780-
* object — `ObjectSchema.fields` and `ObjectExtensionSchema.fieldPatches`
2781-
* (#29366) — so a key the field map can never hold is refused where it is
2782-
* written, never accepted as a patch that no field can match. Declared above
2783-
* `ObjectSchemaBase` for the order reason the block below gives.
2780+
* object — `ObjectSchema.fields`, `ObjectExtensionSchema.fieldPatches`
2781+
* (#29366) and `ObjectExtensionSchema.fields` (#29523) — so a key the field
2782+
* map can never hold is refused where it is written, never accepted as a
2783+
* patch that no field can match or as a field the target's own map would
2784+
* refuse. Declared above `ObjectSchemaBase` for the order reason the block
2785+
* below gives.
27842786
*/
27852787
const FieldNameKeySchema = z.string().regex(/^[a-z_][a-z0-9_]*$/, {
27862788
message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")',
@@ -5035,11 +5037,33 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({
50355037
extend: z.string().describe('Target object name (FQN) to extend'),
50365038

50375039
/**
5038-
* Fields to merge into the target object (additive). `__proto__` is refused
5039-
* on the raw input, as on `ObjectSchema.fields`: zod's record parser skips
5040-
* it, so the save door would store a key the registered extension lacks.
5040+
* Fields to merge into the target object (additive). Each record key is a
5041+
* field name, judged by the field map's own key grammar
5042+
* ({@link FieldNameKeySchema}, as `ObjectSchema.fields`): the fields land in
5043+
* the target's field map, so a key that map would refuse is refused here,
5044+
* where it is written. `__proto__` is refused on the raw input, as on
5045+
* `ObjectSchema.fields`: zod's record parser skips it, so the save door
5046+
* would store a key the registered extension lacks.
50415047
*/
5042-
fields: refuseRecordProtoKey(z.record(z.string(), FieldSchema), 'fields').optional().describe('Fields to add/override'),
5048+
fields: refuseRecordProtoKey(z.record(FieldNameKeySchema, FieldSchema, {
5049+
// [#29523] Keyed by the field map's own key grammar: a key no field name
5050+
// can be (`Region Code`, `region-code`) is refused here, where it is
5051+
// written, instead of parsing and being merged into the target's map.
5052+
error: (issue) => {
5053+
if (issue.code === 'invalid_key') {
5054+
return `\`${String(issue.input)}\` cannot be a field name: an extension's \`fields\` is keyed by the ` +
5055+
'name of each field it adds to the extended object, lowercase snake_case such as `region_code` ' +
5056+
'(`region_code__c` in a customization package), the key grammar of an object\'s own `fields`, ' +
5057+
'never by its label.';
5058+
}
5059+
return undefined;
5060+
},
5061+
}), 'fields')
5062+
.optional()
5063+
.describe(
5064+
'Fields to add/override, keyed by field name (lowercase snake_case, the key grammar of an object\'s ' +
5065+
'`fields`).',
5066+
),
50435067

50445068
/**
50455069
* [ADR-0146 D10, second rule] Per-field display patch of the target's own
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import type { SemanticMigration } from '../../types.js';
4+
5+
// #29523: an object extension's `fields` is keyed by the key schema
6+
// `ObjectSchema.fields` reads, as its `fieldPatches` is (#29366). A semantic
7+
// entry and not a conversion: the key is the name the added field is stored
8+
// and queried under, and a rewrite of the spelling (lower-casing, a space or
9+
// `-` to `_`) names a different column than the one rows, views and formulas
10+
// may already read, or lands on a field the target already declares, so the
11+
// name is the author's to choose.
12+
//
13+
// A stored row in this shape is listed, not rewritten: the stored pass wraps an
14+
// `object_extension` row as an `objectExtensions` entry (the stored-only map in
15+
// `conversions/stored.ts`), and the `REFUSED_STORED_SHAPES` detector of this id
16+
// (`conversions/refused-shapes.ts`) lists each key the extension's own parse
17+
// refuses as a key, under its row, through `os migrate meta --stored`.
18+
export const entry: SemanticMigration = {
19+
id: 'object-extension-field-key-grammar-refused',
20+
surface:
21+
'`objectExtensions[].fields` keys (`defineObjectExtension({ fields })`) that are not a field name: any '
22+
+ 'key outside the lowercase snake_case grammar of an object\'s `fields` keys, such as a label '
23+
+ '(`Region Code`, `RegionCode`) or a kebab spelling (`region-code`).',
24+
replacement:
25+
'A lowercase snake_case field name, the key grammar of the target object\'s own `fields`: '
26+
+ '`fields: { region_code: { type: \'text\', label: \'Region Code\' } }` (`region_code__c` in a '
27+
+ 'customization package), never `fields: { \'Region Code\': { … } }`.',
28+
reason:
29+
'An extension\'s `fields` are merged into the target object\'s field map, and every key of that map is '
30+
+ 'lowercase snake_case: `ObjectSchema.fields` refuses any other key. The extension schema used to take '
31+
+ 'any string, so such a field parsed in `defineStack` and in `defineObjectExtension`, whether or not '
32+
+ 'the target was in the same stack, and was merged into an object whose own declaration could never '
33+
+ 'have held it. The key is now judged where it is written, by the same key schema the field map uses.',
34+
acceptanceCriteria:
35+
'Every `fields` key of every object extension in the stack is lowercase snake_case, and `os validate` '
36+
+ 'passes. A key outside the grammar is refused at parse with one `invalid_key` issue at `fields.KEY` '
37+
+ 'that names the grammar and an example. A stored `object_extension` row whose body still carries such '
38+
+ 'a key no longer parses, so the sync that registers stored extensions names the row '
39+
+ '(`INVALID_METADATA`) and registers none of it, its `fieldPatches` included, and its next save is '
40+
+ 'refused until the field is renamed. `os migrate meta --stored` lists such a row before the upgrade, '
41+
+ 'one TODO for each refused key at `fields.KEY` naming the extended object, and leaves it as stored: '
42+
+ 'rename each listed field to a snake_case name, along with every view, formula and caller that reads '
43+
+ 'it, and save the extension.',
44+
};

0 commit comments

Comments
 (0)