next-sanity 0.5.2 → 0.6.3
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/README.md +10 -3
- package/dist/currentUser.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/next-sanity.cjs.development.js +19 -7
- package/dist/next-sanity.cjs.development.js.map +1 -1
- package/dist/next-sanity.cjs.production.min.js +1 -1
- package/dist/next-sanity.cjs.production.min.js.map +1 -1
- package/dist/next-sanity.esm.js +19 -7
- package/dist/next-sanity.esm.js.map +1 -1
- package/dist/pages/[[...studio]].d.ts +2 -0
- package/dist/types.d.ts +5 -0
- package/dist/useSubscription.d.ts +1 -1
- package/package.json +70 -67
- package/src/client.ts +1 -1
- package/src/currentUser.ts +10 -2
- package/src/index.ts +2 -1
- package/src/types.ts +7 -0
- package/src/useSubscription.ts +14 -6
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ We have plans for optimizations in the roadmap.
|
|
|
41
41
|
|
|
42
42
|
## Optimizing bundle size
|
|
43
43
|
|
|
44
|
-
The first version of `next-sanity` shipped with the [`picosanity`](https://github.com/rexxars/picosanity) client built-in. This caused some confusion for people who
|
|
44
|
+
The first version of `next-sanity` shipped with the [`picosanity`](https://github.com/rexxars/picosanity) client built-in. This caused some confusion for people who not only want to pull data from their Sanity.io content lake, but also send patches and mutations via API routes. Since `picosanity` only supported fetching content, it had a smaller bundle size than the full SDK.
|
|
45
45
|
|
|
46
46
|
You can leverage Next.js' [tree shaking](https://developers.google.com/web/fundamentals/performance/optimizing-javascript/tree-shaking) to avoid shipping unnecessary code to the browser. In order to do so, you first need to isolate the client configuration in its own file, and be sure to only use it inside of the data fetching functions (`getStaticProps`, `getServerProps`, and `getStaticPaths`) or in the function that goes into the API routes (`/pages/api/<your-serverless-function>.js`).
|
|
47
47
|
|
|
@@ -77,6 +77,13 @@ export const config = {
|
|
|
77
77
|
* Authenticated request (like preview) will always bypass the CDN
|
|
78
78
|
**/
|
|
79
79
|
useCdn: process.env.NODE_ENV === 'production',
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* OPTIONAL config to enable authentication with custom token
|
|
83
|
+
* You might need this if you host the preview on a different url than Sanity Studio
|
|
84
|
+
*/
|
|
85
|
+
token: '<sanity access token>',
|
|
86
|
+
EventSource: /* provide your own event source implementation. Required in browsers to support the above token parameter. */
|
|
80
87
|
}
|
|
81
88
|
```
|
|
82
89
|
|
|
@@ -120,7 +127,7 @@ export const getClient = (usePreview) => (usePreview ? previewClient : sanityCli
|
|
|
120
127
|
|
|
121
128
|
## Example: Minimal blog post template
|
|
122
129
|
|
|
123
|
-
A minimal example for a blog post template using the schema from
|
|
130
|
+
A minimal example for a blog post template using the schema from the Sanity Studio blog example. It includes the real-time preview using the configuration illustrated above:
|
|
124
131
|
|
|
125
132
|
```jsx
|
|
126
133
|
// pages/posts/[slug].js
|
|
@@ -239,4 +246,4 @@ $ yarn add @sanity/image-url
|
|
|
239
246
|
|
|
240
247
|
## License
|
|
241
248
|
|
|
242
|
-
MIT-licensed. See LICENSE.
|
|
249
|
+
MIT-licensed. See [LICENSE](LICENSE).
|
package/dist/currentUser.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CurrentUser } from './types';
|
|
2
1
|
import { Aborter } from './aborter';
|
|
2
|
+
import { CurrentUser } from './types';
|
|
3
3
|
export declare function createCurrentUserHook({ projectId }: {
|
|
4
4
|
projectId: string;
|
|
5
5
|
dataset?: string;
|
|
@@ -8,4 +8,4 @@ export declare function createCurrentUserHook({ projectId }: {
|
|
|
8
8
|
error: Error | undefined;
|
|
9
9
|
loading: boolean;
|
|
10
10
|
};
|
|
11
|
-
export declare function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null>;
|
|
11
|
+
export declare function getCurrentUser(projectId: string, abort: Aborter, token?: string): Promise<CurrentUser | null>;
|
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ import type { Aborter as AborterForExport } from './aborter';
|
|
|
3
3
|
export declare type ClientConfig = ClientConfigForExport;
|
|
4
4
|
export declare type SanityClient = SanityClientForExport;
|
|
5
5
|
export declare type Aborter = AborterForExport;
|
|
6
|
-
export * from './types';
|
|
7
6
|
export * from './client';
|
|
8
7
|
export { createCurrentUserHook } from './currentUser';
|
|
8
|
+
export * from './types';
|
|
9
9
|
export { createPreviewSubscriptionHook } from './useSubscription';
|
|
10
10
|
export { default as groq } from 'groq';
|
|
@@ -79,14 +79,19 @@ function getAborter() {
|
|
|
79
79
|
|
|
80
80
|
function createCurrentUserHook(_ref) {
|
|
81
81
|
var projectId = _ref.projectId;
|
|
82
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
82
83
|
return function () {
|
|
83
84
|
return useCurrentUser(projectId);
|
|
84
85
|
};
|
|
85
86
|
}
|
|
86
|
-
function getCurrentUser(projectId, abort) {
|
|
87
|
+
function getCurrentUser(projectId, abort, token) {
|
|
88
|
+
var headers = token ? {
|
|
89
|
+
Authorization: "Bearer " + token
|
|
90
|
+
} : undefined;
|
|
87
91
|
return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
|
|
88
92
|
credentials: 'include',
|
|
89
|
-
signal: abort.signal
|
|
93
|
+
signal: abort.signal,
|
|
94
|
+
headers: headers
|
|
90
95
|
}).then(function (res) {
|
|
91
96
|
return res.json();
|
|
92
97
|
}).then(function (res) {
|
|
@@ -119,10 +124,13 @@ function useCurrentUser(projectId) {
|
|
|
119
124
|
};
|
|
120
125
|
}
|
|
121
126
|
|
|
122
|
-
var EMPTY_PARAMS = {};
|
|
127
|
+
var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
128
|
+
|
|
123
129
|
function createPreviewSubscriptionHook(_ref) {
|
|
124
130
|
var projectId = _ref.projectId,
|
|
125
131
|
dataset = _ref.dataset,
|
|
132
|
+
token = _ref.token,
|
|
133
|
+
EventSource = _ref.EventSource,
|
|
126
134
|
_ref$documentLimit = _ref.documentLimit,
|
|
127
135
|
documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
|
|
128
136
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -143,7 +151,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
143
151
|
query: query,
|
|
144
152
|
params: params,
|
|
145
153
|
initialData: initialData,
|
|
146
|
-
enabled: enabled ? typeof window !== 'undefined' : false
|
|
154
|
+
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
155
|
+
token: token
|
|
147
156
|
});
|
|
148
157
|
};
|
|
149
158
|
|
|
@@ -164,6 +173,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
164
173
|
projectId: projectId,
|
|
165
174
|
dataset: dataset,
|
|
166
175
|
documentLimit: documentLimit,
|
|
176
|
+
token: token,
|
|
177
|
+
EventSource: EventSource,
|
|
167
178
|
listen: true,
|
|
168
179
|
overlayDrafts: true,
|
|
169
180
|
subscriptionThrottleMs: 10
|
|
@@ -181,7 +192,8 @@ function useQuerySubscription(options) {
|
|
|
181
192
|
query = options.query,
|
|
182
193
|
initialData = options.initialData,
|
|
183
194
|
_options$enabled = options.enabled,
|
|
184
|
-
enabled = _options$enabled === void 0 ? false : _options$enabled
|
|
195
|
+
enabled = _options$enabled === void 0 ? false : _options$enabled,
|
|
196
|
+
token = options.token;
|
|
185
197
|
|
|
186
198
|
var _useState = react.useState(),
|
|
187
199
|
error = _useState[0],
|
|
@@ -206,7 +218,7 @@ function useQuerySubscription(options) {
|
|
|
206
218
|
setLoading(true);
|
|
207
219
|
var aborter = getAborter();
|
|
208
220
|
var subscription;
|
|
209
|
-
getCurrentUser(projectId, aborter).then(function (user) {
|
|
221
|
+
getCurrentUser(projectId, aborter, token).then(function (user) {
|
|
210
222
|
if (user) {
|
|
211
223
|
return;
|
|
212
224
|
} // eslint-disable-next-line no-console
|
|
@@ -237,7 +249,7 @@ function useQuerySubscription(options) {
|
|
|
237
249
|
|
|
238
250
|
aborter.abort();
|
|
239
251
|
};
|
|
240
|
-
}, [getStore, query, params, enabled]);
|
|
252
|
+
}, [getStore, query, params, enabled, projectId, token]);
|
|
241
253
|
return {
|
|
242
254
|
data: typeof data === 'undefined' ? initialData : data,
|
|
243
255
|
loading: loading,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.cjs.development.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null> {\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n}) {\n const {getStore, projectId, query, initialData, enabled = false} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAGgBA,aAAaC;AAC3B,SAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;AAAN;AACE,gBAAA,GAAU;AAACC,MAAAA,OAAO,EAAE;AAAV,KAAV;AAOD;;;;SAHCC,QAAA;AACE,SAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;AACD;;;;SALD;AACE,aAAO,KAAKE,OAAZ;AACD;;;;;;AAMH,SAAgBC;AACd,SAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK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BtB,KAAhB,EAAuBE,MAAvB,EAA+B,UAACX,GAAD,EAAMgC,MAAN;AAC5C,YAAIhC,GAAJ,EAAS;AACPJ,UAAAA,QAAQ,CAACI,GAAD,CAAR;AACD,SAFD,MAEO;AACLyB,UAAAA,OAAO,CAACO,MAAD,CAAP;AACD;AACF,OANc,CAAf;AAOD,KAnBH,EAoBGjC,KApBH,CAoBS,UAACC,GAAD;AAAA,aAAiBA,GAAG,CAACC,IAAJ,KAAa,YAAb,GAA4B,IAA5B,GAAmCL,QAAQ,CAACI,GAAD,CAA5D;AAAA,KApBT,EAqBGiC,OArBH,CAqBW;AAAA,aAAMT,UAAU,CAAC,KAAD,CAAhB;AAAA,KArBX;;AAwBA,WAAO;AACL,UAAIG,YAAJ,EAAkB;AAChBA,QAAAA,YAAY,CAACO,WAAb;AACD;;AAEDpC,MAAAA,OAAO,CAACrB,KAAR;AACD,KAND;AAOD,GAxCQ,EAwCN,CAACsC,QAAD,EAAWN,KAAX,EAAkBE,MAAlB,EAA0BE,OAA1B,CAxCM,CAAT;AA0CA,SAAO;AACLpB,IAAAA,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BmB,WAA9B,GAA4CnB,IAD7C;AAELS,IAAAA,OAAO,EAAPA,OAFK;AAGLP,IAAAA,KAAK,EAALA;AAHK,GAAP;AAKD;;;AAGD,SAAS+B,SAAT,CAAmBf,MAAnB;AACE,MAAMwB,iBAAiB,GAAGC,aAAO,CAAC;AAAA,WAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;AAAA,GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;AACA,SAAOyB,aAAO,CAAC;AAAA,WAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;AAAA,GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"next-sanity.cjs.development.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import type {ClientConfig, SanityClient} from '@sanity/client'\nimport sanityClient from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {CurrentUser} from './types'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {GroqStore, Subscription} from '@sanity/groq-store'\nimport {useEffect, useMemo, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {getCurrentUser} from './currentUser'\nimport {ProjectConfig} from './types'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","token","headers","Authorization","undefined","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","EventSource","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAGgBA,aAAaC;EAC3B,OAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;EAAN;IACE,YAAA,GAAU;MAACC,OAAO,EAAE;KAApB;;;;;SAIAC,QAAA;IACE,KAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;;;;;SAJF;MACE,OAAO,KAAKE,OAAZ;;;;;;;AAOJ,SAAgBC;EACd,OAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCdeC;MAAuBC,iBAAAA;;EAErC,OAAO;IAAA,OAAMC,cAAc,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AAA,OAAiBA,GAAG,CAACC,IAAJ,KAAa,YAAb,GAA4B,IAA5B,GAAmCL,QAAQ,CAACI,GAAD,CAA5D;KApBT,EAqBGkC,OArBH,CAqBW;MAAA,OAAMT,UAAU,CAAC,KAAD,CAAhB;KArBX;;IAwBA,OAAO;MACL,IAAIG,YAAJ,EAAkB;QAChBA,YAAY,CAACO,WAAb;;;MAGFrC,OAAO,CAACzB,KAAR;KALF;GAjCO,EAwCN,CAAC2C,QAAD,EAAWN,KAAX,EAAkBE,MAAlB,EAA0BE,OAA1B,EAAmCpC,SAAnC,EAA8CG,KAA9C,CAxCM,CAAT;EA0CA,OAAO;IACLY,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BoB,WAA9B,GAA4CpB,IAD7C;IAELS,OAAO,EAAPA,OAFK;IAGLP,KAAK,EAALA;GAHF;AAKD;;;AAGD,SAASgC,SAAT,CAAmBf,MAAnB;EACE,IAAMwB,iBAAiB,GAAGC,aAAO,CAAC;IAAA,OAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;EACA,OAAOyB,aAAO,CAAC;IAAA,OAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("@sanity/client")),r=require("react"),n=e(require("groq")),o=function(){function e(){this._signal={aborted:!1}}var t,r;return e.prototype.abort=function(){this._signal.aborted=!0},t=e,(r=[{key:"signal",get:function(){return this._signal}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function i(){return"undefined"==typeof AbortController?new o:new AbortController}function u(e,t){return fetch("https://"+e+".api.sanity.io/v1/users/me",{credentials:"include",signal:t.signal}).then((function(e){return e.json()})).then((function(e){return null!=e&&e.id?e:null}))}var a={};exports.groq=n,exports.createClient=function(e){return t(e)},exports.createCurrentUserHook=function(e){var t=e.projectId;return function(){return function(e){var t=r.useState(),n=t[0],o=t[1],a=r.useState(),c=a[0],f=a[1];return r.useEffect((function(){var t=i();return u(e,t).then(o).catch((function(e){return"AbortError"!==e.name&&f(e)})),function(){t.abort()}}),[e]),{data:n,error:c,loading:null!==n||!c}}(t)}},exports.createPreviewSubscriptionHook=function(e){var t,n=e.projectId,o=e.dataset,c=e.
|
|
1
|
+
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("@sanity/client")),r=require("react"),n=e(require("groq")),o=function(){function e(){this._signal={aborted:!1}}var t,r;return e.prototype.abort=function(){this._signal.aborted=!0},t=e,(r=[{key:"signal",get:function(){return this._signal}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function i(){return"undefined"==typeof AbortController?new o:new AbortController}function u(e,t,r){return fetch("https://"+e+".api.sanity.io/v1/users/me",{credentials:"include",signal:t.signal,headers:r?{Authorization:"Bearer "+r}:void 0}).then((function(e){return e.json()})).then((function(e){return null!=e&&e.id?e:null}))}var a={};exports.groq=n,exports.createClient=function(e){return t(e)},exports.createCurrentUserHook=function(e){var t=e.projectId;return function(){return function(e){var t=r.useState(),n=t[0],o=t[1],a=r.useState(),c=a[0],f=a[1];return r.useEffect((function(){var t=i();return u(e,t).then(o).catch((function(e){return"AbortError"!==e.name&&f(e)})),function(){t.abort()}}),[e]),{data:n,error:c,loading:null!==n||!c}}(t)}},exports.createPreviewSubscriptionHook=function(e){var t,n=e.projectId,o=e.dataset,c=e.token,f=e.EventSource,s=e.documentLimit,l=void 0===s?3e3:s;return function(e,t){void 0===t&&(t={});var o=t.params;return function(e){var t=e.getStore,n=e.projectId,o=e.query,a=e.initialData,c=e.enabled,f=void 0!==c&&c,s=e.token,l=r.useState(),d=l[0],b=l[1],p=r.useState(!1),v=p[0],g=p[1],h=r.useState(),y=h[0],m=h[1],w=function(e){var t=r.useMemo((function(){return JSON.stringify(e)}),[e]);return r.useMemo((function(){return JSON.parse(t)}),[t])}(e.params);return r.useEffect((function(){if(f){g(!0);var e,r=i();return u(n,r,s).then((function(e){if(!e)throw console.warn("Not authenticated - preview not available"),new Error("Not authenticated - preview not available")})).then((function(){return t(r)})).then((function(t){e=t.subscribe(o,w,(function(e,t){e?b(e):m(t)}))})).catch((function(e){return"AbortError"===e.name?null:b(e)})).finally((function(){return g(!1)})),function(){e&&e.unsubscribe(),r.abort()}}}),[t,o,w,f,n,s]),{data:void 0===y?a:y,loading:v,error:d}}({getStore:d,projectId:n,query:e,params:void 0===o?a:o,initialData:t.initialData,enabled:!!t.enabled&&"undefined"!=typeof window,token:c})};function d(e){return t||(t=new Promise((function(e){e(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach((function(r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})})),t.default=e,t}(require("@sanity/groq-store")))})).then((function(t){var r=t.groqStore;if(e.signal.aborted){var i=new Error("Cancelling groq store creation");return i.name="AbortError",Promise.reject(i)}return r({projectId:n,dataset:o,documentLimit:l,token:c,EventSource:f,listen:!0,overlayDrafts:!0,subscriptionThrottleMs:10})}))),t}};
|
|
2
2
|
//# sourceMappingURL=next-sanity.cjs.production.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.cjs.production.min.js","sources":["../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts","../src/client.ts"],"sourcesContent":["export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {
|
|
1
|
+
{"version":3,"file":"next-sanity.cjs.production.min.js","sources":["../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts","../src/client.ts"],"sourcesContent":["export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {CurrentUser} from './types'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {GroqStore, Subscription} from '@sanity/groq-store'\nimport {useEffect, useMemo, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {getCurrentUser} from './currentUser'\nimport {ProjectConfig} from './types'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n","import type {ClientConfig, SanityClient} from '@sanity/client'\nimport sanityClient from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n"],"names":["MockAbortController","this","aborted","abort","_signal","getAborter","AbortController","getCurrentUser","projectId","token","fetch","credentials","signal","headers","Authorization","undefined","then","res","json","id","EMPTY_PARAMS","config","sanityClient","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","useCurrentUser","store","dataset","EventSource","documentLimit","query","options","params","getStore","initialData","enabled","setLoading","setData","stringifiedParams","useMemo","JSON","stringify","parse","useParams","subscription","user","console","warn","Error","subscribe","result","finally","unsubscribe","useQuerySubscription","window","groqStore","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs"],"mappings":"qNAKMA,aAAN,aACEC,aAAU,CAACC,SAAS,8BAIpBC,MAAA,WACEF,KAAKG,QAAQF,SAAU,6BAJzB,WACE,OAAOD,KAAKG,yPAOhB,SAAgBC,IACd,MAAkC,oBAApBC,gBACV,IAAIN,EACJ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ter() {
|
|
|
54
54
|
|
|
55
55
|
function createCurrentUserHook(_ref) {
|
|
56
56
|
var projectId = _ref.projectId;
|
|
57
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
57
58
|
return function () {
|
|
58
59
|
return useCurrentUser(projectId);
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
|
-
function getCurrentUser(projectId, abort) {
|
|
62
|
+
function getCurrentUser(projectId, abort, token) {
|
|
63
|
+
var headers = token ? {
|
|
64
|
+
Authorization: "Bearer " + token
|
|
65
|
+
} : undefined;
|
|
62
66
|
return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
|
|
63
67
|
credentials: 'include',
|
|
64
|
-
signal: abort.signal
|
|
68
|
+
signal: abort.signal,
|
|
69
|
+
headers: headers
|
|
65
70
|
}).then(function (res) {
|
|
66
71
|
return res.json();
|
|
67
72
|
}).then(function (res) {
|
|
@@ -94,10 +99,13 @@ function useCurrentUser(projectId) {
|
|
|
94
99
|
};
|
|
95
100
|
}
|
|
96
101
|
|
|
97
|
-
var EMPTY_PARAMS = {};
|
|
102
|
+
var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
103
|
+
|
|
98
104
|
function createPreviewSubscriptionHook(_ref) {
|
|
99
105
|
var projectId = _ref.projectId,
|
|
100
106
|
dataset = _ref.dataset,
|
|
107
|
+
token = _ref.token,
|
|
108
|
+
EventSource = _ref.EventSource,
|
|
101
109
|
_ref$documentLimit = _ref.documentLimit,
|
|
102
110
|
documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
|
|
103
111
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -118,7 +126,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
118
126
|
query: query,
|
|
119
127
|
params: params,
|
|
120
128
|
initialData: initialData,
|
|
121
|
-
enabled: enabled ? typeof window !== 'undefined' : false
|
|
129
|
+
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
130
|
+
token: token
|
|
122
131
|
});
|
|
123
132
|
};
|
|
124
133
|
|
|
@@ -139,6 +148,8 @@ function createPreviewSubscriptionHook(_ref) {
|
|
|
139
148
|
projectId: projectId,
|
|
140
149
|
dataset: dataset,
|
|
141
150
|
documentLimit: documentLimit,
|
|
151
|
+
token: token,
|
|
152
|
+
EventSource: EventSource,
|
|
142
153
|
listen: true,
|
|
143
154
|
overlayDrafts: true,
|
|
144
155
|
subscriptionThrottleMs: 10
|
|
@@ -156,7 +167,8 @@ function useQuerySubscription(options) {
|
|
|
156
167
|
query = options.query,
|
|
157
168
|
initialData = options.initialData,
|
|
158
169
|
_options$enabled = options.enabled,
|
|
159
|
-
enabled = _options$enabled === void 0 ? false : _options$enabled
|
|
170
|
+
enabled = _options$enabled === void 0 ? false : _options$enabled,
|
|
171
|
+
token = options.token;
|
|
160
172
|
|
|
161
173
|
var _useState = useState(),
|
|
162
174
|
error = _useState[0],
|
|
@@ -181,7 +193,7 @@ function useQuerySubscription(options) {
|
|
|
181
193
|
setLoading(true);
|
|
182
194
|
var aborter = getAborter();
|
|
183
195
|
var subscription;
|
|
184
|
-
getCurrentUser(projectId, aborter).then(function (user) {
|
|
196
|
+
getCurrentUser(projectId, aborter, token).then(function (user) {
|
|
185
197
|
if (user) {
|
|
186
198
|
return;
|
|
187
199
|
} // eslint-disable-next-line no-console
|
|
@@ -212,7 +224,7 @@ function useQuerySubscription(options) {
|
|
|
212
224
|
|
|
213
225
|
aborter.abort();
|
|
214
226
|
};
|
|
215
|
-
}, [getStore, query, params, enabled]);
|
|
227
|
+
}, [getStore, query, params, enabled, projectId, token]);
|
|
216
228
|
return {
|
|
217
229
|
data: typeof data === 'undefined' ? initialData : data,
|
|
218
230
|
loading: loading,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-sanity.esm.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import sanityClient from '@sanity/client'\nimport type {ClientConfig, SanityClient} from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\nimport {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(projectId: string, abort: Aborter): Promise<CurrentUser | null> {\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {useState, useEffect, useMemo} from 'react'\nimport {GroqStore, Subscription} from '@sanity/groq-store'\nimport {ProjectConfig} from './types'\nimport {getCurrentUser} from './currentUser'\nimport {getAborter, Aborter} from './aborter'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n}) {\n const {getStore, projectId, query, initialData, enabled = false} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;SAGgBA,aAAaC;AAC3B,SAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;AAAN;AACE,gBAAA,GAAU;AAACC,MAAAA,OAAO,EAAE;AAAV,KAAV;AAOD;;;;SAHCC,QAAA;AACE,SAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;AACD;;;;SALD;AACE,aAAO,KAAKE,OAAZ;AACD;;;;;;AAMH,SAAgBC;AACd,SAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCfeC;MAAuBC,iBAAAA;AACrC,SAAO;AAAA,WAAMC,cAAc,CAACD,SAAD,CAApB;AAAA,GAAP;AACD;AAED,SAAgBE,eAAeF,WAAmBL;AAChD,SAAOQ,KAAK,cAAYH,SAAZ,iCAAmD;AAC7DI,IAAAA,WAAW,EAAE,SADgD;AAE7DC,IAAAA,MAAM,EAAEV,KAAK,CAACU;AAF+C,GAAnD,CAAL,CAIJC,IAJI,CAIC,UAACC,GAAD;AAAA,WAASA,GAAG,CAACC,IAAJ,EAAT;A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AA,KApBT,EAqBGiC,OArBH,CAqBW;AAAA,aAAMT,UAAU,CAAC,KAAD,CAAhB;AAAA,KArBX;;AAwBA,WAAO;AACL,UAAIG,YAAJ,EAAkB;AAChBA,QAAAA,YAAY,CAACO,WAAb;AACD;;AAEDpC,MAAAA,OAAO,CAACrB,KAAR;AACD,KAND;AAOD,GAxCQ,EAwCN,CAACsC,QAAD,EAAWN,KAAX,EAAkBE,MAAlB,EAA0BE,OAA1B,CAxCM,CAAT;AA0CA,SAAO;AACLpB,IAAAA,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BmB,WAA9B,GAA4CnB,IAD7C;AAELS,IAAAA,OAAO,EAAPA,OAFK;AAGLP,IAAAA,KAAK,EAALA;AAHK,GAAP;AAKD;;;AAGD,SAAS+B,SAAT,CAAmBf,MAAnB;AACE,MAAMwB,iBAAiB,GAAGC,OAAO,CAAC;AAAA,WAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;AAAA,GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;AACA,SAAOyB,OAAO,CAAC;AAAA,WAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;AAAA,GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"next-sanity.esm.js","sources":["../src/client.ts","../src/aborter.ts","../src/currentUser.ts","../src/useSubscription.ts"],"sourcesContent":["import type {ClientConfig, SanityClient} from '@sanity/client'\nimport sanityClient from '@sanity/client'\n\nexport function createClient(config: ClientConfig): SanityClient {\n return sanityClient(config)\n}\n","export interface Aborter {\n abort(): void\n signal: AbortSignal\n}\n\nclass MockAbortController {\n _signal = {aborted: false}\n get signal() {\n return this._signal as AbortSignal\n }\n abort() {\n this._signal.aborted = true\n }\n}\n\nexport function getAborter(): Aborter {\n return typeof AbortController === 'undefined'\n ? new MockAbortController()\n : new AbortController()\n}\n","import {useEffect, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {CurrentUser} from './types'\n\nexport function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return () => useCurrentUser(projectId)\n}\n\nexport function getCurrentUser(\n projectId: string,\n abort: Aborter,\n token?: string\n): Promise<CurrentUser | null> {\n const headers = token ? {Authorization: `Bearer ${token}`} : undefined\n return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {\n credentials: 'include',\n signal: abort.signal,\n headers,\n })\n .then((res) => res.json())\n .then((res) => (res?.id ? res : null))\n}\n\nfunction useCurrentUser(projectId: string) {\n const [data, setUser] = useState<CurrentUser | null>()\n const [error, setError] = useState<Error>()\n\n useEffect(() => {\n const aborter = getAborter()\n getCurrentUser(projectId, aborter)\n .then(setUser)\n .catch((err: Error) => err.name !== 'AbortError' && setError(err))\n\n return () => {\n aborter.abort()\n }\n }, [projectId])\n\n return {data, error, loading: data !== null || !error}\n}\n","import {GroqStore, Subscription} from '@sanity/groq-store'\nimport {useEffect, useMemo, useState} from 'react'\n\nimport {Aborter, getAborter} from './aborter'\nimport {getCurrentUser} from './currentUser'\nimport {ProjectConfig} from './types'\n\nconst EMPTY_PARAMS = {}\n\nexport type Params = Record<string, unknown>\nexport interface SubscriptionOptions<R = any> {\n enabled?: boolean\n params?: Params\n initialData?: R\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function createPreviewSubscriptionHook({\n projectId,\n dataset,\n token,\n EventSource,\n documentLimit = 3000,\n}: ProjectConfig & {documentLimit?: number}) {\n // Only construct/setup the store when `getStore()` is called\n let store: Promise<GroqStore>\n\n return function usePreviewSubscription<R = any>(\n query: string,\n options: SubscriptionOptions<R> = {}\n ) {\n const {params = EMPTY_PARAMS, initialData, enabled} = options\n return useQuerySubscription<R>({\n getStore,\n projectId,\n query,\n params,\n initialData: initialData as any,\n enabled: enabled ? typeof window !== 'undefined' : false,\n token,\n })\n }\n\n function getStore(abort: Aborter) {\n if (!store) {\n store = import('@sanity/groq-store').then(({groqStore}) => {\n // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure\n if (abort.signal.aborted) {\n const error = new Error('Cancelling groq store creation')\n // This ensures we can skip it in the catch block same way\n error.name = 'AbortError'\n return Promise.reject(error)\n }\n\n return groqStore({\n projectId,\n dataset,\n documentLimit,\n token,\n EventSource,\n listen: true,\n overlayDrafts: true,\n subscriptionThrottleMs: 10,\n })\n })\n }\n return store\n }\n}\n\nfunction useQuerySubscription<R = any>(options: {\n getStore: (abort: Aborter) => Promise<GroqStore>\n projectId: string\n query: string\n params: Params\n initialData: R\n enabled: boolean\n token?: string\n}) {\n const {getStore, projectId, query, initialData, enabled = false, token} = options\n const [error, setError] = useState<Error>()\n const [loading, setLoading] = useState(false)\n const [data, setData] = useState<R>()\n const params = useParams(options.params)\n\n // Use \"deep\" dependency comparison because params are often not _referentially_ equal,\n // but contains the same shallow properties, eg `{\"slug\": \"some-slug\"}`\n useEffect(() => {\n if (!enabled) {\n return\n }\n\n setLoading(true)\n\n const aborter = getAborter()\n let subscription: Subscription | undefined\n getCurrentUser(projectId, aborter, token)\n .then((user) => {\n if (user) {\n return\n }\n\n // eslint-disable-next-line no-console\n console.warn('Not authenticated - preview not available')\n throw new Error('Not authenticated - preview not available')\n })\n .then(() => getStore(aborter))\n .then((store) => {\n subscription = store.subscribe(query, params, (err, result) => {\n if (err) {\n setError(err)\n } else {\n setData(result)\n }\n })\n })\n .catch((err: Error) => (err.name === 'AbortError' ? null : setError(err)))\n .finally(() => setLoading(false))\n\n // eslint-disable-next-line consistent-return\n return () => {\n if (subscription) {\n subscription.unsubscribe()\n }\n\n aborter.abort()\n }\n }, [getStore, query, params, enabled, projectId, token])\n\n return {\n data: typeof data === 'undefined' ? initialData : data,\n loading,\n error,\n }\n}\n\n// Return params that are stable with deep equal as long as the key order is the same\nfunction useParams(params: Params): Params {\n const stringifiedParams = useMemo(() => JSON.stringify(params), [params])\n return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams])\n}\n"],"names":["createClient","config","sanityClient","MockAbortController","aborted","abort","_signal","getAborter","AbortController","createCurrentUserHook","projectId","useCurrentUser","getCurrentUser","token","headers","Authorization","undefined","fetch","credentials","signal","then","res","json","id","useState","data","setUser","error","setError","useEffect","aborter","catch","err","name","loading","EMPTY_PARAMS","createPreviewSubscriptionHook","dataset","EventSource","documentLimit","store","usePreviewSubscription","query","options","params","initialData","enabled","useQuerySubscription","getStore","window","groqStore","Error","Promise","reject","listen","overlayDrafts","subscriptionThrottleMs","setLoading","setData","useParams","subscription","user","console","warn","subscribe","result","finally","unsubscribe","stringifiedParams","useMemo","JSON","stringify","parse"],"mappings":";;;;SAGgBA,aAAaC;EAC3B,OAAOC,YAAY,CAACD,MAAD,CAAnB;AACD;;;;;;;;;;;;;;;;;;;;;ICAKE;EAAN;IACE,YAAA,GAAU;MAACC,OAAO,EAAE;KAApB;;;;;SAIAC,QAAA;IACE,KAAKC,OAAL,CAAaF,OAAb,GAAuB,IAAvB;;;;;SAJF;MACE,OAAO,KAAKE,OAAZ;;;;;;;AAOJ,SAAgBC;EACd,OAAO,OAAOC,eAAP,KAA2B,WAA3B,GACH,IAAIL,mBAAJ,EADG,GAEH,IAAIK,eAAJ,EAFJ;AAGD;;SCdeC;MAAuBC,iBAAAA;;EAErC,OAAO;IAAA,OAAMC,cAAc,CAACD,SAAD,CAApB;GAAP;AACD;AAED,SAAgBE,eACdF,WACAL,OACAQ;EAEA,IAAMC,OAAO,GAAGD,KAAK,GAAG;IAACE,aAAa,cAAYF;GAA7B,GAAwCG,SAA7D;EACA,OAAOC,KAAK,cAAYP,SAAZ,iCAAmD;IAC7DQ,WAAW,EAAE,SADgD;IAE7DC,MAAM,EAAEd,KAAK,CAACc,MAF+C;IAG7DL,OAAO,EAAPA;GAHU,CAAL,CAKJM,IALI,CAKC,UAACC,GAAD;IAAA,OAASA,GAAG,CAACC,IAAJ,EAAT;GALD,EAMJF,IANI,CAMC,UAACC,GAAD;I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0CA,OAAO;IACLY,IAAI,EAAE,OAAOA,IAAP,KAAgB,WAAhB,GAA8BoB,WAA9B,GAA4CpB,IAD7C;IAELS,OAAO,EAAPA,OAFK;IAGLP,KAAK,EAALA;GAHF;AAKD;;;AAGD,SAASgC,SAAT,CAAmBf,MAAnB;EACE,IAAMwB,iBAAiB,GAAGC,OAAO,CAAC;IAAA,OAAMC,IAAI,CAACC,SAAL,CAAe3B,MAAf,CAAN;GAAD,EAA+B,CAACA,MAAD,CAA/B,CAAjC;EACA,OAAOyB,OAAO,CAAC;IAAA,OAAMC,IAAI,CAACE,KAAL,CAAWJ,iBAAX,CAAN;GAAD,EAAsC,CAACA,iBAAD,CAAtC,CAAd;AACD;;;;"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import type { Config } from '@sanity/groq-store/dist/typings/types';
|
|
2
|
+
export declare type GroqStoreEventSource = Config['EventSource'];
|
|
1
3
|
export interface ProjectConfig {
|
|
2
4
|
projectId: string;
|
|
3
5
|
dataset: string;
|
|
6
|
+
token?: string;
|
|
7
|
+
/** Must be provided when token is used in browser, as native EventSource does not support auth-headers. */
|
|
8
|
+
EventSource?: GroqStoreEventSource;
|
|
4
9
|
}
|
|
5
10
|
export interface CurrentUser {
|
|
6
11
|
id: string;
|
|
@@ -5,7 +5,7 @@ export interface SubscriptionOptions<R = any> {
|
|
|
5
5
|
params?: Params;
|
|
6
6
|
initialData?: R;
|
|
7
7
|
}
|
|
8
|
-
export declare function createPreviewSubscriptionHook({ projectId, dataset, documentLimit, }: ProjectConfig & {
|
|
8
|
+
export declare function createPreviewSubscriptionHook({ projectId, dataset, token, EventSource, documentLimit, }: ProjectConfig & {
|
|
9
9
|
documentLimit?: number;
|
|
10
10
|
}): <R = any>(query: string, options?: SubscriptionOptions<R>) => {
|
|
11
11
|
data: R;
|
package/package.json
CHANGED
|
@@ -1,99 +1,102 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
|
+
"version": "0.6.3",
|
|
3
4
|
"description": "Sanity.io toolkit for Next.js",
|
|
4
|
-
"
|
|
5
|
-
|
|
5
|
+
"keywords": [
|
|
6
|
+
"sanity",
|
|
7
|
+
"sanity.io",
|
|
8
|
+
"next.js",
|
|
9
|
+
"studio",
|
|
10
|
+
"studio-v3"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/sanity-io/next-sanity#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/sanity-io/next-sanity/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+ssh://git@github.com/sanity-io/next-sanity.git"
|
|
19
|
+
},
|
|
6
20
|
"license": "MIT",
|
|
21
|
+
"author": "Sanity.io <hello@sanity.io>",
|
|
7
22
|
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"source": "./src/index.ts",
|
|
26
|
+
"require": "./dist/index.js",
|
|
27
|
+
"default": "./dist/next-sanity.esm.js"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
8
31
|
"main": "dist/index.js",
|
|
9
|
-
"typings": "dist/index.d.ts",
|
|
10
32
|
"module": "dist/next-sanity.esm.js",
|
|
33
|
+
"typings": "dist/index.d.ts",
|
|
11
34
|
"files": [
|
|
12
35
|
"dist",
|
|
36
|
+
"lib",
|
|
13
37
|
"src"
|
|
14
38
|
],
|
|
15
|
-
"engines": {
|
|
16
|
-
"node": ">=12"
|
|
17
|
-
},
|
|
18
39
|
"scripts": {
|
|
19
|
-
"start": "tsdx watch",
|
|
20
40
|
"build": "tsdx build",
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"prepublishOnly": "
|
|
25
|
-
"
|
|
41
|
+
"coverage": "npm test -- --coverage",
|
|
42
|
+
"format": "npm run prettier -- --write . && npm run lint -- --fix",
|
|
43
|
+
"lint": "eslint --ignore-path .gitignore .",
|
|
44
|
+
"prepublishOnly": "npm run lint && npm run build && npm test",
|
|
45
|
+
"prettier": "npx prettier --ignore-path .gitignore",
|
|
46
|
+
"start": "tsdx watch",
|
|
47
|
+
"test": "jest",
|
|
48
|
+
"type-check": "tsc --noEmit"
|
|
49
|
+
},
|
|
50
|
+
"browserslist": "chrome 59, safari 11, firefox 56, edge 14, ie 11",
|
|
51
|
+
"prettier": {
|
|
52
|
+
"bracketSpacing": false,
|
|
53
|
+
"printWidth": 98,
|
|
54
|
+
"semi": false,
|
|
55
|
+
"singleQuote": true
|
|
26
56
|
},
|
|
27
57
|
"dependencies": {
|
|
28
|
-
"@sanity/client": "^3.3.
|
|
29
|
-
"@sanity/groq-store": "^0.
|
|
58
|
+
"@sanity/client": "^3.3.3",
|
|
59
|
+
"@sanity/groq-store": "^0.4.0",
|
|
30
60
|
"groq": "^2.29.3"
|
|
31
61
|
},
|
|
32
62
|
"devDependencies": {
|
|
33
63
|
"@async-fn/jest": "^1.5.3",
|
|
34
64
|
"@testing-library/react-hooks": "^7.0.2",
|
|
35
|
-
"@types/
|
|
65
|
+
"@types/eventsource": "^1.1.9",
|
|
66
|
+
"@types/jest": "^27.5.2",
|
|
36
67
|
"@types/react": "^17.0.17",
|
|
37
68
|
"@types/react-dom": "^17.0.9",
|
|
38
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
39
|
-
"
|
|
40
|
-
"eslint": "^
|
|
41
|
-
"eslint-config-prettier": "^
|
|
42
|
-
"eslint-config-
|
|
43
|
-
"eslint-
|
|
44
|
-
"eslint-plugin-
|
|
45
|
-
"
|
|
69
|
+
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
|
70
|
+
"eslint": "^8.21.0",
|
|
71
|
+
"eslint-config-next": "^12.2.4",
|
|
72
|
+
"eslint-config-prettier": "^8.5.0",
|
|
73
|
+
"eslint-config-sanity": "^6.0.0",
|
|
74
|
+
"eslint-plugin-prettier": "^4.2.1",
|
|
75
|
+
"eslint-plugin-react-hooks": "^4.6.0",
|
|
76
|
+
"eslint-plugin-simple-import-sort": "^7.0.0",
|
|
77
|
+
"jest": "^28.1.3",
|
|
78
|
+
"jest-environment-jsdom": "^28.1.3",
|
|
79
|
+
"next": "^12.2.4",
|
|
80
|
+
"parcel": "^2.7.0",
|
|
81
|
+
"prettier": "^2.7.1",
|
|
82
|
+
"prettier-plugin-packagejson": "^2.2.18",
|
|
46
83
|
"react": ">=17.0.2",
|
|
47
84
|
"react-dom": "^17.0.2",
|
|
85
|
+
"semantic-release": "^19.0.3",
|
|
48
86
|
"tsdx": "^0.14.1",
|
|
49
|
-
"
|
|
50
|
-
"typescript": "^4.6.3"
|
|
87
|
+
"typescript": "^4.7.4"
|
|
51
88
|
},
|
|
52
89
|
"peerDependencies": {
|
|
53
|
-
"react": "
|
|
54
|
-
},
|
|
55
|
-
"repository": {
|
|
56
|
-
"type": "git",
|
|
57
|
-
"url": "git+ssh://git@github.com/sanity-io/next-sanity.git"
|
|
58
|
-
},
|
|
59
|
-
"bugs": {
|
|
60
|
-
"url": "https://github.com/sanity-io/next-sanity/issues"
|
|
90
|
+
"react": "^16.3 || ^17"
|
|
61
91
|
},
|
|
62
|
-
"
|
|
63
|
-
|
|
64
|
-
"sanity",
|
|
65
|
-
"sanity.io",
|
|
66
|
-
"next.js"
|
|
67
|
-
],
|
|
68
|
-
"eslintConfig": {
|
|
69
|
-
"root": true,
|
|
70
|
-
"env": {
|
|
71
|
-
"node": true,
|
|
72
|
-
"browser": true
|
|
73
|
-
},
|
|
74
|
-
"parser": "@typescript-eslint/parser",
|
|
75
|
-
"extends": [
|
|
76
|
-
"plugin:@typescript-eslint/recommended",
|
|
77
|
-
"sanity",
|
|
78
|
-
"sanity/react",
|
|
79
|
-
"sanity/typescript",
|
|
80
|
-
"prettier"
|
|
81
|
-
],
|
|
82
|
-
"rules": {
|
|
83
|
-
"prettier/prettier": "error",
|
|
84
|
-
"@typescript-eslint/explicit-module-boundary-types": "off"
|
|
85
|
-
},
|
|
86
|
-
"plugins": [
|
|
87
|
-
"@typescript-eslint",
|
|
88
|
-
"prettier",
|
|
89
|
-
"react"
|
|
90
|
-
]
|
|
92
|
+
"engines": {
|
|
93
|
+
"node": ">=12"
|
|
91
94
|
},
|
|
92
|
-
"
|
|
93
|
-
"
|
|
94
|
-
"
|
|
95
|
-
|
|
96
|
-
|
|
95
|
+
"targets": {
|
|
96
|
+
"studio": {
|
|
97
|
+
"distDir": "./lib",
|
|
98
|
+
"isLibrary": true,
|
|
99
|
+
"source": "./src/studio/index.ts"
|
|
97
100
|
}
|
|
98
101
|
}
|
|
99
102
|
}
|
package/src/client.ts
CHANGED
package/src/currentUser.ts
CHANGED
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
import {useEffect, useState} from 'react'
|
|
2
|
+
|
|
3
|
+
import {Aborter, getAborter} from './aborter'
|
|
2
4
|
import {CurrentUser} from './types'
|
|
3
|
-
import {getAborter, Aborter} from './aborter'
|
|
4
5
|
|
|
5
6
|
export function createCurrentUserHook({projectId}: {projectId: string; dataset?: string}) {
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
6
8
|
return () => useCurrentUser(projectId)
|
|
7
9
|
}
|
|
8
10
|
|
|
9
|
-
export function getCurrentUser(
|
|
11
|
+
export function getCurrentUser(
|
|
12
|
+
projectId: string,
|
|
13
|
+
abort: Aborter,
|
|
14
|
+
token?: string
|
|
15
|
+
): Promise<CurrentUser | null> {
|
|
16
|
+
const headers = token ? {Authorization: `Bearer ${token}`} : undefined
|
|
10
17
|
return fetch(`https://${projectId}.api.sanity.io/v1/users/me`, {
|
|
11
18
|
credentials: 'include',
|
|
12
19
|
signal: abort.signal,
|
|
20
|
+
headers,
|
|
13
21
|
})
|
|
14
22
|
.then((res) => res.json())
|
|
15
23
|
.then((res) => (res?.id ? res : null))
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type {
|
|
|
2
2
|
ClientConfig as ClientConfigForExport,
|
|
3
3
|
SanityClient as SanityClientForExport,
|
|
4
4
|
} from '@sanity/client'
|
|
5
|
+
|
|
5
6
|
import type {Aborter as AborterForExport} from './aborter'
|
|
6
7
|
|
|
7
8
|
// Re-export to support --isolatedMode and other strict mode features
|
|
@@ -9,8 +10,8 @@ export type ClientConfig = ClientConfigForExport
|
|
|
9
10
|
export type SanityClient = SanityClientForExport
|
|
10
11
|
export type Aborter = AborterForExport
|
|
11
12
|
|
|
12
|
-
export * from './types'
|
|
13
13
|
export * from './client'
|
|
14
14
|
export {createCurrentUserHook} from './currentUser'
|
|
15
|
+
export * from './types'
|
|
15
16
|
export {createPreviewSubscriptionHook} from './useSubscription'
|
|
16
17
|
export {default as groq} from 'groq'
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
import type {Config} from '@sanity/groq-store/dist/typings/types'
|
|
2
|
+
|
|
3
|
+
export type GroqStoreEventSource = Config['EventSource']
|
|
4
|
+
|
|
1
5
|
export interface ProjectConfig {
|
|
2
6
|
projectId: string
|
|
3
7
|
dataset: string
|
|
8
|
+
token?: string
|
|
9
|
+
/** Must be provided when token is used in browser, as native EventSource does not support auth-headers. */
|
|
10
|
+
EventSource?: GroqStoreEventSource
|
|
4
11
|
}
|
|
5
12
|
|
|
6
13
|
export interface CurrentUser {
|
package/src/useSubscription.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {useState, useEffect, useMemo} from 'react'
|
|
2
1
|
import {GroqStore, Subscription} from '@sanity/groq-store'
|
|
3
|
-
import {
|
|
2
|
+
import {useEffect, useMemo, useState} from 'react'
|
|
3
|
+
|
|
4
|
+
import {Aborter, getAborter} from './aborter'
|
|
4
5
|
import {getCurrentUser} from './currentUser'
|
|
5
|
-
import {
|
|
6
|
+
import {ProjectConfig} from './types'
|
|
6
7
|
|
|
7
8
|
const EMPTY_PARAMS = {}
|
|
8
9
|
|
|
@@ -13,9 +14,12 @@ export interface SubscriptionOptions<R = any> {
|
|
|
13
14
|
initialData?: R
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
16
18
|
export function createPreviewSubscriptionHook({
|
|
17
19
|
projectId,
|
|
18
20
|
dataset,
|
|
21
|
+
token,
|
|
22
|
+
EventSource,
|
|
19
23
|
documentLimit = 3000,
|
|
20
24
|
}: ProjectConfig & {documentLimit?: number}) {
|
|
21
25
|
// Only construct/setup the store when `getStore()` is called
|
|
@@ -33,6 +37,7 @@ export function createPreviewSubscriptionHook({
|
|
|
33
37
|
params,
|
|
34
38
|
initialData: initialData as any,
|
|
35
39
|
enabled: enabled ? typeof window !== 'undefined' : false,
|
|
40
|
+
token,
|
|
36
41
|
})
|
|
37
42
|
}
|
|
38
43
|
|
|
@@ -51,6 +56,8 @@ export function createPreviewSubscriptionHook({
|
|
|
51
56
|
projectId,
|
|
52
57
|
dataset,
|
|
53
58
|
documentLimit,
|
|
59
|
+
token,
|
|
60
|
+
EventSource,
|
|
54
61
|
listen: true,
|
|
55
62
|
overlayDrafts: true,
|
|
56
63
|
subscriptionThrottleMs: 10,
|
|
@@ -68,8 +75,9 @@ function useQuerySubscription<R = any>(options: {
|
|
|
68
75
|
params: Params
|
|
69
76
|
initialData: R
|
|
70
77
|
enabled: boolean
|
|
78
|
+
token?: string
|
|
71
79
|
}) {
|
|
72
|
-
const {getStore, projectId, query, initialData, enabled = false} = options
|
|
80
|
+
const {getStore, projectId, query, initialData, enabled = false, token} = options
|
|
73
81
|
const [error, setError] = useState<Error>()
|
|
74
82
|
const [loading, setLoading] = useState(false)
|
|
75
83
|
const [data, setData] = useState<R>()
|
|
@@ -86,7 +94,7 @@ function useQuerySubscription<R = any>(options: {
|
|
|
86
94
|
|
|
87
95
|
const aborter = getAborter()
|
|
88
96
|
let subscription: Subscription | undefined
|
|
89
|
-
getCurrentUser(projectId, aborter)
|
|
97
|
+
getCurrentUser(projectId, aborter, token)
|
|
90
98
|
.then((user) => {
|
|
91
99
|
if (user) {
|
|
92
100
|
return
|
|
@@ -117,7 +125,7 @@ function useQuerySubscription<R = any>(options: {
|
|
|
117
125
|
|
|
118
126
|
aborter.abort()
|
|
119
127
|
}
|
|
120
|
-
}, [getStore, query, params, enabled])
|
|
128
|
+
}, [getStore, query, params, enabled, projectId, token])
|
|
121
129
|
|
|
122
130
|
return {
|
|
123
131
|
data: typeof data === 'undefined' ? initialData : data,
|