@oxyhq/services 22.4.2 → 22.5.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.
Files changed (29) hide show
  1. package/LICENSE +661 -21
  2. package/README.md +1 -1
  3. package/lib/commonjs/index.js +19 -0
  4. package/lib/commonjs/index.js.map +1 -1
  5. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js +4 -1
  6. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js.map +1 -1
  7. package/lib/commonjs/ui/hooks/queries/userCache.js +262 -0
  8. package/lib/commonjs/ui/hooks/queries/userCache.js.map +1 -0
  9. package/lib/module/index.js +6 -0
  10. package/lib/module/index.js.map +1 -1
  11. package/lib/module/ui/hooks/queries/useAccountQueries.js +4 -1
  12. package/lib/module/ui/hooks/queries/useAccountQueries.js.map +1 -1
  13. package/lib/module/ui/hooks/queries/userCache.js +258 -0
  14. package/lib/module/ui/hooks/queries/userCache.js.map +1 -0
  15. package/lib/typescript/commonjs/index.d.ts +2 -0
  16. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  17. package/lib/typescript/commonjs/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  18. package/lib/typescript/commonjs/ui/hooks/queries/userCache.d.ts +93 -0
  19. package/lib/typescript/commonjs/ui/hooks/queries/userCache.d.ts.map +1 -0
  20. package/lib/typescript/module/index.d.ts +2 -0
  21. package/lib/typescript/module/index.d.ts.map +1 -1
  22. package/lib/typescript/module/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  23. package/lib/typescript/module/ui/hooks/queries/userCache.d.ts +93 -0
  24. package/lib/typescript/module/ui/hooks/queries/userCache.d.ts.map +1 -0
  25. package/package.json +3 -3
  26. package/src/index.ts +8 -0
  27. package/src/ui/hooks/queries/__tests__/userCache.test.ts +332 -0
  28. package/src/ui/hooks/queries/useAccountQueries.ts +4 -1
  29. package/src/ui/hooks/queries/userCache.ts +285 -0
