@sanity/sdk-react 3.3.0-rc.1 → 3.4.0-rc.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 (30) hide show
  1. package/dist/_exports/dashboard-internal.d.ts +2 -2
  2. package/dist/_exports/dashboard.d.ts +57 -1
  3. package/dist/_exports/dashboard.d.ts.map +1 -1
  4. package/dist/_exports/dashboard.js +69 -38
  5. package/dist/_exports/dashboard.js.map +1 -1
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +2 -2
  9. package/dist/{useStudioWorkspacesByProjectIdDataset-BZ_Ud887.js → useStudioWorkspacesByProjectIdDataset-B5A5kBH9.js} +85 -5
  10. package/dist/useStudioWorkspacesByProjectIdDataset-B5A5kBH9.js.map +1 -0
  11. package/package.json +8 -8
  12. package/src/_exports/dashboard-internal.ts +6 -1
  13. package/src/_exports/dashboard.test-d.ts +30 -4
  14. package/src/_exports/dashboard.ts +3 -0
  15. package/src/hooks/dashboard/useApplicationBasePath.test.tsx +77 -0
  16. package/src/hooks/dashboard/useApplicationBasePath.ts +23 -0
  17. package/src/hooks/dashboard/useApplications.test.tsx +12 -3
  18. package/src/hooks/dashboard/useApplications.ts +5 -24
  19. package/src/hooks/dashboard/useAuthToken.test.tsx +48 -0
  20. package/src/hooks/dashboard/useAuthToken.ts +20 -0
  21. package/src/hooks/dashboard/useCurrentUser.test.tsx +57 -0
  22. package/src/hooks/dashboard/useCurrentUser.ts +22 -0
  23. package/src/hooks/dashboard/useOrganizationId.test.tsx +52 -1
  24. package/src/hooks/dashboard/useOrganizationId.tsx +15 -2
  25. package/src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.test.tsx +142 -1
  26. package/src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts +58 -1
  27. package/src/hooks/dashboard/useWindowTitle.test.ts +23 -0
  28. package/src/hooks/dashboard/useWindowTitle.ts +14 -0
  29. package/src/hooks/installations/useInstallations.test-d.ts +10 -0
  30. package/dist/useStudioWorkspacesByProjectIdDataset-BZ_Ud887.js.map +0 -1
@@ -1,13 +1,19 @@
1
- import {getDashboardOrganizationId} from '@sanity/sdk'
1
+ import {getDashboardOrganizationId, type OrganizationBase} from '@sanity/sdk'
2
+ import {getTopicState, isDashboardEnvironment} from '@sanity/sdk/_internal'
2
3
  import {useMemo, useSyncExternalStore} from 'react'
3
4
 
4
5
  import {useSanityInstance} from '../context/useSanityInstance'
5
6
 
7
+ type CurrentOrganization = Pick<OrganizationBase, 'id' | 'name' | 'slug'> | null | undefined
8
+
6
9
  /**
7
10
  * @public
8
11
  *
9
12
  * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.
10
13
  *
14
+ * Works in both Dashboard runtimes: it reads the `organizations.current` message bus topic when a
15
+ * host has installed the bus, and falls back to the Comlink connection otherwise.
16
+ *
11
17
  * @example
12
18
  * ```tsx
13
19
  * function DashboardComponent() {
@@ -24,7 +30,14 @@ import {useSanityInstance} from '../context/useSanityInstance'
24
30
  */
25
31
  export function useOrganizationId(): string | undefined {
26
32
  const instance = useSanityInstance()
27
- const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])
33
+ const {subscribe, getCurrent} = useMemo(() => {
34
+ if (!isDashboardEnvironment()) return getDashboardOrganizationId(instance)
35
+ const source = getTopicState(instance, 'organizations.current')
36
+ return {
37
+ subscribe: source.subscribe,
38
+ getCurrent: () => (source.getCurrent() as CurrentOrganization)?.id ?? undefined,
39
+ }
40
+ }, [instance])
28
41
 
29
42
  return useSyncExternalStore(subscribe, getCurrent)
30
43
  }
@@ -1,6 +1,11 @@
1
+ import {installMessageBus, resetMessageBus} from '@sanity/sdk/_internal'
2
+ import {type MessageBusHost, TopicError, type ValueOf} from '@sanity/sdk/dashboard'
1
3
  import {renderHook, waitFor} from '@testing-library/react'
2
- import {describe, expect, it, vi} from 'vitest'
4
+ import {Suspense} from 'react'
5
+ import {ErrorBoundary} from 'react-error-boundary'
6
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
3
7
 
8
+ import {render, renderHook as renderHookWithInstance, screen} from '../../../test/test-utils'
4
9
  import {useWindowConnection} from '../comlink/useWindowConnection'
