@sanity/sdk-react 3.0.0-rc.2 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/dashboard.d.ts +250 -0
- package/dist/_exports/dashboard.d.ts.map +1 -0
- package/dist/_exports/dashboard.js +278 -0
- package/dist/_exports/dashboard.js.map +1 -0
- package/dist/index.d.ts +86 -261
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +114 -616
- package/dist/index.js.map +1 -1
- package/dist/useStudioWorkspacesByProjectIdDataset-DxUlukmF.js +317 -0
- package/dist/useStudioWorkspacesByProjectIdDataset-DxUlukmF.js.map +1 -0
- package/package.json +12 -11
- package/src/_exports/dashboard.ts +12 -0
- package/src/_exports/sdk-react.ts +2 -12
- package/src/components/SDKProvider.test.tsx +5 -5
- package/src/components/auth/AuthBoundary.tsx +5 -5
- package/src/context/{WorkbenchTokenRefresh.test.tsx → DashboardTokenRefresh.test.tsx} +26 -26
- package/src/context/DashboardTokenRefresh.tsx +95 -0
- package/src/context/OrganizationResourcesProvider.test.tsx +9 -9
- package/src/context/OrganizationResourcesProvider.tsx +2 -2
- package/src/context/dashboardToken.ts +63 -0
- package/src/hooks/comlink/useWindowConnection.ts +1 -1
- package/src/hooks/{agent → dashboard}/useAgentResourceContext.ts +1 -1
- package/src/hooks/dashboard/useFavorite.test.tsx +101 -0
- package/src/hooks/dashboard/useFavorite.ts +34 -0
- package/src/hooks/dashboard/useFavoriteContext.ts +61 -0
- package/src/hooks/dashboard/{useDashboardNavigate.test.ts → useNavigate.test.ts} +3 -3
- package/src/hooks/dashboard/{useDashboardNavigate.ts → useNavigate.ts} +5 -5
- package/src/hooks/dashboard/useNavigateToStudioDocument.ts +2 -1
- package/src/hooks/{auth/useDashboardOrganizationId.test.tsx → dashboard/useOrganizationId.test.tsx} +4 -4
- package/src/hooks/{auth/useDashboardOrganizationId.tsx → dashboard/useOrganizationId.tsx} +2 -2
- package/src/hooks/dashboard/useUpdateFavorite.test.tsx +146 -0
- package/src/hooks/dashboard/useUpdateFavorite.ts +74 -0
- package/src/hooks/dashboard/useWindowTitle.ts +1 -1
- package/src/hooks/datasets/useDatasets.test.tsx +29 -22
- package/src/hooks/datasets/useDatasets.ts +31 -53
- package/src/hooks/document/useCreateDocument.ts +2 -1
- package/src/utils/resolveOrgResources.test.ts +2 -2
- package/src/utils/resolveOrgResources.ts +2 -2
- package/src/context/WorkbenchTokenRefresh.tsx +0 -61
- package/src/context/workbenchToken.ts +0 -63
- package/src/hooks/dashboard/useManageFavorite.test.tsx +0 -379
- package/src/hooks/dashboard/useManageFavorite.ts +0 -173
- /package/src/hooks/{agent → dashboard}/useAgentResourceContext.test.tsx +0 -0
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { c } from "react-compiler-runtime";
|
|
2
|
+
import "@sanity/client";
|
|
3
|
+
import { AuthStateType, getAuthState, getDashboardOrganizationId, setAuthToken } from "@sanity/sdk";
|
|
4
|
+
import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
|
5
|
+
import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
|
|
6
|
+
import { getNodeState } from "@sanity/sdk/comlink";
|
|
7
|
+
import { filter, firstValueFrom, from, of } from "rxjs";
|
|
8
|
+
import { jsx } from "react/jsx-runtime";
|
|
9
|
+
import { catchError, switchMap as switchMap$1 } from "rxjs/operators";
|
|
10
|
+
const SanityInstanceContext = createContext(null), useSanityInstance = () => {
|
|
11
|
+
let instance = useContext(SanityInstanceContext);
|
|
12
|
+
if (!instance) throw Error("SanityInstance context not found. Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.");
|
|
13
|
+
return instance;
|
|
14
|
+
};
|
|
15
|
+
function createStateSourceHook(options) {
|
|
16
|
+
let getState = typeof options == "function" ? options : options.getState, suspense = "shouldSuspend" in options && "suspender" in options ? options : void 0;
|
|
17
|
+
function useHook(...t0) {
|
|
18
|
+
let $ = c(3), params = t0, instance = useSanityInstance();
|
|
19
|
+
if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) throw suspense.suspender(instance, ...params);
|
|
20
|
+
let t1;
|
|
21
|
+
$[0] !== instance || $[1] !== params ? (t1 = getState(instance, ...params), $[0] = instance, $[1] = params, $[2] = t1) : t1 = $[2];
|
|
22
|
+
let state = t1;
|
|
23
|
+
return useSyncExternalStore(state.subscribe, state.getCurrent);
|
|
24
|
+
}
|
|
25
|
+
return useHook;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* @internal
|
|
29
|
+
* A React hook that subscribes to authentication state changes.
|
|
30
|
+
*
|
|
31
|
+
* This hook provides access to the current authentication state type from the Sanity auth store.
|
|
32
|
+
* It automatically re-renders when the authentication state changes.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* The hook uses `useSyncExternalStore` to safely subscribe to auth state changes
|
|
36
|
+
* and ensure consistency between server and client rendering.
|
|
37
|
+
*
|
|
38
|
+
* @returns The current authentication state type
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* function AuthStatus() {
|
|
43
|
+
* const authState = useAuthState()
|
|
44
|
+
* return <div>Current auth state: {authState}</div>
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
const useAuthState = createStateSourceHook(getAuthState), useNodeState = createStateSourceHook({
|
|
49
|
+
getState: getNodeState,
|
|
50
|
+
shouldSuspend: (instance, nodeInput) => getNodeState(instance, nodeInput).getCurrent() === void 0,
|
|
51
|
+
suspender: (instance, nodeInput) => firstValueFrom(getNodeState(instance, nodeInput).observable.pipe(filter(Boolean)))
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* @internal
|
|
55
|
+
* Hook to wrap a Comlink node in a React hook.
|
|
56
|
+
* Our store functionality takes care of the lifecycle of the node,
|
|
57
|
+
* as well as sharing a single node between invocations if they share the same name.
|
|
58
|
+
*
|
|
59
|
+
* Generally not to be used directly, but to be used as a dependency of
|
|
60
|
+
* Comlink-powered hooks like `useStudioWorkspacesByProjectIdDataset`.
|
|
61
|
+
*/
|
|
62
|
+
function useWindowConnection(t0) {
|
|
63
|
+
let $ = c(19), { name, connectTo, onMessage } = t0, t1;
|
|
64
|
+
$[0] !== connectTo || $[1] !== name ? (t1 = {
|
|
65
|
+
name,
|
|
66
|
+
connectTo
|
|
67
|
+
}, $[0] = connectTo, $[1] = name, $[2] = t1) : t1 = $[2];
|
|
68
|
+
let { node } = useNodeState(t1), t2;
|
|
69
|
+
$[3] === Symbol.for("react.memo_cache_sentinel") ? (t2 = [], $[3] = t2) : t2 = $[3];
|
|
70
|
+
let messageUnsubscribers = useRef(t2), instance = useSanityInstance(), t3;
|
|
71
|
+
$[4] !== node || $[5] !== onMessage ? (t3 = () => (onMessage && Object.entries(onMessage).forEach((t4) => {
|
|
72
|
+
let [type, handler] = t4, messageUnsubscribe = node.on(type, handler);
|
|
73
|
+
messageUnsubscribe && messageUnsubscribers.current.push(messageUnsubscribe);
|
|
74
|
+
}), () => {
|
|
75
|
+
messageUnsubscribers.current.forEach(_temp), messageUnsubscribers.current = [];
|
|
76
|
+
}), $[4] = node, $[5] = onMessage, $[6] = t3) : t3 = $[6];
|
|
77
|
+
let t4;
|
|
78
|
+
$[7] !== instance || $[8] !== name || $[9] !== node || $[10] !== onMessage ? (t4 = [
|
|
79
|
+
instance,
|
|
80
|
+
name,
|
|
81
|
+
onMessage,
|
|
82
|
+
node
|
|
83
|
+
], $[7] = instance, $[8] = name, $[9] = node, $[10] = onMessage, $[11] = t4) : t4 = $[11], useEffect(t3, t4);
|
|
84
|
+
let t5;
|
|
85
|
+
$[12] === node ? t5 = $[13] : (t5 = (type_0, data) => {
|
|
86
|
+
node.post(type_0, data);
|
|
87
|
+
}, $[12] = node, $[13] = t5);
|
|
88
|
+
let sendMessage = t5, t6;
|
|
89
|
+
$[14] === node ? t6 = $[15] : (t6 = (type_1, data_0, fetchOptions) => node.fetch(type_1, data_0, fetchOptions ?? {}), $[14] = node, $[15] = t6);
|
|
90
|
+
let fetch = t6, t7;
|
|
91
|
+
return $[16] !== fetch || $[17] !== sendMessage ? (t7 = {
|
|
92
|
+
sendMessage,
|
|
93
|
+
fetch
|
|
94
|
+
}, $[16] = fetch, $[17] = sendMessage, $[18] = t7) : t7 = $[18], t7;
|
|
95
|
+
}
|
|
96
|
+
function _temp(unsubscribe) {
|
|
97
|
+
return unsubscribe();
|
|
98
|
+
}
|
|
99
|
+
const OS_BUS_KEY = Symbol.for("sanity.os.bus");
|
|
100
|
+
/**
|
|
101
|
+
* Whether this app is running inside the dashboard, embedded in its window.
|
|
102
|
+
*
|
|
103
|
+
* Apps embedded this way share the dashboard's realm, so the bus it installs
|
|
104
|
+
* is visible on `globalThis`. This is `false` in a standalone app, where we
|
|
105
|
+
* must never import `@sanity/workbench` (it would install a bus and add bundle
|
|
106
|
+
* weight for no reason). Note: this is a different embedding model to the Core
|
|
107
|
+
* UI iframe, which is detected separately via the dashboard context — that
|
|
108
|
+
* signal is not set for apps sharing the dashboard's window.
|
|
109
|
+
*
|
|
110
|
+
* @internal
|
|
111
|
+
*/
|
|
112
|
+
function isDashboardEnvironment() {
|
|
113
|
+
return typeof globalThis == "object" && OS_BUS_KEY in globalThis;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Observes the session token issued by the dashboard "OS", tracking the OS auth
|
|
117
|
+
* state over time.
|
|
118
|
+
*
|
|
119
|
+
* Returns `undefined` when the app is not embedded in the dashboard, so the
|
|
120
|
+
* caller uses its normal auth flow. Inside the dashboard, subscribes to the
|
|
121
|
+
* `auth.token` state topic, emitting the current token — or `null` when the OS
|
|
122
|
+
* is signed out — and re-emitting as the OS auth state changes, so sign-in/out
|
|
123
|
+
* propagates instead of being captured once. Any bus error is treated as "no
|
|
124
|
+
* token" (`null`). The token is used in-memory only and never persisted.
|
|
125
|
+
*
|
|
126
|
+
* @internal
|
|
127
|
+
*/
|
|
128
|
+
function observeDashboardToken() {
|
|
129
|
+
if (isDashboardEnvironment()) return from(import("@sanity/workbench")).pipe(switchMap$1(({ os }) => os.subscribe("auth.token")), catchError(() => of(null)));
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Asks the dashboard "OS" to reissue the session token, e.g. after its current
|
|
133
|
+
* one was rejected with a 401. Fire-and-forget: the reissued token arrives via
|
|
134
|
+
* the `auth.token` subscription in {@link observeDashboardToken}. No-op outside
|
|
135
|
+
* the dashboard.
|
|
136
|
+
*
|
|
137
|
+
* @internal
|
|
138
|
+
*/
|
|
139
|
+
function refreshDashboardToken() {
|
|
140
|
+
isDashboardEnvironment() && import("@sanity/workbench").then(({ os }) => os.emit("auth.token.refresh", void 0), () => {});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Keeps the SDK auth token in sync with the dashboard "OS".
|
|
144
|
+
*
|
|
145
|
+
* When running inside the dashboard the OS owns the session, so we subscribe
|
|
146
|
+
* to its `auth.token` stream and mirror each value into
|
|
147
|
+
* the auth store — a token logs us in, `null` logs us out, and later OS
|
|
148
|
+
* sign-in/out propagates automatically. When a request is rejected with a 401
|
|
149
|
+
* (the token expired), we ask the OS to reissue rather than tearing the session
|
|
150
|
+
* down; the new token arrives back through the same subscription.
|
|
151
|
+
*/
|
|
152
|
+
function DashboardTokenRefresh(t0) {
|
|
153
|
+
let $ = c(8), { children } = t0, instance = useSanityInstance(), authState = useAuthState(), processed401ErrorRef = useRef(null), t1, t2;
|
|
154
|
+
$[0] === instance ? (t1 = $[1], t2 = $[2]) : (t1 = () => {
|
|
155
|
+
let token$ = observeDashboardToken();
|
|
156
|
+
if (!token$) return;
|
|
157
|
+
let subscription = token$.subscribe((token) => setAuthToken(instance, token));
|
|
158
|
+
return () => subscription.unsubscribe();
|
|
159
|
+
}, t2 = [instance], $[0] = instance, $[1] = t1, $[2] = t2), useEffect(t1, t2);
|
|
160
|
+
let t3;
|
|
161
|
+
$[3] !== authState.error || $[4] !== authState.type ? (t3 = () => {
|
|
162
|
+
let has401Error = authState.type === AuthStateType.ERROR && authState.error?.statusCode === 401;
|
|
163
|
+
has401Error && processed401ErrorRef.current !== authState.error ? (processed401ErrorRef.current = authState.error, refreshDashboardToken()) : has401Error || (processed401ErrorRef.current = null);
|
|
164
|
+
}, $[3] = authState.error, $[4] = authState.type, $[5] = t3) : t3 = $[5];
|
|
165
|
+
let t4;
|
|
166
|
+
return $[6] === authState ? t4 = $[7] : (t4 = [authState], $[6] = authState, $[7] = t4), useEffect(t3, t4), children;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Authenticates the SDK with the Sanity Dashboard's session when the app runs
|
|
170
|
+
* inside the dashboard.
|
|
171
|
+
*
|
|
172
|
+
* The dashboard owns the session there: this provider subscribes to the token
|
|
173
|
+
* the dashboard issues, writes each new value into the SDK's auth store (where
|
|
174
|
+
* SDK hooks read it from), and asks the dashboard for a fresh token when a
|
|
175
|
+
* request fails with a 401. Outside the dashboard it renders children
|
|
176
|
+
* unchanged and the app's normal auth flow applies.
|
|
177
|
+
*
|
|
178
|
+
* @remarks
|
|
179
|
+
* `AuthBoundary` mounts this automatically, so most apps never need it
|
|
180
|
+
* directly. Mount it yourself only when your app runs inside the dashboard
|
|
181
|
+
* without `AuthBoundary` — that is, the app renders its own loading and error
|
|
182
|
+
* UI instead of the SDK's login flow — but still uses SDK hooks such as
|
|
183
|
+
* `useQuery`, which need the dashboard's token in the auth store to
|
|
184
|
+
* authenticate their requests.
|
|
185
|
+
*
|
|
186
|
+
* Mount it once, inside the provider that creates the Sanity instance whose
|
|
187
|
+
* store should receive the token.
|
|
188
|
+
*
|
|
189
|
+
* @example
|
|
190
|
+
* ```tsx
|
|
191
|
+
* import {ResourceProvider} from '@sanity/sdk-react'
|
|
192
|
+
* import {TokenRefreshProvider} from '@sanity/sdk-react/dashboard'
|
|
193
|
+
*
|
|
194
|
+
* function EmbeddedApp() {
|
|
195
|
+
* return (
|
|
196
|
+
* <ResourceProvider fallback={<Loading />}>
|
|
197
|
+
* <TokenRefreshProvider>
|
|
198
|
+
* <App />
|
|
199
|
+
* </TokenRefreshProvider>
|
|
200
|
+
* </ResourceProvider>
|
|
201
|
+
* )
|
|
202
|
+
* }
|
|
203
|
+
* ```
|
|
204
|
+
*
|
|
205
|
+
* @public
|
|
206
|
+
*/
|
|
207
|
+
const DashboardTokenRefreshProvider = (t0) => {
|
|
208
|
+
let $ = c(2), { children } = t0;
|
|
209
|
+
if (isDashboardEnvironment()) {
|
|
210
|
+
let t1;
|
|
211
|
+
return $[0] === children ? t1 = $[1] : (t1 = /* @__PURE__ */ jsx(DashboardTokenRefresh, { children }), $[0] = children, $[1] = t1), t1;
|
|
212
|
+
}
|
|
213
|
+
return children;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* @public
|
|
217
|
+
*
|
|
218
|
+
* A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```tsx
|
|
222
|
+
* function DashboardComponent() {
|
|
223
|
+
* const orgId = useOrganizationId()
|
|
224
|
+
*
|
|
225
|
+
* if (!orgId) return null
|
|
226
|
+
*
|
|
227
|
+
* return <div>Organization ID: {String(orgId)}</div>
|
|
228
|
+
* }
|
|
229
|
+
* ```
|
|
230
|
+
*
|
|
231
|
+
* @category Dashboard
|
|
232
|
+
* @returns The dashboard organization ID (string | undefined)
|
|
233
|
+
*/
|
|
234
|
+
function useOrganizationId() {
|
|
235
|
+
let $ = c(2), instance = useSanityInstance(), t0;
|
|
236
|
+
$[0] === instance ? t0 = $[1] : (t0 = getDashboardOrganizationId(instance), $[0] = instance, $[1] = t0);
|
|
237
|
+
let { subscribe, getCurrent } = t0;
|
|
238
|
+
return useSyncExternalStore(subscribe, getCurrent);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Hook that fetches studio workspaces and organizes them by projectId:dataset
|
|
242
|
+
* @internal
|
|
243
|
+
*
|
|
244
|
+
* @example
|
|
245
|
+
* ```tsx
|
|
246
|
+
* import {useStudioWorkspacesByProjectIdDataset} from '@sanity/sdk-react'
|
|
247
|
+
* import {Card, Code, Button} from '@sanity/ui'
|
|
248
|
+
* import {Suspense} from 'react'
|
|
249
|
+
*
|
|
250
|
+
* function WorkspacesCard() {
|
|
251
|
+
* const {workspacesByProjectIdAndDataset, error} = useStudioWorkspacesByProjectIdDataset()
|
|
252
|
+
* if (error) {
|
|
253
|
+
* return <div>Error: {error}</div>
|
|
254
|
+
* }
|
|
255
|
+
* return (
|
|
256
|
+
* <Card padding={4} radius={2} shadow={1}>
|
|
257
|
+
* <Code language="json">
|
|
258
|
+
* {JSON.stringify(workspacesByProjectIdAndDataset, null, 2)}
|
|
259
|
+
* </Code>
|
|
260
|
+
* </Card>
|
|
261
|
+
* )
|
|
262
|
+
* }
|
|
263
|
+
*
|
|
264
|
+
* // Wrap the component with Suspense since the hook may suspend
|
|
265
|
+
* function DashboardWorkspaces() {
|
|
266
|
+
* return (
|
|
267
|
+
* <Suspense fallback={<Button text="Loading..." disabled />}>
|
|
268
|
+
* <WorkspacesCard />
|
|
269
|
+
* </Suspense>
|
|
270
|
+
* )
|
|
271
|
+
* }
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
function useStudioWorkspacesByProjectIdDataset() {
|
|
275
|
+
let $ = c(8), t0;
|
|
276
|
+
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {}, $[0] = t0) : t0 = $[0];
|
|
277
|
+
let [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] = useState(t0), [error, setError] = useState(null), t1;
|
|
278
|
+
$[1] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
|
|
279
|
+
name: SDK_NODE_NAME,
|
|
280
|
+
connectTo: SDK_CHANNEL_NAME
|
|
281
|
+
}, $[1] = t1) : t1 = $[1];
|
|
282
|
+
let { fetch } = useWindowConnection(t1), t2, t3;
|
|
283
|
+
$[2] === fetch ? (t2 = $[3], t3 = $[4]) : (t2 = () => {
|
|
284
|
+
if (!fetch) return;
|
|
285
|
+
let fetchWorkspaces = async function fetchWorkspaces(signal) {
|
|
286
|
+
try {
|
|
287
|
+
let data = await fetch("dashboard/v1/context", void 0, { signal }), workspaceMap = {}, noProjectIdAndDataset = [];
|
|
288
|
+
data.context.availableResources.forEach((resource) => {
|
|
289
|
+
if (resource.type !== "studio") return;
|
|
290
|
+
if (!resource.projectId || !resource.dataset) {
|
|
291
|
+
noProjectIdAndDataset.push(resource);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
let key = `${resource.projectId}:${resource.dataset}`;
|
|
295
|
+
workspaceMap[key] || (workspaceMap[key] = []), workspaceMap[key].push(resource);
|
|
296
|
+
}), noProjectIdAndDataset.length > 0 && (workspaceMap["NO_PROJECT_ID:NO_DATASET"] = noProjectIdAndDataset), setWorkspacesByProjectIdAndDataset(workspaceMap), setError(null);
|
|
297
|
+
} catch (t4) {
|
|
298
|
+
let err = t4;
|
|
299
|
+
if (err instanceof Error) {
|
|
300
|
+
if (err.name === "AbortError") return;
|
|
301
|
+
setError("Failed to fetch workspaces");
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}, controller = new AbortController();
|
|
305
|
+
return fetchWorkspaces(controller.signal), () => {
|
|
306
|
+
controller.abort();
|
|
307
|
+
};
|
|
308
|
+
}, t3 = [fetch], $[2] = fetch, $[3] = t2, $[4] = t3), useEffect(t2, t3);
|
|
309
|
+
let t4;
|
|
310
|
+
return $[5] !== error || $[6] !== workspacesByProjectIdAndDataset ? (t4 = {
|
|
311
|
+
workspacesByProjectIdAndDataset,
|
|
312
|
+
error
|
|
313
|
+
}, $[5] = error, $[6] = workspacesByProjectIdAndDataset, $[7] = t4) : t4 = $[7], t4;
|
|
314
|
+
}
|
|
315
|
+
export { useWindowConnection as a, useSanityInstance as c, isDashboardEnvironment as i, SanityInstanceContext as l, useOrganizationId as n, useAuthState as o, DashboardTokenRefreshProvider as r, createStateSourceHook as s, useStudioWorkspacesByProjectIdDataset as t };
|
|
316
|
+
|
|
317
|
+
//# sourceMappingURL=useStudioWorkspacesByProjectIdDataset-DxUlukmF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useStudioWorkspacesByProjectIdDataset-DxUlukmF.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","from","Observable","of","catchError","switchMap","OS_BUS_KEY","Symbol","for","isDashboardEnvironment","globalThis","observeDashboardToken","undefined","pipe","os","subscribe","refreshDashboardToken","then","emit","ClientError","AuthStateType","setAuthToken","React","PropsWithChildren","useEffect","useRef","useAuthState","useSanityInstance","isDashboardEnvironment","observeDashboardToken","refreshDashboardToken","DashboardTokenRefresh","t0","$","_c","children","instance","authState","processed401ErrorRef","t1","t2","token$","subscription","subscribe","token","unsubscribe","t3","error","type","has401Error","ERROR","statusCode","current","t4","DashboardTokenRefreshProvider","FC","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/context/dashboardToken.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 {from, type Observable, of} from 'rxjs'\nimport {catchError, switchMap} from 'rxjs/operators'\n\n// The dashboard host installs its shared message bus on this well-known global\n// symbol before it loads the apps it embeds in its own window. It must match\n// the key used by `@sanity/workbench` (`Symbol.for('sanity.os.bus')`).\nconst OS_BUS_KEY = Symbol.for('sanity.os.bus')\n\n/**\n * Whether this app is running inside the dashboard, embedded in its window.\n *\n * Apps embedded this way share the dashboard's realm, so the bus it installs\n * is visible on `globalThis`. This is `false` in a standalone app, where we\n * must never import `@sanity/workbench` (it would install a bus and add bundle\n * weight for no reason). Note: this is a different embedding model to the Core\n * UI iframe, which is detected separately via the dashboard context — that\n * signal is not set for apps sharing the dashboard's window.\n *\n * @internal\n */\nexport function isDashboardEnvironment(): boolean {\n return typeof globalThis === 'object' && OS_BUS_KEY in globalThis\n}\n\n/**\n * Observes the session token issued by the dashboard \"OS\", tracking the OS auth\n * state over time.\n *\n * Returns `undefined` when the app is not embedded in the dashboard, so the\n * caller uses its normal auth flow. Inside the dashboard, subscribes to the\n * `auth.token` state topic, emitting the current token — or `null` when the OS\n * is signed out — and re-emitting as the OS auth state changes, so sign-in/out\n * propagates instead of being captured once. Any bus error is treated as \"no\n * token\" (`null`). The token is used in-memory only and never persisted.\n *\n * @internal\n */\nexport function observeDashboardToken(): Observable<string | null> | undefined {\n if (!isDashboardEnvironment()) return undefined\n\n return from(import('@sanity/workbench')).pipe(\n switchMap(({os}) => os.subscribe('auth.token')),\n // Any failure (importing the host bundle, or the subscription) means \"no OS token\".\n catchError(() => of(null)),\n )\n}\n\n/**\n * Asks the dashboard \"OS\" to reissue the session token, e.g. after its current\n * one was rejected with a 401. Fire-and-forget: the reissued token arrives via\n * the `auth.token` subscription in {@link observeDashboardToken}. No-op outside\n * the dashboard.\n *\n * @internal\n */\nexport function refreshDashboardToken(): void {\n if (!isDashboardEnvironment()) return\n\n void import('@sanity/workbench').then(\n ({os}) => os.emit('auth.token.refresh', undefined),\n () => {},\n )\n}\n","import {type ClientError} from '@sanity/client'\nimport {AuthStateType, setAuthToken} from '@sanity/sdk'\nimport React, {type PropsWithChildren, useEffect, useRef} from 'react'\n\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\nimport {\n isDashboardEnvironment,\n observeDashboardToken,\n refreshDashboardToken,\n} from './dashboardToken'\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({children}: PropsWithChildren) {\n const instance = useSanityInstance()\n const authState = useAuthState()\n const processed401ErrorRef = useRef<unknown | null>(null)\n\n useEffect(() => {\n const token$ = observeDashboardToken()\n if (!token$) return undefined\n const subscription = token$.subscribe((token) => setAuthToken(instance, token))\n return () => subscription.unsubscribe()\n }, [instance])\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 refreshDashboardToken()\n } else if (!has401Error) {\n processed401ErrorRef.current = null\n }\n }, [authState])\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 if (isDashboardEnvironment()) {\n return <DashboardTokenRefresh>{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,SAA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D,QAAQ;IAAC,CACjC,GAEGJ,sBAAqBO,SAAU,MACjCR,aAAa,8BAA8BC,wBAG7CZ,mCAAmCW,YAAY,GAC/CV,SAAS,IAAI;GAAC,SAAAmB,IAAA;IACPC,IAAAA,MAAAA;IACP,IAAIA,eAAeC,OAAK;KACtB,IAAID,IAAGxC,SAAU,cAAY;KAG7BoB,SAAS,4BAA4B;IAAC;GACvC;EACF,GAGHsB,aAAmB,IAAIC,gBAAgB;EACL,OAAlCjB,gBAAgBgB,WAAUf,MAAO,SAE1B;GACLe,WAAUE,MAAO;EAAC;CACnB,GACAnB,KAAA,CAACF,KAAK,GAACT,EAAA,KAAAS,OAAAT,EAAA,KAAAU,IAAAV,EAAA,KAAAW,KA/CV9B,UAAU6B,IA+CPC,EAAO;CAAC,IAAAc;CAKV,OALUzB,EAAA,OAAAF,SAAAE,EAAA,OAAAH,mCAEJ4B,KAAA;EAAA5B;EAAAC;CAGP,GAACE,EAAA,KAAAF,OAAAE,EAAA,KAAAH,iCAAAG,EAAA,KAAAyB,MAAAA,KAAAzB,EAAA,IAHMyB;AAGN"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/sdk-react",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Sanity SDK React toolkit for Content OS",
|
|
6
6
|
"keywords": [
|
|
@@ -34,22 +34,23 @@
|
|
|
34
34
|
"types": "./dist/index.d.ts",
|
|
35
35
|
"exports": {
|
|
36
36
|
".": "./dist/index.js",
|
|
37
|
-
"./package.json": "./package.json"
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
"./dashboard": "./dist/_exports/dashboard.js"
|
|
38
39
|
},
|
|
39
40
|
"publishConfig": {
|
|
40
41
|
"access": "public"
|
|
41
42
|
},
|
|
42
43
|
"dependencies": {
|
|
43
|
-
"@sanity/client": "^
|
|
44
|
+
"@sanity/client": "^8.4.0",
|
|
44
45
|
"@sanity/message-protocol": "^0.24.0",
|
|
45
|
-
"@sanity/types": "^6.
|
|
46
|
-
"@sanity/workbench": "0.1.0-alpha.
|
|
46
|
+
"@sanity/types": "^6.12.0",
|
|
47
|
+
"@sanity/workbench": "0.1.0-alpha.45",
|
|
47
48
|
"groq": "3.88.1-typegen-experimental.0",
|
|
48
49
|
"react-compiler-runtime": "^1.0.0",
|
|
49
50
|
"react-error-boundary": "^6.1.2",
|
|
50
51
|
"rxjs": "^7.8.2",
|
|
51
52
|
"xstate": "^5.31.0",
|
|
52
|
-
"@sanity/sdk": "3.
|
|
53
|
+
"@sanity/sdk": "3.1.0"
|
|
53
54
|
},
|
|
54
55
|
"devDependencies": {
|
|
55
56
|
"@sanity/browserslist-config": "^1.0.5",
|
|
@@ -67,21 +68,21 @@
|
|
|
67
68
|
"groq-js": "^2.0.0",
|
|
68
69
|
"jsdom": "^29.1.1",
|
|
69
70
|
"oxfmt": "^0.58.0",
|
|
70
|
-
"react": "^19.2.
|
|
71
|
-
"react-dom": "^19.2.
|
|
71
|
+
"react": "^19.2.8",
|
|
72
|
+
"react-dom": "^19.2.8",
|
|
72
73
|
"rolldown": "^1.2.3",
|
|
73
74
|
"typescript": "^6.0.3",
|
|
74
75
|
"vite": "^8.1.5",
|
|
75
76
|
"vitest": "^4.1.10",
|
|
76
77
|
"@repo/package.bundle": "3.82.0",
|
|
77
|
-
"@repo/config-eslint": "0.0.0",
|
|
78
78
|
"@repo/config-test": "0.0.1",
|
|
79
79
|
"@repo/package.config": "0.0.1",
|
|
80
|
+
"@repo/config-eslint": "0.0.0",
|
|
80
81
|
"@repo/tsconfig": "0.0.1"
|
|
81
82
|
},
|
|
82
83
|
"peerDependencies": {
|
|
83
|
-
"react": "^
|
|
84
|
-
"react-dom": "^
|
|
84
|
+
"react": "^19.2.0",
|
|
85
|
+
"react-dom": "^19.2.0"
|
|
85
86
|
},
|
|
86
87
|
"browserslist": "extends @sanity/browserslist-config",
|
|
87
88
|
"inlinedDependencies": {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export {DashboardTokenRefreshProvider as TokenRefreshProvider} from '../context/DashboardTokenRefresh'
|
|
2
|
+
export {
|
|
3
|
+
type AgentResourceContextOptions,
|
|
4
|
+
useAgentResourceContext,
|
|
5
|
+
} from '../hooks/dashboard/useAgentResourceContext'
|
|
6
|
+
export {useNavigate} from '../hooks/dashboard/useNavigate'
|
|
7
|
+
export {
|
|
8
|
+
type NavigateToStudioResult,
|
|
9
|
+
useNavigateToStudioDocument,
|
|
10
|
+
} from '../hooks/dashboard/useNavigateToStudioDocument'
|
|
11
|
+
export {useOrganizationId} from '../hooks/dashboard/useOrganizationId'
|
|
12
|
+
export {useWindowTitle} from '../hooks/dashboard/useWindowTitle'
|
|
@@ -21,10 +21,6 @@ export {
|
|
|
21
21
|
useAgentTransform,
|
|
22
22
|
useAgentTranslate,
|
|
23
23
|
} from '../hooks/agent/agentActions'
|
|
24
|
-
export {
|
|
25
|
-
type AgentResourceContextOptions,
|
|
26
|
-
useAgentResourceContext,
|
|
27
|
-
} from '../hooks/agent/useAgentResourceContext'
|
|
28
24
|
export {useApplication} from '../hooks/applications/useApplication'
|
|
29
25
|
export {useApplications} from '../hooks/applications/useApplications'
|
|
30
26
|
export {useDeleteApplication} from '../hooks/applications/useDeleteApplication'
|
|
@@ -32,7 +28,6 @@ export {useUpdateApplication} from '../hooks/applications/useUpdateApplication'
|
|
|
32
28
|
export {useAuthState} from '../hooks/auth/useAuthState'
|
|
33
29
|
export {useAuthToken} from '../hooks/auth/useAuthToken'
|
|
34
30
|
export {useCurrentUser} from '../hooks/auth/useCurrentUser'
|
|
35
|
-
export {useDashboardOrganizationId} from '../hooks/auth/useDashboardOrganizationId'
|
|
36
31
|
export {useHandleAuthCallback} from '../hooks/auth/useHandleAuthCallback'
|
|
37
32
|
export {useLoginUrl} from '../hooks/auth/useLoginUrl'
|
|
38
33
|
export {useLogOut} from '../hooks/auth/useLogOut'
|
|
@@ -55,15 +50,10 @@ export {useComments, type UseCommentsResult} from '../hooks/comments/useComments
|
|
|
55
50
|
export {useCommentThreads, type UseCommentThreadsResult} from '../hooks/comments/useCommentThreads'
|
|
56
51
|
export {useResource} from '../hooks/context/useResource'
|
|
57
52
|
export {useSanityInstance} from '../hooks/context/useSanityInstance'
|
|
58
|
-
export {
|
|
59
|
-
export {useManageFavorite} from '../hooks/dashboard/useManageFavorite'
|
|
60
|
-
export {
|
|
61
|
-
type NavigateToStudioResult,
|
|
62
|
-
useNavigateToStudioDocument,
|
|
63
|
-
} from '../hooks/dashboard/useNavigateToStudioDocument'
|
|
53
|
+
export {useFavorite} from '../hooks/dashboard/useFavorite'
|
|
64
54
|
export {useRecordDocumentHistoryEvent} from '../hooks/dashboard/useRecordDocumentHistoryEvent'
|
|
65
55
|
export {useStudioWorkspacesByProjectIdDataset} from '../hooks/dashboard/useStudioWorkspacesByProjectIdDataset'
|
|
66
|
-
export {
|
|
56
|
+
export {useUpdateFavorite} from '../hooks/dashboard/useUpdateFavorite'
|
|
67
57
|
export {useDatasets} from '../hooks/datasets/useDatasets'
|
|
68
58
|
export {useApplyDocumentActions} from '../hooks/document/useApplyDocumentActions'
|
|
69
59
|
export {type CreateDocumentOverrides, useCreateDocument} from '../hooks/document/useCreateDocument'
|
|
@@ -3,7 +3,7 @@ import {render} from '@testing-library/react'
|
|
|
3
3
|
import React from 'react'
|
|
4
4
|
import {beforeEach, describe, expect, it, vi} from 'vitest'
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import {useOrganizationId} from '../hooks/dashboard/useOrganizationId'
|
|
7
7
|
import {resolveOrgResources} from '../utils/resolveOrgResources'
|
|
8
8
|
import {SDKProvider} from './SDKProvider'
|
|
9
9
|
|
|
@@ -14,8 +14,8 @@ vi.mock('../hooks/context/useSanityInstance', () => {
|
|
|
14
14
|
return {useSanityInstance: () => instance}
|
|
15
15
|
})
|
|
16
16
|
|
|
17
|
-
vi.mock('../hooks/
|
|
18
|
-
|
|
17
|
+
vi.mock('../hooks/dashboard/useOrganizationId', () => ({
|
|
18
|
+
useOrganizationId: vi.fn(),
|
|
19
19
|
}))
|
|
20
20
|
|
|
21
21
|
vi.mock('../utils/resolveOrgResources', () => ({
|
|
@@ -53,13 +53,13 @@ vi.mock('./auth/AuthBoundary', () => ({
|
|
|
53
53
|
}))
|
|
54
54
|
|
|
55
55
|
const mockResolveOrgResources = vi.mocked(resolveOrgResources)
|
|
56
|
-
const
|
|
56
|
+
const mockUseOrganizationId = vi.mocked(useOrganizationId)
|
|
57
57
|
|
|
58
58
|
describe('SDKProvider', () => {
|
|
59
59
|
beforeEach(() => {
|
|
60
60
|
vi.clearAllMocks()
|
|
61
61
|
mockResolveOrgResources.mockResolvedValue({})
|
|
62
|
-
|
|
62
|
+
mockUseOrganizationId.mockReturnValue(undefined)
|
|
63
63
|
})
|
|
64
64
|
|
|
65
65
|
it('renders single ResourceProvider with AuthBoundary for a single config', () => {
|
|
@@ -5,8 +5,8 @@ import {useEffect, useMemo} from 'react'
|
|
|
5
5
|
import {ErrorBoundary, type FallbackProps} from 'react-error-boundary'
|
|
6
6
|
|
|
7
7
|
import {ComlinkTokenRefreshProvider} from '../../context/ComlinkTokenRefresh'
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import {isDashboardEnvironment} from '../../context/dashboardToken'
|
|
9
|
+
import {DashboardTokenRefreshProvider} from '../../context/DashboardTokenRefresh'
|
|
10
10
|
import {useAuthState} from '../../hooks/auth/useAuthState'
|
|
11
11
|
import {useLoginUrl} from '../../hooks/auth/useLoginUrl'
|
|
12
12
|
import {useVerifyOrgProjects} from '../../hooks/auth/useVerifyOrgProjects'
|
|
@@ -144,11 +144,11 @@ export function AuthBoundary({
|
|
|
144
144
|
|
|
145
145
|
return (
|
|
146
146
|
<ComlinkTokenRefreshProvider>
|
|
147
|
-
<
|
|
147
|
+
<DashboardTokenRefreshProvider>
|
|
148
148
|
<ErrorBoundary FallbackComponent={FallbackComponent} resetKeys={[sessionResetKey]}>
|
|
149
149
|
<AuthSwitch {...props} />
|
|
150
150
|
</ErrorBoundary>
|
|
151
|
-
</
|
|
151
|
+
</DashboardTokenRefreshProvider>
|
|
152
152
|
</ComlinkTokenRefreshProvider>
|
|
153
153
|
)
|
|
154
154
|
}
|
|
@@ -187,7 +187,7 @@ function AuthSwitch({
|
|
|
187
187
|
const loginUrl = useLoginUrl()
|
|
188
188
|
|
|
189
189
|
useEffect(() => {
|
|
190
|
-
if (isLoggedOut && !isInIframe() && !isStudio && !
|
|
190
|
+
if (isLoggedOut && !isInIframe() && !isStudio && !isDashboardEnvironment()) {
|
|
191
191
|
// We don't want to redirect to login if we're in the Dashboard, in studio
|
|
192
192
|
// mode, or in the workbench (the OS owns the session and mints the token)
|
|
193
193
|
window.location.href = loginUrl
|