@@ -0,0 +1,332 @@
1
+ /**
2
+ * userCache — canonical merge-upsert into the SDK user query cache.
3
+ *
4
+ * Covers the merge semantics that eliminate the "sparse source strips a field an
5
+ * authoritative fetch stored" class of bug:
6
+ * - cold slot seeds the full object STALE (so react-query refetches)
7
+ * - a sparse user merged over a full entry KEEPS relationship / createdAt / etc.
8
+ * - null / empty / undefined incoming fields never strip or degrade
9
+ * - nested name / _count / relationship merge field-by-field
10
+ * - anti-degradation (empty username, 'Unknown user', null avatar)
11
+ * - both cache keys written; by-username is viewer-scoped and case-insensitive
12
+ * - batch upsert; viewer id defaults from the auth store
13
+ */
14
+
15
+ import { QueryClient } from '@tanstack/react-query';
16
+ import { upsertCachedUser, upsertCachedUsers } from '../userCache';
17
+ import type { CacheableUser } from '../userCache';
18
+ import { queryKeys } from '../queryKeys';
19
+ import { useAuthStore } from '../../../stores/authStore';
20
+
21
+ function makeClient(): QueryClient {
22
+ return new QueryClient({
23
+ defaultOptions: { queries: { retry: false } },
24
+ });
25
+ }
26
+
27
+ /** Read the by-id cache entry. */
28
+ function readById(qc: QueryClient, id: string): CacheableUser | undefined {
29
+ return qc.getQueryData<CacheableUser>(queryKeys.users.detail(id));
30
+ }
31
+
32
+ /** Read the viewer-scoped by-username cache entry. */
33
+ function readByUsername(qc: QueryClient, username: string, viewerId: string): CacheableUser | undefined {
34
+ return qc.getQueryData<CacheableUser>(queryKeys.users.byUsername(username, viewerId));
35
+ }
36
+
37
+ beforeEach(() => {
38
+ // Default to anonymous viewer unless a test sets one.
39
+ useAuthStore.setState({ user: null });
40
+ });
41
+
42
+ describe('upsertCachedUser — cold slot', () => {
43
+ it('seeds the full object and marks it STALE (updatedAt: 0) under both keys', () => {
44
+ const qc = makeClient();
45
+ const user: CacheableUser = {
46
+ id: 'u1',
47
+ username: 'Alice',
48
+ name: { displayName: 'Alice A' },
49
+ avatar: 'file_a',
50
+ createdAt: '2020-01-01T00:00:00Z',
51
+ _count: { followers: 10, following: 5 },
52
+ relationship: { isFollowing: true, followsYou: false },
53
+ };
54
+
55
+ upsertCachedUser(qc, user, 'viewer-1');
56
+
57
+ // by-id
58
+ expect(readById(qc, 'u1')).toMatchObject({ id: 'u1', username: 'Alice', avatar: 'file_a' });
59
+ expect(qc.getQueryState(queryKeys.users.detail('u1'))?.dataUpdatedAt).toBe(0);
60
+
61
+ // by-username (viewer-scoped, normalized to lowercase)
62
+ const uname = readByUsername(qc, 'alice', 'viewer-1');
63
+ expect(uname).toMatchObject({ id: 'u1', relationship: { isFollowing: true } });
64
+ expect(qc.getQueryState(queryKeys.users.byUsername('alice', 'viewer-1'))?.dataUpdatedAt).toBe(0);
65
+ });
66
+
67
+ it('resolves the id from _id when id is absent', () => {
68
+ const qc = makeClient();
69
+ upsertCachedUser(qc, { _id: 'mongo1', username: 'bob' }, '');
70
+ expect(readById(qc, 'mongo1')).toMatchObject({ id: 'mongo1', username: 'bob' });
71
+ });
72
+
73
+ it('is a no-op when no id can be resolved', () => {
74
+ const qc = makeClient();
75
+ upsertCachedUser(qc, { username: 'ghost' }, '');
76
+ expect(qc.getQueryCache().getAll()).toHaveLength(0);
77
+ });
78
+
79
+ it('normalizes a plain-string name into { displayName }', () => {
80
+ const qc = makeClient();
81
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', name: 'Alice Display' }, '');
82
+ expect(readById(qc, 'u1')?.name).toEqual({ displayName: 'Alice Display' });
83
+ });
84
+ });
85
+
86
+ describe('upsertCachedUser — merge over an existing full entry', () => {
87
+ const full: CacheableUser = {
88
+ id: 'u1',
89
+ username: 'alice',
90
+ name: { displayName: 'Alice A', first: 'Alice' },
91
+ avatar: 'file_a',
92
+ verified: true,
93
+ badges: ['og'],
94
+ createdAt: '2020-01-01T00:00:00Z',
95
+ _count: { followers: 10, following: 5 },
96
+ relationship: { isFollowing: true, followsYou: true },
97
+ };
98
+
99
+ function seedFull(qc: QueryClient): void {
100
+ // Represents an authoritative single-profile fetch already in cache (fresh).
101
+ qc.setQueryData(queryKeys.users.detail('u1'), full);
102
+ qc.setQueryData(queryKeys.users.byUsername('alice', 'viewer-1'), full);
103
+ }
104
+
105
+ it('keeps relationship + createdAt + _count when a SPARSE feed user is upserted', () => {
106
+ const qc = makeClient();
107
+ seedFull(qc);
108
+
109
+ // A feed author: no relationship, no createdAt, no counts.
110
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', name: { displayName: 'Alice A' }, avatar: 'file_a' }, 'viewer-1');
111
+
112
+ const byId = readById(qc, 'u1');
113
+ expect(byId?.createdAt).toBe('2020-01-01T00:00:00Z');
114
+ expect(byId?._count).toEqual({ followers: 10, following: 5 });
115
+ expect(byId?.verified).toBe(true);
116
+
117
+ const byName = readByUsername(qc, 'alice', 'viewer-1');
118
+ expect(byName?.relationship).toEqual({ isFollowing: true, followsYou: true });
119
+ expect(byName?.createdAt).toBe('2020-01-01T00:00:00Z');
120
+ });
121
+
122
+ it('does NOT mark an existing entry stale', () => {
123
+ const qc = makeClient();
124
+ seedFull(qc);
125
+ const before = qc.getQueryState(queryKeys.users.detail('u1'))?.dataUpdatedAt;
126
+ expect(before).not.toBe(0);
127
+
128
+ upsertCachedUser(qc, { id: 'u1', username: 'alice' }, 'viewer-1');
129
+
130
+ const after = qc.getQueryState(queryKeys.users.detail('u1'))?.dataUpdatedAt;
131
+ expect(after).toBe(before); // freshness preserved, not reset to 0
132
+ });
133
+
134
+ it('null / empty / undefined incoming fields never strip an existing field', () => {
135
+ const qc = makeClient();
136
+ seedFull(qc);
137
+
138
+ upsertCachedUser(
139
+ qc,
140
+ { id: 'u1', username: '', avatar: null, createdAt: '', _count: undefined, relationship: null },
141
+ 'viewer-1',
142
+ );
143
+
144
+ const byId = readById(qc, 'u1');
145
+ expect(byId?.username).toBe('alice');
146
+ expect(byId?.avatar).toBe('file_a');
147
+ expect(byId?.createdAt).toBe('2020-01-01T00:00:00Z');
148
+ expect(byId?._count).toEqual({ followers: 10, following: 5 });
149
+
150
+ const byName = readByUsername(qc, 'alice', 'viewer-1');
151
+ expect(byName?.relationship).toEqual({ isFollowing: true, followsYou: true });
152
+ });
153
+
154
+ it('updates the fields the incoming user DOES carry', () => {
155
+ const qc = makeClient();
156
+ seedFull(qc);
157
+
158
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', bio: 'new bio', avatar: 'file_new' }, 'viewer-1');
159
+
160
+ const byId = readById(qc, 'u1');
161
+ expect(byId?.bio).toBe('new bio');
162
+ expect(byId?.avatar).toBe('file_new');
163
+ // untouched fields survive
164
+ expect(byId?.createdAt).toBe('2020-01-01T00:00:00Z');
165
+ });
166
+
167
+ it('a defined boolean/number (verified:false, _count.followers:0) DOES override', () => {
168
+ const qc = makeClient();
169
+ seedFull(qc);
170
+
171
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', verified: false, _count: { followers: 0 } }, 'viewer-1');
172
+
173
+ const byId = readById(qc, 'u1');
174
+ expect(byId?.verified).toBe(false);
175
+ // partial _count overrides only followers; following kept from existing
176
+ expect(byId?._count).toEqual({ followers: 0, following: 5 });
177
+ });
178
+ });
179
+
180
+ describe('upsertCachedUser — nested merge', () => {
181
+ it('a partial name never replaces a fuller name; displayName upgrades', () => {
182
+ const qc = makeClient();
183
+ qc.setQueryData(queryKeys.users.detail('u1'), {
184
+ id: 'u1',
185
+ username: 'alice',
186
+ name: { first: 'Alice', last: 'Adams', displayName: 'Alice A' },
187
+ });
188
+
189
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', name: { displayName: 'Alice Adams' } }, '');
190
+
191
+ expect(readById(qc, 'u1')?.name).toEqual({
192
+ first: 'Alice',
193
+ last: 'Adams',
194
+ displayName: 'Alice Adams',
195
+ });
196
+ });
197
+
198
+ it('a partial relationship never nulls out the other field', () => {
199
+ const qc = makeClient();
200
+ qc.setQueryData(queryKeys.users.byUsername('alice', 'v1'), {
201
+ id: 'u1',
202
+ username: 'alice',
203
+ relationship: { isFollowing: true, followsYou: true },
204
+ });
205
+
206
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', relationship: { followsYou: false } }, 'v1');
207
+
208
+ expect(readByUsername(qc, 'alice', 'v1')?.relationship).toEqual({ isFollowing: true, followsYou: false });
209
+ });
210
+ });
211
+
212
+ describe('upsertCachedUser — anti-degradation', () => {
213
+ it('never overwrites a good displayName with the "Unknown user" sentinel', () => {
214
+ const qc = makeClient();
215
+ qc.setQueryData(queryKeys.users.detail('u1'), { id: 'u1', username: 'alice', name: { displayName: 'Alice A' } });
216
+
217
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', name: { displayName: 'Unknown user' } }, '');
218
+
219
+ expect(readById(qc, 'u1')?.name).toEqual({ displayName: 'Alice A' });
220
+ });
221
+
222
+ it('never overwrites a good username with an empty one', () => {
223
+ const qc = makeClient();
224
+ qc.setQueryData(queryKeys.users.detail('u1'), { id: 'u1', username: 'alice' });
225
+
226
+ upsertCachedUser(qc, { id: 'u1', username: ' ' }, '');
227
+
228
+ expect(readById(qc, 'u1')?.username).toBe('alice');
229
+ });
230
+
231
+ it('never nulls out a good avatar', () => {
232
+ const qc = makeClient();
233
+ qc.setQueryData(queryKeys.users.detail('u1'), { id: 'u1', username: 'alice', avatar: 'file_a' });
234
+
235
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', avatar: null }, '');
236
+
237
+ expect(readById(qc, 'u1')?.avatar).toBe('file_a');
238
+ });
239
+
240
+ it('upgrades a degraded existing displayName when a real one arrives', () => {
241
+ const qc = makeClient();
242
+ qc.setQueryData(queryKeys.users.detail('u1'), { id: 'u1', username: 'alice', name: { displayName: 'Unknown user' } });
243
+
244
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', name: { displayName: 'Alice A' } }, '');
245
+
246
+ expect(readById(qc, 'u1')?.name).toEqual({ displayName: 'Alice A' });
247
+ });
248
+ });
249
+
250
+ describe('upsertCachedUser — keys & viewer scoping', () => {
251
+ it('writes ONLY the by-id key when no username is present', () => {
252
+ const qc = makeClient();
253
+ upsertCachedUser(qc, { id: 'u1' }, 'v1');
254
+ expect(readById(qc, 'u1')).toBeDefined();
255
+ // no username-derived entries
256
+ const usernameEntries = qc
257
+ .getQueryCache()
258
+ .getAll()
259
+ .filter((q) => (q.queryKey as unknown[]).includes('username'));
260
+ expect(usernameEntries).toHaveLength(0);
261
+ });
262
+
263
+ it('viewer-scopes the by-username key (different viewers -> different entries)', () => {
264
+ const qc = makeClient();
265
+ upsertCachedUser(qc, { id: 'u1', username: 'alice', relationship: { isFollowing: true, followsYou: false } }, 'viewerA');
266
+
267
+ expect(readByUsername(qc, 'alice', 'viewerA')).toBeDefined();
268
+ expect(readByUsername(qc, 'alice', 'viewerB')).toBeUndefined();
269
+ });
270
+
271
+ it('is case-insensitive on username (byUsername normalization)', () => {
272
+ const qc = makeClient();
273
+ upsertCachedUser(qc, { id: 'u1', username: 'AlIcE' }, 'v1');
274
+ // read with any casing resolves the same entry
275
+ expect(readByUsername(qc, 'alice', 'v1')).toMatchObject({ id: 'u1' });
276
+ expect(readByUsername(qc, 'ALICE', 'v1')).toMatchObject({ id: 'u1' });
277
+ });
278
+
279
+ it('defaults the viewer id from the auth store when omitted', () => {
280
+ const qc = makeClient();
281
+ useAuthStore.setState({ user: { id: 'store-viewer', username: 'me', name: { displayName: 'Me' }, publicKey: 'pk' } });
282
+
283
+ upsertCachedUser(qc, { id: 'u1', username: 'alice' });
284
+
285
+ expect(readByUsername(qc, 'alice', 'store-viewer')).toMatchObject({ id: 'u1' });
286
+ expect(readByUsername(qc, 'alice', '')).toBeUndefined();
287
+ });
288
+ });
289
+
290
+ describe('upsertCachedUsers — batch', () => {
291
+ it('upserts every user under both keys', () => {
292
+ const qc = makeClient();
293
+ upsertCachedUsers(
294
+ qc,
295
+ [
296
+ { id: 'u1', username: 'alice' },
297
+ { id: 'u2', username: 'bob' },
298
+ ],
299
+ 'v1',
300
+ );
301
+
302
+ expect(readById(qc, 'u1')).toMatchObject({ username: 'alice' });
303
+ expect(readById(qc, 'u2')).toMatchObject({ username: 'bob' });
304
+ expect(readByUsername(qc, 'alice', 'v1')).toBeDefined();
305
+ expect(readByUsername(qc, 'bob', 'v1')).toBeDefined();
306
+ });
307
+
308
+ it('accumulates fields when the same user appears twice with different slices', () => {
309
+ const qc = makeClient();
310
+ // Seed a fresh (non-cold) authoritative entry first so both batch items merge.
311
+ qc.setQueryData(queryKeys.users.detail('u1'), { id: 'u1', username: 'alice' });
312
+ upsertCachedUsers(
313
+ qc,
314
+ [
315
+ { id: 'u1', username: 'alice', avatar: 'file_a' },
316
+ { id: 'u1', username: 'alice', bio: 'hello' },
317
+ ],
318
+ 'v1',
319
+ );
320
+
321
+ const byId = readById(qc, 'u1');
322
+ expect(byId?.avatar).toBe('file_a');
323
+ expect(byId?.bio).toBe('hello');
324
+ });
325
+
326
+ it('ignores null / empty input', () => {
327
+ const qc = makeClient();
328
+ upsertCachedUsers(qc, null, 'v1');
329
+ upsertCachedUsers(qc, [], 'v1');
330
+ expect(qc.getQueryCache().getAll()).toHaveLength(0);
331
+ });
332
+ });
@@ -200,7 +200,10 @@ export const useUserByUsername = (username: string | null, options?: { enabled?:
200
200
  if (!username) {
201
201
  throw new Error('Username is required');
202
202
  }
203
- return await oxyServices.getProfileByUsername(username);
203
+ // Match queryKeys.users.byUsername normalization so the cache key and
204
+ // the API request agree (case-insensitive local handles).
205
+ const normalizedUsername = username.trim().toLowerCase();
206
+ return await oxyServices.getProfileByUsername(normalizedUsername);
204
207
  },
205
208
  enabled: (options?.enabled !== false) && !!username,
206
209
  staleTime: 5 * 60 * 1000,
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Canonical user-cache UPSERT for the Oxy React Query cache.
3
+ *
4
+ * The problem this solves: many places across an app write a user object into
5
+ * the React Query cache and REPLACE the existing entry — profile fetch, feed /
6
+ * post hydration, search, notifications, lists. Each of those sources carries a
7
+ * DIFFERENT (often sparse) slice of the user: a feed author has no viewer
8
+ * `relationship`, a search hit has no `createdAt`, a notification actor has no
9
+ * `_count`. A plain `setQueryData(key, sparseUser)` therefore STRIPS whatever
10
+ * fields the authoritative single-profile fetch had already stored — the
11
+ * "Follows you tag vanishes when the feed loads" / "counts flash to zero" class
12
+ * of bug.
13
+ *
14
+ * The fix (owned here, in the SDK): ONE canonical upsert that MERGES. It writes
15
+ * under BOTH keys the SDK's user hooks read from:
16
+ * - by-id: `queryKeys.users.detail(id)` (read by `useUserById`)
17
+ * - by-username: `queryKeys.users.byUsername(username, viewerId)` (viewer-scoped;
18
+ * read by `useUserByUsername`, carries the viewer `relationship`)
19
+ *
20
+ * Merge semantics (per key):
21
+ * - No existing entry -> seed the (normalized) incoming object and mark it
22
+ * STALE (`updatedAt: 0`) so react-query refetches the full authoritative
23
+ * profile (viewer-relative `relationship`, counts, `createdAt`, …). Instant
24
+ * first paint, then the real fetch.
25
+ * - Existing entry -> `{ ...existing, ...pickMeaningful(incoming) }`: only
26
+ * the DEFINED, non-empty fields of `incoming` win; every other field is kept
27
+ * from `existing`. A sparse source can never NULL-out or STRIP a field the
28
+ * authoritative fetch set. The entry's freshness is left untouched (never
29
+ * marked stale — it is already managed).
30
+ * - Nested objects (`name`, `_count`, `relationship`) merge field-by-field, so
31
+ * a partial `name`/`_count`/`relationship` never replaces a fuller one.
32
+ * - Anti-degradation: a good `username` / `name.displayName` / `avatar` is
33
+ * never overwritten by a degraded/empty one (empty username, the
34
+ * `'Unknown user'` ghost-author sentinel, `null` avatar).
35
+ *
36
+ * It is a cache write only — zero network, one `setQueryData` per key.
37
+ */
38
+
39
+ import type { QueryClient } from '@tanstack/react-query';
40
+ import type { UserNameResponse } from '@oxyhq/contracts';
41
+ import { queryKeys } from './queryKeys';
42
+ import { useAuthStore } from '../../stores/authStore';
43
+
44
+ /**
45
+ * A user-shaped object that can be upserted into the cache. Intentionally
46
+ * permissive: it covers the SDK `User` PLUS the looser actor objects embedded on
47
+ * posts / notifications / lists, where `name` may be a plain string and the id
48
+ * may arrive as Mongo `_id`. Every field is optional — a sparse feed author is a
49
+ * valid `CacheableUser`. The index signature lets any additional `User` field
50
+ * pass through untouched (so the upsert never has to know the full DTO shape).
51
+ */
52
+ export interface CacheableUser {
53
+ id?: string;
54
+ /** Some sources (post/notification actors) carry the id as Mongo `_id`. */
55
+ _id?: string;
56
+ username?: string;
57
+ /**
58
+ * Canonical structured name (`UserNameResponse`) OR a plain display string on
59
+ * the looser actor objects. Normalized to the object shape on write.
60
+ */
61
+ name?: string | UserNameResponse;
62
+ /** Avatar file id. `null`/`''` are treated as "no avatar" (never degrade). */
63
+ avatar?: string | null;
64
+ /** Social counts. A partial `_count` never replaces a fuller one. */
65
+ _count?: { followers?: number; following?: number } | null;
66
+ /**
67
+ * Viewer-relative follow relationship. Present ONLY on an authenticated
68
+ * single-profile fetch; `null`/absent for anon/self/bulk/feed. Never stripped
69
+ * from an existing entry by a source that lacks it.
70
+ */
71
+ relationship?: { isFollowing?: boolean; followsYou?: boolean } | null;
72
+ [key: string]: unknown;
73
+ }
74
+
75
+ /** The degraded display-name sentinel (ghost-author rule). */
76
+ const DEGRADED_DISPLAY_NAME = 'Unknown user';
77
+
78
+ /** A cache entry always carries a resolved string `id`. */
79
+ type CachedUser = CacheableUser & { id: string; name?: UserNameResponse };
80
+
81
+ /**
82
+ * Whether a value is "meaningful" — i.e. it should override an existing field.
83
+ * Drops `undefined` / `null` / empty-or-whitespace strings so a sparse source
84
+ * can never strip a field. `false`, `0` and other falsy-but-defined values ARE
85
+ * meaningful (a real `verified: false` or `_count.followers: 0`).
86
+ */
87
+ function isMeaningful(value: unknown): boolean {
88
+ if (value === undefined || value === null) return false;
89
+ if (typeof value === 'string') return value.trim() !== '';
90
+ return true;
91
+ }
92
+
93
+ /** A display name is meaningful only when non-empty AND not the degraded sentinel. */
94
+ function isMeaningfulDisplayName(value: unknown): value is string {
95
+ return typeof value === 'string' && value.trim() !== '' && value !== DEGRADED_DISPLAY_NAME;
96
+ }
97
+
98
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
99
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
100
+ }
101
+
102
+ /** Normalize the polymorphic `name` (string | object | nullish) to the canonical object shape. */
103
+ function normalizeName(name: CacheableUser['name']): UserNameResponse | undefined {
104
+ if (name === undefined || name === null) return undefined;
105
+ if (typeof name === 'string') {
106
+ const trimmed = name.trim();
107
+ return trimmed ? { displayName: trimmed } : undefined;
108
+ }
109
+ return name;
110
+ }
111
+
112
+ /**
113
+ * Coerce a user-shaped object to a cache entry: resolve the id from
114
+ * `id ?? _id ?? fallbackId` and normalize `name` to the canonical object shape
115
+ * (the polymorphic `string` name is dropped from the spread and re-set as an
116
+ * object so the cache never holds a bare-string name).
117
+ */
118
+ function toCachedUser(user: CacheableUser, fallbackId: string): CachedUser {
119
+ const { name: rawName, ...rest } = user;
120
+ const id = String(user.id ?? user._id ?? fallbackId);
121
+ const name = normalizeName(rawName);
122
+ const normalized: CachedUser = { ...rest, id };
123
+ if (name !== undefined) normalized.name = name;
124
+ return normalized;
125
+ }
126
+
127
+ /**
128
+ * Normalize an incoming (possibly partial) user to a cache entry. Returns `null`
129
+ * when no id can be resolved (nothing to key on).
130
+ */
131
+ function normalizeIncoming(user: CacheableUser): CachedUser | null {
132
+ const cached = toCachedUser(user, '');
133
+ return cached.id ? cached : null;
134
+ }
135
+
136
+ /** Merge two `name` objects field-by-field, with anti-degradation on `displayName`. */
137
+ function mergeName(
138
+ existing: UserNameResponse | undefined,
139
+ incoming: UserNameResponse | undefined,
140
+ ): UserNameResponse | undefined {
141
+ if (incoming === undefined) return existing;
142
+ if (existing === undefined) return incoming;
143
+ const merged: UserNameResponse = { ...existing };
144
+ for (const [key, value] of Object.entries(incoming)) {
145
+ if (key === 'displayName') continue;
146
+ if (isMeaningful(value)) merged[key] = value;
147
+ }
148
+ // Never let an empty / `'Unknown user'` displayName overwrite a real one.
149
+ if (isMeaningfulDisplayName(incoming.displayName)) {
150
+ merged.displayName = incoming.displayName;
151
+ }
152
+ return merged;
153
+ }
154
+
155
+ /** Merge `_count` field-by-field so a partial count never replaces a fuller one. */
156
+ function mergeCount(
157
+ existing: CacheableUser['_count'],
158
+ incoming: CacheableUser['_count'],
159
+ ): CacheableUser['_count'] {
160
+ if (!isPlainObject(incoming)) return existing;
161
+ const merged: { followers?: number; following?: number } = { ...(isPlainObject(existing) ? existing : {}) };
162
+ if (typeof incoming.followers === 'number') merged.followers = incoming.followers;
163
+ if (typeof incoming.following === 'number') merged.following = incoming.following;
164
+ return merged;
165
+ }
166
+
167
+ /**
168
+ * Merge `relationship`. A source without a relationship (feed/list/notification,
169
+ * or an anon/self/bulk `null`) must NEVER strip an existing viewer relationship.
170
+ */
171
+ function mergeRelationship(
172
+ existing: CacheableUser['relationship'],
173
+ incoming: CacheableUser['relationship'],
174
+ ): CacheableUser['relationship'] {
175
+ if (!isPlainObject(incoming)) return existing;
176
+ const merged: { isFollowing?: boolean; followsYou?: boolean } = {
177
+ ...(isPlainObject(existing) ? existing : {}),
178
+ };
179
+ if (typeof incoming.isFollowing === 'boolean') merged.isFollowing = incoming.isFollowing;
180
+ if (typeof incoming.followsYou === 'boolean') merged.followsYou = incoming.followsYou;
181
+ return merged;
182
+ }
183
+
184
+ /**
185
+ * Merge a (normalized) incoming user over an existing cache entry: keep every
186
+ * existing field, override only with the meaningful fields of `incoming`.
187
+ */
188
+ function mergeUsers(existing: CachedUser, incoming: CachedUser): CachedUser {
189
+ const merged: CachedUser = { ...existing };
190
+ for (const [key, value] of Object.entries(incoming)) {
191
+ if (key === 'name' || key === '_count' || key === 'relationship') continue;
192
+ if (key === 'id') {
193
+ merged.id = incoming.id;
194
+ continue;
195
+ }
196
+ if (isMeaningful(value)) merged[key] = value;
197
+ }
198
+ const name = mergeName(existing.name, incoming.name);
199
+ if (name !== undefined) merged.name = name;
200
+ const count = mergeCount(existing._count, incoming._count);
201
+ if (count !== undefined) merged._count = count;
202
+ const relationship = mergeRelationship(existing.relationship, incoming.relationship);
203
+ if (relationship !== undefined) merged.relationship = relationship;
204
+ return merged;
205
+ }
206
+
207
+ /** Merge-upsert a normalized user into one cache key (see module docs for semantics). */
208
+ function upsertOneKey(
209
+ queryClient: QueryClient,
210
+ key: readonly unknown[],
211
+ incoming: CachedUser,
212
+ ): void {
213
+ const existing = queryClient.getQueryData<CacheableUser>(key);
214
+ if (existing === undefined) {
215
+ // Cold slot: seed the full incoming object, STALE, so react-query refetches
216
+ // the full authoritative profile (relationship, counts, createdAt, …).
217
+ queryClient.setQueryData<CachedUser>(key, incoming, { updatedAt: 0 });
218
+ return;
219
+ }
220
+ // Existing entry: merge and leave its freshness lifecycle untouched. The
221
+ // existing entry is keyed by `incoming.id`, so use it as the fallback id.
222
+ const merged = mergeUsers(toCachedUser(existing, incoming.id), incoming);
223
+ const dataUpdatedAt = queryClient.getQueryState(key)?.dataUpdatedAt ?? 0;
224
+ queryClient.setQueryData<CachedUser>(key, merged, { updatedAt: dataUpdatedAt });
225
+ }
226
+
227
+ /**
228
+ * Resolve the active viewer id. The by-username cache key is viewer-scoped; the
229
+ * seed must land on the exact key `useUserByUsername` reads. When a caller does
230
+ * not pass `viewerId`, read it from the auth store — the same store behind the
231
+ * hook's `useOxy().user?.id`, so seed and read stay in lockstep. An explicit
232
+ * empty string is honoured (anonymous scope).
233
+ */
234
+ function resolveViewerId(viewerId?: string): string {
235
+ return viewerId ?? useAuthStore.getState().user?.id ?? '';
236
+ }
237
+
238
+ /**
239
+ * Merge-upsert a (possibly partial) user into the SDK's user query cache under
240
+ * both the by-id key and, when a username is present, the viewer-scoped
241
+ * by-username key.
242
+ *
243
+ * @param queryClient The app's React Query client.
244
+ * @param user A `User`-shaped object (may be sparse).
245
+ * @param viewerId The active viewer id for the by-username key. Defaults to
246
+ * the current auth-store user id.
247
+ */
248
+ export function upsertCachedUser(
249
+ queryClient: QueryClient,
250
+ user: CacheableUser,
251
+ viewerId?: string,
252
+ ): void {
253
+ const incoming = normalizeIncoming(user);
254
+ if (!incoming) return;
255
+
256
+ // By-id identity entry (read by `useUserById`). Not viewer-scoped.
257
+ upsertOneKey(queryClient, queryKeys.users.detail(incoming.id), incoming);
258
+
259
+ const username = incoming.username;
260
+ if (typeof username === 'string' && username.trim() !== '') {
261
+ // By-username entry (read by `useUserByUsername`). Viewer-scoped because the
262
+ // authenticated single-profile fetch embeds the viewer `relationship`. Build
263
+ // the key through the SAME helper the hook uses so username normalization
264
+ // (`trim().toLowerCase()`) matches byte-for-byte.
265
+ const key = queryKeys.users.byUsername(username, resolveViewerId(viewerId));
266
+ upsertOneKey(queryClient, key, incoming);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Batch merge-upsert many users at once (for a feed / list / search response).
272
+ * Resolves the viewer id once and upserts each user cumulatively — a user that
273
+ * appears twice merges both slices into the single cache entry.
274
+ */
275
+ export function upsertCachedUsers(
276
+ queryClient: QueryClient,
277
+ users: readonly CacheableUser[] | null | undefined,
278
+ viewerId?: string,
279
+ ): void {
280
+ if (!Array.isArray(users) || users.length === 0) return;
281
+ const resolvedViewerId = resolveViewerId(viewerId);
282
+ for (const user of users) {
283
+ if (user) upsertCachedUser(queryClient, user, resolvedViewerId);
284
+ }
285
+ }