@object-ui/data-objectstack 16.0.0 → 17.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * ObjectStackAdapter must surface the framework's write-observability channel
11
+ * (#3431/#3455): when a create/update response carries `droppedFields` — fields
12
+ * the backend LEGALLY stripped (read-only / locked-by-state) — the adapter emits
13
+ * a WriteWarningEvent so the app shell can toast the user instead of letting the
14
+ * dropped value vanish silently. The write itself still succeeded.
15
+ */
16
+ import { describe, it, expect, vi } from 'vitest';
17
+ import { ObjectStackAdapter } from './index';
18
+ import type { WriteWarningEvent } from './index';
19
+
20
+ function makeDS(stub: Record<string, any>) {
21
+ const ds: any = new ObjectStackAdapter({
22
+ baseUrl: 'http://test.local',
23
+ fetch: vi.fn(async () =>
24
+ new Response(JSON.stringify({ success: true, data: { capabilities: {}, routes: {} } }), {
25
+ status: 200,
26
+ headers: { 'Content-Type': 'application/json' },
27
+ }),
28
+ ),
29
+ });
30
+ ds.connected = true;
31
+ ds.connectionState = 'connected';
32
+ ds.client = { data: stub };
33
+ return ds;
34
+ }
35
+
36
+ const ONE_DROP = [{ object: 'approval_case', fields: ['approval_status'], reason: 'readonly' }];
37
+
38
+ describe('ObjectStackAdapter.onWriteWarning', () => {
39
+ it('emits a create write-warning carrying the dropped fields and the new id', async () => {
40
+ const create = vi.fn().mockResolvedValue({ record: { id: 'r1', title: 'A' }, droppedFields: ONE_DROP });
41
+ const ds = makeDS({ create });
42
+ const events: WriteWarningEvent[] = [];
43
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
44
+
45
+ const rec = await ds.create('approval_case', { title: 'A', approval_status: 'approved' });
46
+
47
+ // The write still returns the plain record (unchanged behaviour).
48
+ expect(rec).toEqual({ id: 'r1', title: 'A' });
49
+ expect(events).toEqual([
50
+ { operation: 'create', resource: 'approval_case', id: 'r1', droppedFields: ONE_DROP },
51
+ ]);
52
+ });
53
+
54
+ it('emits an update write-warning carrying the target id', async () => {
55
+ const update = vi.fn().mockResolvedValue({ record: { id: 'r1' }, droppedFields: ONE_DROP });
56
+ const ds = makeDS({ update });
57
+ const events: WriteWarningEvent[] = [];
58
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
59
+
60
+ await ds.update('approval_case', 'r1', { approval_status: 'approved' });
61
+
62
+ expect(events).toEqual([
63
+ { operation: 'update', resource: 'approval_case', id: 'r1', droppedFields: ONE_DROP },
64
+ ]);
65
+ });
66
+
67
+ it('does NOT emit when the response carries no droppedFields (the common case)', async () => {
68
+ const create = vi.fn().mockResolvedValue({ record: { id: 'r1', title: 'A' } });
69
+ const update = vi.fn().mockResolvedValue({ record: { id: 'r1' } });
70
+ const ds = makeDS({ create, update });
71
+ const events: WriteWarningEvent[] = [];
72
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
73
+
74
+ await ds.create('approval_case', { title: 'A' });
75
+ await ds.update('approval_case', 'r1', { title: 'B' });
76
+
77
+ expect(events).toEqual([]);
78
+ });
79
+
80
+ it('does NOT emit for an empty or malformed droppedFields payload', async () => {
81
+ const create = vi
82
+ .fn()
83
+ .mockResolvedValueOnce({ record: { id: 'r1' }, droppedFields: [] })
84
+ .mockResolvedValueOnce({ record: { id: 'r2' }, droppedFields: 'nope' })
85
+ .mockResolvedValueOnce({ record: { id: 'r3' }, droppedFields: [{ object: 'x', fields: [] }] });
86
+ const ds = makeDS({ create });
87
+ const events: WriteWarningEvent[] = [];
88
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
89
+
90
+ await ds.create('x', {});
91
+ await ds.create('x', {});
92
+ await ds.create('x', {}); // event present but its fields[] is empty → filtered out
93
+
94
+ expect(events).toEqual([]);
95
+ });
96
+
97
+ // ── cross-object batch (framework #3794) ─────────────────────────────────
98
+ //
99
+ // `batchTransaction` is the console record form's save path for a
100
+ // master-detail record, so this is where a `readonlyWhen` strip actually
101
+ // reaches a user editing a form. Its response tags each event with the index
102
+ // of the operation that produced it.
103
+
104
+ it('emits a write-warning per event on a cross-object batch, resolving the op', async () => {
105
+ const batchTransaction = vi.fn().mockResolvedValue({
106
+ results: [{ id: 'acc1' }, { id: 'inv1' }],
107
+ droppedFields: [
108
+ { object: 'invoice', fields: ['tax_rate'], reason: 'readonly_when', index: 1 },
109
+ ],
110
+ });
111
+ const ds = makeDS({ batchTransaction });
112
+ ds.atomicBatchCapability = true;
113
+ const events: WriteWarningEvent[] = [];
114
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
115
+
116
+ await ds.batchTransaction([
117
+ { object: 'account', action: 'create', data: { name: 'Acme' } },
118
+ { object: 'invoice', action: 'update', id: 'inv1', data: { status: 'paid', tax_rate: 9 } },
119
+ ]);
120
+
121
+ expect(events).toEqual([
122
+ {
123
+ operation: 'update',
124
+ resource: 'invoice',
125
+ id: 'inv1',
126
+ droppedFields: [{ object: 'invoice', fields: ['tax_rate'], reason: 'readonly_when' }],
127
+ },
128
+ ]);
129
+ });
130
+
131
+ it('does NOT emit for a clean batch or a malformed droppedFields list', async () => {
132
+ const batchTransaction = vi
133
+ .fn()
134
+ .mockResolvedValueOnce({ results: [{ id: 'a' }] })
135
+ .mockResolvedValueOnce({ results: [{ id: 'a' }], droppedFields: [{ object: 'x', fields: [], index: 0 }] });
136
+ const ds = makeDS({ batchTransaction });
137
+ ds.atomicBatchCapability = true;
138
+ const events: WriteWarningEvent[] = [];
139
+ ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
140
+
141
+ await ds.batchTransaction([{ object: 'x', action: 'create', data: {} }]);
142
+ await ds.batchTransaction([{ object: 'x', action: 'create', data: {} }]);
143
+
144
+ expect(events).toEqual([]);
145
+ });
146
+
147
+ it('stops delivering after unsubscribe', async () => {
148
+ const create = vi.fn().mockResolvedValue({ record: { id: 'r1' }, droppedFields: ONE_DROP });
149
+ const ds = makeDS({ create });
150
+ const events: WriteWarningEvent[] = [];
151
+ const unsub = ds.onWriteWarning((e: WriteWarningEvent) => events.push(e));
152
+
153
+ await ds.create('approval_case', {});
154
+ unsub();
155
+ await ds.create('approval_case', {});
156
+
157
+ expect(events).toHaveLength(1);
158
+ });
159
+
160
+ it('isolates a throwing listener so the write still resolves and other listeners fire', async () => {
161
+ const update = vi.fn().mockResolvedValue({ record: { id: 'r1' }, droppedFields: ONE_DROP });
162
+ const ds = makeDS({ update });
163
+ const good = vi.fn();
164
+ ds.onWriteWarning(() => { throw new Error('boom'); });
165
+ ds.onWriteWarning(good);
166
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
167
+
168
+ await expect(ds.update('approval_case', 'r1', { approval_status: 'x' })).resolves.toBeTruthy();
169
+ expect(good).toHaveBeenCalledTimes(1);
170
+ warn.mockRestore();
171
+ });
172
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * Every shape `QueryParams['$orderby']` declares reaches the wire as a sort.
11
+ *
12
+ * `find()` has TWO routes to the server — a plain read goes through
13
+ * `convertQueryParams` and the client SDK, a read with `$expand`/`$search`
14
+ * through `rawFindWithPopulate` — and each used to carry its own copy of the
15
+ * "which `$orderby` shape is this?" fold. Both copies handled three of the four
16
+ * declared shapes; both missed the bare string, and missed it the same
17
+ * spectacular way: the string fell into the `Record<field, direction>` branch,
18
+ * where `Object.entries('name asc')` enumerates character indices and the
19
+ * request went out as `sort=0,1,2,3,4,5,6,7`.
20
+ *
21
+ * That is not a cosmetic mistranslation. Since objectstack#4226 the server
22
+ * refuses a sort it cannot read (`400 INVALID_SORT`) rather than dropping it,
23
+ * so the whole list fails to load — and `"${field} ${order}"` is exactly what a
24
+ * standalone `ObjectGrid` builds from its view metadata's `sort`.
25
+ *
26
+ * Both routes are asserted for every shape, because "the two routes agree" is
27
+ * the property that was actually missing; one serializer now backs both.
28
+ */
29
+
30
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
31
+ import { ObjectStackAdapter, clearSharedDiscoveryCache, serializeOrderBy } from './index';
32
+
33
+ function makeAdapter() {
34
+ const calls: string[] = [];
35
+ const fetchImpl = vi.fn(async (url: any) => {
36
+ const u = String(url);
37
+ calls.push(u);
38
+ if (u.includes('/api/v1/discovery')) {
39
+ return {
40
+ ok: true, status: 200, statusText: 'OK',
41
+ json: async () => ({ success: true, data: { version: 'v1', routes: {} } }),
42
+ } as any;
43
+ }
44
+ return {
45
+ ok: true, status: 200, statusText: 'OK',
46
+ json: async () => ({ success: true, data: { object: 'account', records: [], total: 0 } }),
47
+ } as any;
48
+ });
49
+ const adapter = new ObjectStackAdapter({
50
+ baseUrl: 'http://localhost:3000', token: 't', autoReconnect: false, fetch: fetchImpl as any,
51
+ });
52
+ return { adapter, calls };
53
+ }
54
+
55
+ /** The `sort=` this `$orderby` produced on the wire, or `undefined` if none was sent. */
56
+ async function sortOnWire($orderby: unknown, route: 'plain' | 'expand'): Promise<string | undefined> {
57
+ const { adapter, calls } = makeAdapter();
58
+ await adapter.find('account', {
59
+ $orderby,
60
+ ...(route === 'expand' ? { $expand: ['owner'] } : {}),
61
+ } as any);
62
+ const dataCall = calls.filter((u) => u.includes('/data/account')).pop();
63
+ const raw = dataCall ? new URL(dataCall).searchParams.get('sort') : null;
64
+ return raw === null ? undefined : raw;
65
+ }
66
+
67
+ /** Run one input down both `find()` routes and assert they agree. */
68
+ function bothRoutes(name: string, $orderby: unknown, expected: string | undefined) {
69
+ for (const route of ['plain', 'expand'] as const) {
70
+ it(`${name} (${route} route)`, async () => {
71
+ expect(await sortOnWire($orderby, route)).toBe(expected);
72
+ });
73
+ }
74
+ }
75
+
76
+ describe('$orderby reaches the wire for every declared shape', () => {
77
+ beforeEach(() => clearSharedDiscoveryCache());
78
+
79
+ // The regression: ObjectGrid's own `"${field} ${order}"`.
80
+ bothRoutes('a bare "field order" string', 'name asc', 'name asc');
81
+ bothRoutes('a bare string with a descending key', 'created_at desc', 'created_at desc');
82
+ bothRoutes('a bare string already in `-field` shorthand', '-created_at', '-created_at');
83
+ bothRoutes('a bare multi-key string', 'status asc,-created_at', 'status asc,-created_at');
84
+
85
+ bothRoutes('a SortNode[]', [{ field: 'name', order: 'asc' }], 'name');
86
+ bothRoutes(
87
+ 'a SortNode[] with a descending key',
88
+ [{ field: 'status', order: 'asc' }, { field: 'created_at', order: 'desc' }],
89
+ 'status,-created_at',
90
+ );
91
+ bothRoutes('a string[]', ['name', '-age'], 'name,-age');
92
+ bothRoutes('a Record<field, direction>', { name: 'asc', age: 'desc' }, 'name,-age');
93
+
94
+ bothRoutes('no sort at all', undefined, undefined);
95
+ bothRoutes('an empty array', [], undefined);
96
+ bothRoutes('an empty object', {}, undefined);
97
+ bothRoutes('a whitespace-only string', ' ', undefined);
98
+ });
99
+
100
+ describe('serializeOrderBy', () => {
101
+ it('never enumerates a string as an object — the defect this replaced', () => {
102
+ // `Object.entries('name asc')` → [['0','n'],['1','a'],…]. The old fold
103
+ // reached that branch for every string input.
104
+ expect(serializeOrderBy('name asc')).toBe('name asc');
105
+ expect(serializeOrderBy('name asc')).not.toMatch(/^0,1,2/);
106
+ });
107
+
108
+ it('reads `order` case-insensitively', () => {
109
+ expect(serializeOrderBy([{ field: 'name', order: 'DESC' as any }])).toBe('-name');
110
+ });
111
+
112
+ it('defaults a missing direction to ascending', () => {
113
+ expect(serializeOrderBy([{ field: 'name' }])).toBe('name');
114
+ });
115
+ });
@@ -7,7 +7,11 @@
7
7
  */
8
8
 
9
9
  import { describe, it, expect, beforeEach, vi } from 'vitest';
10
- import { ObjectStackAdapter, clearSharedDiscoveryCache } from './index';
10
+ import {
11
+ ObjectStackAdapter,
12
+ clearSharedDiscoveryCache,
13
+ isAnalyticsNotInstalledError,
14
+ } from './index';
11
15
 
12
16
  /** A fetch mock that answers discovery + records the dataset-query POST. */
13
17
  function makeFetch(datasetResponse: { ok: boolean; status?: number; body: unknown }) {
@@ -80,4 +84,49 @@ describe('ObjectStackAdapter.queryDataset', () => {
80
84
  const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
81
85
  await expect(adapter.queryDataset(inlineDataset as any, selection)).rejects.toThrow(/relationship not declared/);
82
86
  });
87
+
88
+ // framework#3891 retired the degraded in-kernel analytics fallback, so a
89
+ // deployment without @objectstack/service-analytics answers 501 (REST route
90
+ // present, no service) or 404 (framework#4019 stopped mounting the routes).
91
+ // Neither is an authoring mistake — the caller gets a typed, readable error
92
+ // instead of `Dataset query failed: 501 Not Implemented — …`.
93
+ describe('analytics capability absent', () => {
94
+ it('maps 501 NOT_IMPLEMENTED to a readable ANALYTICS_NOT_INSTALLED error', async () => {
95
+ const { fetchImpl } = makeFetch({
96
+ ok: false,
97
+ status: 501,
98
+ body: {
99
+ code: 'NOT_IMPLEMENTED',
100
+ message: 'Analytics dataset query is not available on this deployment (no analytics service with queryDataset).',
101
+ },
102
+ });
103
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
104
+
105
+ const err = await adapter.queryDataset(inlineDataset as any, selection).catch((e) => e);
106
+
107
+ expect(isAnalyticsNotInstalledError(err)).toBe(true);
108
+ expect(err.code).toBe('ANALYTICS_NOT_INSTALLED');
109
+ expect(err.message).toContain('Analytics capability is not installed');
110
+ expect(err.message).toContain('@objectstack/service-analytics');
111
+ });
112
+
113
+ it('maps a 404 (routes not mounted) the same way', async () => {
114
+ const { fetchImpl } = makeFetch({ ok: false, status: 404, body: { error: 'Not found' } });
115
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
116
+
117
+ const err = await adapter.queryDataset(inlineDataset as any, selection).catch((e) => e);
118
+
119
+ expect(isAnalyticsNotInstalledError(err)).toBe(true);
120
+ });
121
+
122
+ it('leaves a real compile error alone (it is NOT a missing capability)', async () => {
123
+ const { fetchImpl } = makeFetch({ ok: false, status: 400, body: { message: 'relationship not declared in include' } });
124
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
125
+
126
+ const err = await adapter.queryDataset(inlineDataset as any, selection).catch((e) => e);
127
+
128
+ expect(isAnalyticsNotInstalledError(err)).toBe(false);
129
+ expect(String(err.message)).toContain('relationship not declared');
130
+ });
131
+ });
83
132
  });
@@ -0,0 +1,120 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
10
+ import { ObjectStackAdapter, clearSharedDiscoveryCache } from './index';
11
+
12
+ /** A fetch mock that answers discovery + records the global-search GET. */
13
+ function makeFetch(searchResponse: { ok: boolean; status?: number; body: unknown }) {
14
+ const calls: Array<{ url: string; init?: any }> = [];
15
+ const fetchImpl = vi.fn(async (url: any, init?: any) => {
16
+ const u = String(url);
17
+ calls.push({ url: u, init });
18
+ if (u.includes('/api/v1/discovery')) {
19
+ return { ok: true, status: 200, statusText: 'OK', json: async () => ({ success: true, data: { version: 'v1', routes: {} } }) } as any;
20
+ }
21
+ if (u.includes('/api/v1/search')) {
22
+ return {
23
+ ok: searchResponse.ok,
24
+ status: searchResponse.status ?? (searchResponse.ok ? 200 : 400),
25
+ statusText: searchResponse.ok ? 'OK' : 'Error',
26
+ json: async () => searchResponse.body,
27
+ } as any;
28
+ }
29
+ return { ok: true, status: 200, statusText: 'OK', json: async () => ({}) } as any;
30
+ });
31
+ return { fetchImpl, calls };
32
+ }
33
+
34
+ const WAYNE_HITS = {
35
+ query: 'Wayne',
36
+ hits: [
37
+ { object: 'crm_account', id: 'a1', title: 'Wayne Enterprises', snippet: 'Wayne Enterprises', record: { id: 'a1', account_number: 'ACC-000005' } },
38
+ { object: 'crm_opportunity', id: 'o1', title: 'Wayne Q1 Expansion', record: { id: 'o1' } },
39
+ ],
40
+ };
41
+
42
+ describe('ObjectStackAdapter.searchAll', () => {
43
+ beforeEach(() => clearSharedDiscoveryCache());
44
+
45
+ it('GETs /api/v1/search?q= and returns normalized ranked hits', async () => {
46
+ const { fetchImpl, calls } = makeFetch({ ok: true, body: WAYNE_HITS });
47
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', token: 'tok_123', autoReconnect: false, fetch: fetchImpl as any });
48
+
49
+ const result = await adapter.searchAll('Wayne');
50
+
51
+ expect(result.query).toBe('Wayne');
52
+ expect(result.hits.map((h) => `${h.object}:${h.id}`)).toEqual(['crm_account:a1', 'crm_opportunity:o1']);
53
+ expect(result.hits[0].title).toBe('Wayne Enterprises');
54
+ expect(result.hits[0].record).toEqual({ id: 'a1', account_number: 'ACC-000005' });
55
+
56
+ const get = calls.find((c) => c.url.includes('/api/v1/search'))!;
57
+ const url = new URL(get.url);
58
+ expect(url.pathname).toBe('/api/v1/search');
59
+ expect(url.searchParams.get('q')).toBe('Wayne');
60
+ expect(get.init.method).toBe('GET');
61
+ expect(get.init.headers.Authorization).toBe('Bearer tok_123');
62
+ });
63
+
64
+ it('trims the query and forwards limit + objects scoping', async () => {
65
+ const { fetchImpl, calls } = makeFetch({ ok: true, body: { query: 'Wayne', hits: [] } });
66
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
67
+
68
+ await adapter.searchAll(' Wayne ', { limit: 12, objects: ['crm_account', 'crm_opportunity'] });
69
+
70
+ const url = new URL(calls.find((c) => c.url.includes('/api/v1/search'))!.url);
71
+ expect(url.searchParams.get('q')).toBe('Wayne');
72
+ expect(url.searchParams.get('limit')).toBe('12');
73
+ expect(url.searchParams.get('objects')).toBe('crm_account,crm_opportunity');
74
+ });
75
+
76
+ it('short-circuits an empty query without hitting the network', async () => {
77
+ const { fetchImpl, calls } = makeFetch({ ok: true, body: { query: '', hits: [] } });
78
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
79
+
80
+ const result = await adapter.searchAll(' ');
81
+
82
+ expect(result).toEqual({ query: '', hits: [] });
83
+ expect(calls.some((c) => c.url.includes('/api/v1/search'))).toBe(false);
84
+ });
85
+
86
+ it('unwraps a { success, data } envelope', async () => {
87
+ const { fetchImpl } = makeFetch({ ok: true, body: { success: true, data: WAYNE_HITS } });
88
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
89
+ const result = await adapter.searchAll('Wayne');
90
+ expect(result.hits).toHaveLength(2);
91
+ });
92
+
93
+ it('treats a 404 (search plugin absent) as an empty result, not an error', async () => {
94
+ const { fetchImpl } = makeFetch({ ok: false, status: 404, body: { message: 'not found' } });
95
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
96
+ await expect(adapter.searchAll('Wayne')).resolves.toEqual({ query: 'Wayne', hits: [] });
97
+ });
98
+
99
+ it('throws with the server message on a non-404 error', async () => {
100
+ const { fetchImpl } = makeFetch({ ok: false, status: 500, body: { error: { message: 'index unavailable' } } });
101
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
102
+ await expect(adapter.searchAll('Wayne')).rejects.toThrow(/index unavailable/);
103
+ });
104
+
105
+ it('drops malformed hits (missing object or id)', async () => {
106
+ const { fetchImpl } = makeFetch({
107
+ ok: true,
108
+ body: { query: 'x', hits: [
109
+ { object: 'crm_account', id: 'a1', title: 'Keep' },
110
+ { id: 'no_object' },
111
+ { object: 'crm_lead' },
112
+ null,
113
+ { object: 'crm_contact', record: { id: 'c9' } },
114
+ ] },
115
+ });
116
+ const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any });
117
+ const result = await adapter.searchAll('x');
118
+ expect(result.hits.map((h) => `${h.object}:${h.id}`)).toEqual(['crm_account:a1', 'crm_contact:c9']);
119
+ });
120
+ });
@@ -144,7 +144,6 @@ describe('createObjectStackUserStateAdapter', () => {
144
144
  user_id: 'u1',
145
145
  key: 'ui.favorites',
146
146
  value: [{ id: 'a' }],
147
- updated_at: expect.any(String),
148
147
  });
