Skip to content

Commit 2ff18a7

Browse files
committed
feat(spec)!: key an object extension's fieldPatches by the field map's own key grammar
`ObjectExtensionSchema.fieldPatches` was `z.record(z.string(), …)`, so a key no field name can be (`Industry`, `Annual Revenue`) parsed and reached only the downstream target judge. The `ObjectSchema.fields` key schema is hoisted to one module constant, `FieldNameKeySchema`, and both records read it; a key outside the grammar gets one `invalid_key` at `fieldPatches.KEY` with a prescription. Claude-Session: https://claude.ai/code/session_01ADHkmSCC3J91hA9anBJ81g Co-authored-by: Claude <noreply@anthropic.com>
1 parent cafe8ee commit 2ff18a7

2 files changed

Lines changed: 94 additions & 11 deletions

File tree

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

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { describe, expect, it } from 'vitest';
1010
import type { z } from 'zod';
1111
import { BASE_FIELD_DISPLAY_WHITELIST, EXTENSION_FIELD_SUFFIX, isExtensionFieldName } from './field-customization';
1212
import { FieldSchema, SelectOptionSchema } from './field.zod';
13-
import { ObjectExtensionSchema } from './object.zod';
13+
import { ObjectExtensionSchema, ObjectSchema } from './object.zod';
1414

1515
/** The object shape behind a (possibly optional) schema. */
1616
function shapeOf(schema: unknown): Record<string, z.ZodTypeAny> {
@@ -349,3 +349,65 @@ describe('`fieldPatches` — what the slot refuses beyond its keys, and the rena
349349
}
350350
});
351351
});
352+
353+
/** Parse an extension whose `fieldPatches` is `fieldPatches`; return the issues. */
354+
function fieldPatchesIssues(fieldPatches: Record<string, unknown>): Issue[] {
355+
const r = ObjectExtensionSchema.safeParse({ extend: 'crm_account', fieldPatches });
356+
return r.success ? [] : (r.error.issues as unknown as Issue[]);
357+
}
358+
359+
/** Does `ObjectSchema.fields` admit `key` as a field name? Read off its own parse, so the grammar is not restated. */
360+
function objectFieldsAdmit(key: string): boolean {
361+
const r = ObjectSchema.safeParse({ name: 'crm_account', label: 'Account', fields: { [key]: { type: 'text', label: 'X' } } });
362+
const issues = r.success ? [] : (r.error.issues as unknown as Issue[]);
363+
return !issues.some((i) => i.code === 'invalid_key' && i.path.join('.') === `fields.${key}`);
364+
}
365+
366+
describe('`fieldPatches` keys — the field map\'s own key grammar', () => {
367+
it.each([['Industry'], ['Annual Revenue'], ['annual-revenue'], ['2nd_phone']])(
368+
'refuses `%s`, which no field name can be: one `invalid_key` at its key, naming the grammar and an example',
369+
(key) => {
370+
const issues = fieldPatchesIssues({ [key]: { label: 'Sector' } });
371+
expect(issues).toHaveLength(1);
372+
expect(issues[0]!.code).toBe('invalid_key');
373+
expect(issues[0]!.path).toEqual(['fieldPatches', key]);
374+
expect(issues[0]!.message).toMatch(new RegExp(`^\`${key}\` cannot be a field name`));
375+
expect(issues[0]!.message).toContain('lowercase snake_case such as `industry`');
376+
expect(issues[0]!.message).not.toMatch(/#\d{3,}/);
377+
},
378+
);
379+
380+
it('control: a snake_case key parses, and so does a `__c` key, which stays the `__c` rule\'s to refuse', () => {
381+
expect(fieldPatchesIssues({ annual_revenue: { label: 'Revenue' } })).toEqual([]);
382+
const issues = fieldPatchesIssues({ region__c: { label: 'Region' } });
383+
expect(issues.map((i) => [i.code, i.path.join('.')])).toEqual([['custom', 'fieldPatches.region__c']]);
384+
});
385+
386+
it('control: the authored example of the object-extension guide still parses whole', () => {
387+
// `content/docs/data-modeling/object-extensions.mdx`, "Relabelling a vendor field".
388+
const parsed = ObjectExtensionSchema.parse({
389+
extend: 'crm_account',
390+
fieldPatches: {
391+
industry: {
392+
label: 'Sector',
393+
inlineHelpText: 'The market the account sells into.',
394+
options: { technology: { label: 'Tech' } },
395+
},
396+
},
397+
});
398+
expect(parsed.fieldPatches?.industry?.label).toBe('Sector');
399+
});
400+
401+
it('the key schema IS the one `ObjectSchema.fields` reads: both admit exactly the same keys', () => {
402+
const keys = ['industry', 'annual_revenue', '_internal', 'region__c', 'a1', 'Industry', 'Annual Revenue', 'annual-revenue', '2nd_phone', 'industryName', ''];
403+
const admitted = keys.filter((key) => objectFieldsAdmit(key));
404+
// Guard against a vacuous agreement: the sample holds keys on both sides of the grammar.
405+
expect(admitted.length).toBeGreaterThan(0);
406+
expect(admitted.length).toBeLessThan(keys.length);
407+
for (const key of keys) {
408+
const refusedAtKey = fieldPatchesIssues({ [key]: { label: 'L' } })
409+
.some((i) => i.code === 'invalid_key' && i.path.join('.') === `fieldPatches.${key}`);
410+
expect(refusedAtKey, key).toBe(!admitted.includes(key));
411+
}
412+
});
413+
});

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

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2768,6 +2768,18 @@ function refuseDuplicateActionNames(objectName: unknown, actions: unknown, ctx:
27682768
}
27692769
}
27702770