5
10
  import {useStudioWorkspacesByProjectIdDataset} from './useStudioWorkspacesByProjectIdDataset'
6
11
 
@@ -218,3 +223,139 @@ describe('useStudioWorkspacesByResourceId', () => {
218
223
  })
219
224
  })
220
225
  })
226
+
227
+ describe('useStudioWorkspacesByProjectIdDataset (message bus)', () => {
228
+ const MESSAGE_BUS_KEY = Symbol.for('sanity.os.bus')
229
+ let host: MessageBusHost
230
+
231
+ const deployment = {
232
+ id: 'deployment-1',
233
+ applicationId: 'studio-1',
234
+ size: null,
235
+ version: '4.0.0',
236
+ isAutoUpdating: true,
237
+ isActiveDeployment: true,
238
+ deployedBy: null,
239
+ createdAt: '2026-01-01T00:00:00.000Z',
240
+ updatedAt: '2026-01-02T00:00:00.000Z',
241
+ interfaces: [],
242
+ }
243
+
244
+ const workspace = {
245
+ id: 'workspace-1',
246
+ name: 'production',
247
+ title: 'Production',
248
+ subtitle: null,
249
+ projectId: 'project1',
250
+ dataset: 'dataset1',
251
+ schemaDescriptorId: null,
252
+ basePath: '/production',
253
+ icon: null,
254
+ }
255
+
256
+ const studio = {
257
+ id: 'studio-1',
258
+ type: 'studio',
259
+ title: 'My Studio',
260
+ name: 'my-studio',
261
+ reference: 'organization-1/my-studio',
262
+ icon: null,
263
+ isSingleton: false,
264
+ visibility: 'default',
265
+ slug: 'my-studio',
266
+ externalUrl: null,
267
+ organizationId: 'organization-1',
268
+ createdAt: '2026-01-01T00:00:00.000Z',
269
+ updatedAt: '2026-01-02T00:00:00.000Z',
270
+ config: {},
271
+ activeDeployment: {
272
+ ...deployment,
273
+ workspaces: [
274
+ workspace,
275
+ {...workspace, id: 'workspace-2', name: 'staging', title: null, basePath: null},
276
+ {...workspace, id: 'workspace-3', projectId: 'project2', dataset: 'dataset2'},
277
+ ],
278
+ },
279
+ }
280
+
281
+ const coreApp = {
282
+ ...studio,
283
+ id: 'app-1',
284
+ type: 'coreApp',
285
+ activeDeployment: {...deployment, applicationId: 'app-1', workspaces: [workspace]},
286
+ }
287
+
288
+ const emitApplications = (value: unknown[] | null) =>
289
+ host.connections.subscribe((client) =>
290
+ client.emit(
291
+ 'applications.list',
292
+ (value === null ? null : {ok: true, value}) as ValueOf<'applications.list'>,
293
+ ),
294
+ )
295
+
296
+ beforeEach(() => {
297
+ vi.stubGlobal('__SANITY_APP_ID__', 'app')
298
+ host = installMessageBus({appId: 'dashboard'})
299
+ })
300
+
301
+ afterEach(() => {
302
+ resetMessageBus()
303
+ delete (globalThis as {[MESSAGE_BUS_KEY]?: unknown})[MESSAGE_BUS_KEY]
304
+ vi.unstubAllGlobals()
305
+ })
306
+
307
+ it('maps studio workspaces to resources keyed by projectId:dataset', () => {
308
+ emitApplications([studio, coreApp])
309
+
310
+ const {result} = renderHookWithInstance(() => useStudioWorkspacesByProjectIdDataset())
311
+
312
+ expect(useWindowConnection).not.toHaveBeenCalled()
313
+ expect(result.current.error).toBeNull()
314
+ expect(result.current.workspacesByProjectIdAndDataset).toEqual({
315
+ 'project1:dataset1': [
316
+ {
317
+ id: 'workspace-1',
318
+ name: 'production',
319
+ title: 'Production',
320
+ basePath: '/production',
321
+ projectId: 'project1',
322
+ dataset: 'dataset1',
323
+ type: 'studio',
324
+ userApplicationId: 'studio-1',
325
+ url: 'https://my-studio.sanity.studio',
326
+ },
327
+ expect.objectContaining({id: 'workspace-2', title: 'My Studio', basePath: ''}),
328
+ ],
329
+ 'project2:dataset2': [expect.objectContaining({id: 'workspace-3'})],
330
+ })
331
+ })
332
+
333
+ it('returns an empty map when the dashboard clears its applications', () => {
334
+ emitApplications(null)
335
+
336
+ const {result} = renderHookWithInstance(() => useStudioWorkspacesByProjectIdDataset())
337
+
338
+ expect(result.current.workspacesByProjectIdAndDataset).toEqual({})
339
+ })
340
+
341
+ it('throws a TopicError to the error boundary when the dashboard fails to load applications', () => {
342
+ host.connections.subscribe((client) => client.emit('applications.list', {ok: false}))
343
+ const onError = vi.fn()
344
+
345
+ function Workspaces() {
346
+ const {workspacesByProjectIdAndDataset} = useStudioWorkspacesByProjectIdDataset()
347
+ return <span>{Object.keys(workspacesByProjectIdAndDataset).length} workspaces</span>
348
+ }
349
+
350
+ render(
351
+ <ErrorBoundary fallback={<span>Failed</span>} onError={onError}>
352
+ <Suspense fallback="Loading">
353
+ <Workspaces />
354
+ </Suspense>
355
+ </ErrorBoundary>,
356
+ )
357
+
358
+ expect(screen.getByText('Failed')).toBeInTheDocument()
359
+ expect(onError.mock.calls[0][0]).toBeInstanceOf(TopicError)
360
+ })
361
+ })
@@ -1,7 +1,11 @@
1
+ /* eslint-disable react-compiler/react-compiler -- the transport branch in `useStudioWorkspacesByProjectIdDataset` is a deliberate rules-of-hooks exception; the compiler refuses files that disable it */
1
2
  import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'
