@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/package.json
CHANGED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import {ClientError, type SanityClient} from '@sanity/client'
|
|
2
|
+
import {
|
|
3
|
+
catchError,
|
|
4
|
+
forkJoin,
|
|
5
|
+
from,
|
|
6
|
+
map,
|
|
7
|
+
mergeMap,
|
|
8
|
+
type Observable,
|
|
9
|
+
of,
|
|
10
|
+
switchMap,
|
|
11
|
+
take,
|
|
12
|
+
throwError,
|
|
13
|
+
toArray,
|
|
14
|
+
} from 'rxjs'
|
|
15
|
+
|
|
16
|
+
import {getClientAuthState} from '../auth/authStore'
|
|
17
|
+
import {getClientErrorApiBody} from '../auth/utils'
|
|
18
|
+
import {type ClientOptions, getClientState} from '../client/clientStore'
|
|
19
|
+
import {type SanityInstance} from '../store/createSanityInstance'
|
|
20
|
+
import {type GetUsersOptions, type SanityUser, type SanityUserResponse} from './types'
|
|
21
|
+
import {
|
|
22
|
+
DISALLOWED_USER_ID_TTL_MS,
|
|
23
|
+
FORBIDDEN_USER_ID_LEAF_RETRIES,
|
|
24
|
+
FORBIDDEN_USER_ID_LINEAR_RETRIES,
|
|
25
|
+
FORBIDDEN_USER_ID_MAX_SPLITS,
|
|
26
|
+
MAX_CONCURRENT_USER_ID_CHUNKS,
|
|
27
|
+
MAX_DISALLOWED_USER_ID_CACHE_ENTRIES,
|
|
28
|
+
MAX_USER_IDS_BATCH_SIZE,
|
|
29
|
+
PROJECT_API_VERSION,
|
|
30
|
+
} from './usersConstants'
|
|
31
|
+
|
|
32
|
+
const SANITY_USER_ID_RE = /^g[a-zA-Z0-9-]+$/
|
|
33
|
+
const PROJECT_USER_ID_RE = /^p[a-zA-Z0-9-]+$/
|
|
34
|
+
const EXTERNAL_USER_ID_RE = /^e[a-zA-Z0-9\-_]+$/
|
|
35
|
+
const DISALLOWED_USER_ID_RE = /Not allowed to fetch user with ID ([a-zA-Z0-9_-]+)/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Shape returned by the legacy `GET /users/:userId` endpoint for project (`p*`), global (`g*`),
|
|
39
|
+
* and external (`e*`) users.
|
|
40
|
+
*/
|
|
41
|
+
export interface LegacyUser {
|
|
42
|
+
id: string
|
|
43
|
+
sanityUserId?: string
|
|
44
|
+
displayName: string
|
|
45
|
+
email?: string | null
|
|
46
|
+
familyName?: string | null
|
|
47
|
+
givenName?: string | null
|
|
48
|
+
middleName?: string | null
|
|
49
|
+
imageUrl?: string | null
|
|
50
|
+
provider?: string | null
|
|
51
|
+
providerId?: string
|
|
52
|
+
tosAcceptedAt?: string | null
|
|
53
|
+
createdAt: string
|
|
54
|
+
updatedAt?: string
|
|
55
|
+
isCurrentUser?: boolean
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Normalizes a legacy `/users/:userId` record into the SDK's {@link SanityUser} shape.
|
|
60
|
+
*/
|
|
61
|
+
export function toSanityUser(user: LegacyUser): SanityUser {
|
|
62
|
+
return {
|
|
63
|
+
sanityUserId: user.sanityUserId ?? user.id,
|
|
64
|
+
profile: {
|
|
65
|
+
id: user.id,
|
|
66
|
+
displayName: user.displayName,
|
|
67
|
+
familyName: user.familyName ?? undefined,
|
|
68
|
+
givenName: user.givenName ?? undefined,
|
|
69
|
+
middleName: user.middleName ?? undefined,
|
|
70
|
+
imageUrl: user.imageUrl ?? undefined,
|
|
71
|
+
createdAt: user.createdAt,
|
|
72
|
+
updatedAt: user.updatedAt,
|
|
73
|
+
isCurrentUser: user.isCurrentUser,
|
|
74
|
+
email: user.email ?? '',
|
|
75
|
+
provider: user.provider ?? '',
|
|
76
|
+
...(user.tosAcceptedAt ? {tosAcceptedAt: user.tosAcceptedAt} : {}),
|
|
77
|
+
...(user.providerId ? {providerId: user.providerId} : {}),
|
|
78
|
+
},
|
|
79
|
+
memberships: [],
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isResolvableUserId(id: string, isProjectScoped: boolean): boolean {
|
|
84
|
+
if (SANITY_USER_ID_RE.test(id) || PROJECT_USER_ID_RE.test(id)) return true
|
|
85
|
+
return isProjectScoped && EXTERNAL_USER_ID_RE.test(id)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function normalizeUserIds(userIds: readonly string[], isProjectScoped: boolean): string[] {
|
|
89
|
+
const unique = new Set<string>()
|
|
90
|
+
for (const id of userIds) {
|
|
91
|
+
if (isResolvableUserId(id, isProjectScoped)) {
|
|
92
|
+
unique.add(id)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return Array.from(unique).sort()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function chunkIds(ids: readonly string[], size: number): string[][] {
|
|
99
|
+
const chunks: string[][] = []
|
|
100
|
+
for (let i = 0; i < ids.length; i += size) {
|
|
101
|
+
chunks.push(ids.slice(i, i + size))
|
|
102
|
+
}
|
|
103
|
+
return chunks
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface DisallowedCache {
|
|
107
|
+
credential: unknown
|
|
108
|
+
/** Maps `${scopeKey}:${userId}` to the epoch ms when the remembered 403 expires */
|
|
109
|
+
entries: Map<string, number>
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const disallowedByInstance = new WeakMap<SanityInstance, DisallowedCache>()
|
|
113
|
+
|
|
114
|
+
function getDisallowedEntries(instance: SanityInstance): Map<string, number> {
|
|
115
|
+
const credential = getClientAuthState(instance).getCurrent()
|
|
116
|
+
const existing = disallowedByInstance.get(instance)
|
|
117
|
+
if (existing && existing.credential === credential) {
|
|
118
|
+
return existing.entries
|
|
119
|
+
}
|
|
120
|
+
const entries = new Map<string, number>()
|
|
121
|
+
disallowedByInstance.set(instance, {credential, entries})
|
|
122
|
+
return entries
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isDisallowedUserId(entries: Map<string, number>, key: string, now: number): boolean {
|
|
126
|
+
const expiresAt = entries.get(key)
|
|
127
|
+
if (expiresAt === undefined) return false
|
|
128
|
+
if (expiresAt <= now) {
|
|
129
|
+
entries.delete(key)
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
return true
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function rememberDisallowedUserId(entries: Map<string, number>, key: string): void {
|
|
136
|
+
const now = Date.now()
|
|
137
|
+
entries.delete(key)
|
|
138
|
+
if (entries.size >= MAX_DISALLOWED_USER_ID_CACHE_ENTRIES) {
|
|
139
|
+
const oldest = entries.keys().next().value
|
|
140
|
+
if (oldest !== undefined) entries.delete(oldest)
|
|
141
|
+
}
|
|
142
|
+
entries.set(key, now + DISALLOWED_USER_ID_TTL_MS)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function extractDisallowedUserId(error: ClientError): string | undefined {
|
|
146
|
+
const message = getClientErrorApiBody(error)?.message ?? error.message
|
|
147
|
+
return DISALLOWED_USER_ID_RE.exec(message)?.[1]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function retryRemainingIds(
|
|
151
|
+
client: SanityClient,
|
|
152
|
+
remaining: readonly string[],
|
|
153
|
+
recordDisallowed: (id: string) => void,
|
|
154
|
+
retriesLeft: number,
|
|
155
|
+
splitsLeft: number,
|
|
156
|
+
): Observable<SanityUser[]> {
|
|
157
|
+
if (remaining.length === 0) return of([])
|
|
158
|
+
|
|
159
|
+
if (retriesLeft > 0) {
|
|
160
|
+
return fetchUsersChunk(client, remaining, recordDisallowed, retriesLeft - 1, splitsLeft)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (splitsLeft <= 0) return of([])
|
|
164
|
+
|
|
165
|
+
if (remaining.length === 1) {
|
|
166
|
+
return fetchUsersChunk(client, remaining, recordDisallowed, 0, 0)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const mid = Math.ceil(remaining.length / 2)
|
|
170
|
+
const nextSplits = splitsLeft - 1
|
|
171
|
+
const nextRetries = nextSplits === 0 ? FORBIDDEN_USER_ID_LEAF_RETRIES : 0
|
|
172
|
+
return forkJoin([
|
|
173
|
+
fetchUsersChunk(client, remaining.slice(0, mid), recordDisallowed, nextRetries, nextSplits),
|
|
174
|
+
fetchUsersChunk(client, remaining.slice(mid), recordDisallowed, nextRetries, nextSplits),
|
|
175
|
+
]).pipe(map((batches) => batches.flat()))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function recoverChunkError(
|
|
179
|
+
client: SanityClient,
|
|
180
|
+
ids: readonly string[],
|
|
181
|
+
error: unknown,
|
|
182
|
+
recordDisallowed: (id: string) => void,
|
|
183
|
+
retriesLeft: number,
|
|
184
|
+
splitsLeft: number,
|
|
185
|
+
): Observable<SanityUser[]> {
|
|
186
|
+
if (!(error instanceof ClientError)) return throwError(() => error)
|
|
187
|
+
if (error.statusCode === 404) return of([])
|
|
188
|
+
if (error.statusCode !== 403) return throwError(() => error)
|
|
189
|
+
|
|
190
|
+
const disallowedId = extractDisallowedUserId(error)
|
|
191
|
+
if (!disallowedId || !ids.includes(disallowedId)) return of([])
|
|
192
|
+
|
|
193
|
+
recordDisallowed(disallowedId)
|
|
194
|
+
return retryRemainingIds(
|
|
195
|
+
client,
|
|
196
|
+
ids.filter((id) => id !== disallowedId),
|
|
197
|
+
recordDisallowed,
|
|
198
|
+
retriesLeft,
|
|
199
|
+
splitsLeft,
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function fetchUsersChunk(
|
|
204
|
+
client: SanityClient,
|
|
205
|
+
ids: readonly string[],
|
|
206
|
+
recordDisallowed: (id: string) => void,
|
|
207
|
+
retriesLeft = FORBIDDEN_USER_ID_LINEAR_RETRIES,
|
|
208
|
+
splitsLeft = FORBIDDEN_USER_ID_MAX_SPLITS,
|
|
209
|
+
): Observable<SanityUser[]> {
|
|
210
|
+
return client.observable
|
|
211
|
+
.request<LegacyUser | LegacyUser[]>({
|
|
212
|
+
method: 'GET',
|
|
213
|
+
url: `/users/${ids.join(',')}`,
|
|
214
|
+
tag: 'users.get',
|
|
215
|
+
})
|
|
216
|
+
.pipe(
|
|
217
|
+
map((response) => (Array.isArray(response) ? response : response ? [response] : [])),
|
|
218
|
+
map((items) => items.map(toSanityUser)),
|
|
219
|
+
catchError((error: unknown) =>
|
|
220
|
+
recoverChunkError(client, ids, error, recordDisallowed, retriesLeft, splitsLeft),
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Normalized lookup descriptor for resolving specific user IDs via the legacy `/users/:ids` API.
|
|
227
|
+
* Used as both the cache key and request scope so callers passing the same IDs in different order
|
|
228
|
+
* or with duplicates share a single cached entry.
|
|
229
|
+
*/
|
|
230
|
+
export function usersByIdsSource(
|
|
231
|
+
instance: SanityInstance,
|
|
232
|
+
{
|
|
233
|
+
userIds,
|
|
234
|
+
resourceType,
|
|
235
|
+
organizationId,
|
|
236
|
+
projectId = instance.config.projectId,
|
|
237
|
+
}: GetUsersOptions & {userIds: string[]},
|
|
238
|
+
): {scope: 'global'; userIds: string[]} | {projectId: string; userIds: string[]} {
|
|
239
|
+
const isGlobal = resourceType === 'organization' || Boolean(organizationId) || !projectId
|
|
240
|
+
if (isGlobal) {
|
|
241
|
+
return {scope: 'global', userIds: normalizeUserIds(userIds, false)}
|
|
242
|
+
}
|
|
243
|
+
return {projectId, userIds: normalizeUserIds(userIds, true)}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Resolves a specific list of user IDs through the legacy comma-separated `GET /users/:ids`
|
|
248
|
+
* endpoint, chunking large batches and gracefully omitting unknown, deleted, or inaccessible IDs.
|
|
249
|
+
*/
|
|
250
|
+
export function readUsersByIds(
|
|
251
|
+
instance: SanityInstance,
|
|
252
|
+
options: GetUsersOptions & {userIds: string[]},
|
|
253
|
+
): Observable<SanityUserResponse> {
|
|
254
|
+
const source = usersByIdsSource(instance, options)
|
|
255
|
+
const disallowed = getDisallowedEntries(instance)
|
|
256
|
+
const scopeKey = 'scope' in source ? 'global' : `project:${source.projectId}`
|
|
257
|
+
const now = Date.now()
|
|
258
|
+
const allowedIds = source.userIds.filter(
|
|
259
|
+
(id) => !isDisallowedUserId(disallowed, `${scopeKey}:${id}`, now),
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
if (allowedIds.length === 0) {
|
|
263
|
+
return of({data: [], totalCount: 0, nextCursor: null})
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const recordDisallowed = (id: string) => rememberDisallowedUserId(disallowed, `${scopeKey}:${id}`)
|
|
267
|
+
|
|
268
|
+
const clientOptions: ClientOptions =
|
|
269
|
+
'scope' in source
|
|
270
|
+
? {scope: 'global', apiVersion: PROJECT_API_VERSION}
|
|
271
|
+
: {projectId: source.projectId, apiVersion: PROJECT_API_VERSION}
|
|
272
|
+
|
|
273
|
+
const chunks = chunkIds(allowedIds, MAX_USER_IDS_BATCH_SIZE)
|
|
274
|
+
|
|
275
|
+
return getClientState(instance, clientOptions).observable.pipe(
|
|
276
|
+
take(1),
|
|
277
|
+
switchMap((client) =>
|
|
278
|
+
from(chunks).pipe(
|
|
279
|
+
mergeMap(
|
|
280
|
+
(chunk, index) =>
|
|
281
|
+
fetchUsersChunk(client, chunk, recordDisallowed).pipe(map((users) => ({index, users}))),
|
|
282
|
+
MAX_CONCURRENT_USER_ID_CHUNKS,
|
|
283
|
+
),
|
|
284
|
+
toArray(),
|
|
285
|
+
map((batches) => batches.sort((a, b) => a.index - b.index).flatMap((batch) => batch.users)),
|
|
286
|
+
),
|
|
287
|
+
),
|
|
288
|
+
map((data) => ({data, totalCount: data.length, nextCursor: null})),
|
|
289
|
+
)
|
|
290
|
+
}
|
package/src/users/types.ts
CHANGED
|
@@ -46,6 +46,12 @@ export interface GetUsersOptions extends ProjectHandle {
|
|
|
46
46
|
resourceType?: 'organization' | 'project'
|
|
47
47
|
batchSize?: number
|
|
48
48
|
organizationId?: string
|
|
49
|
+
/**
|
|
50
|
+
* Specific user IDs to resolve (`p*` project users, `g*` global users, or `e*` external users
|
|
51
|
+
* when project-scoped). When provided, only those users are fetched instead of paginating the
|
|
52
|
+
* resource directory, and unknown, deleted, or inaccessible IDs are omitted rather than failing.
|
|
53
|
+
*/
|
|
54
|
+
userIds?: string[]
|
|
49
55
|
/**
|
|
50
56
|
* @deprecated Read one user with `useUser` or `resolveUser`. Removed in the next major.
|
|
51
57
|
*/
|