next-sanity 0.6.2 → 0.6.5

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 CHANGED
@@ -77,7 +77,7 @@ 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
-
80
+
81
81
  /**
82
82
  * OPTIONAL config to enable authentication with custom token
83
83
  * You might need this if you host the preview on a different url than Sanity Studio
package/package.json CHANGED
@@ -1,29 +1,41 @@
1
1
  {
2
2
  "name": "next-sanity",
3
+ "version": "0.6.5",
3
4
  "description": "Sanity.io toolkit for Next.js",
4
- "version": "0.6.2",
5
- "author": "Sanity.io <hello@sanity.io>",
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
- "scripts": {
19
- "start": "tsdx watch",
20
- "build": "tsdx build",
21
- "test": "tsdx test",
22
- "lint": "eslint .",
23
- "posttest": "npm run lint",
24
- "prepublishOnly": "tsdx build && npm test",
25
- "coverage": "tsdx test --coverage"
26
- },
27
39
  "dependencies": {
28
40
  "@sanity/client": "^3.3.3",
29
41
  "@sanity/groq-store": "^0.4.0",
@@ -31,70 +43,42 @@
31
43
  },
32
44
  "devDependencies": {
33
45
  "@async-fn/jest": "^1.5.3",
46
+ "@sanity/eslint-config-studio": "^2.0.0",
47
+ "@semantic-release/exec": "^6.0.3",
34
48
  "@testing-library/react-hooks": "^7.0.2",
35
- "@types/jest": "^27.0.0",
49
+ "@types/eventsource": "^1.1.9",
50
+ "@types/jest": "^28.1.6",
36
51
  "@types/react": "^17.0.17",
37
- "@types/react-dom": "^17.0.9",
38
- "@typescript-eslint/eslint-plugin": "^5.30.4",
39
- "@typescript-eslint/parser": "^5.30.4",
40
- "eslint": "^8.19.0",
52
+ "@types/react-dom": "^18.0.6",
53
+ "@types/styled-components": "^5.1.26",
54
+ "@typescript-eslint/eslint-plugin": "^5.33.0",
55
+ "eslint": "^8.21.0",
56
+ "eslint-config-next": "^12.2.4",
41
57
  "eslint-config-prettier": "^8.5.0",
42
- "eslint-config-react-app": "^7.0.1",
43
- "eslint-config-sanity": "^5.1.0",
58
+ "eslint-config-sanity": "^6.0.0",
59
+ "eslint-gitignore": "^0.1.0",
44
60
  "eslint-plugin-prettier": "^4.2.1",
61
+ "eslint-plugin-simple-import-sort": "^7.0.0",
62
+ "jest": "^28.1.3",
63
+ "jest-environment-jsdom": "^28.1.3",
64
+ "next": "^12.2.4",
65
+ "parcel": "^2.7.0",
45
66
  "prettier": "^2.7.1",
46
- "react": ">=17.0.2",
67
+ "prettier-plugin-packagejson": "^2.2.18",
68
+ "react": "^17.0.2",
47
69
  "react-dom": "^17.0.2",
70
+ "react-is": "^17.0.2",
71
+ "sanity": "^3.0.0-dev-preview.12",
48
72
  "semantic-release": "^19.0.3",
73
+ "styled-components": "^5.3.5",
49
74
  "tsdx": "^0.14.1",
50
- "tslib": "^2.4.0",
51
- "typescript": "^4.7.4"
52
- },
53
- "peerDependencies": {
54
- "react": ">=16.3.0"
55
- },
56
- "repository": {
57
- "type": "git",
58
- "url": "git+ssh://git@github.com/sanity-io/next-sanity.git"
59
- },
60
- "bugs": {
61
- "url": "https://github.com/sanity-io/next-sanity/issues"
75
+ "typescript": "^4.7.4",
76
+ "write-file-atomic": "^4.0.1"
62
77
  },
63
- "homepage": "https://github.com/sanity-io/next-sanity#readme",
64
- "keywords": [
65
- "sanity",
66
- "sanity.io",
67
- "next.js"
68
- ],
69
- "eslintConfig": {
70
- "root": true,
71
- "env": {
72
- "node": true,
73
- "browser": true
74
- },
75
- "parser": "@typescript-eslint/parser",
76
- "extends": [
77
- "plugin:@typescript-eslint/recommended",
78
- "sanity",
79
- "sanity/react",
80
- "sanity/typescript",
81
- "prettier"
82
- ],
83
- "rules": {
84
- "prettier/prettier": "error",
85
- "@typescript-eslint/explicit-module-boundary-types": "off"
86
- },
87
- "plugins": [
88
- "@typescript-eslint",
89
- "prettier",
90
- "react"
91
- ]
78
+ "engines": {
79
+ "node": ">=12"
92
80
  },
93
- "jest": {
94
- "globals": {
95
- "ts-jest": {
96
- "diagnostics": false
97
- }
98
- }
81
+ "peerDependencies": {
82
+ "react": "^16.3 || ^17 || ^18"
99
83
  }
100
84
  }
package/src/client.ts CHANGED
@@ -1,5 +1,5 @@
1
- import sanityClient from '@sanity/client'
2
1
  import type {ClientConfig, SanityClient} from '@sanity/client'
2
+ import sanityClient from '@sanity/client'
3
3
 
4
4
  export function createClient(config: ClientConfig): SanityClient {
5
5
  return sanityClient(config)
@@ -1,6 +1,7 @@
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}) {
6
7
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
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'
@@ -0,0 +1,89 @@
1
+ import {memo} from 'react'
2
+ import {type StudioProps, Studio} from 'sanity'
3
+
4
+ import {
5
+ type NextStudioHeadProps,
6
+ NextStudioGlobalStyle,
7
+ NextStudioGlobalStyleProps,
8
+ NextStudioHead,
9
+ useBackgroundColorsFromTheme,
10
+ useTheme,
11
+ } from '.'
12
+
13
+ export interface NextStudioProps extends StudioProps {
14
+ /**
15
+ * Override how the Studio renders by passing children.
16
+ * This is useful for advanced use cases where you're using StudioProvider and StudioLayout instead of Studio:
17
+ * import {StudioProvider, StudioLayout} from 'sanity'
18
+ * import {NextStudio} from 'next-sanity/studio'
19
+ * <NextStudio config={config}>
20
+ * <StudioProvider config={config}>
21
+ * <CustomComponentThatUsesContextFromStudioProvider />
22
+ * <StudioLayout />
23
+ * </StudioProvider>
24
+ * </NextStudio>
25
+ */
26
+ children?: React.ReactNode
27
+ /**
28
+ * Turns off the default global styling
29
+ */
30
+ unstable__noGlobalStyle?: boolean
31
+ /**
32
+ * Apply fix with SVG icon centering that happens if TailwindCSS is loaded, on by defautl
33
+ */
34
+ unstable__noTailwindSvgFix?: NextStudioGlobalStyleProps['unstable__tailwindSvgFix']
35
+ /**
36
+ * Add stuff to the head with next/head
37
+ */
38
+ unstable__head?: NextStudioHeadProps['children']
39
+ /**
40
+ * Sets the document title
41
+ */
42
+ unstable__document_title?: NextStudioHeadProps['title']
43
+ /**
44
+ * Sets the background color of <html>
45
+ */
46
+ unstable__bg?: NextStudioGlobalStyleProps['bg']
47
+ /**
48
+ * Don't load the favicon meta tags
49
+ */
50
+ unstable__noFavicons?: boolean
51
+ }
52
+ /**
53
+ * Intended to render at the root of a page, letting the Studio own that page and render much like it would if you used `npx sanity start` to render
54
+ * It's a drop-in replacement for `import {Studio} from 'sanity'`
55
+ */
56
+ const NextStudioComponent = ({
57
+ children,
58
+ config,
59
+ unstable__noGlobalStyle,
60
+ unstable__noTailwindSvgFix,
61
+ unstable__head,
62
+ unstable__document_title,
63
+ unstable__bg,
64
+ unstable__noFavicons,
65
+ ...props
66
+ }: NextStudioProps) => {
67
+ const theme = useTheme(config)
68
+ const {themeColorLight, themeColorDark} = useBackgroundColorsFromTheme(theme)
69
+ return (
70
+ <>
71
+ {children || <Studio config={config} {...props} />}
72
+ <NextStudioHead
73
+ themeColorLight={themeColorLight}
74
+ themeColorDark={themeColorDark}
75
+ title={unstable__document_title}
76
+ favicons={!unstable__noFavicons}
77
+ >
78
+ {unstable__head}
79
+ </NextStudioHead>
80
+ {!unstable__noGlobalStyle && (
81
+ <NextStudioGlobalStyle
82
+ bg={unstable__bg ?? themeColorLight}
83
+ unstable__tailwindSvgFix={!unstable__noTailwindSvgFix}
84
+ />
85
+ )}
86
+ </>
87
+ )
88
+ }
89
+ export const NextStudio = memo(NextStudioComponent)
@@ -0,0 +1,34 @@
1
+ import {createGlobalStyle, css} from 'styled-components'
2
+
3
+ export interface NextStudioGlobalStyleProps {
4
+ bg?: string
5
+ unstable__tailwindSvgFix?: boolean
6
+ }
7
+ export const NextStudioGlobalStyle = createGlobalStyle<NextStudioGlobalStyleProps>`
8
+ ${({bg}) =>
9
+ bg
10
+ ? css`
11
+ html {
12
+ background-color: ${bg};
13
+ }
14
+ `
15
+ : ''}
16
+ html,
17
+ body,
18
+ #__next {
19
+ height: 100%;
20
+ }
21
+ body {
22
+ margin: 0;
23
+ overscroll-behavior: none;
24
+ -webkit-font-smoothing: antialiased;
25
+ }
26
+ ${({unstable__tailwindSvgFix}) =>
27
+ unstable__tailwindSvgFix
28
+ ? css`
29
+ /* override tailwind reset */
30
+ :root svg {
31
+ display: inline;
32
+ }
33
+ `
34
+ : ''}`
@@ -0,0 +1,99 @@
1
+ /* eslint-disable no-process-env */
2
+ import Head from 'next/head'
3
+ import {type ComponentProps, memo, useCallback} from 'react'
4
+
5
+ import iconApple from '../../public/apple-touch-icon.png'
6
+ import iconIco from '../../public/favicon.ico'
7
+ import iconSvg from '../../public/favicon.svg'
8
+ import icon192 from '../../public/favicon-192.png'
9
+ import icon512 from '../../public/favicon-512.png'
10
+ import webmanifest from '../../public/webmanifest.json'
11
+ import type {MetaThemeColors} from './utils'
12
+
13
+ // Interop between how Parcel and Next deals with asset imports
14
+ const interop = (href: string | {src: string}): string =>
15
+ typeof href === 'string' ? href : href.src
16
+
17
+ export interface NextStudioHeadProps extends Partial<MetaThemeColors> {
18
+ children?: ComponentProps<typeof Head>['children']
19
+ title?: string
20
+ favicons?: boolean
21
+ }
22
+ const NextStudioHeadComponent = ({
23
+ children,
24
+ themeColorDark,
25
+ themeColorLight,
26
+ title = 'Sanity Studio',
27
+ favicons,
28
+ }: NextStudioHeadProps) => {
29
+ const inlineWebmanifest = useCallback(() => {
30
+ const manifest = JSON.parse(JSON.stringify(webmanifest))
31
+ const icons = manifest.icons.map((icon: any) => {
32
+ // Inline manifests works best when URLs are absolute
33
+ const src =
34
+ // eslint-disable-next-line no-nested-ternary
35
+ icon.src === './favicon-192.png'
36
+ ? interop(icon192)
37
+ : icon.src === './favicon-512.png'
38
+ ? interop(icon512)
39
+ : icon.src
40
+ return {
41
+ ...icon,
42
+ src: process.env.NEXT_PUBLIC_VERCEL_URL
43
+ ? new URL(src, `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`).toString()
44
+ : src,
45
+ }
46
+ })
47
+ return `data:application/manifest+json,${encodeURIComponent(
48
+ JSON.stringify({...manifest, icons})
49
+ )}`
50
+ }, [])
51
+
52
+ return (
53
+ <Head>
54
+ <meta
55
+ name="viewport"
56
+ // Studio implements display cutouts CSS (The iPhone Notch ™ ) and needs `viewport-fit=covered` for it to work correctly
57
+ content="width=device-width, initial-scale=1, viewport-fit=cover"
58
+ />
59
+ <meta name="robots" content="noindex" />
60
+ <meta name="referrer" content="same-origin" />
61
+ <title>{title}</title>
62
+ {favicons && <link rel="icon" href={interop(iconIco)} sizes="any" />}
63
+ {favicons && <link rel="icon" href={interop(iconSvg)} type="image/svg+xml" />}
64
+ {favicons && <link rel="apple-touch-icon" href={interop(iconApple)} />}
65
+ {favicons && (
66
+ <link
67
+ rel="manifest"
68
+ // eslint-disable-next-line no-warning-comments
69
+ // @TODO until parcel fixes https://github.com/parcel-bundler/parcel/issues/8025 and stops stripping process.env.NEXT_PUBLIC_VERCEL_URL from the compiled code, use the remove webmanifest
70
+ href={
71
+ process.env.NEXT_PUBLIC_VERCEL_URL
72
+ ? inlineWebmanifest()
73
+ : 'https://next-studio-layout.sanity.build/manifest.webmanifest'
74
+ }
75
+ />
76
+ )}
77
+ {/* These theme-color tags makes the Studio look really really good on devices like iPads as the browser chrome adopts the Studio background */}
78
+ {themeColorLight && (
79
+ <meta
80
+ key="theme-color-light"
81
+ name="theme-color"
82
+ content={themeColorLight}
83
+ media="(prefers-color-scheme: light)"
84
+ />
85
+ )}
86
+ {themeColorDark && (
87
+ <meta
88
+ key="theme-color-dark"
89
+ name="theme-color"
90
+ content={themeColorDark}
91
+ media="(prefers-color-scheme: dark)"
92
+ />
93
+ )}
94
+ {children}
95
+ </Head>
96
+ )
97
+ }
98
+
99
+ export const NextStudioHead = memo(NextStudioHeadComponent)
@@ -0,0 +1,54 @@
1
+ // We can disable this rule safely as we're not trying to use it outside pages/document, we're shipping a wrapper
2
+ // eslint-disable-next-line @next/next/no-document-import-in-page
3
+ import Document, {type DocumentContext} from 'next/document'
4
+ import {ServerStyleSheet} from 'styled-components'
5
+
6
+ /**
7
+ * Usage, from a pages/_document.tsx file:
8
+ * import {ServerStyleSheetDocument} from 'next-sanity/studio'
9
+ *
10
+ * export default class MyDocument extends ServerStyleSheetDocument {}
11
+ *
12
+ * To do extra stuff in getInitialProps:
13
+ * import {ServerStyleSheetDocument} from 'next-sanity/studio'
14
+ * import { type DocumentContext } from 'next/document'
15
+ *
16
+ * export default class MyDocument extends ServerStyleSheetDocument {
17
+ * static async getInitialProps(ctx: DocumentContext) {
18
+ * // You can still override renderPage:
19
+ * const originalRenderPage = ctx.renderPage
20
+ * ctx.renderPage = () => originalRenderPage({
21
+ * enhanceApp: (App) => (props) => <App {...props} />
22
+ * })
23
+ *
24
+ * const initialProps = await ServerStyleSheetDocument.getInitialProps(ctx)
25
+ * const extraStyles = await getStyles()
26
+ * return {
27
+ * ...initialProps,
28
+ * styles: [initialProps.styles, extraStyles],
29
+ * }
30
+ * }
31
+ * }
32
+ */
33
+
34
+ export class ServerStyleSheetDocument extends Document {
35
+ static async getInitialProps(ctx: DocumentContext) {
36
+ const sheet = new ServerStyleSheet()
37
+ const originalRenderPage = ctx.renderPage
38
+
39
+ try {
40
+ ctx.renderPage = () =>
41
+ originalRenderPage({
42
+ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
43
+ })
44
+
45
+ const initialProps = await Document.getInitialProps(ctx)
46
+ return {
47
+ ...initialProps,
48
+ styles: [initialProps.styles, sheet.getStyleElement()],
49
+ }
50
+ } finally {
51
+ sheet.seal()
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ export * from './NextStudio'
2
+ export * from './NextStudioGlobalStyle'
3
+ export * from './NextStudioHead'
4
+ export * from './ServerStyleSheetDocument'
5
+ export * from './utils'
@@ -0,0 +1,77 @@
1
+ import {useRouter} from 'next/router'
2
+ import {useMemo} from 'react'
3
+ import {type Config, type StudioTheme, type WorkspaceOptions, defaultTheme} from 'sanity'
4
+
5
+ export function isWorkspaces(config: Config): config is WorkspaceOptions[] {
6
+ return Array.isArray(config)
7
+ }
8
+
9
+ export interface WorkspaceWithTheme extends Omit<WorkspaceOptions, 'theme'> {
10
+ theme: StudioTheme
11
+ }
12
+
13
+ export function isWorkspaceWithTheme(
14
+ workspace: WorkspaceOptions
15
+ ): workspace is WorkspaceWithTheme {
16
+ return Boolean(workspace.theme)
17
+ }
18
+
19
+ export function useTheme(config: Config): StudioTheme {
20
+ const workspace = useMemo<WorkspaceOptions>(
21
+ () => (isWorkspaces(config) ? config[0] : config),
22
+ [config]
23
+ )
24
+ return useMemo<StudioTheme>(
25
+ () => (isWorkspaceWithTheme(workspace) ? workspace.theme : defaultTheme),
26
+ [workspace]
27
+ )
28
+ }
29
+
30
+ export type MetaThemeColors = {
31
+ themeColorLight: string
32
+ themeColorDark: string
33
+ }
34
+ export const useBackgroundColorsFromTheme = (theme: StudioTheme): MetaThemeColors => {
35
+ return useMemo<MetaThemeColors>(
36
+ () => ({
37
+ themeColorLight: theme.color.light.default.base.bg,
38
+ themeColorDark: theme.color.dark.default.base.bg,
39
+ }),
40
+ [theme]
41
+ )
42
+ }
43
+
44
+ /**
45
+ * Parses the next route to determine the what the base path for Sanity Studio should be
46
+ */
47
+ export function useBasePath(): string {
48
+ const router = useRouter()
49
+ return useMemo(() => {
50
+ const [basePath = '/'] = router.route.split('/[')
51
+ return basePath
52
+ }, [router.route])
53
+ }
54
+
55
+ export interface WorkspaceWithBasePath extends Omit<WorkspaceOptions, 'basePath'> {
56
+ basePath: string
57
+ }
58
+ export type ConfigWithBasePath = WorkspaceWithBasePath | WorkspaceWithBasePath[]
59
+ /**
60
+ * Apply the base path from next to the config, prefixing any defined base path
61
+ */
62
+ export function useConfigWithBasePath(config: Config): ConfigWithBasePath {
63
+ const basePath = useBasePath()
64
+ return useMemo(() => {
65
+ if (isWorkspaces(config)) {
66
+ return config.map((workspace) => ({
67
+ ...workspace,
68
+ basePath:
69
+ workspace.basePath === '/' ? basePath : `${basePath}${workspace.basePath || ''}`,
70
+ }))
71
+ }
72
+ return {
73
+ ...config,
74
+ basePath: config.basePath === '/' ? basePath : `${basePath}${config.basePath || ''}`,
75
+ }
76
+ }, [config, basePath])
77
+ }
package/src/studio.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './studio/index'
@@ -1,8 +1,9 @@
1
- import {useState, useEffect, useMemo} from 'react'
2
1
  import {GroqStore, Subscription} from '@sanity/groq-store'
3
- import {ProjectConfig} from './types'
2
+ import {useEffect, useMemo, useState} from 'react'
3
+
4
+ import {Aborter, getAborter} from './aborter'
4
5
  import {getCurrentUser} from './currentUser'
5
- import {getAborter, Aborter} from './aborter'
6
+ import {ProjectConfig} from './types'
6
7
 
7
8
  const EMPTY_PARAMS = {}
8
9
 
package/dist/aborter.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export interface Aborter {
2
- abort(): void;
3
- signal: AbortSignal;
4
- }
5
- export declare function getAborter(): Aborter;
package/dist/client.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import type { ClientConfig, SanityClient } from '@sanity/client';
2
- export declare function createClient(config: ClientConfig): SanityClient;
@@ -1,11 +0,0 @@
1
- import { CurrentUser } from './types';
2
- import { Aborter } from './aborter';
3
- export declare function createCurrentUserHook({ projectId }: {
4
- projectId: string;
5
- dataset?: string;
6
- }): () => {
7
- data: CurrentUser | null | undefined;
8
- error: Error | undefined;
9
- loading: boolean;
10
- };
11
- export declare function getCurrentUser(projectId: string, abort: Aborter, token?: string): Promise<CurrentUser | null>;
package/dist/index.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import type { ClientConfig as ClientConfigForExport, SanityClient as SanityClientForExport } from '@sanity/client';
2
- import type { Aborter as AborterForExport } from './aborter';
3
- export declare type ClientConfig = ClientConfigForExport;
4
- export declare type SanityClient = SanityClientForExport;
5
- export declare type Aborter = AborterForExport;
6
- export * from './types';
7
- export * from './client';
8
- export { createCurrentUserHook } from './currentUser';
9
- export { createPreviewSubscriptionHook } from './useSubscription';
10
- export { default as groq } from 'groq';
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
-
2
- 'use strict'
3
-
4
- if (process.env.NODE_ENV === 'production') {
5
- module.exports = require('./next-sanity.cjs.production.min.js')
6
- } else {
7
- module.exports = require('./next-sanity.cjs.development.js')
8
- }
@@ -1,274 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) { return e; } else {
9
- var n = {};
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- var d = Object.getOwnPropertyDescriptor(e, k);
13
- Object.defineProperty(n, k, d.get ? d : {
14
- enumerable: true,
15
- get: function () {
16
- return e[k];
17
- }
18
- });
19
- });
20
- }
21
- n['default'] = e;
22
- return n;
23
- }
24
- }
25
-
26
- var sanityClient = _interopDefault(require('@sanity/client'));
27
- var react = require('react');
28
- var groq = _interopDefault(require('groq'));
29
-
30
- function createClient(config) {
31
- return sanityClient(config);
32
- }
33
-
34
- function _defineProperties(target, props) {
35
- for (var i = 0; i < props.length; i++) {
36
- var descriptor = props[i];
37
- descriptor.enumerable = descriptor.enumerable || false;
38
- descriptor.configurable = true;
39
- if ("value" in descriptor) descriptor.writable = true;
40
- Object.defineProperty(target, descriptor.key, descriptor);
41
- }
42
- }
43
-
44
- function _createClass(Constructor, protoProps, staticProps) {
45
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
46
- if (staticProps) _defineProperties(Constructor, staticProps);
47
- Object.defineProperty(Constructor, "prototype", {
48
- writable: false
49
- });
50
- return Constructor;
51
- }
52
-
53
- var MockAbortController = /*#__PURE__*/function () {
54
- function MockAbortController() {
55
- this._signal = {
56
- aborted: false
57
- };
58
- }
59
-
60
- var _proto = MockAbortController.prototype;
61
-
62
- _proto.abort = function abort() {
63
- this._signal.aborted = true;
64
- };
65
-
66
- _createClass(MockAbortController, [{
67
- key: "signal",
68
- get: function get() {
69
- return this._signal;
70
- }
71
- }]);
72
-
73
- return MockAbortController;
74
- }();
75
-
76
- function getAborter() {
77
- return typeof AbortController === 'undefined' ? new MockAbortController() : new AbortController();
78
- }
79
-
80
- function createCurrentUserHook(_ref) {
81
- var projectId = _ref.projectId;
82
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
83
- return function () {
84
- return useCurrentUser(projectId);
85
- };
86
- }
87
- function getCurrentUser(projectId, abort, token) {
88
- var headers = token ? {
89
- Authorization: "Bearer " + token
90
- } : undefined;
91
- return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
92
- credentials: 'include',
93
- signal: abort.signal,
94
- headers: headers
95
- }).then(function (res) {
96
- return res.json();
97
- }).then(function (res) {
98
- return res != null && res.id ? res : null;
99
- });
100
- }
101
-
102
- function useCurrentUser(projectId) {
103
- var _useState = react.useState(),
104
- data = _useState[0],
105
- setUser = _useState[1];
106
-
107
- var _useState2 = react.useState(),
108
- error = _useState2[0],
109
- setError = _useState2[1];
110
-
111
- react.useEffect(function () {
112
- var aborter = getAborter();
113
- getCurrentUser(projectId, aborter).then(setUser).catch(function (err) {
114
- return err.name !== 'AbortError' && setError(err);
115
- });
116
- return function () {
117
- aborter.abort();
118
- };
119
- }, [projectId]);
120
- return {
121
- data: data,
122
- error: error,
123
- loading: data !== null || !error
124
- };
125
- }
126
-
127
- var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
128
-
129
- function createPreviewSubscriptionHook(_ref) {
130
- var projectId = _ref.projectId,
131
- dataset = _ref.dataset,
132
- token = _ref.token,
133
- EventSource = _ref.EventSource,
134
- _ref$documentLimit = _ref.documentLimit,
135
- documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
136
- // Only construct/setup the store when `getStore()` is called
137
- var store;
138
- return function usePreviewSubscription(query, options) {
139
- if (options === void 0) {
140
- options = {};
141
- }
142
-
143
- var _options = options,
144
- _options$params = _options.params,
145
- params = _options$params === void 0 ? EMPTY_PARAMS : _options$params,
146
- initialData = _options.initialData,
147
- enabled = _options.enabled;
148
- return useQuerySubscription({
149
- getStore: getStore,
150
- projectId: projectId,
151
- query: query,
152
- params: params,
153
- initialData: initialData,
154
- enabled: enabled ? typeof window !== 'undefined' : false,
155
- token: token
156
- });
157
- };
158
-
159
- function getStore(abort) {
160
- if (!store) {
161
- store = new Promise(function (resolve) { resolve(_interopNamespace(require('@sanity/groq-store'))); }).then(function (_ref2) {
162
- var groqStore = _ref2.groqStore;
163
-
164
- // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure
165
- if (abort.signal.aborted) {
166
- var error = new Error('Cancelling groq store creation'); // This ensures we can skip it in the catch block same way
167
-
168
- error.name = 'AbortError';
169
- return Promise.reject(error);
170
- }
171
-
172
- return groqStore({
173
- projectId: projectId,
174
- dataset: dataset,
175
- documentLimit: documentLimit,
176
- token: token,
177
- EventSource: EventSource,
178
- listen: true,
179
- overlayDrafts: true,
180
- subscriptionThrottleMs: 10
181
- });
182
- });
183
- }
184
-
185
- return store;
186
- }
187
- }
188
-
189
- function useQuerySubscription(options) {
190
- var getStore = options.getStore,
191
- projectId = options.projectId,
192
- query = options.query,
193
- initialData = options.initialData,
194
- _options$enabled = options.enabled,
195
- enabled = _options$enabled === void 0 ? false : _options$enabled,
196
- token = options.token;
197
-
198
- var _useState = react.useState(),
199
- error = _useState[0],
200
- setError = _useState[1];
201
-
202
- var _useState2 = react.useState(false),
203
- loading = _useState2[0],
204
- setLoading = _useState2[1];
205
-
206
- var _useState3 = react.useState(),
207
- data = _useState3[0],
208
- setData = _useState3[1];
209
-
210
- var params = useParams(options.params); // Use "deep" dependency comparison because params are often not _referentially_ equal,
211
- // but contains the same shallow properties, eg `{"slug": "some-slug"}`
212
-
213
- react.useEffect(function () {
214
- if (!enabled) {
215
- return;
216
- }
217
-
218
- setLoading(true);
219
- var aborter = getAborter();
220
- var subscription;
221
- getCurrentUser(projectId, aborter, token).then(function (user) {
222
- if (user) {
223
- return;
224
- } // eslint-disable-next-line no-console
225
-
226
-
227
- console.warn('Not authenticated - preview not available');
228
- throw new Error('Not authenticated - preview not available');
229
- }).then(function () {
230
- return getStore(aborter);
231
- }).then(function (store) {
232
- subscription = store.subscribe(query, params, function (err, result) {
233
- if (err) {
234
- setError(err);
235
- } else {
236
- setData(result);
237
- }
238
- });
239
- }).catch(function (err) {
240
- return err.name === 'AbortError' ? null : setError(err);
241
- }).finally(function () {
242
- return setLoading(false);
243
- }); // eslint-disable-next-line consistent-return
244
-
245
- return function () {
246
- if (subscription) {
247
- subscription.unsubscribe();
248
- }
249
-
250
- aborter.abort();
251
- };
252
- }, [getStore, query, params, enabled, projectId, token]);
253
- return {
254
- data: typeof data === 'undefined' ? initialData : data,
255
- loading: loading,
256
- error: error
257
- };
258
- } // Return params that are stable with deep equal as long as the key order is the same
259
-
260
-
261
- function useParams(params) {
262
- var stringifiedParams = react.useMemo(function () {
263
- return JSON.stringify(params);
264
- }, [params]);
265
- return react.useMemo(function () {
266
- return JSON.parse(stringifiedParams);
267
- }, [stringifiedParams]);
268
- }
269
-
270
- exports.groq = groq;
271
- exports.createClient = createClient;
272
- exports.createCurrentUserHook = createCurrentUserHook;
273
- exports.createPreviewSubscriptionHook = createPreviewSubscriptionHook;
274
- //# sourceMappingURL=next-sanity.cjs.development.js.map
@@ -1 +0,0 @@
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 // 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 {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\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;;SCfeC;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;IAAA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A,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 +0,0 @@
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
- //# sourceMappingURL=next-sanity.cjs.production.min.js.map
@@ -1 +0,0 @@
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 {CurrentUser} from './types'\nimport {getAborter, Aborter} from './aborter'\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 {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\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 sanityClient from '@sanity/client'\nimport type {ClientConfig, 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,IAAIM,gBCTV,SAAgBC,EACdC,EACAL,EACAM,GAGA,OAAOC,iBAAiBF,+BAAuC,CAC7DG,YAAa,UACbC,OAAQT,EAAMS,OACdC,QAJcJ,EAAQ,CAACK,wBAAyBL,QAAWM,IAM1DC,MAAK,SAACC,GAAD,OAASA,EAAIC,UAClBF,MAAK,SAACC,GAAD,aAAUA,GAAAA,EAAKE,GAAKF,EAAM,QCfpC,IAAMG,EAAe,gDCHQC,GAC3B,OAAOC,EAAaD,kDFAiBb,IAAAA,UAErC,OAAO,WAAA,OA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AAK4B,GAC9C5B,EACFJ,EAASI,GAETe,EAAQa,SAIb7B,OAAM,SAACC,GAAD,MAA8B,eAAbA,EAAIC,KAAwB,KAAOL,EAASI,MACnE6B,SAAQ,WAAA,OAAMf,GAAW,MAGrB,WACDQ,GACFA,EAAaQ,cAGfhC,EAAQ1B,YAET,CAACuC,EAAUH,EAAOE,EAAQG,EAASpC,EAAWC,IAE1C,CACLe,UAAsB,IAATA,EAAuBmB,EAAcnB,EAClDS,QAAAA,EACAP,MAAAA,GApGOoC,CAAwB,CAC7BpB,SAAAA,EACAlC,UAAAA,EACA+B,MAAAA,EACAE,kBALcrB,IAMduB,YANoDH,EAAxBG,YAO5BC,UAPoDJ,EAAXI,SAOJ,oBAAXmB,OAC1BtD,MAAAA,KAIJ,SAASiC,EAASvC,GAuBhB,OAtBKgC,IACHA,EAAQ,8QAAO,2BAAsBnB,MAAK,gBAAEgD,IAAAA,UAE1C,GAAI7D,EAAMS,OAAOV,QAAS,CACxB,IAAMwB,EAAQ,IAAI+B,MAAM,kCAGxB,OADA/B,EAAMM,KAAO,aACNiC,QAAQC,OAAOxC,GAGxB,OAAOsC,EAAU,CACfxD,UAAAA,EACA4B,QAAAA,EACAE,cAAAA,EACA7B,MAAAA,EACA4B,YAAAA,EACA8B,QAAQ,EACRC,eAAe,EACfC,uBAAwB,SAIvBlC"}
@@ -1,246 +0,0 @@
1
- import sanityClient from '@sanity/client';
2
- import { useState, useEffect, useMemo } from 'react';
3
- export { default as groq } from 'groq';
4
-
5
- function createClient(config) {
6
- return sanityClient(config);
7
- }
8
-
9
- function _defineProperties(target, props) {
10
- for (var i = 0; i < props.length; i++) {
11
- var descriptor = props[i];
12
- descriptor.enumerable = descriptor.enumerable || false;
13
- descriptor.configurable = true;
14
- if ("value" in descriptor) descriptor.writable = true;
15
- Object.defineProperty(target, descriptor.key, descriptor);
16
- }
17
- }
18
-
19
- function _createClass(Constructor, protoProps, staticProps) {
20
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
21
- if (staticProps) _defineProperties(Constructor, staticProps);
22
- Object.defineProperty(Constructor, "prototype", {
23
- writable: false
24
- });
25
- return Constructor;
26
- }
27
-
28
- var MockAbortController = /*#__PURE__*/function () {
29
- function MockAbortController() {
30
- this._signal = {
31
- aborted: false
32
- };
33
- }
34
-
35
- var _proto = MockAbortController.prototype;
36
-
37
- _proto.abort = function abort() {
38
- this._signal.aborted = true;
39
- };
40
-
41
- _createClass(MockAbortController, [{
42
- key: "signal",
43
- get: function get() {
44
- return this._signal;
45
- }
46
- }]);
47
-
48
- return MockAbortController;
49
- }();
50
-
51
- function getAborter() {
52
- return typeof AbortController === 'undefined' ? new MockAbortController() : new AbortController();
53
- }
54
-
55
- function createCurrentUserHook(_ref) {
56
- var projectId = _ref.projectId;
57
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
58
- return function () {
59
- return useCurrentUser(projectId);
60
- };
61
- }
62
- function getCurrentUser(projectId, abort, token) {
63
- var headers = token ? {
64
- Authorization: "Bearer " + token
65
- } : undefined;
66
- return fetch("https://" + projectId + ".api.sanity.io/v1/users/me", {
67
- credentials: 'include',
68
- signal: abort.signal,
69
- headers: headers
70
- }).then(function (res) {
71
- return res.json();
72
- }).then(function (res) {
73
- return res != null && res.id ? res : null;
74
- });
75
- }
76
-
77
- function useCurrentUser(projectId) {
78
- var _useState = useState(),
79
- data = _useState[0],
80
- setUser = _useState[1];
81
-
82
- var _useState2 = useState(),
83
- error = _useState2[0],
84
- setError = _useState2[1];
85
-
86
- useEffect(function () {
87
- var aborter = getAborter();
88
- getCurrentUser(projectId, aborter).then(setUser).catch(function (err) {
89
- return err.name !== 'AbortError' && setError(err);
90
- });
91
- return function () {
92
- aborter.abort();
93
- };
94
- }, [projectId]);
95
- return {
96
- data: data,
97
- error: error,
98
- loading: data !== null || !error
99
- };
100
- }
101
-
102
- var EMPTY_PARAMS = {}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
103
-
104
- function createPreviewSubscriptionHook(_ref) {
105
- var projectId = _ref.projectId,
106
- dataset = _ref.dataset,
107
- token = _ref.token,
108
- EventSource = _ref.EventSource,
109
- _ref$documentLimit = _ref.documentLimit,
110
- documentLimit = _ref$documentLimit === void 0 ? 3000 : _ref$documentLimit;
111
- // Only construct/setup the store when `getStore()` is called
112
- var store;
113
- return function usePreviewSubscription(query, options) {
114
- if (options === void 0) {
115
- options = {};
116
- }
117
-
118
- var _options = options,
119
- _options$params = _options.params,
120
- params = _options$params === void 0 ? EMPTY_PARAMS : _options$params,
121
- initialData = _options.initialData,
122
- enabled = _options.enabled;
123
- return useQuerySubscription({
124
- getStore: getStore,
125
- projectId: projectId,
126
- query: query,
127
- params: params,
128
- initialData: initialData,
129
- enabled: enabled ? typeof window !== 'undefined' : false,
130
- token: token
131
- });
132
- };
133
-
134
- function getStore(abort) {
135
- if (!store) {
136
- store = import('@sanity/groq-store').then(function (_ref2) {
137
- var groqStore = _ref2.groqStore;
138
-
139
- // Skip creating the groq store if we've been unmounted to save memory and reduce gc pressure
140
- if (abort.signal.aborted) {
141
- var error = new Error('Cancelling groq store creation'); // This ensures we can skip it in the catch block same way
142
-
143
- error.name = 'AbortError';
144
- return Promise.reject(error);
145
- }
146
-
147
- return groqStore({
148
- projectId: projectId,
149
- dataset: dataset,
150
- documentLimit: documentLimit,
151
- token: token,
152
- EventSource: EventSource,
153
- listen: true,
154
- overlayDrafts: true,
155
- subscriptionThrottleMs: 10
156
- });
157
- });
158
- }
159
-
160
- return store;
161
- }
162
- }
163
-
164
- function useQuerySubscription(options) {
165
- var getStore = options.getStore,
166
- projectId = options.projectId,
167
- query = options.query,
168
- initialData = options.initialData,
169
- _options$enabled = options.enabled,
170
- enabled = _options$enabled === void 0 ? false : _options$enabled,
171
- token = options.token;
172
-
173
- var _useState = useState(),
174
- error = _useState[0],
175
- setError = _useState[1];
176
-
177
- var _useState2 = useState(false),
178
- loading = _useState2[0],
179
- setLoading = _useState2[1];
180
-
181
- var _useState3 = useState(),
182
- data = _useState3[0],
183
- setData = _useState3[1];
184
-
185
- var params = useParams(options.params); // Use "deep" dependency comparison because params are often not _referentially_ equal,
186
- // but contains the same shallow properties, eg `{"slug": "some-slug"}`
187
-
188
- useEffect(function () {
189
- if (!enabled) {
190
- return;
191
- }
192
-
193
- setLoading(true);
194
- var aborter = getAborter();
195
- var subscription;
196
- getCurrentUser(projectId, aborter, token).then(function (user) {
197
- if (user) {
198
- return;
199
- } // eslint-disable-next-line no-console
200
-
201
-
202
- console.warn('Not authenticated - preview not available');
203
- throw new Error('Not authenticated - preview not available');
204
- }).then(function () {
205
- return getStore(aborter);
206
- }).then(function (store) {
207
- subscription = store.subscribe(query, params, function (err, result) {
208
- if (err) {
209
- setError(err);
210
- } else {
211
- setData(result);
212
- }
213
- });
214
- }).catch(function (err) {
215
- return err.name === 'AbortError' ? null : setError(err);
216
- }).finally(function () {
217
- return setLoading(false);
218
- }); // eslint-disable-next-line consistent-return
219
-
220
- return function () {
221
- if (subscription) {
222
- subscription.unsubscribe();
223
- }
224
-
225
- aborter.abort();
226
- };
227
- }, [getStore, query, params, enabled, projectId, token]);
228
- return {
229
- data: typeof data === 'undefined' ? initialData : data,
230
- loading: loading,
231
- error: error
232
- };
233
- } // Return params that are stable with deep equal as long as the key order is the same
234
-
235
-
236
- function useParams(params) {
237
- var stringifiedParams = useMemo(function () {
238
- return JSON.stringify(params);
239
- }, [params]);
240
- return useMemo(function () {
241
- return JSON.parse(stringifiedParams);
242
- }, [stringifiedParams]);
243
- }
244
-
245
- export { createClient, createCurrentUserHook, createPreviewSubscriptionHook };
246
- //# sourceMappingURL=next-sanity.esm.js.map
@@ -1 +0,0 @@
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 // 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 {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\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;;SCfeC;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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A,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,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 DELETED
@@ -1,14 +0,0 @@
1
- import type { Config } from '@sanity/groq-store/dist/typings/types';
2
- export declare type GroqStoreEventSource = Config['EventSource'];
3
- export interface ProjectConfig {
4
- projectId: string;
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;
9
- }
10
- export interface CurrentUser {
11
- id: string;
12
- name: string;
13
- profileImage?: string;
14
- }
@@ -1,14 +0,0 @@
1
- import { ProjectConfig } from './types';
2
- export declare type Params = Record<string, unknown>;
3
- export interface SubscriptionOptions<R = any> {
4
- enabled?: boolean;
5
- params?: Params;
6
- initialData?: R;
7
- }
8
- export declare function createPreviewSubscriptionHook({ projectId, dataset, token, EventSource, documentLimit, }: ProjectConfig & {
9
- documentLimit?: number;
10
- }): <R = any>(query: string, options?: SubscriptionOptions<R>) => {
11
- data: R;
12
- loading: boolean;
13
- error: Error | undefined;
14
- };