2
- import {useEffect, useState} from 'react'
3
+ import {getApplicationOrigin, isDashboardEnvironment} from '@sanity/sdk/_internal'
4
+ import {type TopicData} from '@sanity/sdk/dashboard'
5
+ import {useEffect, useMemo, useState} from 'react'
3
6
 
4
7
  import {useWindowConnection} from '../comlink/useWindowConnection'
8
+ import {useTopic} from './useTopic'
5
9
 
6
10
  export interface DashboardResource {
7
11
  id: string
@@ -24,8 +28,13 @@ interface StudioWorkspacesResult {
24
28
  error: string | null
25
29
  }
26
30
 
31
+ type DashboardApplications = NonNullable<TopicData<'applications.list'>>
32
+
27
33
  /**
28
34
  * Hook that fetches studio workspaces and organizes them by projectId:dataset
35
+ *
36
+ * Works in both Dashboard runtimes: it derives workspaces from the `applications.list` message
37
+ * bus topic when a host has installed the bus, and falls back to the Comlink connection otherwise.
29
38
  * @internal
30
39
  *
31
40
  * @example
@@ -59,6 +68,54 @@ interface StudioWorkspacesResult {
59
68
  * ```
60
69
  */
61
70
  export function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {
71
+ // The branch is stable: the transport is fixed for the page lifetime, so one set of hooks
72
+ // always runs and the other never does.
73
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime
74
+ if (isDashboardEnvironment()) return useBusStudioWorkspaces()
75
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime
76
+ return useComlinkStudioWorkspaces()
77
+ }
78
+
79
+ // The legacy Comlink protocol models studios at the workspace level, so each workspace of a
80
+ // studio's active deployment becomes one resource, addressed by the studio's origin.
81
+ function toResources(application: DashboardApplications[number]): DashboardResource[] {
82
+ if (application.type !== 'studio') return []
83
+ const url = getApplicationOrigin(application) ?? ''
84
+ return (application.activeDeployment?.workspaces ?? []).map((workspace) => ({
85
+ id: workspace.id,
86
+ name: workspace.name,
87
+ title: workspace.title ?? application.title,
88
+ basePath: workspace.basePath ?? '',
89
+ projectId: workspace.projectId,
90
+ dataset: workspace.dataset,
91
+ type: 'studio',
92
+ userApplicationId: application.id,
93
+ url,
94
+ }))
95
+ }
96
+
97
+ function toWorkspaceMap(applications: DashboardApplications): WorkspacesByProjectIdDataset {
98
+ const workspaceMap: WorkspacesByProjectIdDataset = {}
99
+ for (const resource of applications.flatMap(toResources)) {
100
+ const key = `${resource.projectId}:${resource.dataset}` as const
101
+ workspaceMap[key] ??= []
102
+ workspaceMap[key].push(resource)
103
+ }
104
+ return workspaceMap
105
+ }
106
+
107
+ // Suspends until the host publishes its application list and throws a `TopicError` on failure,
108
+ // like every bus hook, so `error` is always `null` on this path.
109
+ function useBusStudioWorkspaces(): StudioWorkspacesResult {
110
+ const applications = useTopic('applications.list')
111
+ const workspacesByProjectIdAndDataset = useMemo(
112
+ () => toWorkspaceMap(applications ?? []),
113
+ [applications],
114
+ )
115
+ return {workspacesByProjectIdAndDataset, error: null}
116
+ }
117
+
118
+ function useComlinkStudioWorkspaces(): StudioWorkspacesResult {
62
119
  const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =
63
120
  useState<WorkspacesByProjectIdDataset>({})
64
121
  const [error, setError] = useState<string | null>(null)
@@ -1,3 +1,4 @@
1
+ import {installMessageBus, resetMessageBus} from '@sanity/sdk/_internal'
1
2
  import {renderHook, waitFor} from '@testing-library/react'
2
3
  import {afterEach, describe, expect, it, vi} from 'vitest'
3
4
 
@@ -8,6 +9,8 @@ vi.mock('../comlink/useWindowConnection', () => ({
8
9
  useWindowConnection: vi.fn(),
9
10
  }))
10
11
 
12
+ const MESSAGE_BUS_KEY = Symbol.for('sanity.os.bus')
13
+
11
14
  function createContextResponse(resource: Record<string, unknown>) {
12
15
  return {context: {resource}}
13
16
  }
@@ -242,3 +245,23 @@ describe('useWindowTitle', () => {
242
245
  consoleSpy.mockRestore()
243
246
  })
244
247
  })