149
148
  });
150
149
 
@@ -165,11 +164,35 @@ describe('createObjectStackUserStateAdapter', () => {
165
164
 
166
165
  expect(ds.update).toHaveBeenCalledWith('sys_user_preference', 'row-99', {
167
166
  value: [{ id: 'x' }],
168
- updated_at: expect.any(String),
169
167
  });
170
168
  expect(ds.create).not.toHaveBeenCalled();
171
169
  });
172
170
 
171
+ // #3794 — `updated_at` is server-managed. A caller-supplied value is
172
+ // stripped (framework #2948) and reported back as a dropped field, which
173
+ // the console turns into a "Some fields were not saved" toast. Stamping it
174
+ // here fired that warning on every recents/favorites write, about a field
175
+ // no user ever touched — noise on the exact surface that is supposed to
176
+ // tell a user their edit did not land.
177
+ it('never sends the server-managed updated_at column', async () => {
178
+ const ds = mockDataSource({
179
+ find: vi.fn().mockResolvedValue({ data: [] }) as any,
180
+ create: vi.fn().mockResolvedValue({ id: 'row-1' }) as any,
181
+ });
182
+ const adapter = createObjectStackUserStateAdapter({
183
+ dataSource: ds,
184
+ userId: 'u',
185
+ key: 'ui.recent',
186
+ });
187
+
188
+ await adapter.save([{ id: 'a' } as any]);
189
+ await adapter.save([{ id: 'b' } as any]);
190
+
191
+ for (const call of [...(ds.create as any).mock.calls, ...(ds.update as any).mock.calls]) {
192
+ expect(call[call.length - 1]).not.toHaveProperty('updated_at');
193
+ }
194
+ });
195
+
173
196
  it('uses the cached row id from a previous load on subsequent saves', async () => {
174
197
  const ds = mockDataSource({
175
198
  find: vi.fn().mockResolvedValue({
@@ -242,7 +265,6 @@ describe('createObjectStackUserStateAdapter', () => {
242
265
  expect(ds.create).toHaveBeenCalledTimes(1);
243
266
  expect(ds.update).toHaveBeenCalledWith('sys_user_preference', 'row-7', {
244
267
  value: [{ id: 'q' }],
245
- updated_at: expect.any(String),
246
268
  });
247
269
  });
248
270
 
@@ -270,7 +292,6 @@ describe('createObjectStackUserStateAdapter', () => {
270
292
  expect(ds.create).toHaveBeenCalledTimes(1);
271
293
  expect(ds.update).toHaveBeenCalledWith('sys_user_preference', 'row-1', {
272
294
  value: [{ id: 'a' }, { id: 'b' }],
273
- updated_at: expect.any(String),
274
295
  });
275
296
  });
276
297
 
package/src/userState.ts CHANGED
@@ -159,13 +159,18 @@ export function createObjectStackUserStateAdapter<T = unknown>(
159
159
  // (a concurrent writer created the row, or the backend dropped our find
160
160
  // predicate), recover by re-finding and updating rather than surfacing the
161
161
  // failed insert.
162
+ //
163
+ // Deliberately does NOT stamp `updated_at`: the column is server-managed, and
164
+ // a non-system caller's write to it is stripped (framework #2948) and reported
165
+ // back as a dropped field — which the console surfaces as a "Some fields were
166
+ // not saved" toast (#3431). Sending it made every recents/favorites write pop
167
+ // a scary warning about a field the user never touched, drowning the real
168
+ // signal the toast exists for (#3794). The server stamps it either way.
162
169
  const upsert = async (items: T[]): Promise<void> => {
163
- const now = new Date().toISOString();
164
-
165
170
  // Fast path: we already know the row id from a previous load/save.
166
171
  if (cachedRowId !== null) {
167
172
  try {
168
- await dataSource.update(resource, cachedRowId, { value: items, updated_at: now });
173
+ await dataSource.update(resource, cachedRowId, { value: items });
169
174
  return;
170
175
  } catch (updateError) {
171
176
  // Row may have been deleted server-side — fall through to find/insert.
@@ -177,7 +182,7 @@ export function createObjectStackUserStateAdapter<T = unknown>(
177
182
  const existing = await findExisting();
178
183
  if (existing && existing.id !== undefined && existing.id !== null) {
179
184
  cachedRowId = existing.id;
180
- await dataSource.update(resource, existing.id, { value: items, updated_at: now });
185
+ await dataSource.update(resource, existing.id, { value: items });
181
186
  return;
182
187
  }
183
188
 
@@ -186,7 +191,6 @@ export function createObjectStackUserStateAdapter<T = unknown>(
186
191
  user_id: userId,
187
192
  key,
188
193
  value: items,
189
- updated_at: now,
190
194
  });
191
195
  const newId = (created as UserPreferenceRecord | undefined)?.id;
192
196
  if (newId !== undefined && newId !== null) cachedRowId = newId;
@@ -196,7 +200,7 @@ export function createObjectStackUserStateAdapter<T = unknown>(
196
200
  const recovered = await findExisting();
197
201
  if (recovered && recovered.id !== undefined && recovered.id !== null) {
198
202
  cachedRowId = recovered.id;
199
- await dataSource.update(resource, recovered.id, { value: items, updated_at: now });
203
+ await dataSource.update(resource, recovered.id, { value: items });
200
204
  return;
201
205
  }
202
206
  throw createError;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect } from 'vitest';
10
+
11
+ import { normaliseClientError } from './index';
12
+ import { ValidationError } from './errors';
13
+
14
+ /**
15
+ * The server has always sent per-field rejection detail; the adapter used to
16
+ * hand callers the raw client error, so `fields[]` had no typed home and every
17
+ * form fell back to one undirected toast.
18
+ */
19
+ describe('normaliseClientError — VALIDATION_FAILED', () => {
20
+ // `@objectstack/rest` serves a thrown validation failure as 400 with `fields[]`
21
+ // verbatim; `@objectstack/client` sets `error.details` to the parsed body's
22
+ // `details` OR — as here, since the envelope has no such key — the whole body.
23
+ const upstream = () =>
24
+ Object.assign(new Error('Name is required; Stage is not a valid option'), {
25
+ code: 'VALIDATION_FAILED',
26
+ httpStatus: 400,
27
+ details: {
28
+ error: 'Name is required; Stage is not a valid option',
29
+ code: 'VALIDATION_FAILED',
30
+ fields: [
31
+ { field: 'name', code: 'required', message: 'Name is required' },
32
+ { field: 'stage', code: 'invalid_option', message: 'Stage is not a valid option' },
33
+ ],
34
+ object: 'crm_opportunity',
35
+ },
36
+ });
37
+
38
+ it('wraps it into a typed ValidationError', () => {
39
+ const normalised = normaliseClientError(upstream());
40
+ expect(normalised).toBeInstanceOf(ValidationError);
41
+ });
42
+
43
+ it('carries every field entry through', () => {
44
+ const normalised = normaliseClientError(upstream()) as ValidationError;
45
+ expect(normalised.validationErrors).toEqual([
46
+ { field: 'name', message: 'Name is required' },
47
+ { field: 'stage', message: 'Stage is not a valid option' },
48
+ ]);
49
+ });
50
+
51
+ it('keeps the server message verbatim — it names every field', () => {
52
+ const normalised = normaliseClientError(upstream()) as ValidationError;
53
+ expect(normalised.message).toBe('Name is required; Stage is not a valid option');
54
+ });
55
+
56
+ it('exposes the first offending field on `.field`', () => {
57
+ const normalised = normaliseClientError(upstream()) as ValidationError;
58
+ expect(normalised.field).toBe('name');
59
+ });
60
+
61
+ it('falls back to the machine code when an entry has no message', () => {
62
+ const err = Object.assign(new Error('Validation failed'), {
63
+ code: 'VALIDATION_FAILED',
64
+ details: { fields: [{ field: 'name', code: 'required' }] },
65
+ });
66
+ const normalised = normaliseClientError(err) as ValidationError;
67
+ expect(normalised.validationErrors).toEqual([{ field: 'name', message: 'required' }]);
68
+ });
69
+
70
+ it('drops entries with no field rather than inventing one', () => {
71
+ const err = Object.assign(new Error('Validation failed'), {
72
+ code: 'VALIDATION_FAILED',
73
+ details: { fields: [{ message: 'something is wrong' }] },
74
+ });
75
+ const normalised = normaliseClientError(err) as ValidationError;
76
+ expect(normalised.validationErrors).toEqual([]);
77
+ });
78
+
79
+ it('still wraps when the error carries `fields` directly (hand-rolled shape)', () => {
80
+ // The server duck-types on `code`/`name`, so a hook throwing the bare shape
81
+ // is served identically — the client must not be pickier than the server.
82
+ const err = Object.assign(new Error('nope'), {
83
+ name: 'ValidationError',
84
+ fields: [{ field: 'amount', message: 'Amount must be positive' }],
85
+ });
86
+ const normalised = normaliseClientError(err) as ValidationError;
87
+ expect(normalised.validationErrors).toEqual([{ field: 'amount', message: 'Amount must be positive' }]);
88
+ });
89
+
90
+ it('leaves an unrelated 400 untouched', () => {
91
+ const err = Object.assign(new Error('bad request'), { code: 'BAD_REQUEST', httpStatus: 400 });
92
+ expect(normaliseClientError(err)).toBe(err);
93
+ });
94
+ });