Skip to content

Commit 391216f

Browse files
fix(objectql)!: a string-typed field refuses a plain object or an array instead of storing its JSON text (#29223)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi94xHkrh5JJ1hAdnahZC193U)_ Fixes #29133 Clause-②: no (narrowing) — measured: on base `fea2dbb7` a plain object or an array on a `text` / `textarea` field was admitted by `validateRecord` on insert and on update; on head it is refused `invalid_type` on every member of `BOUNDED_STRING_FIELD_TYPES`, on insert, update and multi-update. Nothing is widened. Metadata-protocol: none — measured: no schema, key, accepted metadata value or export changes; only a record write carrying a value of the wrong shape is refused. Skills-docs: none — no skill or doc teaches writing an object or an array into a string field, and the refusal reuses the existing catalog sentence. ## 维护者速读 - 改了什么:文本类字段(text、textarea、email、url 等 12 种)收到对象或数组时,现在直接拒收(invalid_type),不再把它转成 JSON 文本存进去。 - 为什么改:之前创建、PATCH、屏幕流恢复时给文本字段传对象或数组都返回 201/200,库里存的是一段 JSON 文本,数据悄悄变脏。 - 风险与回滚:是收窄,原来能写进去的错形状值现在会被拒;数字和布尔值仍按原样转成字符串,不受影响。回滚即 revert 本 PR。 - 先看:`packages/objectql/src/validation/record-validator.ts` 字符串分支新增的那段;`record-validator.text-shape.test.ts`;`operator-object-write-value.test.ts` 的两处改动。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/validation/record-validator.text-shape.test.ts`,预期 107 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes - `packages/objectql/src/validation/record-validator.ts`, the `BOUNDED_STRING_FIELD_TYPES` arm: a plain object or an array is refused before any bound is judged, with the validator's existing `invalid_type` code and the existing ADR-0104 `invalid_value_shape` sentence (detail `expected a string, received an object` / `an array`). No new error code, no new message key, no `packages/spec` edit. It is a shape test, so it runs ahead of `shapeOnly` and a readonly field's value is judged the same way; the `ReadonlyValueScope` docblock lists it. - A filter-operator object keeps its own earlier sentence (the operator rule runs first). Numbers, booleans, `null`, a missing value, `json` and the structured-JSON types are unchanged. - Changeset `.changeset/29133-text-field-refuses-object-array.md` (`@objectstack/objectql` patch, BREAKING banner, ADR-0087 `not-required (no-migration-prescription)`). ## Tests - New `packages/objectql/src/validation/record-validator.text-shape.test.ts` (107 cases): every member of the spec set × object / array / empty object / empty array × insert / update refuses with `code` + `constraint.type` + detail; the message names field, type and shape; the readonly scope refuses; the operator sentence still wins; strings, numbers, booleans, null and `json` still pass; the engine's insert, update and multi-update answer `VALIDATION_FAILED` and the driver is never written. - **Forced test edit**: `operator-object-write-value.test.ts`, two pins in "what the rule deliberately leaves alone" (`admits an UNDECLARED $-spelling`, `admits a plain non-operator object`) wrote `{ $inn: [...] }` / `{ a: 1 }` into the `text` field `title` and asserted admission. That is the coercion this card removes. Both pins move to the free-form `select` field `stage_free` already in that schema, so they keep asserting what they state (the operator rule is derived from the vocabulary, not from the `$` sigil) without depending on the text arm. ## Acceptance notes - A number or a boolean on a string field keeps its string reading, as the card's scope says. Not measured exhaustively across seeds and fixtures, so it was left alone rather than narrowed; every consumer suite below stayed green with it. - Out of scope, noted not filed: a free-form `select` with no `options` still admits a plain object (the pin moved above shows it); same class as this card, different arm. ## Verification All readings at head `a50b8dce` unless named. <details><summary>Premise on base fea2dbb</summary> A scratch `validateRecord` probe (deleted after): `{"nested":true}`, `["a","b"]`, `42`, `true` on `text` + `textarea` — ADMIT on insert and update, all eight. </details> <details><summary>Suites</summary> - `@objectstack/objectql` test: Test Files 528 passed (528), Tests 10233 passed; typecheck exit 0 (lock VERDICT command-exit 0). - `@objectstack/metadata-protocol` test: Test Files 297 passed, 4 skipped (301); Tests 22062 passed, 26 skipped. - `@objectstack/service-automation` test (screen-flow resume): Test Files 257 passed (257); Tests 3309 passed. - `@objectstack/dogfood` (full battery, narrowing arm): Test Files 386 passed, 3 skipped (389); Tests 3195 passed, 28 skipped (3223); lock VERDICT command-exit 0, after building the `@objectstack/dogfood^...` closure. No failure. - eslint over `packages/objectql` (`--no-inline-config`): exit 0. </details> <details><summary>Ablation</summary> `scripts/ablation-replace.mjs` replaced the guard `if (isPlainObjectValue(value) || Array.isArray(value)) {` with a never-true condition (anchor 1 → 0, replacement 0 → 1, blob 002f842 → 40e5174d). The new file ran red: Test Files 1 failed, Tests 100 failed | 7 passed (107) — every refusal case red with `expected [] to have a length of 1 but got +0`; the seven green are the leave-alone cases. Restore: blob == HEAD 002f842, `git diff HEAD` empty; rerun 107/107 green. The suite imports the validator from `src`, so no dist leg; `ablation-dist-preflight --absent` confirmed the built dist never carried the marker. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `a50b8dce` derived 61 families; all 61 run, each exit 0. `--ran` reconciliation: 61 derived, 61 run, 0 NOT-MEASURED, 0 UNRUN. Two first ran exit 3 on container prerequisites and were rerun green: `check-plugin-teardown-shape --self-test` (after `git fetch --depth=1` of its fixture commit) and `check:dual-build-cjs-loads` (after the dogfood closure build). CI families: read from this PR's check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRRicnRgy1gLFe46z7)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8a8a03d commit 391216f

4 files changed

Lines changed: 234 additions & 5 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a string-typed field refuses a plain object or an array as its value, instead of storing its JSON text (#29133)
6+
7+
Clause-②: no (narrowing) — a create, update or screen-flow resume that writes a plain object or an array into a `text`-family field (the twelve `BOUNDED_STRING_FIELD_TYPES`) is refused `invalid_type`, where it was admitted and stored as JSON text. Nothing is widened.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type changes: what a metadata author writes is read exactly as before. Only a record write carrying a value of the wrong shape is refused, with the validator's existing invalid_type code and the existing ADR-0104 shape sentence, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** accept-set narrowing at the record write door (`@objectstack/objectql`), served by every door that runs the record validator: REST create and PATCH, the engine's insert / update / multi-update, a flow's record nodes, the screen-flow resume, and `os validate` / `os build` over seed records.
13+
14+
- **Before.** The string arm judged `String(value)` while the write carried `value`, so `{ "nested": true }` or `["a", "b"]` on a `text`, `textarea`, `email`, `url`, `phone`, `password`, `markdown`, `html`, `richtext`, `code`, `signature` or `qrcode` field passed every bound and the driver stored its JSON text (201 / 200).
15+
- **Now.** Both shapes are refused `invalid_type` with the sentence `<Label> has an invalid <type> value: expected a string, received an object` (or `an array`), in all four locales. The driver is never written. A readonly field's value is judged the same way, as a shape check.
16+
- **Unchanged.** A string, a number and a boolean (a number or boolean keeps its string reading), `null` and a missing value. A filter-operator object keeps its own earlier refusal sentence. A `json` field and the structured-JSON types still hold any object.
17+
18+
**The remedy.** Send the string you mean: `JSON.stringify(value)` on the client if JSON text is really what the field should hold, or declare the field `json` when it holds structured data.

‎packages/objectql/src/validation/operator-object-write-value.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,16 @@ describe('#5922 — what the rule deliberately leaves alone', () => {
136136
// The rule is derived from the spec's operator vocabulary, not from the
137137
// `$` sigil. `{ $inn: … }` is out of scope by construction; judging every
138138
// plain object on a scalar field is #5922's option A, which this is not.
139-
expect(() => validateRecord(schema, { title: { $inn: ['a'] } }, 'update')).not.toThrow();
139+
//
140+
// [#29133] Pinned on a free-form `select`, not on `text`: the text family
141+
// now refuses every plain object by its own shape rule (see
142+
// `record-validator.text-shape.test.ts`), which would make this pin pass
143+
// for a reason other than the one it states.
144+
expect(() => validateRecord(schema, { stage_free: { $inn: ['a'] } }, 'update')).not.toThrow();
140145
});
141146

142147
it('admits a plain non-operator object (same reason)', () => {
143-
expect(() => validateRecord(schema, { title: { a: 1 } }, 'update')).not.toThrow();
148+
expect(() => validateRecord(schema, { stage_free: { a: 1 } }, 'update')).not.toThrow();
144149
});
145150
});
146151

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29133] A string-typed field (`BOUNDED_STRING_FIELD_TYPES`) refuses a plain
5+
* object or an array as its value.
6+
*
7+
* Measured on `origin/main` @ `fea2dbb7` before the change: `validateRecord`
8+
* admitted `{ nested: true }` and `['a', 'b']` on `text` and `textarea`, on
9+
* insert and on update, because the arm judged `String(value)` while the write
10+
* carried `value`; the driver then stored the JSON text. The arm now refuses
11+
* both shapes with the validator's existing `invalid_type` wire code and the
12+
* ADR-0104 `invalid_value_shape` sentence. Numbers, booleans and a missing
13+
* value are untouched.
14+
*/
15+
16+
import { describe, it, expect } from 'vitest';
17+
import { BOUNDED_STRING_FIELD_TYPES } from '@objectstack/spec/data';
18+
import { validateRecord, validateRecordInScope, ValidationError } from './record-validator.js';
19+
import { ObjectQL } from '../engine.js';
20+
21+
const STRING_TYPES = [...BOUNDED_STRING_FIELD_TYPES];
22+
23+
function errorsOf(
24+
schema: { fields: Record<string, any> },
25+
data: Record<string, unknown>,
26+
mode: 'insert' | 'update',
27+
) {
28+
try {
29+
validateRecord(schema, data, mode);
30+
} catch (e) {
31+
if (e instanceof ValidationError) return e.fields;
32+
throw e;
33+
}
34+
return [];
35+
}
36+
37+
describe('#29133 — a string-typed field refuses a plain object or an array', () => {
38+
it('reads the spec set, which still holds the twelve members this pin was written against', () => {
39+
// A member joining or leaving the spec set moves this door with it; the
40+
// count is pinned so a change is seen here, not inferred.
41+
expect(STRING_TYPES).toHaveLength(12);
42+
expect(STRING_TYPES).toContain('text');
43+
expect(STRING_TYPES).toContain('textarea');
44+
});
45+
46+
for (const type of STRING_TYPES) {
47+
const schema = { fields: { f: { type, label: 'F' } } };
48+
for (const [shape, value, received] of [
49+
['object', { nested: true }, 'an object'],
50+
['array', ['a', 'b'], 'an array'],
51+
['empty object', {}, 'an object'],
52+
['empty array', [], 'an array'],
53+
] as const) {
54+
for (const mode of ['insert', 'update'] as const) {
55+
it(`${type}: refuses ${shape} on ${mode} as invalid_type`, () => {
56+
const errs = errorsOf(schema, { f: value }, mode);
57+
expect(errs).toHaveLength(1);
58+
expect(errs[0].field).toBe('f');
59+
expect(errs[0].code).toBe('invalid_type');
60+
expect(errs[0].constraint).toMatchObject({
61+
type,
62+
detail: `expected a string, received ${received}`,
63+
});
64+
});
65+
}
66+
}
67+
}
68+
69+
it('says what was wrong in the message: the field, the type and the received shape', () => {
70+
const errs = errorsOf({ fields: { title: { type: 'text', label: 'Title' } } }, { title: { nested: true } }, 'insert');
71+
expect(errs[0].message).toContain('Title');
72+
expect(errs[0].message).toContain('text');
73+
expect(errs[0].message).toContain('expected a string, received an object');
74+
});
75+
76+
it('refuses the shape on a readonly field too (a shape arm, reached under the readonly scope)', () => {
77+
const schema = { fields: { stamp: { type: 'text', label: 'Stamp', readonly: true } } };
78+
let err: unknown = null;
79+
try {
80+
validateRecordInScope(schema, { stamp: ['x'] }, 'insert', 'include');
81+
} catch (e) {
82+
err = e;
83+
}
84+
expect(err).toBeInstanceOf(ValidationError);
85+
expect((err as ValidationError).fields.map((f) => [f.field, f.code])).toEqual([['stamp', 'invalid_type']]);
86+
});
87+
88+
it('a filter-operator object keeps its own, earlier sentence', () => {
89+
const errs = errorsOf({ fields: { title: { type: 'text', label: 'Title' } } }, { title: { $in: ['a'] } }, 'update');
90+
expect(errs).toHaveLength(1);
91+
expect(errs[0].message).toContain('$in is a filter operator, not a value');
92+
});
93+
});
94+
95+
describe('#29133 — what the rule leaves alone', () => {
96+
const schema = {
97+
fields: {
98+
title: { type: 'text', label: 'Title', maxLength: 5 },
99+
payload: { type: 'json', label: 'Payload' },
100+
mail: { type: 'email', label: 'Mail' },
101+
},
102+
};
103+
104+
it('a string is admitted, and its bounds still bind', () => {
105+
expect(errorsOf(schema, { title: 'ok' }, 'insert')).toEqual([]);
106+
expect(errorsOf(schema, { title: 'too long' }, 'insert')[0].code).toBe('max_length');
107+
});
108+
109+
it('a number and a boolean keep their string reading (out of this rule)', () => {
110+
expect(errorsOf(schema, { title: 42 }, 'insert')).toEqual([]);
111+
expect(errorsOf(schema, { title: true }, 'update')).toEqual([]);
112+
});
113+
114+
it('null and undefined are unchanged', () => {
115+
expect(errorsOf(schema, { title: null }, 'update')).toEqual([]);
116+
expect(errorsOf(schema, { title: undefined }, 'insert')).toEqual([]);
117+
});
118+
119+
it('a json field still holds any object', () => {
120+
expect(errorsOf(schema, { payload: { nested: true } }, 'insert')).toEqual([]);
121+
});
122+
123+
it('a format type answers the shape refusal, not its format sentence', () => {
124+
const errs = errorsOf(schema, { mail: { address: 'a@b.co' } }, 'insert');
125+
expect(errs.map((e) => e.code)).toEqual(['invalid_type']);
126+
});
127+
});
128+
129+
/**
130+
* The end-to-end half: the engine's create, update and multi-update doors
131+
* reach the rule, answer the VALIDATION_FAILED envelope, and the driver is
132+
* never written.
133+
*/
134+
describe('#29133 — write path end to end: no JSON text reaches the driver', () => {
135+
async function boot() {
136+
const engine = new ObjectQL();
137+
const writes: unknown[] = [];
138+
const rows = new Map<string, Record<string, unknown>>([['rec_1', { id: 'rec_1', title: 'orig' }]]);
139+
engine.registerDriver({
140+
name: 'recording', version: '0.0.0', supports: {},
141+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
142+
async execute() { return null; },
143+
async find() { return Array.from(rows.values()); },
144+
async findOne(_o: string, ast: any) { return rows.get(ast?.where?.id) ?? null; },
145+
async create(_o: string, data: Record<string, unknown>) { writes.push(data); return { ...data, id: 'x' }; },
146+
async update(_o: string, id: string, data: Record<string, unknown>) { writes.push(data); return { ...data, id }; },
147+
async updateMany(_o: unknown, _a: unknown, data: unknown) { writes.push(data); return 0; },
148+
async delete() { return true; }, async count() { return rows.size; },
149+
async bulkCreate() { return []; }, async bulkUpdate() { return []; }, async bulkDelete() {},
150+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
151+
async commit() {}, async rollback() {},
152+
} as any, true);
153+
await engine.init();
154+
engine.registry.registerObject({
155+
name: 'shape_task', label: 'Task',
156+
fields: {
157+
id: { name: 'id', label: 'ID', type: 'text', primaryKey: true },
158+
title: { name: 'title', label: 'Title', type: 'text' },
159+
},
160+
} as any);
161+
return { engine, writes, rows };
162+
}
163+
164+
it('refuses on insert, update and multi-update, and the driver sees no write', async () => {
165+
const { engine, writes, rows } = await boot();
166+
for (const run of [
167+
() => engine.insert('shape_task', { title: { nested: true } } as any),
168+
() => engine.update('shape_task', { title: ['a', 'b'] } as any, { where: { id: 'rec_1' } } as any),
169+
() => engine.update('shape_task', { title: { nested: true } } as any, { multi: true } as any),
170+
]) {
171+
const err = await run().then(() => null, (e: unknown) => e as ValidationError);
172+
expect(err).toBeInstanceOf(ValidationError);
173+
expect(err!.code).toBe('VALIDATION_FAILED');
174+
expect(err!.fields.map((f) => [f.field, f.code])).toEqual([['title', 'invalid_type']]);
175+
}
176+
expect(writes).toEqual([]);
177+
expect(rows.get('rec_1')).toEqual({ id: 'rec_1', title: 'orig' });
178+
});
179+
180+
it('a string write on the same path still lands', async () => {
181+
const { engine, writes } = await boot();
182+
await engine.update('shape_task', { title: 'renamed' } as any, { where: { id: 'rec_1' } } as any);
183+
expect(writes).toEqual([expect.objectContaining({ title: 'renamed' })]);
184+
});
185+
});