248
+
249
+ describe('useWindowTitle (message bus)', () => {
250
+ afterEach(() => {
251
+ resetMessageBus()
252
+ delete (globalThis as {[MESSAGE_BUS_KEY]?: unknown})[MESSAGE_BUS_KEY]
253
+ vi.unstubAllGlobals()
254
+ document.title = ''
255
+ })
256
+
257
+ it('no-ops without suspending under the message bus', () => {
258
+ vi.stubGlobal('__SANITY_APP_ID__', 'app')
259
+ installMessageBus({appId: 'dashboard'})
260
+ document.title = 'Host Owned Title'
261
+
262
+ renderHook(() => useWindowTitle('Movies'))
263
+
264
+ expect(document.title).toBe('Host Owned Title')
265
+ expect(useWindowConnection).not.toHaveBeenCalled()
266
+ })
267
+ })
@@ -1,4 +1,6 @@
1
+ /* eslint-disable react-compiler/react-compiler -- the transport branch in `useWindowTitle` is a deliberate rules-of-hooks exception; the compiler refuses files that disable it */
1
2
  import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'
3
+ import {isDashboardEnvironment} from '@sanity/sdk/_internal'
2
4
  import {useEffect, useState} from 'react'
3
5
 
4
6
  import {useWindowConnection} from '../comlink/useWindowConnection'