2771+
/**
2772+
* The key grammar of an object's field map: a field name is lowercase
2773+
* snake_case. ONE schema, read by every record keyed by a field name of an
2774+
* object — `ObjectSchema.fields` and `ObjectExtensionSchema.fieldPatches`
2775+
* (#29366) — so a key the field map can never hold is refused where it is
2776+
* written, never accepted as a patch that no field can match. Declared above
2777+
* `ObjectSchemaBase` for the order reason the block below gives.
2778+
*/
2779+
const FieldNameKeySchema = z.string().regex(/^[a-z_][a-z0-9_]*$/, {
2780+
message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")',
2781+
});
2782+
27712783
// ⚠️ ORDER IS LOAD-BEARING (#5593). This map used to live ~700 lines BELOW
27722784
// `ObjectSchemaBase`, and the error map that reads it was built lazily
27732785
// (`objectUnknownKeyErrorImpl ??= …`) purely to step around the temporal dead
@@ -3189,13 +3201,7 @@ const ObjectSchemaBase = strictObject(
31893201
message: 'Field names must not be "constructor" or "prototype" (reserved JavaScript prototype property names).',
31903202
path: [reserved],
31913203
}),
3192-
z.record(
3193-
z.string()
3194-
.regex(/^[a-z_][a-z0-9_]*$/, {
3195-
message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")',
3196-
}),
3197-
FieldSchema,
3198-
),
3204+
z.record(FieldNameKeySchema, FieldSchema),
31993205
),
32003206
'fields',
32013207
).describe('Field definitions map. Keys must be snake_case identifiers; "__proto__", "constructor" and "prototype" are refused.'),
@@ -4933,7 +4939,8 @@ function refuseFieldPatchOfReplacedField(fields: unknown, fieldPatches: unknown,
49334939
/** [ADR-0146 D10] The `fieldPatches` description, its member list read from {@link BASE_FIELD_DISPLAY_WHITELIST}. */
49344940
function fieldPatchesDescription(): string {
49354941
return (
4936-
'Display patches of the target object\'s own fields, keyed by field name: change a vendor field\'s ' +
4942+
'Display patches of the target object\'s own fields, keyed by field name (lowercase snake_case, the ' +
4943+
'key grammar of an object\'s `fields`): change a vendor field\'s ' +
49374944
`display properties (BASE_FIELD_DISPLAY_WHITELIST: ${backtickList(BASE_FIELD_DISPLAY_WHITELIST.field)} ` +
49384945
`on the field, ${backtickList(BASE_FIELD_DISPLAY_WHITELIST.option)} on an option under \`options\`, ` +
49394946
'keyed by its stored value) without taking the field over, so its type, values and rules stay the ' +
@@ -5030,7 +5037,9 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({
50305037

50315038
/**
50325039
* [ADR-0146 D10, second rule] Per-field display patch of the target's own
5033-
* fields. Keys are DERIVED from `BASE_FIELD_DISPLAY_WHITELIST`; structural
5040+
* fields. Each record key is a field name, judged by the field map's own
5041+
* key grammar ({@link FieldNameKeySchema}, as `ObjectSchema.fields`). A
5042+
* patch's keys are DERIVED from `BASE_FIELD_DISPLAY_WHITELIST`; structural
50345043
* keys are refused by name with the D6 prescription; an `__c` key, and a
50355044
* field the same extension replaces in `fields`, are refused by the root
50365045
* refinement below; `__proto__` is refused on the raw input. Pure shape: whether the target has the field
@@ -5039,7 +5048,19 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({
50395048
* `os validate`, named in the boot log — and the merge that applies the patch
50405049
* is `@objectstack/objectql`'s `mergeObjectDefinitions`.
50415050
*/
5042-
fieldPatches: refuseRecordProtoKey(z.record(z.string(), FieldDisplayPatchSchema), 'fieldPatches')
5051+
fieldPatches: refuseRecordProtoKey(z.record(FieldNameKeySchema, FieldDisplayPatchSchema, {
5052+
// [#29366] Keyed by the field map's own key grammar: a key no field name
5053+
// can be (`Industry`, `Annual Revenue`) is refused here, where it is
5054+
// written, instead of parsing and reaching only the target judge.
5055+
error: (issue) => {
5056+
if (issue.code === 'invalid_key') {
5057+
return `\`${String(issue.input)}\` cannot be a field name, so no field sits under it: \`fieldPatches\` is ` +
5058+
'keyed by the name of a field the extended object declares, lowercase snake_case such as ' +
5059+
'`industry` or `annual_revenue` (the key of its `fields` entry), never by its label.';
5060+
}
5061+
return undefined;
5062+
},
5063+
}), 'fieldPatches')
50435064
.optional()
50445065
.describe(fieldPatchesDescription()),
50455066

0 commit comments

Comments
 (0)