‎packages/objectql/src/validation/record-validator.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -672,9 +672,10 @@ export function normalizeMultiValueFields(
672672
* the declared type at all", with the same wire code and the same sentence a
673673
* non-readonly field gets: a `date` / `datetime` / `time` the platform reads,
674674
* a number for a number-typed field, a boolean, an array for a multi-value
675-
* field, no filter-operator object, and the ADR-0104 reference / media /
676-
* structured-JSON shape under the object's own posture (warn-first until the
677-
* deployment's evidence says otherwise). It is never REQUIRED.
675+
* field, no plain object or array on a string-typed field, no filter-operator
676+
* object, and the ADR-0104 reference / media / structured-JSON shape under
677+
* the object's own posture (warn-first until the deployment's evidence says
678+
* otherwise). It is never REQUIRED.
678679
*
679680
* ⛔ It does NOT reach the author-declared constraints on top of the type:
680681
* option membership (`invalid_option`), `maxLength` / `minLength`,
@@ -1122,6 +1123,26 @@ function validateOne(
11221123
if (BOUNDED_STRING_FIELD_TYPES.has(t)) {
11231124
// A string type's stored shape is a string; everything below is a bound,
11241125
// a domain or a format the author declared on top of it.
1126+
//
1127+
// [#29133] A plain object or an array is refused, never stringified. The
1128+
// arm used to judge `String(value)` while the write carried `value`, so
1129+
// `{ nested: true }` passed every bound (`"[object Object]"` is 15 chars)
1130+
// and reached the driver as sent, which stored its JSON text — on create,
1131+
// PATCH and the screen-flow resume alike. Neither shape is the spec's
1132+
// stored value for this class and neither has a string reading the author
1133+
// meant, so the arm refuses it with the number arm's #20309 posture: never
1134+
// silently alter a value. It is a SHAPE test, so it runs ahead of
1135+
// `shapeOnly`. A number or a boolean keeps its string reading; a
1136+
// filter-operator object was already refused above, with its own sentence.
1137+
if (isPlainObjectValue(value) || Array.isArray(value)) {
1138+
return fail(
1139+
'invalid_type',
1140+
{ type: t, detail: `expected a string, received ${Array.isArray(value) ? 'an array' : 'an object'}` },
1141+
// The ADR-0104 shape sentence the operator refusal above also uses:
1142+
// one catalog entry for "this value's SHAPE is wrong for this type".
1143+
'invalid_value_shape',
1144+
);
1145+
}
11251146
if (shapeOnly) return null;
11261147
const s = typeof value === 'string' ? value : String(value);
11271148
if (def.maxLength !== undefined && s.length > def.maxLength) {

0 commit comments

Comments
 (0)