@@ -38,6 +40,9 @@ function resolveAppTitle(resource: ContextResource): string | undefined {
38
40
  *
39
41
  * The Sanity dashboard appends `| Sanity` to produce the final browser tab title.
40
42
  *
43
+ * Works in both Dashboard runtimes: it manages the document title over the Comlink connection, and
44
+ * no-ops under the message bus, where the Dashboard host owns the title.
45
+ *
41
46
  * @param viewTitle - An optional view-specific title to prepend to the app title.
42
47
  *
43
48
  * @example
@@ -66,6 +71,15 @@ function resolveAppTitle(resource: ContextResource): string | undefined {
66
71
  * @public
67
72
  */
68
73
  export function useWindowTitle(viewTitle?: string): void {
74
+ // The document title is set by the Dashboard host under the message bus, so this hook only
75
+ // manages it in the Comlink runtime. The branch is stable: the transport is fixed for the page
76
+ // lifetime, so the Comlink hooks below always run or never run.
77
+ if (isDashboardEnvironment()) return
78
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime
79
+ useComlinkWindowTitle(viewTitle)
80
+ }
81
+
82
+ function useComlinkWindowTitle(viewTitle?: string): void {
69
83
  const [appTitle, setAppTitle] = useState<string | null>(null)
70
84
 
71
85
  const {fetch} = useWindowConnection({
@@ -20,6 +20,16 @@ test('useInstallations — include shapes each item', () => {
20
20
  expectTypeOf<Item['access']>().toEqualTypeOf<InstallationAccess[]>()
21
21
  })
22
22
 
23
+ test('useInstallations — includes the module federation manifest', () => {
24
+ const result = useInstallations({
25
+ organizationId: 'org_1',
26
+ include: ['config.mfManifest'],
27
+ })
28
+ expectTypeOf(result.data.data).toEqualTypeOf<Installation<'config.mfManifest'>[]>()
29
+ type Item = (typeof result.data.data)[number]
30
+ expectTypeOf<Item['application']['config']['mfManifest']>().toEqualTypeOf<unknown>()
31
+ })
32
+
23
33
  test('useInstallations — requires an organizationId', () => {
24
34
  // @ts-expect-error — organizationId is required
25
35
  void useInstallations({})
@@ -1 +0,0 @@
1
- {"version":3,"file":"useStudioWorkspacesByProjectIdDataset-BZ_Ud887.js","names":["SanityInstance","createContext","SanityInstanceContext","SanityInstance","useContext","SanityInstanceContext","useSanityInstance","instance","Error","SanityConfig","SanityInstance","StateSource","useSyncExternalStore","useSanityInstance","StateSourceFactory","instance","params","TParams","TState","CreateStateSourceHookOptions","getState","shouldSuspend","suspender","Promise","getConfig","createStateSourceHook","options","suspense","undefined","useHook","t0","$","_c","t1","state","subscribe","getCurrent","AuthState","getAuthState","createStateSourceHook","useAuthState","MessageData","NodeInput","SanityInstance","StateSource","FrameMessage","getNodeState","NodeState","WindowMessage","useCallback","useEffect","useRef","filter","firstValueFrom","useSanityInstance","createStateSourceHook","WindowMessageHandler","event","TFrameMessage","UseWindowConnectionOptions","name","connectTo","onMessage","Record","TMessage","WindowConnection","sendMessage","type","TType","data","Extract","fetch","options","signal","AbortSignal","suppressWarnings","responseTimeout","Promise","TResponse","useNodeState","getState","instance","nodeInput","shouldSuspend","getCurrent","undefined","suspender","observable","pipe","Boolean","useWindowConnection","t0","$","_c","t1","node","t2","Symbol","for","messageUnsubscribers","t3","Object","entries","forEach","t4","handler","messageUnsubscribe","on","current","push","_temp","t5","type_0","post","t6","type_1","data_0","fetchOptions","t7","unsubscribe","React","MODULE_SLOT_KEY","Symbol","for","ModuleContext","Context","ModuleSlot","WeakMap","createContext","getDashboardModuleContext","globals","globalThis","slot","key","context","get","undefined","set","ClientError","AuthStateType","setAuthToken","getDashboardMessageBus","MessageBus","React","PropsWithChildren","useContext","useEffect","useRef","useState","defer","of","catchError","getDashboardModuleContext","useAuthState","useSanityInstance","DashboardTokenRefresh","t0","$","_c","children","messageBus","instance","authState","processed401ErrorRef","t1","t2","subscription","subscribe","pipe","_temp","token","unsubscribe","t3","error","type","has401Error","ERROR","statusCode","current","emit","undefined","catch","_temp2","t4","console","warn","DashboardTokenRefreshProvider","FC","Symbol","for","moduleId","getDashboardOrganizationId","useMemo","useSyncExternalStore","useSanityInstance","useOrganizationId","$","_c","instance","t0","subscribe","getCurrent","SDK_CHANNEL_NAME","SDK_NODE_NAME","useEffect","useState","useWindowConnection","DashboardResource","id","name","title","basePath","projectId","dataset","type","userApplicationId","url","WorkspacesByProjectIdDataset","key","StudioWorkspacesResult","workspacesByProjectIdAndDataset","error","useStudioWorkspacesByProjectIdDataset","$","_c","t0","Symbol","for","setWorkspacesByProjectIdAndDataset","setError","t1","connectTo","fetch","t2","t3","fetchWorkspaces","signal","data","undefined","workspaceMap","noProjectIdAndDataset","context","availableResources","forEach","resource","push","const","length","t4","err","Error","controller","AbortController","abort"],"sources":["../src/context/SanityInstanceContext.ts","../src/hooks/context/useSanityInstance.ts","../src/hooks/helpers/createStateSourceHook.tsx","../src/hooks/auth/useAuthState.tsx","../src/hooks/comlink/useWindowConnection.ts","../src/dashboard/module.ts","../src/context/DashboardTokenRefresh.tsx","../src/hooks/dashboard/useOrganizationId.tsx","../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts"],"sourcesContent":["import {type SanityInstance} from '@sanity/sdk'\nimport {createContext} from 'react'\n\nexport const SanityInstanceContext = createContext<SanityInstance | null>(null)\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\n/**\n * Retrieves the current Sanity instance from context\n *\n * @public\n *\n * @category Platform\n * @returns The current Sanity instance\n *\n * @remarks\n * This hook accesses the nearest Sanity instance from the React context.\n * The hook must be used within a component wrapped by a `ResourceProvider` or `SanityApp`.\n *\n * @example Get the current instance\n * ```tsx\n * const instance = useSanityInstance()\n * console.log(instance.config.projectId)\n * ```\n *\n * @throws Error if no SanityInstance is found in context\n */\nexport const useSanityInstance = (): SanityInstance => {\n const instance = useContext(SanityInstanceContext)\n\n if (!instance) {\n throw new Error(\n `SanityInstance context not found. Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.`,\n )\n }\n\n return instance\n}\n","import {type SanityConfig, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ntype StateSourceFactory<TParams extends unknown[], TState> = (\n instance: SanityInstance,\n ...params: TParams\n) => StateSource<TState>\n\ninterface CreateStateSourceHookOptions<TParams extends unknown[], TState> {\n getState: StateSourceFactory<TParams, TState>\n shouldSuspend?: (instance: SanityInstance, ...params: TParams) => boolean\n suspender?: (instance: SanityInstance, ...params: TParams) => Promise<unknown>\n getConfig?: (...params: TParams) => SanityConfig | undefined\n}\n\nexport function createStateSourceHook<TParams extends unknown[], TState>(\n options: StateSourceFactory<TParams, TState> | CreateStateSourceHookOptions<TParams, TState>,\n): (...params: TParams) => TState {\n const getState = typeof options === 'function' ? options : options.getState\n const suspense = 'shouldSuspend' in options && 'suspender' in options ? options : undefined\n\n function useHook(...params: TParams) {\n const instance = useSanityInstance()\n\n if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) {\n throw suspense.suspender(instance, ...params)\n }\n\n const state = getState(instance, ...params)\n return useSyncExternalStore(state.subscribe, state.getCurrent)\n }\n\n return useHook\n}\n","import {type AuthState, getAuthState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n * A React hook that subscribes to authentication state changes.\n *\n * This hook provides access to the current authentication state type from the Sanity auth store.\n * It automatically re-renders when the authentication state changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes\n * and ensure consistency between server and client rendering.\n *\n * @returns The current authentication state type\n *\n * @example\n * ```tsx\n * function AuthStatus() {\n * const authState = useAuthState()\n * return <div>Current auth state: {authState}</div>\n * }\n * ```\n */\nexport const useAuthState: () => AuthState = createStateSourceHook(getAuthState)\n","import {type MessageData, type NodeInput} from '@sanity/comlink'\nimport {type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {\n type FrameMessage,\n getNodeState,\n type NodeState,\n type WindowMessage,\n} from '@sanity/sdk/comlink'\nimport {useCallback, useEffect, useRef} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n fetch: <TResponse>(\n type: string,\n data?: MessageData,\n options?: {\n signal?: AbortSignal\n suppressWarnings?: boolean\n responseTimeout?: number\n },\n ) => Promise<TResponse>\n}\n\nconst useNodeState = createStateSourceHook({\n getState: getNodeState as (\n instance: SanityInstance,\n nodeInput: NodeInput,\n ) => StateSource<NodeState>,\n shouldSuspend: (instance: SanityInstance, nodeInput: NodeInput) =>\n getNodeState(instance, nodeInput).getCurrent() === undefined,\n suspender: (instance: SanityInstance, nodeInput: NodeInput) => {\n return firstValueFrom(getNodeState(instance, nodeInput).observable.pipe(filter(Boolean)))\n },\n})\n\n/**\n * @internal\n * Hook to wrap a Comlink node in a React hook.\n * Our store functionality takes care of the lifecycle of the node,\n * as well as sharing a single node between invocations if they share the same name.\n *\n * Generally not to be used directly, but to be used as a dependency of\n * Comlink-powered hooks like `useStudioWorkspacesByProjectIdDataset`.\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>({\n name,\n connectTo,\n onMessage,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {node} = useNodeState({name, connectTo})\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n if (messageUnsubscribe) {\n messageUnsubscribers.current.push(messageUnsubscribe)\n }\n })\n }\n\n return () => {\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n }\n }, [instance, name, onMessage, node])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n node.post(type, data)\n },\n [node],\n )\n\n const fetch = useCallback(\n <TResponse>(\n type: string,\n data?: MessageData,\n fetchOptions?: {\n responseTimeout?: number\n signal?: AbortSignal\n suppressWarnings?: boolean\n },\n ): Promise<TResponse> => {\n return node.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [node],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import * as React from 'react'\n\nconst MODULE_SLOT_KEY = Symbol.for('sanity.os.module')\n\ntype ModuleContext = React.Context<string | undefined>\ntype ModuleSlot = WeakMap<typeof React.createContext, ModuleContext>\n\n/**\n * Returns the React context that carries the current federation module id.\n *\n * @remarks\n * This is the slot the CLI-generated wrapper populates with\n * `renderOptions.moduleId`. The context lives in a per-React-copy slot on\n * `globalThis` so the CLI wrapper and the SDK share the same context even\n * across module copies. Each React copy gets its own context, since a context\n * created by one copy is inert in another.\n *\n * The slot is keyed on `React.createContext` rather than the `React` namespace\n * object: `import * as React` and `import React from 'react'` can yield\n * different wrapper objects for the same React copy under bundler interop,\n * whereas the `createContext` function is the same reference under both.\n *\n * The provider side lives in the CLI, which must not import the SDK:\n * `packages/@sanity/workbench-cli/src/actions/build/render-remote.ts` in\n * `sanity-io/cli` reconstructs this accessor (same symbol, same key) and\n * wraps `App` in the context's `Provider`. Nothing in this repo exports it.\n * @internal\n */\nexport function getDashboardModuleContext(): ModuleContext {\n const globals = globalThis as {[MODULE_SLOT_KEY]?: ModuleSlot}\n const slot = (globals[MODULE_SLOT_KEY] ??= new WeakMap())\n const key = React.createContext\n let context = slot.get(key)\n if (!context) {\n context = React.createContext<string | undefined>(undefined)\n slot.set(key, context)\n }\n return context\n}\n","import {type ClientError} from '@sanity/client'\nimport {AuthStateType, setAuthToken} from '@sanity/sdk'\nimport {getDashboardMessageBus} from '@sanity/sdk/_internal'\nimport {type MessageBus} from '@sanity/sdk/dashboard'\nimport React, {type PropsWithChildren, useContext, useEffect, useRef, useState} from 'react'\nimport {defer, of} from 'rxjs'\nimport {catchError} from 'rxjs/operators'\n\nimport {getDashboardModuleContext} from '../dashboard/module'\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\n\n/**\n * Keeps the SDK auth token in sync with the dashboard \"OS\".\n *\n * When running inside the dashboard the OS owns the session, so we subscribe\n * to its `auth.token` stream and mirror each value into\n * the auth store — a token logs us in, `null` logs us out, and later OS\n * sign-in/out propagates automatically. When a request is rejected with a 401\n * (the token expired), we ask the OS to reissue rather than tearing the session\n * down; the new token arrives back through the same subscription.\n */\nfunction DashboardTokenRefresh({\n children,\n messageBus,\n}: PropsWithChildren<{messageBus: MessageBus}>) {\n const instance = useSanityInstance()\n const authState = useAuthState()\n const processed401ErrorRef = useRef<unknown | null>(null)\n\n useEffect(() => {\n const subscription = defer(() => messageBus.subscribe('auth.token'))\n .pipe(catchError(() => of(null)))\n .subscribe((token) => setAuthToken(instance, token))\n return () => subscription.unsubscribe()\n }, [instance, messageBus])\n\n useEffect(() => {\n const has401Error =\n authState.type === AuthStateType.ERROR && (authState.error as ClientError)?.statusCode === 401\n\n if (has401Error && processed401ErrorRef.current !== authState.error) {\n processed401ErrorRef.current = authState.error\n // Event topics have no replay, so a missing responder or timeout is otherwise dropped silently.\n messageBus.emit('auth.token.refresh', undefined).catch((error) => {\n // eslint-disable-next-line no-console\n console.warn('[sanity/sdk] Dashboard token refresh failed:', error)\n })\n } else if (!has401Error) {\n processed401ErrorRef.current = null\n }\n }, [authState, messageBus])\n\n return children\n}\n\n/**\n * Authenticates the SDK with the Sanity Dashboard's session when the app runs\n * inside the dashboard.\n *\n * The dashboard owns the session there: this provider subscribes to the token\n * the dashboard issues, writes each new value into the SDK's auth store (where\n * SDK hooks read it from), and asks the dashboard for a fresh token when a\n * request fails with a 401. Outside the dashboard it renders children\n * unchanged and the app's normal auth flow applies.\n *\n * @remarks\n * `AuthBoundary` mounts this automatically, so most apps never need it\n * directly. Mount it yourself only when your app runs inside the dashboard\n * without `AuthBoundary` — that is, the app renders its own loading and error\n * UI instead of the SDK's login flow — but still uses SDK hooks such as\n * `useQuery`, which need the dashboard's token in the auth store to\n * authenticate their requests.\n *\n * Mount it once, inside the provider that creates the Sanity instance whose\n * store should receive the token.\n *\n * @example\n * ```tsx\n * import {ResourceProvider} from '@sanity/sdk-react'\n * import {TokenRefreshProvider} from '@sanity/sdk-react/dashboard'\n *\n * function EmbeddedApp() {\n * return (\n * <ResourceProvider fallback={<Loading />}>\n * <TokenRefreshProvider>\n * <App />\n * </TokenRefreshProvider>\n * </ResourceProvider>\n * )\n * }\n * ```\n *\n * @public\n */\nexport const DashboardTokenRefreshProvider: React.FC<PropsWithChildren> = ({children}) => {\n const instance = useSanityInstance()\n const moduleId = useContext(getDashboardModuleContext())\n // The connection is first-caller-wins per instance, and hooks below read it during their\n // render, before any effect here could run. Connecting in the first render pins the module\n // identity before they do; nothing has subscribed to the store yet, so the write is safe.\n // The module id is read once: the CLI wrapper provides it statically above this tree.\n // No retry: the host installs the bus at module evaluation, before any remote renders, and\n // a standalone app has no host to wait for.\n const [messageBus] = useState(() => getDashboardMessageBus(instance, moduleId))\n if (messageBus) {\n return <DashboardTokenRefresh messageBus={messageBus}>{children}</DashboardTokenRefresh>\n }\n\n return children\n}\n","import {getDashboardOrganizationId} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n *\n * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.\n *\n * @example\n * ```tsx\n * function DashboardComponent() {\n * const orgId = useOrganizationId()\n *\n * if (!orgId) return null\n *\n * return <div>Organization ID: {String(orgId)}</div>\n * }\n * ```\n *\n * @category Dashboard\n * @returns The dashboard organization ID (string | undefined)\n */\nexport function useOrganizationId(): string | undefined {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\nexport interface DashboardResource {\n id: string\n name: string\n title: string\n basePath: string\n projectId: string\n dataset: string\n type: string\n userApplicationId: string\n url: string\n}\n\ninterface WorkspacesByProjectIdDataset {\n [key: `${string}:${string}`]: DashboardResource[] // key format: `${projectId}:${dataset}`\n}\n\ninterface StudioWorkspacesResult {\n workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset\n error: string | null\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n *\n * @example\n * ```tsx\n * import {useStudioWorkspacesByProjectIdDataset} from '@sanity/sdk-react'\n * import {Card, Code, Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function WorkspacesCard() {\n * const {workspacesByProjectIdAndDataset, error} = useStudioWorkspacesByProjectIdDataset()\n * if (error) {\n * return <div>Error: {error}</div>\n * }\n * return (\n * <Card padding={4} radius={2} shadow={1}>\n * <Code language=\"json\">\n * {JSON.stringify(workspacesByProjectIdAndDataset, null, 2)}\n * </Code>\n * </Card>\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function DashboardWorkspaces() {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <WorkspacesCard />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n // Once computed, this should probably be in a store and poll for changes\n // However, our stores are currently being refactored\n useEffect(() => {\n if (!fetch) return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/context', undefined, {signal})\n\n const workspaceMap: WorkspacesByProjectIdDataset = {}\n const noProjectIdAndDataset: DashboardResource[] = []\n\n data.context.availableResources.forEach((resource) => {\n if (resource.type !== 'studio') return\n if (!resource.projectId || !resource.dataset) {\n noProjectIdAndDataset.push(resource)\n return\n }\n const key = `${resource.projectId}:${resource.dataset}` as const\n if (!workspaceMap[key]) {\n workspaceMap[key] = []\n }\n workspaceMap[key].push(resource)\n })\n\n if (noProjectIdAndDataset.length > 0) {\n workspaceMap['NO_PROJECT_ID:NO_DATASET'] = noProjectIdAndDataset\n }\n\n setWorkspacesByProjectIdAndDataset(workspaceMap)\n setError(null)\n } catch (err: unknown) {\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return\n }\n setError('Failed to fetch workspaces')\n }\n }\n }\n\n const controller = new AbortController()\n fetchWorkspaces(controller.signal)\n\n return () => {\n controller.abort()\n }\n }, [fetch])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n }\n}\n"],"mappings":";;;;;;;;;;;;AAGA,MAAaE,wBAAwBD,cAAqC,IAAI,GCsBjEK,0BAAoB;CAC/B,IAAAC,WAAiBH,WAAWC,qBAAqB;CAEjD,IAAI,CAACE,UACH,MAAUC,MACR,gIACF;CACD,OAEMD;AAAQ;ACjBjB,SAAgBkB,sBACdC,SACgC;CAChC,IAAMN,WAAW,OAAOM,WAAY,aAAaA,UAAUA,QAAQN,UAC7DO,WAAW,mBAAmBD,WAAW,eAAeA,UAAUA,UAAUE,KAAAA;CAElF,SAAAC,QAAA,GAAAC,IAAA;EAAA,IAAAC,IAAAC,EAAA,CAAA,GAAiBhB,SAAAc,IACff,WAAiBF,kBAAkB;EAEnC,IAAIc,UAAQL,aAAeK,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