@sanity/sdk 3.18.0 → 3.19.0-next.20261201202025
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.
- package/dist/_exports/_internal.d.ts +2 -2
- package/dist/_exports/_internal.js +1 -1
- package/dist/_exports/dashboard.d.ts +2 -2
- package/dist/{applications-2W_CezBF.d.ts → applications-C_AvsbsG.d.ts} +9 -2
- package/dist/{applications-2W_CezBF.d.ts.map → applications-C_AvsbsG.d.ts.map} +1 -1
- package/dist/{bus-DrItUMwC.d.ts → bus-COH83GrU.d.ts} +2 -2
- package/dist/{bus-DrItUMwC.d.ts.map → bus-COH83GrU.d.ts.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +144 -1239
- package/dist/index.js.map +1 -1
- package/dist/{version-CnBDPBaC.js → version-DCewYvQI.js} +1205 -7
- package/dist/version-DCewYvQI.js.map +1 -0
- package/package.json +1 -1
- package/src/users/readUsersByIds.ts +290 -0
- package/src/users/types.ts +6 -0
- package/src/users/users.test.ts +427 -2
- package/src/users/users.ts +13 -33
- package/src/users/usersConstants.ts +7 -0
- package/src/users/usersStore.ts +6 -25
- package/dist/version-CnBDPBaC.js.map +0 -1
package/src/users/users.test.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {type SanityClient} from '@sanity/client'
|
|
2
|
-
import {of} from 'rxjs'
|
|
1
|
+
import {ClientError, type SanityClient, ServerError} from '@sanity/client'
|
|
2
|
+
import {of, Subject, throwError} from 'rxjs'
|
|
3
3
|
import {afterEach, beforeEach, describe, expect, it, onTestFinished, vi} from 'vitest'
|
|
4
4
|
|
|
5
|
+
import {setAuthToken} from '../auth/authStore'
|
|
5
6
|
import {getClientState} from '../client/clientStore'
|
|
6
7
|
import {uninstallTestMessageBus} from '../dashboard/messageBus/__fixtures__/uninstallTestMessageBus'
|
|
7
8
|
import {installMessageBus} from '../dashboard/messageBus/bus'
|
|
@@ -9,6 +10,7 @@ import {createSanityInstance, type SanityInstance} from '../store/createSanityIn
|
|
|
9
10
|
import {type StateSource} from '../store/createStateSourceAction'
|
|
10
11
|
import {type SanityUser} from './types'
|
|
11
12
|
import {users} from './users'
|
|
13
|
+
import {DISALLOWED_USER_ID_TTL_MS, MAX_CONCURRENT_USER_ID_CHUNKS} from './usersConstants'
|
|
12
14
|
|
|
13
15
|
vi.mock('../client/clientStore')
|
|
14
16
|
|
|
@@ -239,3 +241,426 @@ describe('users with a userId', () => {
|
|
|
239
241
|
expect(request).not.toHaveBeenCalled()
|
|
240
242
|
})
|
|
241
243
|
})
|
|
244
|
+
|
|
245
|
+
describe('users with userIds', () => {
|
|
246
|
+
let instance: SanityInstance
|
|
247
|
+
const request = vi.fn()
|
|
248
|
+
|
|
249
|
+
const legacyUser = (
|
|
250
|
+
id: string,
|
|
251
|
+
overrides: Partial<{
|
|
252
|
+
sanityUserId: string
|
|
253
|
+
displayName: string
|
|
254
|
+
email: string | null
|
|
255
|
+
provider: string | null
|
|
256
|
+
imageUrl: string | null
|
|
257
|
+
}> = {},
|
|
258
|
+
) => ({
|
|
259
|
+
id,
|
|
260
|
+
displayName: `User ${id}`,
|
|
261
|
+
email: `${id}@example.com`,
|
|
262
|
+
familyName: null,
|
|
263
|
+
givenName: null,
|
|
264
|
+
middleName: null,
|
|
265
|
+
imageUrl: null,
|
|
266
|
+
provider: 'google',
|
|
267
|
+
createdAt: '2023-01-01T00:00:00Z',
|
|
268
|
+
updatedAt: '2023-01-01T00:00:00Z',
|
|
269
|
+
isCurrentUser: false,
|
|
270
|
+
...overrides,
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
const clientError = (statusCode: number, message: string) =>
|
|
274
|
+
new ClientError({statusCode, headers: {}, body: {statusCode, error: 'Error', message}})
|
|
275
|
+
|
|
276
|
+
beforeEach(() => {
|
|
277
|
+
instance = createSanityInstance({projectId: 'test', dataset: 'test'})
|
|
278
|
+
request.mockReset()
|
|
279
|
+
vi.mocked(getClientState).mockClear()
|
|
280
|
+
vi.mocked(getClientState).mockReturnValue({
|
|
281
|
+
observable: of({observable: {request}} as unknown as SanityClient),
|
|
282
|
+
} as StateSource<SanityClient>)
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
afterEach(() => instance.dispose())
|
|
286
|
+
|
|
287
|
+
it('fetches multiple mixed project, global, and external IDs in a single project-scoped request', async () => {
|
|
288
|
+
request.mockReturnValue(
|
|
289
|
+
of([
|
|
290
|
+
legacyUser('e-ext1', {provider: null}),
|
|
291
|
+
legacyUser('gGlobal1'),
|
|
292
|
+
legacyUser('pProj1', {sanityUserId: 'gLinked1'}),
|
|
293
|
+
]),
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
const pages = await users.resolveState(instance, {
|
|
297
|
+
userIds: ['pProj1', 'gGlobal1', 'e-ext1'],
|
|
298
|
+
projectId: 'project1',
|
|
299
|
+
})
|
|
300
|
+
|
|
301
|
+
expect(getClientState).toHaveBeenCalledWith(
|
|
302
|
+
instance,
|
|
303
|
+
expect.objectContaining({projectId: 'project1', apiVersion: '2025-07-18'}),
|
|
304
|
+
)
|
|
305
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
306
|
+
method: 'GET',
|
|
307
|
+
url: '/users/e-ext1,gGlobal1,pProj1',
|
|
308
|
+
tag: 'users.get',
|
|
309
|
+
})
|
|
310
|
+
expect(pages).toEqual([
|
|
311
|
+
{
|
|
312
|
+
data: [
|
|
313
|
+
expect.objectContaining({
|
|
314
|
+
sanityUserId: 'e-ext1',
|
|
315
|
+
profile: expect.objectContaining({id: 'e-ext1', provider: ''}),
|
|
316
|
+
memberships: [],
|
|
317
|
+
}),
|
|
318
|
+
expect.objectContaining({
|
|
319
|
+
sanityUserId: 'gGlobal1',
|
|
320
|
+
profile: expect.objectContaining({id: 'gGlobal1'}),
|
|
321
|
+
memberships: [],
|
|
322
|
+
}),
|
|
323
|
+
expect.objectContaining({
|
|
324
|
+
sanityUserId: 'gLinked1',
|
|
325
|
+
profile: expect.objectContaining({id: 'pProj1'}),
|
|
326
|
+
memberships: [],
|
|
327
|
+
}),
|
|
328
|
+
],
|
|
329
|
+
totalCount: 3,
|
|
330
|
+
nextCursor: null,
|
|
331
|
+
},
|
|
332
|
+
])
|
|
333
|
+
})
|
|
334
|
+
|
|
335
|
+
it('handles a single user ID when the legacy API returns an object instead of an array', async () => {
|
|
336
|
+
request.mockReturnValue(of(legacyUser('pOnly1', {sanityUserId: 'gOnly1', email: null})))
|
|
337
|
+
|
|
338
|
+
const pages = await users.resolveState(instance, {userIds: ['pOnly1']})
|
|
339
|
+
|
|
340
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
341
|
+
method: 'GET',
|
|
342
|
+
url: '/users/pOnly1',
|
|
343
|
+
tag: 'users.get',
|
|
344
|
+
})
|
|
345
|
+
expect(pages[0]?.data).toEqual([
|
|
346
|
+
expect.objectContaining({
|
|
347
|
+
sanityUserId: 'gOnly1',
|
|
348
|
+
profile: expect.objectContaining({id: 'pOnly1', email: ''}),
|
|
349
|
+
}),
|
|
350
|
+
])
|
|
351
|
+
expect(pages[0]?.totalCount).toBe(1)
|
|
352
|
+
expect(pages[0]?.nextCursor).toBeNull()
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
it('uses the global client for organization-scoped or project-less instances and omits e* IDs', async () => {
|
|
356
|
+
instance.dispose()
|
|
357
|
+
instance = createSanityInstance({})
|
|
358
|
+
request.mockReturnValue(of([legacyUser('g1'), legacyUser('p1', {sanityUserId: 'g2'})]))
|
|
359
|
+
|
|
360
|
+
await users.resolveState(instance, {userIds: ['p1', 'g1', 'e-external']})
|
|
361
|
+
|
|
362
|
+
expect(getClientState).toHaveBeenCalledWith(
|
|
363
|
+
instance,
|
|
364
|
+
expect.objectContaining({scope: 'global', apiVersion: '2025-07-18'}),
|
|
365
|
+
)
|
|
366
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
367
|
+
method: 'GET',
|
|
368
|
+
url: '/users/g1,p1',
|
|
369
|
+
tag: 'users.get',
|
|
370
|
+
})
|
|
371
|
+
})
|
|
372
|
+
|
|
373
|
+
it('deduplicates, filters invalid IDs, and shares the cache regardless of order', async () => {
|
|
374
|
+
request.mockReturnValue(of([legacyUser('g1'), legacyUser('p1', {sanityUserId: 'g2'})]))
|
|
375
|
+
|
|
376
|
+
await users.resolveState(instance, {userIds: ['p1', '<system>', 'g1', 'p1', 'invalid!']})
|
|
377
|
+
await users.resolveState(instance, {userIds: ['g1', 'p1']})
|
|
378
|
+
|
|
379
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
380
|
+
method: 'GET',
|
|
381
|
+
url: '/users/g1,p1',
|
|
382
|
+
tag: 'users.get',
|
|
383
|
+
})
|
|
384
|
+
})
|
|
385
|
+
|
|
386
|
+
it('returns an empty result without making a request when no valid user IDs are provided', async () => {
|
|
387
|
+
const emptyPages = await users.resolveState(instance, {userIds: []})
|
|
388
|
+
const invalidPages = await users.resolveState(instance, {userIds: ['<system>', 'not-valid']})
|
|
389
|
+
|
|
390
|
+
expect(emptyPages).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
391
|
+
expect(invalidPages).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
392
|
+
expect(request).not.toHaveBeenCalled()
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
it('chunks large user ID lists into batches of 100', async () => {
|
|
396
|
+
const ids = Array.from({length: 105}, (_, i) => `pUser${String(i).padStart(3, '0')}`)
|
|
397
|
+
request
|
|
398
|
+
.mockReturnValueOnce(of(ids.slice(0, 100).map((id) => legacyUser(id))))
|
|
399
|
+
.mockReturnValueOnce(of(ids.slice(100).map((id) => legacyUser(id))))
|
|
400
|
+
|
|
401
|
+
const pages = await users.resolveState(instance, {userIds: ids})
|
|
402
|
+
|
|
403
|
+
expect(request).toHaveBeenCalledTimes(2)
|
|
404
|
+
expect(request).toHaveBeenNthCalledWith(1, {
|
|
405
|
+
method: 'GET',
|
|
406
|
+
url: `/users/${ids.slice(0, 100).join(',')}`,
|
|
407
|
+
tag: 'users.get',
|
|
408
|
+
})
|
|
409
|
+
expect(request).toHaveBeenNthCalledWith(2, {
|
|
410
|
+
method: 'GET',
|
|
411
|
+
url: `/users/${ids.slice(100).join(',')}`,
|
|
412
|
+
tag: 'users.get',
|
|
413
|
+
})
|
|
414
|
+
expect(pages[0]?.data).toHaveLength(105)
|
|
415
|
+
expect(pages[0]?.totalCount).toBe(105)
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
it('strips disallowed or robot IDs on 403 and resolves the remaining users', async () => {
|
|
419
|
+
request
|
|
420
|
+
.mockReturnValueOnce(
|
|
421
|
+
throwError(() => clientError(403, 'Not allowed to fetch user with ID g-mlRobot1')),
|
|
422
|
+
)
|
|
423
|
+
.mockReturnValueOnce(
|
|
424
|
+
throwError(() => clientError(403, 'Not allowed to fetch user with ID gUnknown')),
|
|
425
|
+
)
|
|
426
|
+
.mockReturnValueOnce(of([legacyUser('gAlice'), legacyUser('pBob', {sanityUserId: 'gBob'})]))
|
|
427
|
+
|
|
428
|
+
const pages = await users.resolveState(instance, {
|
|
429
|
+
userIds: ['gAlice', 'pBob', 'g-mlRobot1', 'gUnknown'],
|
|
430
|
+
})
|
|
431
|
+
|
|
432
|
+
expect(request).toHaveBeenCalledTimes(3)
|
|
433
|
+
expect(request).toHaveBeenLastCalledWith({
|
|
434
|
+
method: 'GET',
|
|
435
|
+
url: '/users/gAlice,pBob',
|
|
436
|
+
tag: 'users.get',
|
|
437
|
+
})
|
|
438
|
+
expect(pages[0]?.data.map((u) => u.profile.id)).toEqual(['gAlice', 'pBob'])
|
|
439
|
+
expect(pages[0]?.totalCount).toBe(2)
|
|
440
|
+
})
|
|
441
|
+
|
|
442
|
+
it('returns an empty result without throwing on 404 or a generic 403', async () => {
|
|
443
|
+
request.mockReturnValueOnce(throwError(() => clientError(404, 'User not found')))
|
|
444
|
+
const notFound = await users.resolveState(instance, {userIds: ['pMissing']})
|
|
445
|
+
|
|
446
|
+
request.mockReturnValueOnce(throwError(() => clientError(403, 'Forbidden')))
|
|
447
|
+
const forbidden = await users.resolveState(instance, {userIds: ['pNoAccess1', 'pNoAccess2']})
|
|
448
|
+
|
|
449
|
+
expect(notFound).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
450
|
+
expect(forbidden).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
it('bisects chunks after linear 403 retries so many disallowed IDs never drop valid users', async () => {
|
|
454
|
+
const denied = Array.from({length: 15}, (_, i) => `g-robot${String(i).padStart(2, '0')}`)
|
|
455
|
+
const valid = Array.from({length: 10}, (_, i) => `gUser${String(i).padStart(2, '0')}`)
|
|
456
|
+
const deniedSet = new Set(denied)
|
|
457
|
+
|
|
458
|
+
request.mockImplementation(({url}: {url: string}) => {
|
|
459
|
+
const requested = url.replace('/users/', '').split(',')
|
|
460
|
+
const blocked = requested.find((id) => deniedSet.has(id))
|
|
461
|
+
if (blocked) {
|
|
462
|
+
return throwError(() => clientError(403, `Not allowed to fetch user with ID ${blocked}`))
|
|
463
|
+
}
|
|
464
|
+
return of(requested.map((id) => legacyUser(id)))
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
const pages = await users.resolveState(instance, {userIds: [...denied, ...valid]})
|
|
468
|
+
|
|
469
|
+
expect(pages[0]?.data.map((u) => u.profile.id)).toEqual(valid)
|
|
470
|
+
expect(pages[0]?.totalCount).toBe(valid.length)
|
|
471
|
+
// After the 4th 403, remaining IDs split so the valid right half resolves in one call
|
|
472
|
+
expect(request).toHaveBeenCalledWith(
|
|
473
|
+
expect.objectContaining({url: `/users/${valid.join(',')}`}),
|
|
474
|
+
)
|
|
475
|
+
})
|
|
476
|
+
|
|
477
|
+
it('still fetches the last remaining valid ID when linear 403 retries exhaust with one ID left', async () => {
|
|
478
|
+
const denied = ['g-d1', 'g-d2', 'g-d3', 'g-d4']
|
|
479
|
+
const deniedSet = new Set(denied)
|
|
480
|
+
|
|
481
|
+
request.mockImplementation(({url}: {url: string}) => {
|
|
482
|
+
const requested = url.replace('/users/', '').split(',')
|
|
483
|
+
const blocked = requested.find((id) => deniedSet.has(id))
|
|
484
|
+
if (blocked) {
|
|
485
|
+
return throwError(() => clientError(403, `Not allowed to fetch user with ID ${blocked}`))
|
|
486
|
+
}
|
|
487
|
+
return of(legacyUser(requested[0]!))
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
const pages = await users.resolveState(instance, {userIds: [...denied, 'gValid']})
|
|
491
|
+
|
|
492
|
+
expect(pages[0]?.data.map((u) => u.profile.id)).toEqual(['gValid'])
|
|
493
|
+
expect(pages[0]?.totalCount).toBe(1)
|
|
494
|
+
})
|
|
495
|
+
|
|
496
|
+
it('caps 403 retries at leaf sub-chunks when every ID in a 100-ID chunk is disallowed', async () => {
|
|
497
|
+
const ids = Array.from({length: 100}, (_, i) => `gDenied${String(i).padStart(3, '0')}`)
|
|
498
|
+
request.mockImplementation(({url}: {url: string}) => {
|
|
499
|
+
const firstId = url.replace('/users/', '').split(',')[0]
|
|
500
|
+
return throwError(() => clientError(403, `Not allowed to fetch user with ID ${firstId}`))
|
|
501
|
+
})
|
|
502
|
+
|
|
503
|
+
const pages = await users.resolveState(instance, {userIds: ids})
|
|
504
|
+
|
|
505
|
+
// 1 initial + 3 linear + 2 first-level splits + 4 leaves * (1 + 2 retries) = 18 requests
|
|
506
|
+
expect(request).toHaveBeenCalledTimes(18)
|
|
507
|
+
expect(pages).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
508
|
+
})
|
|
509
|
+
|
|
510
|
+
it('bounds concurrent chunk requests and preserves chunk order when chunks settle out of order', async () => {
|
|
511
|
+
const ids = Array.from({length: 350}, (_, i) => `pUser${String(i).padStart(3, '0')}`)
|
|
512
|
+
let inFlight = 0
|
|
513
|
+
let maxInFlight = 0
|
|
514
|
+
const pending: Array<{ids: string[]; subject: Subject<ReturnType<typeof legacyUser>[]>}> = []
|
|
515
|
+
|
|
516
|
+
request.mockImplementation(({url}: {url: string}) => {
|
|
517
|
+
const requested = url.replace('/users/', '').split(',')
|
|
518
|
+
const subject = new Subject<ReturnType<typeof legacyUser>[]>()
|
|
519
|
+
inFlight++
|
|
520
|
+
maxInFlight = Math.max(maxInFlight, inFlight)
|
|
521
|
+
pending.push({ids: requested, subject})
|
|
522
|
+
return subject.asObservable()
|
|
523
|
+
})
|
|
524
|
+
|
|
525
|
+
const promise = users.resolveState(instance, {userIds: ids})
|
|
526
|
+
|
|
527
|
+
await vi.waitFor(() => expect(pending).toHaveLength(MAX_CONCURRENT_USER_ID_CHUNKS))
|
|
528
|
+
expect(maxInFlight).toBe(MAX_CONCURRENT_USER_ID_CHUNKS)
|
|
529
|
+
|
|
530
|
+
// Complete chunk 1 before chunk 0 to verify deterministic ordering
|
|
531
|
+
const finish = (index: number) => {
|
|
532
|
+
const entry = pending[index]!
|
|
533
|
+
inFlight--
|
|
534
|
+
entry.subject.next(entry.ids.map((id) => legacyUser(id)))
|
|
535
|
+
entry.subject.complete()
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
finish(1)
|
|
539
|
+
expect(pending).toHaveLength(3)
|
|
540
|
+
expect(maxInFlight).toBe(MAX_CONCURRENT_USER_ID_CHUNKS)
|
|
541
|
+
|
|
542
|
+
finish(0)
|
|
543
|
+
expect(pending).toHaveLength(4)
|
|
544
|
+
expect(maxInFlight).toBe(MAX_CONCURRENT_USER_ID_CHUNKS)
|
|
545
|
+
|
|
546
|
+
finish(3)
|
|
547
|
+
finish(2)
|
|
548
|
+
|
|
549
|
+
const pages = await promise
|
|
550
|
+
expect(pages[0]?.data.map((u) => u.profile.id)).toEqual(ids)
|
|
551
|
+
expect(pages[0]?.totalCount).toBe(ids.length)
|
|
552
|
+
})
|
|
553
|
+
|
|
554
|
+
it('remembers disallowed IDs across transient retries, revalidations, TTL expiry, and auth changes', async () => {
|
|
555
|
+
vi.useFakeTimers()
|
|
556
|
+
onTestFinished(() => {
|
|
557
|
+
vi.useRealTimers()
|
|
558
|
+
})
|
|
559
|
+
|
|
560
|
+
// 1. 403 discovers g-robot1, then transient 503 forces retryRead to replay readUsersByIds
|
|
561
|
+
request
|
|
562
|
+
.mockReturnValueOnce(
|
|
563
|
+
throwError(() => clientError(403, 'Not allowed to fetch user with ID g-robot1')),
|
|
564
|
+
)
|
|
565
|
+
.mockReturnValueOnce(
|
|
566
|
+
throwError(
|
|
567
|
+
() =>
|
|
568
|
+
new ServerError({
|
|
569
|
+
statusCode: 503,
|
|
570
|
+
headers: {},
|
|
571
|
+
body: {statusCode: 503, error: 'Service Unavailable', message: 'Try again'},
|
|
572
|
+
}),
|
|
573
|
+
),
|
|
574
|
+
)
|
|
575
|
+
.mockReturnValueOnce(of([legacyUser('gAlice')]))
|
|
576
|
+
|
|
577
|
+
const pending = users.resolveState(instance, {userIds: ['g-robot1', 'gAlice']})
|
|
578
|
+
await vi.advanceTimersByTimeAsync(1_000)
|
|
579
|
+
const first = await pending
|
|
580
|
+
|
|
581
|
+
expect(first[0]?.data.map((u) => u.profile.id)).toEqual(['gAlice'])
|
|
582
|
+
// Retry skips g-robot1 instead of replaying its 403
|
|
583
|
+
expect(request).toHaveBeenCalledTimes(3)
|
|
584
|
+
expect(request).toHaveBeenNthCalledWith(3, {
|
|
585
|
+
method: 'GET',
|
|
586
|
+
url: '/users/gAlice',
|
|
587
|
+
tag: 'users.get',
|
|
588
|
+
})
|
|
589
|
+
|
|
590
|
+
// 2. Subsequent refetch within TTL skips g-robot1 without triggering a 403
|
|
591
|
+
request.mockClear()
|
|
592
|
+
request.mockReturnValueOnce(of([legacyUser('gAlice')]))
|
|
593
|
+
await users.refetch(instance, {userIds: ['g-robot1', 'gAlice']})
|
|
594
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
595
|
+
method: 'GET',
|
|
596
|
+
url: '/users/gAlice',
|
|
597
|
+
tag: 'users.get',
|
|
598
|
+
})
|
|
599
|
+
|
|
600
|
+
// 3. Another project scope is not affected by the disallowed cache for project 'test'
|
|
601
|
+
request.mockClear()
|
|
602
|
+
request.mockReturnValueOnce(of([legacyUser('g-robot1'), legacyUser('gAlice')]))
|
|
603
|
+
await users.resolveState(instance, {
|
|
604
|
+
projectId: 'other-project',
|
|
605
|
+
userIds: ['g-robot1', 'gAlice'],
|
|
606
|
+
})
|
|
607
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
608
|
+
method: 'GET',
|
|
609
|
+
url: '/users/g-robot1,gAlice',
|
|
610
|
+
tag: 'users.get',
|
|
611
|
+
})
|
|
612
|
+
|
|
613
|
+
// 4. Credential change clears remembered disallowed IDs so newly permitted users resolve
|
|
614
|
+
request.mockClear()
|
|
615
|
+
setAuthToken(instance, 'renewed-token')
|
|
616
|
+
request.mockReturnValueOnce(
|
|
617
|
+
throwError(() => clientError(403, 'Not allowed to fetch user with ID g-robot1')),
|
|
618
|
+
)
|
|
619
|
+
request.mockReturnValueOnce(of([legacyUser('gAlice')]))
|
|
620
|
+
await users.refetch(instance, {userIds: ['g-robot1', 'gAlice']})
|
|
621
|
+
expect(request).toHaveBeenNthCalledWith(1, {
|
|
622
|
+
method: 'GET',
|
|
623
|
+
url: '/users/g-robot1,gAlice',
|
|
624
|
+
tag: 'users.get',
|
|
625
|
+
})
|
|
626
|
+
|
|
627
|
+
// 5. After TTL expires, g-robot1 is probed again
|
|
628
|
+
request.mockClear()
|
|
629
|
+
await vi.advanceTimersByTimeAsync(DISALLOWED_USER_ID_TTL_MS + 1)
|
|
630
|
+
request.mockReturnValueOnce(of([legacyUser('g-robot1'), legacyUser('gAlice')]))
|
|
631
|
+
const afterTtl = await users.refetch(instance, {userIds: ['g-robot1', 'gAlice']})
|
|
632
|
+
expect(request).toHaveBeenCalledExactlyOnceWith({
|
|
633
|
+
method: 'GET',
|
|
634
|
+
url: '/users/g-robot1,gAlice',
|
|
635
|
+
tag: 'users.get',
|
|
636
|
+
})
|
|
637
|
+
expect(afterTtl[0]?.data.map((u) => u.profile.id)).toEqual(['g-robot1', 'gAlice'])
|
|
638
|
+
})
|
|
639
|
+
|
|
640
|
+
it('skips network requests entirely when every requested ID is already remembered as disallowed', async () => {
|
|
641
|
+
request.mockReturnValueOnce(
|
|
642
|
+
throwError(() => clientError(403, 'Not allowed to fetch user with ID gDeniedOnly')),
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
const first = await users.resolveState(instance, {userIds: ['gDeniedOnly']})
|
|
646
|
+
expect(first).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
647
|
+
expect(request).toHaveBeenCalledTimes(1)
|
|
648
|
+
|
|
649
|
+
request.mockClear()
|
|
650
|
+
const second = await users.refetch(instance, {userIds: ['gDeniedOnly']})
|
|
651
|
+
expect(second).toEqual([{data: [], totalCount: 0, nextCursor: null}])
|
|
652
|
+
expect(request).not.toHaveBeenCalled()
|
|
653
|
+
})
|
|
654
|
+
|
|
655
|
+
it('propagates non-403/404 errors like 400 Bad Request and non-ClientError failures', async () => {
|
|
656
|
+
const failure = clientError(400, 'Bad Request')
|
|
657
|
+
request.mockReturnValueOnce(throwError(() => failure))
|
|
658
|
+
|
|
659
|
+
await expect(users.resolveState(instance, {userIds: ['p1']})).rejects.toBe(failure)
|
|
660
|
+
|
|
661
|
+
const networkError = new Error('network down')
|
|
662
|
+
request.mockReturnValueOnce(throwError(() => networkError))
|
|
663
|
+
|
|
664
|
+
await expect(users.resolveState(instance, {userIds: ['p2']})).rejects.toBe(networkError)
|
|
665
|
+
})
|
|
666
|
+
})
|
package/src/users/users.ts
CHANGED
|
@@ -1,21 +1,13 @@
|
|
|
1
|
-
import {type SanityUser as SanityUserFromClient} from '@sanity/client'
|
|
2
1
|
import {filter, map, type Observable, of, switchMap, take} from 'rxjs'
|
|
3
2
|
|
|
4
3
|
import {type ClientOptions, getClientState} from '../client/clientStore'
|
|
5
4
|
import {observeAppOrganizationId} from '../organization/appOrganization'
|
|
6
5
|
import {type SanityInstance} from '../store/createSanityInstance'
|
|
7
6
|
import {definePagedFetcher} from '../store/fetcherStore'
|
|
7
|
+
import {type LegacyUser, readUsersByIds, toSanityUser, usersByIdsSource} from './readUsersByIds'
|
|
8
8
|
import {type GetUsersOptions, type SanityUser, type SanityUserResponse} from './types'
|
|
9
9
|
import {API_VERSION, DEFAULT_USERS_BATCH_SIZE, PROJECT_API_VERSION} from './usersConstants'
|
|
10
10
|
|
|
11
|
-
// A user as the project API answers
|
|
12
|
-
type ProjectUser = Omit<SanityUserFromClient, 'id'> & {
|
|
13
|
-
id: string
|
|
14
|
-
sanityUserId: string
|
|
15
|
-
email: string
|
|
16
|
-
provider: string
|
|
17
|
-
}
|
|
18
|
-
|
|
19
11
|
function get<T>(
|
|
20
12
|
instance: SanityInstance,
|
|
21
13
|
clientOptions: ClientOptions,
|
|
@@ -80,31 +72,13 @@ function readUser(
|
|
|
80
72
|
),
|
|
81
73
|
)
|
|
82
74
|
}
|
|
83
|
-
return get<
|
|
75
|
+
return get<LegacyUser>(
|
|
84
76
|
instance,
|
|
85
77
|
{apiVersion: PROJECT_API_VERSION, projectId: source.projectId},
|
|
86
78
|
{url: `/users/${source.userId}`, tag: 'users.get'},
|
|
87
79
|
).pipe(
|
|
88
80
|
map((projectUser) => ({
|
|
89
|
-
data: [
|
|
90
|
-
{
|
|
91
|
-
sanityUserId: projectUser.sanityUserId,
|
|
92
|
-
profile: {
|
|
93
|
-
id: projectUser.id,
|
|
94
|
-
displayName: projectUser.displayName,
|
|
95
|
-
familyName: projectUser.familyName ?? undefined,
|
|
96
|
-
givenName: projectUser.givenName ?? undefined,
|
|
97
|
-
middleName: projectUser.middleName ?? undefined,
|
|
98
|
-
imageUrl: projectUser.imageUrl ?? undefined,
|
|
99
|
-
createdAt: projectUser.createdAt,
|
|
100
|
-
updatedAt: projectUser.updatedAt,
|
|
101
|
-
isCurrentUser: projectUser.isCurrentUser,
|
|
102
|
-
email: projectUser.email,
|
|
103
|
-
provider: projectUser.provider,
|
|
104
|
-
},
|
|
105
|
-
memberships: [],
|
|
106
|
-
},
|
|
107
|
-
],
|
|
81
|
+
data: [toSanityUser(projectUser)],
|
|
108
82
|
totalCount: 1,
|
|
109
83
|
nextCursor: null,
|
|
110
84
|
})),
|
|
@@ -114,22 +88,28 @@ function readUser(
|
|
|
114
88
|
/**
|
|
115
89
|
* Fetcher for the users of a project or an organization, on the shared fetcher cache, a batch at
|
|
116
90
|
* a time. Without an `organizationId`, an organization's list waits for the app's organization.
|
|
117
|
-
* With
|
|
91
|
+
* With `userIds`, it resolves only those users via the legacy `/users/:ids` endpoint. With a
|
|
92
|
+
* `userId`, it reads only that user.
|
|
118
93
|
*
|
|
119
94
|
* @internal
|
|
120
95
|
*/
|
|
121
96
|
export const users = definePagedFetcher<[options?: GetUsersOptions], SanityUserResponse>({
|
|
122
97
|
name: 'users',
|
|
123
|
-
getKey: (instance, options) =>
|
|
124
|
-
|
|
98
|
+
getKey: (instance, options) => {
|
|
99
|
+
if (options?.userIds) {
|
|
100
|
+
return JSON.stringify(usersByIdsSource(instance, {...options, userIds: options.userIds}))
|
|
101
|
+
}
|
|
102
|
+
return JSON.stringify(
|
|
125
103
|
options?.userId
|
|
126
104
|
? userSource(instance, {...options, userId: options.userId})
|
|
127
105
|
: {
|
|
128
106
|
...usersResource(instance, options),
|
|
129
107
|
batchSize: options?.batchSize ?? DEFAULT_USERS_BATCH_SIZE,
|
|
130
108
|
},
|
|
131
|
-
)
|
|
109
|
+
)
|
|
110
|
+
},
|
|
132
111
|
fetch: (instance) => (cursor, options) => {
|
|
112
|
+
if (options?.userIds) return readUsersByIds(instance, {...options, userIds: options.userIds})
|
|
133
113
|
if (options?.userId) return readUser(instance, {...options, userId: options.userId})
|
|
134
114
|
const {type, id} = usersResource(instance, options)
|
|
135
115
|
const limit = String(options?.batchSize ?? DEFAULT_USERS_BATCH_SIZE)
|
|
@@ -3,3 +3,10 @@ export const API_VERSION = 'vX'
|
|
|
3
3
|
export const PROJECT_API_VERSION = '2025-07-18'
|
|
4
4
|
export const USERS_STATE_CLEAR_DELAY = 5000
|
|
5
5
|
export const DEFAULT_USERS_BATCH_SIZE = 100
|
|
6
|
+
export const MAX_USER_IDS_BATCH_SIZE = 100
|
|
7
|
+
export const MAX_CONCURRENT_USER_ID_CHUNKS = 2
|
|
8
|
+
export const FORBIDDEN_USER_ID_LINEAR_RETRIES = 3
|
|
9
|
+
export const FORBIDDEN_USER_ID_MAX_SPLITS = 2
|
|
10
|
+
export const FORBIDDEN_USER_ID_LEAF_RETRIES = 2
|
|
11
|
+
export const DISALLOWED_USER_ID_TTL_MS = 5 * 60 * 1000
|
|
12
|
+
export const MAX_DISALLOWED_USER_ID_CACHE_ENTRIES = 1000
|
package/src/users/usersStore.ts
CHANGED
|
@@ -35,6 +35,7 @@ import {type StoreState} from '../store/createStoreState'
|
|
|
35
35
|
import {defineStore, type StoreContext} from '../store/defineStore'
|
|
36
36
|
import {randomId} from '../utils/ids'
|
|
37
37
|
import {setCleanupTimeout} from '../utils/setCleanupTimeout'
|
|
38
|
+
import {toSanityUser} from './readUsersByIds'
|
|
38
39
|
import {
|
|
39
40
|
addSubscription,
|
|
40
41
|
cancelRequest,
|
|
@@ -180,31 +181,11 @@ const listenForLoadMoreAndFetch = ({state, instance}: StoreContext<UsersStoreSta
|
|
|
180
181
|
tag: 'users.get',
|
|
181
182
|
}),
|
|
182
183
|
).pipe(
|
|
183
|
-
map((user) => {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
id: user.id,
|
|
189
|
-
displayName: user.displayName,
|
|
190
|
-
familyName: user.familyName ?? undefined,
|
|
191
|
-
givenName: user.givenName ?? undefined,
|
|
192
|
-
middleName: user.middleName ?? undefined,
|
|
193
|
-
imageUrl: user.imageUrl ?? undefined,
|
|
194
|
-
createdAt: user.createdAt,
|
|
195
|
-
updatedAt: user.updatedAt,
|
|
196
|
-
isCurrentUser: user.isCurrentUser,
|
|
197
|
-
email: user.email,
|
|
198
|
-
provider: user.provider,
|
|
199
|
-
},
|
|
200
|
-
memberships: [],
|
|
201
|
-
}
|
|
202
|
-
return {
|
|
203
|
-
data: [convertedUser],
|
|
204
|
-
totalCount: 1,
|
|
205
|
-
nextCursor: null,
|
|
206
|
-
}
|
|
207
|
-
}),
|
|
184
|
+
map((user) => ({
|
|
185
|
+
data: [toSanityUser(user)],
|
|
186
|
+
totalCount: 1,
|
|
187
|
+
nextCursor: null,
|
|
188
|
+
})),
|
|
208
189
|
retryRead(getClientAuthState(instance), setError),
|
|
209
190
|
tap((response) => state.set('setUsersData', setUsersData(group$.key, response))),
|
|
210
191
|
)
|