next-sanity 12.4.0 → 12.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PresentationComlink.js.map +1 -1
- package/dist/SanityLive.js.map +1 -1
- package/dist/isCorsOriginError.js.map +1 -1
- package/dist/live/client-components/index.d.ts +0 -11
- package/dist/live/client-components/index.d.ts.map +1 -1
- package/dist/live/conditions/default/index.d.ts +83 -5
- package/dist/live/conditions/default/index.d.ts.map +1 -1
- package/dist/live/conditions/default/index.js +78 -0
- package/dist/live/conditions/default/index.js.map +1 -1
- package/dist/live/conditions/next-js/index.d.ts +83 -5
- package/dist/live/conditions/next-js/index.d.ts.map +1 -1
- package/dist/live/conditions/next-js/index.js +78 -0
- package/dist/live/conditions/next-js/index.js.map +1 -1
- package/dist/live/conditions/react-server/index.d.ts +88 -2
- package/dist/live/conditions/react-server/index.d.ts.map +1 -0
- package/dist/live/conditions/react-server/index.js +148 -68
- package/dist/live/conditions/react-server/index.js.map +1 -1
- package/dist/live/server-actions/{index.default.d.ts → index.d.ts} +1 -1
- package/dist/live/server-actions/index.d.ts.map +1 -0
- package/dist/live/server-actions/{index.default.js → index.js} +1 -1
- package/dist/live/server-actions/index.js.map +1 -0
- package/dist/{defineLive.d.ts → types.d.ts} +39 -26
- package/dist/types.d.ts.map +1 -0
- package/dist/visual-editing/server-actions/index.d.ts +2 -2
- package/dist/visual-editing/server-actions/index.js +3 -3
- package/dist/visual-editing/server-actions/index.js.map +1 -1
- package/package.json +3 -5
- package/dist/defineLive.d.ts.map +0 -1
- package/dist/live/server-actions/index.default.d.ts.map +0 -1
- package/dist/live/server-actions/index.default.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {
|
|
1
|
+
{"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useEffectEvent} from 'react'\n\nimport {setComlink, setComlinkClientConfig} from '../hooks/context'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n draftModePerspective: ClientPerspective\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled, draftModePerspective} = props\n const router = useRouter()\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (perspective: ClientPerspective, signal: AbortSignal) => {\n if (draftModeEnabled && perspective !== draftModePerspective) {\n setPerspectiveCookie(perspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n }\n }, [])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;AAaA,SAAS,oBAAoB,OAKA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,aAAgC,WAAwB;AACvD,MAAI,oBAAoB,gBAAgB,qBACtC,sBAAqB,YAAY,CAC9B,WAAW;AACV,OAAI,OAAO,QAAS;AACpB,UAAO,SAAS;IAChB,CACD,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAI;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;;IAEP,EAAE,CAAC;AAEN,QAAO;;AAET,oBAAoB,cAAc"}
|
package/dist/SanityLive.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SanityLive.js","names":["defaultRevalidateSyncTags","revalidateSyncTags"],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent, startTransition} from 'react'\n\nimport {isCorsOriginError} from '#live/isCorsOriginError'\n\nimport {setEnvironment, setPerspective} from '../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\n/**\n * @public\n */\nexport interface SanityLiveProps extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {\n // handleDraftModeAction: (secret: string) => Promise<void | string>\n draftModeEnabled: boolean\n draftModePerspective?: ClientPerspective\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n /**\n * Delays events until after a configured Sanity Function has processed them and called the callback endpoint.\n * When omitted, events are delivered immediately.\n *\n * @remarks\n * When set, any custom `revalidateSyncTags` will not be called — revalidation is handled by the Function instead.\n */\n waitFor?: 'function'\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n token,\n requestTagPrefix,\n // handleDraftModeAction,\n draftModeEnabled,\n draftModePerspective,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags = defaultRevalidateSyncTags,\n waitFor,\n } = props\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n } else if (event.type === 'message') {\n if (waitFor === 'function') {\n // Cache is already revalidated by the Sanity Function, just refresh the router\n startTransition(() => router.refresh())\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') startTransition(() => router.refresh())\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n // Disable long polling when restart/reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n // @TODO add support for `onRestart` and `onReconnect` events so this can be customized\n startTransition(() => router.refresh())\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n startTransition(() => setRefreshOnInterval(intervalOnGoAway))\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts: !!token, tag: requestTag, waitFor})\n .subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n // console.error('What?', err)\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token, waitFor])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (draftModeEnabled && draftModePerspective) {\n setPerspective(draftModePerspective)\n } else {\n setPerspective('unknown')\n }\n }, [draftModeEnabled, draftModePerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n return (\n <>\n {draftModeEnabled && loadComlink && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n // handleDraftModeAction={handleDraftModeAction}\n draftModeEnabled={draftModeEnabled}\n draftModePerspective={draftModePerspective!}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && (\n <RefreshOnInterval interval={refreshOnInterval} />\n )}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;;AAkBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,oBAAoB,cAAc,OAAO,0BAAuB;AACtE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AAwCxE,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAIxB,SAAS,eAAe,OAAwB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KAC9E;;IAEH,CAAC,iBAAiB,CAAC;AAEtB,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eACnB,oBAAC,qBAAD;GACa;GACF;GAES;GACI;GACtB,CAAA;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,qBAAqB,OAAO,SAAS,kBAAkB,IAAI,oBAAoB,KAC9E,oBAAC,mBAAD,EAAmB,UAAU,mBAAqB,CAAA;EAEnD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAD,EAAkB,CAAA;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAD,EAAsB,CAAA;EACjE,EAAA,CAAA;;AAIP,WAAW,cAAc"}
|
|
1
|
+
{"version":3,"file":"SanityLive.js","names":["defaultRevalidateSyncTags","revalidateSyncTags"],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent, startTransition} from 'react'\n\nimport {isCorsOriginError} from '#live/isCorsOriginError'\n\nimport {setEnvironment, setPerspective} from '../hooks/context'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnInterval = dynamic(() => import('./RefreshOnInterval'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\n/**\n * @public\n */\nexport interface SanityLiveProps extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {\n draftModeEnabled: boolean\n draftModePerspective?: ClientPerspective\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n waitFor?: 'function'\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n token,\n requestTagPrefix,\n draftModeEnabled,\n draftModePerspective,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags = defaultRevalidateSyncTags,\n waitFor,\n } = props\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [refreshOnInterval, setRefreshOnInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n } else if (event.type === 'message') {\n if (waitFor === 'function') {\n // Cache is already revalidated by the Sanity Function, just refresh the router\n startTransition(() => router.refresh())\n } else {\n void revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') startTransition(() => router.refresh())\n })\n }\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n // Disable long polling when restart/reconnect event is received, this is a no-op if long polling is already disabled\n startTransition(() => setRefreshOnInterval(false))\n // @TODO add support for `onRestart` and `onReconnect` events so this can be customized\n startTransition(() => router.refresh())\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n startTransition(() => setRefreshOnInterval(intervalOnGoAway))\n }\n })\n useEffect(() => {\n const subscription = client.live\n .events({includeDrafts: !!token, tag: requestTag, waitFor})\n .subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n // console.error('What?', err)\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token, waitFor])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (draftModeEnabled && draftModePerspective) {\n setPerspective(draftModePerspective)\n } else {\n setPerspective('unknown')\n }\n }, [draftModeEnabled, draftModePerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n return (\n <>\n {draftModeEnabled && loadComlink && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n draftModePerspective={draftModePerspective!}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {refreshOnInterval && Number.isFinite(refreshOnInterval) && refreshOnInterval > 0 && (\n <RefreshOnInterval interval={refreshOnInterval} />\n )}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;;AAkBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,oBAAoB,cAAc,OAAO,0BAAuB;AACtE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AA4BxE,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAIxB,SAAS,eAAe,OAAwB,kBAAkC;AAChF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAIL,SAAS,WAAW,OAAkD;CACpE,MAAM,EACJ,WACA,SACA,SACA,YACA,oBACA,OACA,kBACA,kBACA,sBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBAAA,uBAAqBA,oBACrB,YACE;CAEJ,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B;EACA,QAAQ;EACR;EACD,CAAC,EACJ;EAAC;EAAS;EAAY;EAAS;EA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["../src/live/shared/isCorsOriginError.ts"],"sourcesContent":["import type {CorsOriginError} from '@sanity/client'\n\n/** @public */\nexport function isCorsOriginError(error: unknown): error is CorsOriginError {\n return error instanceof Error && error.name === 'CorsOriginError'\n}\n
|
|
1
|
+
{"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/live/shared/isCorsOriginError.ts"],"sourcesContent":["import type {CorsOriginError} from '@sanity/client'\n\n/** @public */\nexport function isCorsOriginError(error: unknown): error is CorsOriginError {\n return error instanceof Error && error.name === 'CorsOriginError'\n}\n"],"mappings":";AAGA,SAAgB,kBAAkB,OAA0C;AAC1E,QAAO,iBAAiB,SAAS,MAAM,SAAS"}
|
|
@@ -9,21 +9,10 @@ interface SanityLiveProps extends Pick<InitializedClientConfig, "projectId" | "d
|
|
|
9
9
|
refreshOnFocus?: boolean;
|
|
10
10
|
refreshOnReconnect?: boolean;
|
|
11
11
|
requestTag: string | undefined;
|
|
12
|
-
/**
|
|
13
|
-
* Handle errors from the Live Events subscription.
|
|
14
|
-
* By default it's reported using `console.error`, you can override this prop to handle it in your own way.
|
|
15
|
-
*/
|
|
16
12
|
onError?: (error: unknown) => void;
|
|
17
13
|
intervalOnGoAway?: number | false;
|
|
18
14
|
onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void;
|
|
19
15
|
revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | "refresh">;
|
|
20
|
-
/**
|
|
21
|
-
* Delays events until after a configured Sanity Function has processed them and called the callback endpoint.
|
|
22
|
-
* When omitted, events are delivered immediately.
|
|
23
|
-
*
|
|
24
|
-
* @remarks
|
|
25
|
-
* When set, any custom `revalidateSyncTags` will not be called — revalidation is handled by the Function instead.
|
|
26
|
-
*/
|
|
27
16
|
waitFor?: "function";
|
|
28
17
|
}
|
|
29
18
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"mappings":";;AA2BA;;UAAiB,eAAA,SAAwB,IAAA,CACvC,uBAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"mappings":";;AA2BA;;UAAiB,eAAA,SAAwB,IAAA,CACvC,uBAAA;EASA,gBAAA;EACA,oBAAA,GAAuB,iBAAA;EACvB,cAAA;EACA,cAAA;EACA,kBAAA;EACA,UAAA;EACA,OAAA,IAAW,KAAA;EACX,gBAAA;EACA,QAAA,IAAY,KAAA,EAAO,eAAA,EAAiB,gBAAA;EACpC,kBAAA,IAAsB,IAAA,EAAM,OAAA,OAAc,OAAA;EAC1C,OAAA;AAAA;;AApBF;;cCnBa,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,eAAA"}
|
|
@@ -1,11 +1,89 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { n as
|
|
2
|
+
import { i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
3
|
/**
|
|
4
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
5
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
6
|
+
* cached content and update in response to fine-grained content changes.
|
|
7
|
+
*
|
|
8
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
9
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import {createClient} from 'next-sanity'
|
|
14
|
+
* import {defineLive} from 'next-sanity/live'
|
|
15
|
+
*
|
|
16
|
+
* const client = createClient({
|
|
17
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
18
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
19
|
+
* useCdn: true,
|
|
20
|
+
* perspective: 'published',
|
|
21
|
+
* })
|
|
22
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
23
|
+
*
|
|
24
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
25
|
+
* client,
|
|
26
|
+
* browserToken: token,
|
|
27
|
+
* serverToken: token,
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```tsx
|
|
33
|
+
* // app/layout.tsx
|
|
34
|
+
* import {SanityLive} from '@/sanity/live'
|
|
35
|
+
*
|
|
36
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
37
|
+
* return (
|
|
38
|
+
* <html lang="en">
|
|
39
|
+
* <body>
|
|
40
|
+
* {children}
|
|
41
|
+
* <SanityLive />
|
|
42
|
+
* </body>
|
|
43
|
+
* </html>
|
|
44
|
+
* )
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* // app/[slug]/page.tsx
|
|
51
|
+
* import {defineQuery} from 'next-sanity'
|
|
52
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
53
|
+
*
|
|
54
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
55
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
56
|
+
* `)
|
|
57
|
+
* const POST_QUERY = defineQuery(`
|
|
58
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
59
|
+
* `)
|
|
60
|
+
*
|
|
61
|
+
* export async function generateStaticParams() {
|
|
62
|
+
* const {data} = await sanityFetch({
|
|
63
|
+
* query: POSTS_SLUGS_QUERY,
|
|
64
|
+
* perspective: 'published',
|
|
65
|
+
* stega: false,
|
|
66
|
+
* })
|
|
67
|
+
*
|
|
68
|
+
* return data
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
72
|
+
* const {slug} = await props.params
|
|
73
|
+
* const {data} = await sanityFetch({
|
|
74
|
+
* query: POST_QUERY,
|
|
75
|
+
* params: {slug},
|
|
76
|
+
* })
|
|
77
|
+
*
|
|
78
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
79
|
+
* }
|
|
80
|
+
* ```
|
|
81
|
+
*
|
|
4
82
|
* @public
|
|
5
83
|
*/
|
|
6
|
-
declare function defineLive(_config:
|
|
7
|
-
sanityFetch:
|
|
8
|
-
SanityLive: React.ComponentType<
|
|
84
|
+
declare function defineLive(_config: DefineLiveOptions): {
|
|
85
|
+
sanityFetch: DefinedFetchType;
|
|
86
|
+
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
9
87
|
};
|
|
10
|
-
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
|
|
88
|
+
export { type DefineLiveOptions as DefineSanityLiveOptions, type DefinedFetchType as DefinedSanityFetchType, type DefinedLiveProps as DefinedSanityLiveProps, type LivePerspective, defineLive, isCorsOriginError };
|
|
11
89
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"mappings":";;;;AAmFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,OAAA,EAAS,iBAAA;EAClC,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA"}
|
|
@@ -1,5 +1,83 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
2
|
/**
|
|
3
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
4
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
5
|
+
* cached content and update in response to fine-grained content changes.
|
|
6
|
+
*
|
|
7
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
8
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```tsx
|
|
12
|
+
* import {createClient} from 'next-sanity'
|
|
13
|
+
* import {defineLive} from 'next-sanity/live'
|
|
14
|
+
*
|
|
15
|
+
* const client = createClient({
|
|
16
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
17
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
18
|
+
* useCdn: true,
|
|
19
|
+
* perspective: 'published',
|
|
20
|
+
* })
|
|
21
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
22
|
+
*
|
|
23
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
24
|
+
* client,
|
|
25
|
+
* browserToken: token,
|
|
26
|
+
* serverToken: token,
|
|
27
|
+
* })
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```tsx
|
|
32
|
+
* // app/layout.tsx
|
|
33
|
+
* import {SanityLive} from '@/sanity/live'
|
|
34
|
+
*
|
|
35
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
36
|
+
* return (
|
|
37
|
+
* <html lang="en">
|
|
38
|
+
* <body>
|
|
39
|
+
* {children}
|
|
40
|
+
* <SanityLive />
|
|
41
|
+
* </body>
|
|
42
|
+
* </html>
|
|
43
|
+
* )
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```tsx
|
|
49
|
+
* // app/[slug]/page.tsx
|
|
50
|
+
* import {defineQuery} from 'next-sanity'
|
|
51
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
52
|
+
*
|
|
53
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
54
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
55
|
+
* `)
|
|
56
|
+
* const POST_QUERY = defineQuery(`
|
|
57
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
58
|
+
* `)
|
|
59
|
+
*
|
|
60
|
+
* export async function generateStaticParams() {
|
|
61
|
+
* const {data} = await sanityFetch({
|
|
62
|
+
* query: POSTS_SLUGS_QUERY,
|
|
63
|
+
* perspective: 'published',
|
|
64
|
+
* stega: false,
|
|
65
|
+
* })
|
|
66
|
+
*
|
|
67
|
+
* return data
|
|
68
|
+
* }
|
|
69
|
+
*
|
|
70
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
71
|
+
* const {slug} = await props.params
|
|
72
|
+
* const {data} = await sanityFetch({
|
|
73
|
+
* query: POST_QUERY,
|
|
74
|
+
* params: {slug},
|
|
75
|
+
* })
|
|
76
|
+
*
|
|
77
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
3
81
|
* @public
|
|
4
82
|
*/
|
|
5
83
|
function defineLive(_config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/default/index.ts"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, DefineLiveOptions} from '#live/types'\n\n/**\n * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,\n * which connect your Sanity client to the Live Content API so pages can serve\n * cached content and update in response to fine-grained content changes.\n *\n * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)\n * @see [Sanity Live](https://www.sanity.io/live)\n *\n * @example\n * ```tsx\n * import {createClient} from 'next-sanity'\n * import {defineLive} from 'next-sanity/live'\n *\n * const client = createClient({\n * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,\n * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,\n * useCdn: true,\n * perspective: 'published',\n * })\n * const token = process.env.SANITY_API_READ_TOKEN\n *\n * export const {sanityFetch, SanityLive} = defineLive({\n * client,\n * browserToken: token,\n * serverToken: token,\n * })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import {SanityLive} from '@/sanity/live'\n *\n * export default function RootLayout({children}: {children: React.ReactNode}) {\n * return (\n * <html lang=\"en\">\n * <body>\n * {children}\n * <SanityLive />\n * </body>\n * </html>\n * )\n * }\n * ```\n *\n * @example\n * ```tsx\n * // app/[slug]/page.tsx\n * import {defineQuery} from 'next-sanity'\n * import {sanityFetch} from '@/sanity/live'\n *\n * const POSTS_SLUGS_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current]{\"slug\": slug.current}\n * `)\n * const POST_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current == $slug][0]\n * `)\n *\n * export async function generateStaticParams() {\n * const {data} = await sanityFetch({\n * query: POSTS_SLUGS_QUERY,\n * perspective: 'published',\n * stega: false,\n * })\n *\n * return data\n * }\n *\n * export default async function Page(props: PageProps<'/[slug]'>) {\n * const {slug} = await props.params\n * const {data} = await sanityFetch({\n * query: POST_QUERY,\n * params: {slug},\n * })\n *\n * return <pre>{JSON.stringify(data, null, 2)}</pre>\n * }\n * ```\n *\n * @public\n */\nexport function defineLive(_config: DefineLiveOptions): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n} {\n throw new Error('defineLive can only be used in React Server Components')\n}\n\nexport type {\n DefinedFetchType as DefinedSanityFetchType,\n DefinedLiveProps as DefinedSanityLiveProps,\n DefineLiveOptions as DefineSanityLiveOptions,\n LivePerspective,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MAAM,yDAAyD"}
|
|
@@ -1,11 +1,89 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { n as
|
|
2
|
+
import { i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
3
|
/**
|
|
4
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
5
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
6
|
+
* cached content and update in response to fine-grained content changes.
|
|
7
|
+
*
|
|
8
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
9
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import {createClient} from 'next-sanity'
|
|
14
|
+
* import {defineLive} from 'next-sanity/live'
|
|
15
|
+
*
|
|
16
|
+
* const client = createClient({
|
|
17
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
18
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
19
|
+
* useCdn: true,
|
|
20
|
+
* perspective: 'published',
|
|
21
|
+
* })
|
|
22
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
23
|
+
*
|
|
24
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
25
|
+
* client,
|
|
26
|
+
* browserToken: token,
|
|
27
|
+
* serverToken: token,
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```tsx
|
|
33
|
+
* // app/layout.tsx
|
|
34
|
+
* import {SanityLive} from '@/sanity/live'
|
|
35
|
+
*
|
|
36
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
37
|
+
* return (
|
|
38
|
+
* <html lang="en">
|
|
39
|
+
* <body>
|
|
40
|
+
* {children}
|
|
41
|
+
* <SanityLive />
|
|
42
|
+
* </body>
|
|
43
|
+
* </html>
|
|
44
|
+
* )
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* // app/[slug]/page.tsx
|
|
51
|
+
* import {defineQuery} from 'next-sanity'
|
|
52
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
53
|
+
*
|
|
54
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
55
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
56
|
+
* `)
|
|
57
|
+
* const POST_QUERY = defineQuery(`
|
|
58
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
59
|
+
* `)
|
|
60
|
+
*
|
|
61
|
+
* export async function generateStaticParams() {
|
|
62
|
+
* const {data} = await sanityFetch({
|
|
63
|
+
* query: POSTS_SLUGS_QUERY,
|
|
64
|
+
* perspective: 'published',
|
|
65
|
+
* stega: false,
|
|
66
|
+
* })
|
|
67
|
+
*
|
|
68
|
+
* return data
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
72
|
+
* const {slug} = await props.params
|
|
73
|
+
* const {data} = await sanityFetch({
|
|
74
|
+
* query: POST_QUERY,
|
|
75
|
+
* params: {slug},
|
|
76
|
+
* })
|
|
77
|
+
*
|
|
78
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
79
|
+
* }
|
|
80
|
+
* ```
|
|
81
|
+
*
|
|
4
82
|
* @public
|
|
5
83
|
*/
|
|
6
|
-
declare function defineLive(_config:
|
|
7
|
-
sanityFetch:
|
|
8
|
-
SanityLive: React.ComponentType<
|
|
84
|
+
declare function defineLive(_config: DefineLiveOptions): {
|
|
85
|
+
sanityFetch: DefinedFetchType;
|
|
86
|
+
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
9
87
|
};
|
|
10
|
-
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, defineLive, isCorsOriginError };
|
|
88
|
+
export { type DefineLiveOptions as DefineSanityLiveOptions, type DefinedFetchType as DefinedSanityFetchType, type DefinedLiveProps as DefinedSanityLiveProps, type LivePerspective, defineLive, isCorsOriginError };
|
|
11
89
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"mappings":";;;;AAmFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,OAAA,EAAS,iBAAA;EAClC,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA"}
|
|
@@ -1,5 +1,83 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
2
|
/**
|
|
3
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
4
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
5
|
+
* cached content and update in response to fine-grained content changes.
|
|
6
|
+
*
|
|
7
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
8
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```tsx
|
|
12
|
+
* import {createClient} from 'next-sanity'
|
|
13
|
+
* import {defineLive} from 'next-sanity/live'
|
|
14
|
+
*
|
|
15
|
+
* const client = createClient({
|
|
16
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
17
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
18
|
+
* useCdn: true,
|
|
19
|
+
* perspective: 'published',
|
|
20
|
+
* })
|
|
21
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
22
|
+
*
|
|
23
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
24
|
+
* client,
|
|
25
|
+
* browserToken: token,
|
|
26
|
+
* serverToken: token,
|
|
27
|
+
* })
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```tsx
|
|
32
|
+
* // app/layout.tsx
|
|
33
|
+
* import {SanityLive} from '@/sanity/live'
|
|
34
|
+
*
|
|
35
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
36
|
+
* return (
|
|
37
|
+
* <html lang="en">
|
|
38
|
+
* <body>
|
|
39
|
+
* {children}
|
|
40
|
+
* <SanityLive />
|
|
41
|
+
* </body>
|
|
42
|
+
* </html>
|
|
43
|
+
* )
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```tsx
|
|
49
|
+
* // app/[slug]/page.tsx
|
|
50
|
+
* import {defineQuery} from 'next-sanity'
|
|
51
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
52
|
+
*
|
|
53
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
54
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
55
|
+
* `)
|
|
56
|
+
* const POST_QUERY = defineQuery(`
|
|
57
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
58
|
+
* `)
|
|
59
|
+
*
|
|
60
|
+
* export async function generateStaticParams() {
|
|
61
|
+
* const {data} = await sanityFetch({
|
|
62
|
+
* query: POSTS_SLUGS_QUERY,
|
|
63
|
+
* perspective: 'published',
|
|
64
|
+
* stega: false,
|
|
65
|
+
* })
|
|
66
|
+
*
|
|
67
|
+
* return data
|
|
68
|
+
* }
|
|
69
|
+
*
|
|
70
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
71
|
+
* const {slug} = await props.params
|
|
72
|
+
* const {data} = await sanityFetch({
|
|
73
|
+
* query: POST_QUERY,
|
|
74
|
+
* params: {slug},
|
|
75
|
+
* })
|
|
76
|
+
*
|
|
77
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
3
81
|
* @public
|
|
4
82
|
*/
|
|
5
83
|
function defineLive(_config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/live/conditions/next-js/index.ts"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, DefineLiveOptions} from '#live/types'\n\n/**\n * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,\n * which connect your Sanity client to the Live Content API so pages can serve\n * cached content and update in response to fine-grained content changes.\n *\n * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)\n * @see [Sanity Live](https://www.sanity.io/live)\n *\n * @example\n * ```tsx\n * import {createClient} from 'next-sanity'\n * import {defineLive} from 'next-sanity/live'\n *\n * const client = createClient({\n * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,\n * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,\n * useCdn: true,\n * perspective: 'published',\n * })\n * const token = process.env.SANITY_API_READ_TOKEN\n *\n * export const {sanityFetch, SanityLive} = defineLive({\n * client,\n * browserToken: token,\n * serverToken: token,\n * })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import {SanityLive} from '@/sanity/live'\n *\n * export default function RootLayout({children}: {children: React.ReactNode}) {\n * return (\n * <html lang=\"en\">\n * <body>\n * {children}\n * <SanityLive />\n * </body>\n * </html>\n * )\n * }\n * ```\n *\n * @example\n * ```tsx\n * // app/[slug]/page.tsx\n * import {defineQuery} from 'next-sanity'\n * import {sanityFetch} from '@/sanity/live'\n *\n * const POSTS_SLUGS_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current]{\"slug\": slug.current}\n * `)\n * const POST_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current == $slug][0]\n * `)\n *\n * export async function generateStaticParams() {\n * const {data} = await sanityFetch({\n * query: POSTS_SLUGS_QUERY,\n * perspective: 'published',\n * stega: false,\n * })\n *\n * return data\n * }\n *\n * export default async function Page(props: PageProps<'/[slug]'>) {\n * const {slug} = await props.params\n * const {data} = await sanityFetch({\n * query: POST_QUERY,\n * params: {slug},\n * })\n *\n * return <pre>{JSON.stringify(data, null, 2)}</pre>\n * }\n * ```\n *\n * @public\n */\nexport function defineLive(_config: DefineLiveOptions): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n} {\n throw new Error(\n 'defineLive does not yet support `cacheComponents: true`. Wait for the next major version of next-sanity, or use the prerelease with `pnpm install next-sanity@cache-components`',\n )\n}\n\nexport type {\n DefinedFetchType as DefinedSanityFetchType,\n DefinedLiveProps as DefinedSanityLiveProps,\n DefineLiveOptions as DefineSanityLiveOptions,\n LivePerspective,\n} from '#live/types'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAgB,WAAW,SAGzB;AACA,OAAM,IAAI,MACR,kLACD"}
|
|
@@ -1,3 +1,89 @@
|
|
|
1
1
|
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
|
-
import { i as
|
|
3
|
-
|
|
2
|
+
import { i as LivePerspective, n as DefinedFetchType, r as DefinedLiveProps, t as DefineLiveOptions } from "../../../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
5
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
6
|
+
* cached content and update in response to fine-grained content changes.
|
|
7
|
+
*
|
|
8
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
9
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import {createClient} from 'next-sanity'
|
|
14
|
+
* import {defineLive} from 'next-sanity/live'
|
|
15
|
+
*
|
|
16
|
+
* const client = createClient({
|
|
17
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
18
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
19
|
+
* useCdn: true,
|
|
20
|
+
* perspective: 'published',
|
|
21
|
+
* })
|
|
22
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
23
|
+
*
|
|
24
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
25
|
+
* client,
|
|
26
|
+
* browserToken: token,
|
|
27
|
+
* serverToken: token,
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```tsx
|
|
33
|
+
* // app/layout.tsx
|
|
34
|
+
* import {SanityLive} from '@/sanity/live'
|
|
35
|
+
*
|
|
36
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
37
|
+
* return (
|
|
38
|
+
* <html lang="en">
|
|
39
|
+
* <body>
|
|
40
|
+
* {children}
|
|
41
|
+
* <SanityLive />
|
|
42
|
+
* </body>
|
|
43
|
+
* </html>
|
|
44
|
+
* )
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* // app/[slug]/page.tsx
|
|
51
|
+
* import {defineQuery} from 'next-sanity'
|
|
52
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
53
|
+
*
|
|
54
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
55
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
56
|
+
* `)
|
|
57
|
+
* const POST_QUERY = defineQuery(`
|
|
58
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
59
|
+
* `)
|
|
60
|
+
*
|
|
61
|
+
* export async function generateStaticParams() {
|
|
62
|
+
* const {data} = await sanityFetch({
|
|
63
|
+
* query: POSTS_SLUGS_QUERY,
|
|
64
|
+
* perspective: 'published',
|
|
65
|
+
* stega: false,
|
|
66
|
+
* })
|
|
67
|
+
*
|
|
68
|
+
* return data
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
72
|
+
* const {slug} = await props.params
|
|
73
|
+
* const {data} = await sanityFetch({
|
|
74
|
+
* query: POST_QUERY,
|
|
75
|
+
* params: {slug},
|
|
76
|
+
* })
|
|
77
|
+
*
|
|
78
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
79
|
+
* }
|
|
80
|
+
* ```
|
|
81
|
+
*
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
declare function defineLive(config: DefineLiveOptions): {
|
|
85
|
+
sanityFetch: DefinedFetchType;
|
|
86
|
+
SanityLive: React.ComponentType<DefinedLiveProps>;
|
|
87
|
+
};
|
|
88
|
+
export { type DefineLiveOptions as DefineSanityLiveOptions, type DefinedFetchType as DefinedSanityFetchType, type DefinedLiveProps as DefinedSanityLiveProps, type LivePerspective, defineLive, isCorsOriginError };
|
|
89
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"mappings":";;;;AA2FA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,UAAA,CAAW,MAAA,EAAQ,iBAAA;EACjC,WAAA,EAAa,gBAAA;EACb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,gBAAA;AAAA"}
|
|
@@ -3,11 +3,88 @@ import { t as sanitizePerspective } from "../../../sanitizePerspective.js";
|
|
|
3
3
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
4
4
|
import { cookies, draftMode } from "next/headers";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
|
-
import "@sanity/client";
|
|
7
6
|
import { SanityLive } from "next-sanity/live/client-components";
|
|
8
7
|
import { PHASE_PRODUCTION_BUILD } from "next/constants";
|
|
9
8
|
import { preconnect } from "react-dom";
|
|
10
9
|
/**
|
|
10
|
+
* Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,
|
|
11
|
+
* which connect your Sanity client to the Live Content API so pages can serve
|
|
12
|
+
* cached content and update in response to fine-grained content changes.
|
|
13
|
+
*
|
|
14
|
+
* @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)
|
|
15
|
+
* @see [Sanity Live](https://www.sanity.io/live)
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* import {createClient} from 'next-sanity'
|
|
20
|
+
* import {defineLive} from 'next-sanity/live'
|
|
21
|
+
*
|
|
22
|
+
* const client = createClient({
|
|
23
|
+
* projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
|
|
24
|
+
* dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
|
|
25
|
+
* useCdn: true,
|
|
26
|
+
* perspective: 'published',
|
|
27
|
+
* })
|
|
28
|
+
* const token = process.env.SANITY_API_READ_TOKEN
|
|
29
|
+
*
|
|
30
|
+
* export const {sanityFetch, SanityLive} = defineLive({
|
|
31
|
+
* client,
|
|
32
|
+
* browserToken: token,
|
|
33
|
+
* serverToken: token,
|
|
34
|
+
* })
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```tsx
|
|
39
|
+
* // app/layout.tsx
|
|
40
|
+
* import {SanityLive} from '@/sanity/live'
|
|
41
|
+
*
|
|
42
|
+
* export default function RootLayout({children}: {children: React.ReactNode}) {
|
|
43
|
+
* return (
|
|
44
|
+
* <html lang="en">
|
|
45
|
+
* <body>
|
|
46
|
+
* {children}
|
|
47
|
+
* <SanityLive />
|
|
48
|
+
* </body>
|
|
49
|
+
* </html>
|
|
50
|
+
* )
|
|
51
|
+
* }
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```tsx
|
|
56
|
+
* // app/[slug]/page.tsx
|
|
57
|
+
* import {defineQuery} from 'next-sanity'
|
|
58
|
+
* import {sanityFetch} from '@/sanity/live'
|
|
59
|
+
*
|
|
60
|
+
* const POSTS_SLUGS_QUERY = defineQuery(`
|
|
61
|
+
* *[_type == "post" && slug.current]{"slug": slug.current}
|
|
62
|
+
* `)
|
|
63
|
+
* const POST_QUERY = defineQuery(`
|
|
64
|
+
* *[_type == "post" && slug.current == $slug][0]
|
|
65
|
+
* `)
|
|
66
|
+
*
|
|
67
|
+
* export async function generateStaticParams() {
|
|
68
|
+
* const {data} = await sanityFetch({
|
|
69
|
+
* query: POSTS_SLUGS_QUERY,
|
|
70
|
+
* perspective: 'published',
|
|
71
|
+
* stega: false,
|
|
72
|
+
* })
|
|
73
|
+
*
|
|
74
|
+
* return data
|
|
75
|
+
* }
|
|
76
|
+
*
|
|
77
|
+
* export default async function Page(props: PageProps<'/[slug]'>) {
|
|
78
|
+
* const {slug} = await props.params
|
|
79
|
+
* const {data} = await sanityFetch({
|
|
80
|
+
* query: POST_QUERY,
|
|
81
|
+
* params: {slug},
|
|
82
|
+
* })
|
|
83
|
+
*
|
|
84
|
+
* return <pre>{JSON.stringify(data, null, 2)}</pre>
|
|
85
|
+
* }
|
|
86
|
+
* ```
|
|
87
|
+
*
|
|
11
88
|
* @public
|
|
12
89
|
*/
|
|
13
90
|
function defineLive(config) {
|
|
@@ -21,74 +98,77 @@ function defineLive(config) {
|
|
|
21
98
|
});
|
|
22
99
|
const { token: originalToken } = client.config();
|
|
23
100
|
const studioUrlDefined = typeof client.config().stega.studioUrl !== "undefined";
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
revalidate,
|
|
53
|
-
tags: cacheTags
|
|
54
|
-
},
|
|
55
|
-
useCdn,
|
|
56
|
-
cacheMode,
|
|
57
|
-
tag: requestTag
|
|
58
|
-
});
|
|
59
|
-
return {
|
|
60
|
-
data: result,
|
|
61
|
-
sourceMap: resultSourceMap || null,
|
|
101
|
+
const sanityFetch = async function sanityFetch({ query, params = {}, stega: _stega, tags = [], perspective: _perspective, tag, requestTag = tag ?? "next-loader.fetch" }) {
|
|
102
|
+
const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled);
|
|
103
|
+
const perspective = _perspective ?? await resolveCookiePerspective();
|
|
104
|
+
const useCdn = perspective === "published";
|
|
105
|
+
const revalidate = fetchOptions?.revalidate !== void 0 ? fetchOptions.revalidate : process.env.NODE_ENV === "production" ? false : void 0;
|
|
106
|
+
const isBuildPhase = process.env["NEXT_PHASE"] === PHASE_PRODUCTION_BUILD;
|
|
107
|
+
const cacheMode = useCdn && !isBuildPhase ? "noStale" : void 0;
|
|
108
|
+
const { syncTags } = await client.fetch(query, await params, {
|
|
109
|
+
filterResponse: false,
|
|
110
|
+
perspective,
|
|
111
|
+
stega: false,
|
|
112
|
+
returnQuery: false,
|
|
113
|
+
next: {
|
|
114
|
+
revalidate,
|
|
115
|
+
tags: [...tags, "sanity:fetch-sync-tags"]
|
|
116
|
+
},
|
|
117
|
+
useCdn,
|
|
118
|
+
cacheMode,
|
|
119
|
+
tag: [requestTag, "fetch-sync-tags"].filter(Boolean).join(".")
|
|
120
|
+
});
|
|
121
|
+
const cacheTags = [...tags, ...syncTags?.map((tag) => `sanity:${tag}`) || []];
|
|
122
|
+
const { result, resultSourceMap } = await client.fetch(query, await params, {
|
|
123
|
+
filterResponse: false,
|
|
124
|
+
perspective,
|
|
125
|
+
stega,
|
|
126
|
+
token: perspective !== "published" && serverToken ? serverToken : originalToken,
|
|
127
|
+
next: {
|
|
128
|
+
revalidate,
|
|
62
129
|
tags: cacheTags
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
130
|
+
},
|
|
131
|
+
useCdn,
|
|
132
|
+
cacheMode,
|
|
133
|
+
tag: requestTag
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
data: result,
|
|
137
|
+
sourceMap: resultSourceMap || null,
|
|
138
|
+
tags: cacheTags
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
const SanityLive$2 = async function SanityLive$1(props) {
|
|
142
|
+
const { refreshOnMount, refreshOnFocus, refreshOnReconnect, tag, requestTag = tag, onError, onGoAway, intervalOnGoAway, revalidateSyncTags, waitFor } = props;
|
|
143
|
+
const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
|
|
144
|
+
const { isEnabled: isDraftModeEnabled } = await draftMode();
|
|
145
|
+
const { origin } = new URL(client.getUrl("", false));
|
|
146
|
+
preconnect(origin);
|
|
147
|
+
return /* @__PURE__ */ jsx(SanityLive, {
|
|
148
|
+
projectId,
|
|
149
|
+
dataset,
|
|
150
|
+
apiHost,
|
|
151
|
+
apiVersion,
|
|
152
|
+
useProjectHostname,
|
|
153
|
+
requestTagPrefix,
|
|
154
|
+
requestTag,
|
|
155
|
+
token: typeof browserToken === "string" && isDraftModeEnabled ? browserToken : void 0,
|
|
156
|
+
draftModeEnabled: isDraftModeEnabled,
|
|
157
|
+
draftModePerspective: await resolveCookiePerspective(),
|
|
158
|
+
refreshOnMount,
|
|
159
|
+
refreshOnFocus,
|
|
160
|
+
refreshOnReconnect,
|
|
161
|
+
onError,
|
|
162
|
+
onGoAway,
|
|
163
|
+
intervalOnGoAway,
|
|
164
|
+
revalidateSyncTags,
|
|
165
|
+
waitFor
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
SanityLive$2.displayName = "SanityLiveServerComponent";
|
|
169
|
+
return {
|
|
170
|
+
sanityFetch,
|
|
171
|
+
SanityLive: SanityLive$2
|
|
92
172
|
};
|
|
93
173
|
}
|
|
94
174
|
async function resolveCookiePerspective() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {draftMode, cookies} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `false` if draftMode().isEnabled, otherwise `true` if not inside an iframe\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.\n * @defaultValue `true`\n */\n refreshOnReconnect?: boolean\n /**\n * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.\n * This typically happens if the connection limit is reached, or if the connection is idle for too long.\n * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.\n * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.\n * @defaultValue `30_000` 30 seconds interval\n */\n intervalOnGoAway?: number | false\n\n /**\n * Delays events until after a Sanity Function has processed them and called the callback endpoint.\n * When omitted, events are delivered immediately.\n */\n waitFor?: 'function'\n\n /**\n * @deprecated use `requestTag` instead\n */\n tag?: never\n\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live'\n */\n requestTag?: string\n\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n\n /**\n * Handle the `goaway` event if the connection is rejected/closed.\n * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.\n * When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.\n * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.\n */\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n /**\n * Override how cache tags are invalidated, you need to pass a server action here.\n * You can also pass a `use client` function here, and have `router.refresh()` be called if the promise resolves to `'refresh'`.\n */\n revalidateSyncTags?: (tags: SyncTag[]) => Promise<void | 'refresh'>\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n * @deprecated this option is removed in the next major version, use `export const revalidate` on the `page.tsx` or `layout.tsx` instead\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\n/**\n * @public\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n * @public\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n * @public\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = [],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n tag,\n requestTag = tag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags,\n waitFor,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n projectId={projectId}\n dataset={dataset}\n apiHost={apiHost}\n apiVersion={apiVersion}\n useProjectHostname={useProjectHostname}\n requestTagPrefix={requestTagPrefix}\n requestTag={requestTag}\n token={typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined}\n draftModeEnabled={isDraftModeEnabled}\n draftModePerspective={await resolveCookiePerspective()}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n waitFor={waitFor}\n />\n )\n }\n\n return {\n sanityFetch,\n SanityLive,\n }\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;;;;AA6JA,SAAgB,WAAW,QAWzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAAC;CAC3E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAC9C,MAAM,mBAAmB,OAAO,OAAO,QAAQ,CAAC,MAAM,cAAc;AAwGpE,QAAO;EACL,aAAA,eAvGyD,YAEzD,EACA,OACA,SAAS,EAAE,EACX,OAAO,QACP,OAAO,EAAE,EACT,aAAa,cACb,KACA,aAAa,OAAO,uBASnB;GACD,MAAM,QAAQ,WAAW,gBAAgB,qBAAqB,MAAM,WAAW,EAAE;GACjF,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;GACrE,MAAM,SAAS,gBAAgB;GAC/B,MAAM,aACJ,cAAc,eAAe,KAAA,IACzB,aAAa,aACb,QAAQ,IAAI,aAAa,eACvB,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AAA;;EAOL;;AAGH,eAAe,2BAAuE;AACpF,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import type {ClientPerspective, QueryParams} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {PHASE_PRODUCTION_BUILD} from 'next/constants'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport type {DefinedFetchType, DefinedLiveProps, DefineLiveOptions} from '#live/types'\n\n/**\n * Set up Sanity Live. `defineLive` returns `sanityFetch` and `<SanityLive />`,\n * which connect your Sanity client to the Live Content API so pages can serve\n * cached content and update in response to fine-grained content changes.\n *\n * @see [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api)\n * @see [Sanity Live](https://www.sanity.io/live)\n *\n * @example\n * ```tsx\n * import {createClient} from 'next-sanity'\n * import {defineLive} from 'next-sanity/live'\n *\n * const client = createClient({\n * projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,\n * dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,\n * useCdn: true,\n * perspective: 'published',\n * })\n * const token = process.env.SANITY_API_READ_TOKEN\n *\n * export const {sanityFetch, SanityLive} = defineLive({\n * client,\n * browserToken: token,\n * serverToken: token,\n * })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import {SanityLive} from '@/sanity/live'\n *\n * export default function RootLayout({children}: {children: React.ReactNode}) {\n * return (\n * <html lang=\"en\">\n * <body>\n * {children}\n * <SanityLive />\n * </body>\n * </html>\n * )\n * }\n * ```\n *\n * @example\n * ```tsx\n * // app/[slug]/page.tsx\n * import {defineQuery} from 'next-sanity'\n * import {sanityFetch} from '@/sanity/live'\n *\n * const POSTS_SLUGS_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current]{\"slug\": slug.current}\n * `)\n * const POST_QUERY = defineQuery(`\n * *[_type == \"post\" && slug.current == $slug][0]\n * `)\n *\n * export async function generateStaticParams() {\n * const {data} = await sanityFetch({\n * query: POSTS_SLUGS_QUERY,\n * perspective: 'published',\n * stega: false,\n * })\n *\n * return data\n * }\n *\n * export default async function Page(props: PageProps<'/[slug]'>) {\n * const {slug} = await props.params\n * const {data} = await sanityFetch({\n * query: POST_QUERY,\n * params: {slug},\n * })\n *\n * return <pre>{JSON.stringify(data, null, 2)}</pre>\n * }\n * ```\n *\n * @public\n */\nexport function defineLive(config: DefineLiveOptions): {\n sanityFetch: DefinedFetchType\n SanityLive: React.ComponentType<DefinedLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = [],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n const isBuildPhase = process.env['NEXT_PHASE'] === PHASE_PRODUCTION_BUILD\n const cacheMode = useCdn && !isBuildPhase ? 'noStale' : undefined\n\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedLiveProps> = async function SanityLive(props) {\n const {\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n tag,\n requestTag = tag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags,\n waitFor,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n projectId={projectId}\n dataset={dataset}\n apiHost={apiHost}\n apiVersion={apiVersion}\n useProjectHostname={useProjectHostname}\n requestTagPrefix={requestTagPrefix}\n requestTag={requestTag}\n token={typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined}\n draftModeEnabled={isDraftModeEnabled}\n draftModePerspective={await resolveCookiePerspective()}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n waitFor={waitFor}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {sanityFetch, SanityLive}\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,SAAgB,WAAW,QAGzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAAC;CAC3E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAC9C,MAAM,m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S,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EACjB,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;EAGzD,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAACC,YAAD;GACa;GACF;GACA;GACG;GACQ;GACF;GACN;GACZ,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;GAC/E,kBAAkB;GAClB,sBAAsB,MAAM,0BAA0B;GACtC;GACA;GACI;GACX;GACC;GACQ;GACE;GACX;GACT,CAAA;;AAGN,cAAW,cAAc;AAEzB,QAAO;EAAC;EAAa,YAAA;EAAW;;AAGlC,eAAe,2BAAuE;AACpF,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
|
|
@@ -2,4 +2,4 @@ import { ClientPerspective, SyncTag } from "@sanity/client";
|
|
|
2
2
|
declare function revalidateSyncTags(tags: SyncTag[]): Promise<void>;
|
|
3
3
|
declare function setPerspectiveCookie(perspective: ClientPerspective): Promise<void>;
|
|
4
4
|
export { revalidateSyncTags, setPerspectiveCookie };
|
|
5
|
-
//# sourceMappingURL=index.
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/server-actions/index.ts"],"mappings":";iBASsB,kBAAA,CAAmB,IAAA,EAAM,OAAA,KAAY,OAAA;AAAA,iBAwBrC,oBAAA,CAAqB,WAAA,EAAa,iBAAA,GAAoB,OAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective, SyncTag} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag, updateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\nexport async function revalidateSyncTags(tags: SyncTag[]): Promise<void> {\n const {isEnabled: isDraftMode} = await draftMode()\n\n if (!isDraftMode) {\n revalidateTag('sanity:fetch-sync-tags', 'max')\n }\n\n const logTags: string[] = []\n for (const _tag of tags) {\n const tag = `sanity:${_tag}`\n if (isDraftMode) {\n revalidateTag(tag, 'max')\n } else {\n updateTag(tag)\n }\n logTags.push(tag)\n }\n\n // oxlint-disable-next-line no-console\n console.log(\n `<SanityLive /> ${isDraftMode ? `revalidated tags: ${logTags.join(', ')} with cache profile \"max\" ` : `updated tags: ${logTags.join(', ')} and revalidated tag: \"sanity:fetch-sync-tags\" with cache profile \"max\"`}`,\n )\n}\n\nexport async function setPerspectiveCookie(perspective: ClientPerspective): Promise<void> {\n if (!(await draftMode()).isEnabled) {\n // throw new Error('Draft mode is not enabled, setting perspective cookie is not allowed')\n return\n }\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (perspective !== sanitizedPerspective) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n ;(await cookies()).set(\n perspectiveCookieName,\n Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(',') : sanitizedPerspective,\n {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n },\n )\n}\n"],"mappings":";;;;;AASA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,EAAC,WAAW,gBAAe,MAAM,WAAW;AAElD,KAAI,CAAC,YACH,eAAc,0BAA0B,MAAM;CAGhD,MAAM,UAAoB,EAAE;AAC5B,MAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,MAAM,UAAU;AACtB,MAAI,YACF,eAAc,KAAK,MAAM;MAEzB,WAAU,IAAI;AAEhB,UAAQ,KAAK,IAAI;;AAInB,SAAQ,IACN,kBAAkB,cAAc,qBAAqB,QAAQ,KAAK,KAAK,CAAC,8BAA8B,iBAAiB,QAAQ,KAAK,KAAK,CAAC,2EAC3I;;AAGH,eAAsB,qBAAqB,aAA+C;AACxF,KAAI,EAAE,MAAM,WAAW,EAAE,UAEvB;CAEF,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KAAI,gBAAgB,qBAClB,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAG7D,EAAC,MAAM,SAAS,EAAE,IACjB,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF"}
|
|
@@ -1,19 +1,43 @@
|
|
|
1
|
-
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "
|
|
1
|
+
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "next-sanity";
|
|
2
2
|
/**
|
|
3
|
+
* Perspectives supported by Sanity Live.
|
|
4
|
+
* Using the legacy `'raw'` perspective is not supported and leads to undefined behavior.
|
|
5
|
+
*/
|
|
6
|
+
type LivePerspective = Exclude<ClientPerspective, "raw">;
|
|
7
|
+
/**
|
|
8
|
+
* Use this function to fetch data from Sanity in your React Server Components.
|
|
9
|
+
* When used within a `generateMetadata` or `generateViewport` function, make sure you set `stega: false`.
|
|
10
|
+
* When used within a `generateStaticParams` function, make sure you set `stega: false` and `perspective: 'published'`.
|
|
3
11
|
* @public
|
|
4
12
|
*/
|
|
5
|
-
type
|
|
13
|
+
type DefinedFetchType = <const QueryString extends string>(options: {
|
|
14
|
+
/**
|
|
15
|
+
* GROQ query to execute.
|
|
16
|
+
*/
|
|
6
17
|
query: QueryString;
|
|
18
|
+
/**
|
|
19
|
+
* Parameters used by the GROQ query.
|
|
20
|
+
*/
|
|
7
21
|
params?: QueryParams | Promise<QueryParams>;
|
|
8
22
|
/**
|
|
23
|
+
* Content perspective used for the fetch.
|
|
24
|
+
*
|
|
25
|
+
* @defaultValue 'published' or when in draft mode it's 'drafts' or the value of a cookie named 'sanity-preview-perspective' that is set by `defineEnableDraftMode`.
|
|
26
|
+
*/
|
|
27
|
+
perspective?: LivePerspective;
|
|
28
|
+
/**
|
|
29
|
+
* Enables stega encoding of the data. This is typically only used in draft
|
|
30
|
+
* mode with `perspective: 'drafts'` and `@sanity/visual-editing`.
|
|
31
|
+
*
|
|
32
|
+
* @defaultValue `false` or when in draft mode it's `true`
|
|
33
|
+
*/
|
|
34
|
+
stega?: boolean;
|
|
35
|
+
/**
|
|
9
36
|
* Add custom `next.tags` to the underlying fetch request.
|
|
10
37
|
* @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags
|
|
11
38
|
* This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).
|
|
12
|
-
* @defaultValue `['sanity']`
|
|
13
39
|
*/
|
|
14
40
|
tags?: string[];
|
|
15
|
-
perspective?: Exclude<ClientPerspective, "raw">;
|
|
16
|
-
stega?: boolean;
|
|
17
41
|
/**
|
|
18
42
|
* @deprecated use `requestTag` instead
|
|
19
43
|
*/
|
|
@@ -25,14 +49,15 @@ type DefinedSanityFetchType = <const QueryString extends string>(options: {
|
|
|
25
49
|
*/
|
|
26
50
|
requestTag?: string;
|
|
27
51
|
}) => Promise<{
|
|
28
|
-
data: ClientReturn<QueryString>;
|
|
52
|
+
data: ClientReturn<QueryString, unknown>;
|
|
29
53
|
sourceMap: ContentSourceMap | null;
|
|
30
54
|
tags: string[];
|
|
31
55
|
}>;
|
|
32
56
|
/**
|
|
57
|
+
* Render this in your root layout.tsx to make your page revalidate on new content live, automatically.
|
|
33
58
|
* @public
|
|
34
59
|
*/
|
|
35
|
-
interface
|
|
60
|
+
interface DefinedLiveProps {
|
|
36
61
|
/**
|
|
37
62
|
* Automatic refresh of RSC when the component <SanityLive /> is mounted.
|
|
38
63
|
* Note that this is different from revalidation, which is based on tags and causes `sanityFetch` calls to be re-fetched.
|
|
@@ -60,8 +85,11 @@ interface DefinedSanityLiveProps {
|
|
|
60
85
|
*/
|
|
61
86
|
intervalOnGoAway?: number | false;
|
|
62
87
|
/**
|
|
63
|
-
* Delays events until after a Sanity Function has processed them and called the callback endpoint.
|
|
88
|
+
* Delays events until after a configured Sanity Function has processed them and called the callback endpoint.
|
|
64
89
|
* When omitted, events are delivered immediately.
|
|
90
|
+
*
|
|
91
|
+
* @remarks
|
|
92
|
+
* When set, any custom `revalidateSyncTags` will not be called — revalidation is handled by the Function instead.
|
|
65
93
|
*/
|
|
66
94
|
waitFor?: "function";
|
|
67
95
|
/**
|
|
@@ -95,7 +123,7 @@ interface DefinedSanityLiveProps {
|
|
|
95
123
|
/**
|
|
96
124
|
* @public
|
|
97
125
|
*/
|
|
98
|
-
interface
|
|
126
|
+
interface DefineLiveOptions {
|
|
99
127
|
/**
|
|
100
128
|
* Required for `sanityFetch` and `SanityLive` to work
|
|
101
129
|
*/
|
|
@@ -127,20 +155,5 @@ interface DefineSanityLiveOptions {
|
|
|
127
155
|
*/
|
|
128
156
|
stega?: boolean;
|
|
129
157
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
*/
|
|
133
|
-
declare function defineLive(config: DefineSanityLiveOptions): {
|
|
134
|
-
/**
|
|
135
|
-
* Use this function to fetch data from Sanity in your React Server Components.
|
|
136
|
-
* @public
|
|
137
|
-
*/
|
|
138
|
-
sanityFetch: DefinedSanityFetchType;
|
|
139
|
-
/**
|
|
140
|
-
* Render this in your root layout.tsx to make your page revalidate on new content live, automatically.
|
|
141
|
-
* @public
|
|
142
|
-
*/
|
|
143
|
-
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
144
|
-
};
|
|
145
|
-
export { defineLive as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
|
|
146
|
-
//# sourceMappingURL=defineLive.d.ts.map
|
|
158
|
+
export { LivePerspective as i, DefinedFetchType as n, DefinedLiveProps as r, DefineLiveOptions as t };
|
|
159
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/live/shared/types.ts"],"mappings":";;AAcA;;;KAAY,eAAA,GAAkB,OAAA,CAAQ,iBAAA;;AAQtC;;;;;KAAY,gBAAA,sCAAsD,OAAA;;;;EAIhE,KAAA,EAAO,WAAA;;;;EAIP,MAAA,GAAS,WAAA,GAAc,OAAA,CAAQ,WAAA;;;;;;EAM/B,WAAA,GAAc,eAAA;;;;;;;EAOd,KAAA;;;;;;EAMA,IAAA;;;;EAIA,GAAA;EAiBF;;;;;EAXE,UAAA;AAAA,MACI,OAAA;EACJ,IAAA,EAAM,YAAA,CAAa,WAAA;EACnB,SAAA,EAAW,gBAAA;EACX,IAAA;AAAA;;;;;UAOe,gBAAA;;;;;;EAMf,cAAA;;;;;;EAMA,cAAA;EA6De;;;;;EAvDf,kBAAA;;;;;;;;EAQA,gBAAA;;;;;;;;EASA,OAAA;;;;EAKA,GAAA;;;;;;EAOA,UAAA;;;;;EAMA,OAAA,IAAW,KAAA;;;;;;;EAQX,QAAA,IAAY,KAAA,EAAO,eAAA,EAAiB,gBAAA;;;;;EAMpC,kBAAA,IAAsB,IAAA,EAAM,OAAA,OAAc,OAAA;AAAA;;;;UAM3B,iBAAA;;;;EAIf,MAAA,EAAQ,YAAA;;;;;EAKR,WAAA;;;;;EAKA,YAAA;;;;;EAKA,YAAA;;;;;IAKE,UAAA;EAAA;;;;;EAMF,KAAA;AAAA"}
|
|
@@ -2,6 +2,6 @@ import { ClientPerspective } from "@sanity/client";
|
|
|
2
2
|
/**
|
|
3
3
|
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
4
4
|
*/
|
|
5
|
-
declare function
|
|
6
|
-
export {
|
|
5
|
+
declare function perspectiveChangeAction(perspective: ClientPerspective): Promise<void>;
|
|
6
|
+
export { perspectiveChangeAction };
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -6,13 +6,13 @@ import { refresh } from "next/cache";
|
|
|
6
6
|
/**
|
|
7
7
|
* @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.
|
|
8
8
|
*/
|
|
9
|
-
async function
|
|
9
|
+
async function perspectiveChangeAction(perspective) {
|
|
10
10
|
const sanitizedPerspective = sanitizePerspective(perspective, "drafts");
|
|
11
11
|
if (!sanitizedPerspective || Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0) throw new Error(`Invalid perspective`, { cause: perspective });
|
|
12
12
|
const nextPerspective = Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(",") : sanitizedPerspective;
|
|
13
13
|
const jar = await cookies();
|
|
14
14
|
if (nextPerspective === jar.get(perspectiveCookieName)?.value && process.env.NODE_ENV !== "production") {
|
|
15
|
-
console.debug("
|
|
15
|
+
console.debug("perspectiveChangeAction", "Perspective is the same, skipping", nextPerspective);
|
|
16
16
|
return;
|
|
17
17
|
}
|
|
18
18
|
jar.set(perspectiveCookieName, nextPerspective, {
|
|
@@ -23,6 +23,6 @@ async function actionPerspectiveChange(perspective) {
|
|
|
23
23
|
});
|
|
24
24
|
refresh();
|
|
25
25
|
}
|
|
26
|
-
export {
|
|
26
|
+
export { perspectiveChangeAction };
|
|
27
27
|
|
|
28
28
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {refresh} from 'next/cache'\nimport {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.\n */\nexport async function
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {refresh} from 'next/cache'\nimport {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\n/**\n * @internal CAUTION: this is an internal action and does not follow semver. Using it directly is at your own risk.\n */\nexport async function perspectiveChangeAction(perspective: ClientPerspective): Promise<void> {\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (\n !sanitizedPerspective ||\n (Array.isArray(sanitizedPerspective) && sanitizedPerspective.length === 0)\n ) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n const nextPerspective = Array.isArray(sanitizedPerspective)\n ? sanitizedPerspective.join(',')\n : sanitizedPerspective\n const jar = await cookies()\n if (\n nextPerspective === jar.get(perspectiveCookieName)?.value &&\n process.env.NODE_ENV !== 'production'\n ) {\n // oxlint-disable-next-line no-console\n console.debug('perspectiveChangeAction', 'Perspective is the same, skipping', nextPerspective)\n return\n }\n jar.set(perspectiveCookieName, nextPerspective, {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n })\n\n refresh()\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,wBAAwB,aAA+C;CAC3F,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KACE,CAAC,wBACA,MAAM,QAAQ,qBAAqB,IAAI,qBAAqB,WAAW,EAExE,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;CAG9D,MAAM,kBAAkB,MAAM,QAAQ,qBAAqB,GACvD,qBAAqB,KAAK,IAAI,GAC9B;CACJ,MAAM,MAAM,MAAM,SAAS;AAC3B,KACE,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,SACpD,QAAQ,IAAI,aAAa,cACzB;AAEA,UAAQ,MAAM,2BAA2B,qCAAqC,gBAAgB;AAC9F;;AAEF,KAAI,IAAI,uBAAuB,iBAAiB;EAC9C,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CAAC;AAEF,UAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
|
-
"version": "12.4.
|
|
3
|
+
"version": "12.4.1",
|
|
4
4
|
"description": "Sanity.io toolkit for Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"live",
|
|
@@ -47,9 +47,7 @@
|
|
|
47
47
|
"default": "./dist/live/conditions/default/index.js"
|
|
48
48
|
},
|
|
49
49
|
"./live/client-components": "./dist/live/client-components/index.js",
|
|
50
|
-
"./live/server-actions":
|
|
51
|
-
"default": "./dist/live/server-actions/index.default.js"
|
|
52
|
-
},
|
|
50
|
+
"./live/server-actions": "./dist/live/server-actions/index.js",
|
|
53
51
|
"./studio": "./dist/studio/index.js",
|
|
54
52
|
"./studio/client-component": "./dist/studio/client-component/index.js",
|
|
55
53
|
"./visual-editing": "./dist/visual-editing/index.js",
|
|
@@ -79,7 +77,7 @@
|
|
|
79
77
|
"@vitejs/plugin-react": "^6.0.1",
|
|
80
78
|
"@vitest/coverage-v8": "^4.1.5",
|
|
81
79
|
"js-yaml": "^4.1.1",
|
|
82
|
-
"next": "16.3.0-canary.
|
|
80
|
+
"next": "16.3.0-canary.10",
|
|
83
81
|
"publint": "^0.3.18",
|
|
84
82
|
"react": "^19.2.5",
|
|
85
83
|
"react-dom": "^19.2.5",
|
package/dist/defineLive.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/conditions/react-server/defineLive.tsx"],"mappings":";;AAoBA;;KAAY,sBAAA,sCAA4D,OAAA;EACtE,KAAA,EAAO,WAAA;EACP,MAAA,GAAS,WAAA,GAAc,OAAA,CAAQ,WAAA;;;;;;;EAO/B,IAAA;EACA,WAAA,GAAc,OAAA,CAAQ,iBAAA;EACtB,KAAA;EAWI;;;EAPJ,GAAA;;;;;;EAMA,UAAA;AAAA,MACI,OAAA;EACJ,IAAA,EAAM,YAAA,CAAa,WAAA;EACnB,SAAA,EAAW,gBAAA;EACX,IAAA;AAAA;;;;UAMe,sBAAA;;;;;;EAMf,cAAA;EANF;;;;;EAYE,cAAA;;;;;;EAMA,kBAAA;;;;;;;;EAQA,gBAAA;;;;;EAMA,OAAA;;;AAsCF;EAjCE,GAAA;;;;;;EAOA,UAAA;;;;;EAMA,OAAA,IAAW,KAAA;EAwDb;;;;;;EAhDE,QAAA,IAAY,KAAA,EAAO,eAAA,EAAiB,gBAAA;;;;;EAMpC,kBAAA,IAAsB,IAAA,EAAM,OAAA,OAAc,OAAA;AAAA;;;;UAM3B,uBAAA;;;;EAIf,MAAA,EAAQ,YAAA;;;;;EAKR,WAAA;;;;;EAKA,YAAA;;;;;EAKA,YAAA;;;;;IAKE,UAAA;EAAA;;;;;EAMF,KAAA;AAAA;;;;iBAMc,UAAA,CAAW,MAAA,EAAQ,uBAAA;;;;;EAKjC,WAAA,EAAa,sBAAA;;;;;EAKb,UAAA,EAAY,KAAA,CAAM,aAAA,CAAc,sBAAA;AAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.default.d.ts","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"mappings":";iBASsB,kBAAA,CAAmB,IAAA,EAAM,OAAA,KAAY,OAAA;AAAA,iBAwBrC,oBAAA,CAAqB,WAAA,EAAa,iBAAA,GAAoB,OAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.default.js","names":[],"sources":["../../../src/live/server-actions/index.default.ts"],"sourcesContent":["'use server'\n\nimport type {ClientPerspective, SyncTag} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {revalidateTag, updateTag} from 'next/cache'\nimport {cookies, draftMode} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\n\nexport async function revalidateSyncTags(tags: SyncTag[]): Promise<void> {\n const {isEnabled: isDraftMode} = await draftMode()\n\n if (!isDraftMode) {\n revalidateTag('sanity:fetch-sync-tags', 'max')\n }\n\n const logTags: string[] = []\n for (const _tag of tags) {\n const tag = `sanity:${_tag}`\n if (isDraftMode) {\n revalidateTag(tag, 'max')\n } else {\n updateTag(tag)\n }\n logTags.push(tag)\n }\n\n // oxlint-disable-next-line no-console\n console.log(\n `<SanityLive /> ${isDraftMode ? `revalidated tags: ${logTags.join(', ')} with cache profile \"max\" ` : `updated tags: ${logTags.join(', ')} and revalidated tag: \"sanity:fetch-sync-tags\" with cache profile \"max\"`}`,\n )\n}\n\nexport async function setPerspectiveCookie(perspective: ClientPerspective): Promise<void> {\n if (!(await draftMode()).isEnabled) {\n // throw new Error('Draft mode is not enabled, setting perspective cookie is not allowed')\n return\n }\n const sanitizedPerspective = sanitizePerspective(perspective, 'drafts')\n if (perspective !== sanitizedPerspective) {\n throw new Error(`Invalid perspective`, {cause: perspective})\n }\n\n ;(await cookies()).set(\n perspectiveCookieName,\n Array.isArray(sanitizedPerspective) ? sanitizedPerspective.join(',') : sanitizedPerspective,\n {\n httpOnly: true,\n path: '/',\n secure: true,\n sameSite: 'none',\n },\n )\n}\n"],"mappings":";;;;;AASA,eAAsB,mBAAmB,MAAgC;CACvE,MAAM,EAAC,WAAW,gBAAe,MAAM,WAAW;AAElD,KAAI,CAAC,YACH,eAAc,0BAA0B,MAAM;CAGhD,MAAM,UAAoB,EAAE;AAC5B,MAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,MAAM,UAAU;AACtB,MAAI,YACF,eAAc,KAAK,MAAM;MAEzB,WAAU,IAAI;AAEhB,UAAQ,KAAK,IAAI;;AAInB,SAAQ,IACN,kBAAkB,cAAc,qBAAqB,QAAQ,KAAK,KAAK,CAAC,8BAA8B,iBAAiB,QAAQ,KAAK,KAAK,CAAC,2EAC3I;;AAGH,eAAsB,qBAAqB,aAA+C;AACxF,KAAI,EAAE,MAAM,WAAW,EAAE,UAEvB;CAEF,MAAM,uBAAuB,oBAAoB,aAAa,SAAS;AACvE,KAAI,gBAAgB,qBAClB,OAAM,IAAI,MAAM,uBAAuB,EAAC,OAAO,aAAY,CAAC;AAG7D,EAAC,MAAM,SAAS,EAAE,IACjB,uBACA,MAAM,QAAQ,qBAAqB,GAAG,qBAAqB,KAAK,IAAI,GAAG,sBACvE;EACE,UAAU;EACV,MAAM;EACN,QAAQ;EACR,UAAU;EACX,CACF"}
|