next-sanity 11.7.0-canary.2 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +4 -2
  2. package/dist/NextStudio.js +2 -2
  3. package/dist/NextStudio.js.map +1 -1
  4. package/dist/PresentationComlink.js +2 -3
  5. package/dist/PresentationComlink.js.map +1 -1
  6. package/dist/PresentationComlink2.js +1 -2
  7. package/dist/PresentationComlink2.js.map +1 -1
  8. package/dist/SanityLiveStream.js +3 -4
  9. package/dist/SanityLiveStream.js.map +1 -1
  10. package/dist/VisualEditing.js +1 -1
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/defineLive.d.ts.map +1 -0
  13. package/dist/draft-mode/index.d.ts.map +1 -0
  14. package/dist/draft-mode/index.js +2 -2
  15. package/dist/experimental/client-components/live.d.ts.map +1 -0
  16. package/dist/experimental/client-components/live.js +5 -6
  17. package/dist/experimental/client-components/live.js.map +1 -1
  18. package/dist/experimental/live.d.ts.map +1 -0
  19. package/dist/experimental/live.js +3 -3
  20. package/dist/experimental/live.js.map +1 -1
  21. package/dist/hooks/index.d.ts +1 -1
  22. package/dist/hooks/index.d.ts.map +1 -0
  23. package/dist/hooks/index.js +1 -2
  24. package/dist/hooks/index.js.map +1 -1
  25. package/dist/image/index.d.ts.map +1 -0
  26. package/dist/image/index.js +2 -2
  27. package/dist/image/index.js.map +1 -1
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/isCorsOriginError.d.ts.map +1 -0
  31. package/dist/live/client-components/live/index.d.ts.map +1 -0
  32. package/dist/live/client-components/live/index.js +4 -5
  33. package/dist/live/client-components/live/index.js.map +1 -1
  34. package/dist/live/client-components/live-stream/index.d.ts.map +1 -0
  35. package/dist/live/server-actions/index.d.ts.map +1 -0
  36. package/dist/live/server-actions/index.js +1 -1
  37. package/dist/live.js +5 -5
  38. package/dist/live.server-only.d.ts.map +1 -0
  39. package/dist/studio/client-component/index.d.ts.map +1 -0
  40. package/dist/studio/client-component/index.js +1 -1
  41. package/dist/studio/index.d.ts.map +1 -0
  42. package/dist/studio/index.js +1 -1
  43. package/dist/visual-editing/client-component/index.d.ts.map +1 -0
  44. package/dist/visual-editing/client-component/index.js +1 -1
  45. package/dist/visual-editing/index.d.ts.map +1 -0
  46. package/dist/visual-editing/server-actions/index.d.ts.map +1 -0
  47. package/dist/webhook/index.d.ts.map +1 -0
  48. package/package.json +27 -68
  49. package/src/experimental/client-components/PresentationComlink.tsx +1 -2
  50. package/src/experimental/client-components/live.tsx +1 -2
  51. package/src/experimental/live.tsx +4 -2
  52. package/src/experimental/types.ts +10 -11
  53. package/src/live/client-components/live/PresentationComlink.tsx +1 -5
  54. package/src/live/client-components/live/SanityLive.tsx +11 -13
  55. package/src/live/client-components/live-stream/SanityLiveStream.tsx +5 -4
  56. package/src/live/hooks/usePresentationQuery.ts +1 -2
package/README.md CHANGED
@@ -634,7 +634,7 @@ The `token` passed to `defineLive` needs [Viewer rights](https://www.sanity.io/d
634
634
  The same token can be used as both `browserToken` and `serverToken`, as the `browserToken` is only shared with the browser when Draft Mode is enabled. Draft Mode can only be initiated by either Sanity's Presentation Tool or the Vercel Toolbar.
635
635
 
636
636
  > Good to know:
637
- > Enterprise plans allow the creation of custom roles with more resticted access rights than the `Viewer` role, enabling the use of a `browserToken` specifically for authenticating the Live Content API. We're working to extend this capability to all Sanity price plans.
637
+ > Enterprise plans allow the creation of custom roles with more restricted access rights than the `Viewer` role, enabling the use of a `browserToken` specifically for authenticating the Live Content API. We're working to extend this capability to all Sanity price plans.
638
638
 
639
639
  #### 2. Render `<SanityLive />` in the root `layout.tsx`
640
640
 
@@ -1153,8 +1153,9 @@ function StudioPage() {
1153
1153
  ## Migration guides
1154
1154
 
1155
1155
  > [!IMPORTANT]
1156
- > You're looking at the README for v11, the README for [v10 is available here](https://github.com/sanity-io/next-sanity/tree/v10?tab=readme-ov-file#next-sanity) as well as an [migration guide][migrate-v10-to-v11].
1156
+ > You're looking at the README for v12, the README for [v11 is available here](https://github.com/sanity-io/next-sanity/tree/v11?tab=readme-ov-file#next-sanity) as well as an [migration guide][migrate-v11-to-v12].
1157
1157
 
1158
+ - [From `v11` to `v12`][migrate-v11-to-v12]
1158
1159
  - [From `v10` to `v11`][migrate-v10-to-v11]
1159
1160
  - [From `v9` to `v10`][migrate-v9-to-v10]
1160
1161
  - [From `v8` to `v9`][migrate-v8-to-v9]
@@ -1186,6 +1187,7 @@ MIT-licensed. See [LICENSE][LICENSE].
1186
1187
  [migrate-v8-to-v9]: https://github.com/sanity-io/next-sanity/blob/main/packages/next-sanity/MIGRATE-v8-to-v9.md
1187
1188
  [migrate-v9-to-v10]: https://github.com/sanity-io/next-sanity/blob/main/packages/next-sanity/MIGRATE-v9-to-v10.md
1188
1189
  [migrate-v10-to-v11]: https://github.com/sanity-io/next-sanity/blob/main/packages/next-sanity/MIGRATE-v10-to-v11.md
1190
+ [migrate-v11-to-v12]: https://github.com/sanity-io/next-sanity/blob/main/packages/next-sanity/MIGRATE-v11-to-v12.md
1189
1191
  [next-cache]: https://nextjs.org/docs/app/building-your-application/caching
1190
1192
  [next-docs]: https://nextjs.org/docs
1191
1193
  [next-revalidate-docs]: https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnextrevalidate
@@ -1,6 +1,6 @@
1
1
  import { n as NextStudioLayout, t as NextStudioNoScript } from "./NextStudioNoScript.js";
2
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
2
  import { useMemo, useSyncExternalStore } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  import { Studio } from "sanity";
5
5
  import { createHashHistory } from "history";
6
6
  function createHashHistoryForStudio() {
@@ -44,7 +44,7 @@ function useIsMounted() {
44
44
  return useSyncExternalStore(emptySubscribe, () => true, () => false);
45
45
  }
46
46
  const emptySubscribe = () => () => {};
47
- function NextStudioComponent({ children, config, unstable__noScript = true, scheme, history,...props }) {
47
+ function NextStudioComponent({ children, config, unstable__noScript = true, scheme, history, ...props }) {
48
48
  const isMounted = useIsMounted();
49
49
  const unstableHistory = useMemo(() => {
50
50
  if (props.unstable_history && history) throw new Error("Cannot use both `unstable_history` and `history` props at the same time");
@@ -1 +1 @@
1
- {"version":3,"file":"NextStudio.js","names":[],"sources":["../src/studio/client-component/createHashHistoryForStudio.ts","../src/studio/client-component/useIsMounted.ts","../src/studio/client-component/NextStudio.tsx"],"sourcesContent":["import {createHashHistory, type History, type Listener} from 'history'\n\n/** @internal */\nexport function createHashHistoryForStudio(): History {\n const history = createHashHistory()\n return {\n get action() {\n return history.action\n },\n get location() {\n return history.location\n },\n get createHref() {\n return history.createHref\n },\n get push() {\n return history.push\n },\n get replace() {\n return history.replace\n },\n get go() {\n return history.go\n },\n get back() {\n return history.back\n },\n get forward() {\n return history.forward\n },\n get block() {\n return history.block\n },\n // Overriding listen to workaround a problem where native history provides history.listen(location => void), but the npm package is history.listen(({action, location}) => void)\n listen(listener: Listener) {\n // return history.listen(({ action, location }) => {\n return history.listen(({location}) => {\n // console.debug('history.listen', action, location)\n // @ts-expect-error -- working around a bug? in studio\n listener(location)\n })\n },\n }\n}\n","import {useSyncExternalStore} from 'react'\n\n/** @internal */\nexport function useIsMounted(): boolean {\n return useSyncExternalStore(\n emptySubscribe,\n () => true,\n () => false,\n )\n}\n// eslint-disable-next-line no-empty-function\nconst emptySubscribe = () => () => {}\n","import {useMemo} from 'react'\nimport {Studio, type StudioProps} from 'sanity'\n\nimport {NextStudioLayout} from '../NextStudioLayout'\nimport {NextStudioNoScript} from '../NextStudioNoScript'\nimport {createHashHistoryForStudio} from './createHashHistoryForStudio'\nimport {useIsMounted} from './useIsMounted'\n\n/** @public */\nexport interface NextStudioProps extends StudioProps {\n children?: React.ReactNode\n /**\n * Render the <noscript> tag\n * @defaultValue true\n * @alpha\n */\n unstable__noScript?: boolean\n /**\n * The 'hash' option is new feature that is not yet stable for production, but is available for testing and its API won't change in a breaking way.\n * If 'hash' doesn't work for you, or if you want to use a memory based history, you can use the `unstable_history` prop instead.\n * @alpha\n * @defaultValue 'browser'\n */\n history?: 'browser' | 'hash'\n}\n/**\n * Override how the Studio renders by passing children.\n * This is useful for advanced use cases where you're using StudioProvider and StudioLayout instead of Studio:\n * ```\n * import {StudioProvider, StudioLayout} from 'sanity'\n * import {NextStudio} from 'next-sanity/studio'\n * <NextStudio config={config}>\n * <StudioProvider config={config}>\n * <CustomComponentThatUsesContextFromStudioProvider />\n * <StudioLayout />\n * </StudioProvider>\n * </NextStudio>\n * ```\n * @public\n */\nexport default function NextStudioComponent({\n children,\n config,\n unstable__noScript = true,\n scheme,\n history,\n ...props\n}: NextStudioProps): React.JSX.Element {\n const isMounted = useIsMounted()\n const unstableHistory = useMemo<typeof props.unstable_history>(() => {\n if (props.unstable_history && history) {\n throw new Error('Cannot use both `unstable_history` and `history` props at the same time')\n }\n\n if (isMounted && history === 'hash') {\n return createHashHistoryForStudio()\n }\n return props.unstable_history\n }, [history, isMounted, props.unstable_history])\n\n return (\n <>\n {unstable__noScript && <NextStudioNoScript />}\n <NextStudioLayout>\n {history === 'hash' && !isMounted\n ? null\n : children || (\n <Studio\n config={config}\n scheme={scheme}\n unstable_globalStyles\n {...props}\n unstable_history={unstableHistory}\n />\n )}\n </NextStudioLayout>\n </>\n )\n}\n"],"mappings":";;;;;AAGA,SAAgB,6BAAsC;CACpD,MAAM,UAAU,mBAAmB;AACnC,QAAO;EACL,IAAI,SAAS;AACX,UAAO,QAAQ;;EAEjB,IAAI,WAAW;AACb,UAAO,QAAQ;;EAEjB,IAAI,aAAa;AACf,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,KAAK;AACP,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,QAAQ;AACV,UAAO,QAAQ;;EAGjB,OAAO,UAAoB;AAEzB,UAAO,QAAQ,QAAQ,EAAC,eAAc;AAGpC,aAAS,SAAS;KAClB;;EAEL;;ACvCH,SAAgB,eAAwB;AACtC,QAAO,qBACL,sBACM,YACA,MACP;;AAGH,MAAM,6BAA6B;AC6BnC,SAAwB,oBAAoB,EAC1C,UACA,QACA,qBAAqB,MACrB,QACA,QACA,GAAG,SACkC;CACrC,MAAM,YAAY,cAAc;CAChC,MAAM,kBAAkB,cAA6C;AACnE,MAAI,MAAM,oBAAoB,QAC5B,OAAM,IAAI,MAAM,0EAA0E;AAG5F,MAAI,aAAa,YAAY,OAC3B,QAAO,4BAA4B;AAErC,SAAO,MAAM;IACZ;EAAC;EAAS;EAAW,MAAM;EAAiB,CAAC;AAEhD,QACE,qBAAA,UAAA,EAAA,UAAA,CACG,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB,EAC7C,oBAAC,kBAAA,EAAA,UACE,YAAY,UAAU,CAAC,YACpB,OACA,YACE,oBAAC,QAAA;EACS;EACA;EACR,uBAAA;EACA,GAAI;EACJ,kBAAkB;GAClB,EAAA,CAES,CAAA,EAAA,CAClB"}
1
+ {"version":3,"file":"NextStudio.js","names":[],"sources":["../src/studio/client-component/createHashHistoryForStudio.ts","../src/studio/client-component/useIsMounted.ts","../src/studio/client-component/NextStudio.tsx"],"sourcesContent":["import {createHashHistory, type History, type Listener} from 'history'\n\n/** @internal */\nexport function createHashHistoryForStudio(): History {\n const history = createHashHistory()\n return {\n get action() {\n return history.action\n },\n get location() {\n return history.location\n },\n get createHref() {\n return history.createHref\n },\n get push() {\n return history.push\n },\n get replace() {\n return history.replace\n },\n get go() {\n return history.go\n },\n get back() {\n return history.back\n },\n get forward() {\n return history.forward\n },\n get block() {\n return history.block\n },\n // Overriding listen to workaround a problem where native history provides history.listen(location => void), but the npm package is history.listen(({action, location}) => void)\n listen(listener: Listener) {\n // return history.listen(({ action, location }) => {\n return history.listen(({location}) => {\n // console.debug('history.listen', action, location)\n // @ts-expect-error -- working around a bug? in studio\n listener(location)\n })\n },\n }\n}\n","import {useSyncExternalStore} from 'react'\n\n/** @internal */\nexport function useIsMounted(): boolean {\n return useSyncExternalStore(\n emptySubscribe,\n () => true,\n () => false,\n )\n}\n// eslint-disable-next-line no-empty-function\nconst emptySubscribe = () => () => {}\n","import {useMemo} from 'react'\nimport {Studio, type StudioProps} from 'sanity'\n\nimport {NextStudioLayout} from '../NextStudioLayout'\nimport {NextStudioNoScript} from '../NextStudioNoScript'\nimport {createHashHistoryForStudio} from './createHashHistoryForStudio'\nimport {useIsMounted} from './useIsMounted'\n\n/** @public */\nexport interface NextStudioProps extends StudioProps {\n children?: React.ReactNode\n /**\n * Render the <noscript> tag\n * @defaultValue true\n * @alpha\n */\n unstable__noScript?: boolean\n /**\n * The 'hash' option is new feature that is not yet stable for production, but is available for testing and its API won't change in a breaking way.\n * If 'hash' doesn't work for you, or if you want to use a memory based history, you can use the `unstable_history` prop instead.\n * @alpha\n * @defaultValue 'browser'\n */\n history?: 'browser' | 'hash'\n}\n/**\n * Override how the Studio renders by passing children.\n * This is useful for advanced use cases where you're using StudioProvider and StudioLayout instead of Studio:\n * ```\n * import {StudioProvider, StudioLayout} from 'sanity'\n * import {NextStudio} from 'next-sanity/studio'\n * <NextStudio config={config}>\n * <StudioProvider config={config}>\n * <CustomComponentThatUsesContextFromStudioProvider />\n * <StudioLayout />\n * </StudioProvider>\n * </NextStudio>\n * ```\n * @public\n */\nexport default function NextStudioComponent({\n children,\n config,\n unstable__noScript = true,\n scheme,\n history,\n ...props\n}: NextStudioProps): React.JSX.Element {\n const isMounted = useIsMounted()\n const unstableHistory = useMemo<typeof props.unstable_history>(() => {\n if (props.unstable_history && history) {\n throw new Error('Cannot use both `unstable_history` and `history` props at the same time')\n }\n\n if (isMounted && history === 'hash') {\n return createHashHistoryForStudio()\n }\n return props.unstable_history\n }, [history, isMounted, props.unstable_history])\n\n return (\n <>\n {unstable__noScript && <NextStudioNoScript />}\n <NextStudioLayout>\n {history === 'hash' && !isMounted\n ? null\n : children || (\n <Studio\n config={config}\n scheme={scheme}\n unstable_globalStyles\n {...props}\n unstable_history={unstableHistory}\n />\n )}\n </NextStudioLayout>\n </>\n )\n}\n"],"mappings":";;;;;AAGA,SAAgB,6BAAsC;CACpD,MAAM,UAAU,mBAAmB;AACnC,QAAO;EACL,IAAI,SAAS;AACX,UAAO,QAAQ;;EAEjB,IAAI,WAAW;AACb,UAAO,QAAQ;;EAEjB,IAAI,aAAa;AACf,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,KAAK;AACP,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,QAAQ;AACV,UAAO,QAAQ;;EAGjB,OAAO,UAAoB;AAEzB,UAAO,QAAQ,QAAQ,EAAC,eAAc;AAGpC,aAAS,SAAS;KAClB;;EAEL;;ACvCH,SAAgB,eAAwB;AACtC,QAAO,qBACL,sBACM,YACA,MACP;;AAGH,MAAM,6BAA6B;AC6BnC,SAAwB,oBAAoB,EAC1C,UACA,QACA,qBAAqB,MACrB,QACA,SACA,GAAG,SACkC;CACrC,MAAM,YAAY,cAAc;CAChC,MAAM,kBAAkB,cAA6C;AACnE,MAAI,MAAM,oBAAoB,QAC5B,OAAM,IAAI,MAAM,0EAA0E;AAG5F,MAAI,aAAa,YAAY,OAC3B,QAAO,4BAA4B;AAErC,SAAO,MAAM;IACZ;EAAC;EAAS;EAAW,MAAM;EAAiB,CAAC;AAEhD,QACE,qBAAA,UAAA,EAAA,UAAA,CACG,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB,EAC7C,oBAAC,kBAAA,EAAA,UACE,YAAY,UAAU,CAAC,YACpB,OACA,YACE,oBAAC,QAAA;EACS;EACA;EACR,uBAAA;EACA,GAAI;EACJ,kBAAkB;GAClB,EAAA,CAES,CAAA,EAAA,CAClB"}
@@ -1,10 +1,9 @@
1
- import { t as sanitizePerspective } from "./utils.js";
2
1
  import { f as setPerspective, l as setComlink, s as perspective, u as setComlinkClientConfig } from "./context.js";
2
+ import { t as sanitizePerspective } from "./utils.js";
3
3
  import { useRouter } from "next/navigation";
4
- import { startTransition, useEffect } from "react";
4
+ import { startTransition, useEffect, useEffectEvent } from "react";
5
5
  import { createNode, createNodeMachine } from "@sanity/comlink";
6
6
  import { createCompatibilityActors } from "@sanity/presentation-comlink";
7
- import { useEffectEvent } from "use-effect-event";
8
7
  import { setPerspectiveCookie } from "next-sanity/live/server-actions";
9
8
  function PresentationComlink(props) {
10
9
  const { projectId, dataset, draftModeEnabled } = props;
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink.js","names":["controller: AbortController | undefined"],"sources":["../src/experimental/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {\n setComlink,\n setComlinkClientConfig,\n setPerspective,\n perspective,\n} from '../../live/hooks/context'\nimport {sanitizePerspective} from '../../live/utils'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled} = 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 const nextPerspective = sanitizePerspective(_perspective, 'drafts')\n if (draftModeEnabled && perspective.toString() !== nextPerspective.toString()) {\n setPerspective(nextPerspective)\n startTransition(() =>\n setPerspectiveCookie(nextPerspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) =>\n console.error('Failed to set the preview perspective cookie', reason),\n ),\n )\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\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}\n"],"mappings":";;;;;;;;AAmBA,SAAwB,oBAAoB,OAIf;CAC3B,MAAM,EAAC,WAAW,SAAS,qBAAoB;CAC/C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,cAAiC,WAAwB;EACxD,MAAM,kBAAkB,oBAAoB,cAAc,SAAS;AACnE,MAAI,oBAAoB,YAAY,UAAU,KAAK,gBAAgB,UAAU,EAAE;AAC7E,kBAAe,gBAAgB;AAC/B,yBACE,qBAAqB,gBAAgB,CAClC,WAAW;AACV,QAAI,OAAO,QAAS;AACpB,WAAO,SAAS;KAChB,CACD,OAAO,WACN,QAAQ,MAAM,gDAAgD,OAAO,CACtE,CACJ;;GAGN;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAIA;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"}
1
+ {"version":3,"file":"PresentationComlink.js","names":["controller: AbortController | undefined"],"sources":["../src/experimental/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent} from 'react'\nimport {\n setComlink,\n setComlinkClientConfig,\n setPerspective,\n perspective,\n} from '../../live/hooks/context'\nimport {sanitizePerspective} from '../../live/utils'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled} = 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 const nextPerspective = sanitizePerspective(_perspective, 'drafts')\n if (draftModeEnabled && perspective.toString() !== nextPerspective.toString()) {\n setPerspective(nextPerspective)\n startTransition(() =>\n setPerspectiveCookie(nextPerspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) =>\n console.error('Failed to set the preview perspective cookie', reason),\n ),\n )\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\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}\n"],"mappings":";;;;;;;AAkBA,SAAwB,oBAAoB,OAIf;CAC3B,MAAM,EAAC,WAAW,SAAS,qBAAoB;CAC/C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,cAAiC,WAAwB;EACxD,MAAM,kBAAkB,oBAAoB,cAAc,SAAS;AACnE,MAAI,oBAAoB,YAAY,UAAU,KAAK,gBAAgB,UAAU,EAAE;AAC7E,kBAAe,gBAAgB;AAC/B,yBACE,qBAAqB,gBAAgB,CAClC,WAAW;AACV,QAAI,OAAO,QAAS;AACpB,WAAO,SAAS;KAChB,CACD,OAAO,WACN,QAAQ,MAAM,gDAAgD,OAAO,CACtE,CACJ;;GAGN;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAIA;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"}
@@ -1,9 +1,8 @@
1
1
  import { l as setComlink, u as setComlinkClientConfig } from "./context.js";
2
2
  import { useRouter } from "next/navigation";
3
- import { useEffect } from "react";
3
+ import { useEffect, useEffectEvent } from "react";
4
4
  import { createNode, createNodeMachine } from "@sanity/comlink";
5
5
  import { createCompatibilityActors } from "@sanity/presentation-comlink";
6
- import { useEffectEvent } from "use-effect-event";
7
6
  import { setPerspectiveCookie } from "next-sanity/live/server-actions";
8
7
  function PresentationComlink(props) {
9
8
  const { projectId, dataset, draftModeEnabled, draftModePerspective } = props;
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink2.js","names":["controller: AbortController | undefined"],"sources":["../src/live/client-components/live/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useRouter} from 'next/navigation'\nimport {\n useEffect,\n // useState\n} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {setComlink, setComlinkClientConfig} from '../../hooks/context'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n // handleDraftModeAction: (secret: string) => Promise<void | 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 // const [presentationComlink, setPresentationComlink] = useState<Node<\n // LoaderControllerMsg,\n // LoaderNodeMsg\n // > | null>(null)\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 // eslint-disable-next-line no-console\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n // const [status, setStatus] = useState('disconnected')\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 // comlink.onStatus((status) => {\n // setStatus(status)\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 // setPresentationComlink(comlink)\n setComlink(comlink)\n // eslint-disable-next-line no-console\n // console.log('setting comlink', comlink)\n return () => {\n // eslint-disable-next-line no-console\n // console.log('stopping comlink')\n stop()\n }\n }, [])\n\n // @TODO come back to this later\n // const handleEnableDraftMode = useEffectEvent(async (signal: AbortSignal) => {\n // if (signal.aborted) return\n // const {secret} = await (presentationComlink?.fetch(\n // {\n // type: 'loader/fetch-preview-url-secret' as const,\n // data: {projectId, dataset},\n // },\n // {signal},\n // ) || {secret: null})\n // if (signal.aborted) return\n // const error = await handleDraftModeAction(secret!)\n // // eslint-disable-next-line no-console\n // // @TODO call another server action here that can tell us if draft mode is actually enabled\n // if (error) {\n // // @TODO use sonnet or whatever to push a toast with the error\n // // eslint-disable-next-line no-console\n // console.error('Error enabling draft mode', error)\n // return\n // }\n // // console.log('Draft mode enabled?', {enabled})\n // if (signal.aborted) return\n // router.refresh()\n // })\n // const connected = status === 'connected'\n // useEffect(() => {\n // if (connected && !draftModeEnabled) {\n // const controller = new AbortController()\n // handleEnableDraftMode(controller.signal).catch((reason) => {\n // // eslint-disable-next-line no-console\n // console.error('Failed to enable draft mode', reason)\n // return handleEnableDraftMode(controller.signal)\n // })\n // return () => {\n // controller.abort()\n // }\n // }\n // return undefined\n // }, [connected, draftModeEnabled, handleEnableDraftMode])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;;AAoBA,SAAS,oBAAoB,OAMA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAO1B,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,CAED,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAGD,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAMD,IAAIA;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAE5B,aAAW,QAAQ;AAGnB,eAAa;AAGX,SAAM;;IAEP,EAAE,CAAC;AA0CN,QAAO;;AAET,oBAAoB,cAAc;AAElC,IAAA,8BAAe"}
1
+ {"version":3,"file":"PresentationComlink2.js","names":["controller: AbortController | undefined"],"sources":["../src/live/client-components/live/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useEffectEvent} from 'react'\nimport {setComlink, setComlinkClientConfig} from '../../hooks/context'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n // handleDraftModeAction: (secret: string) => Promise<void | 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 // const [presentationComlink, setPresentationComlink] = useState<Node<\n // LoaderControllerMsg,\n // LoaderNodeMsg\n // > | null>(null)\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 // eslint-disable-next-line no-console\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n // const [status, setStatus] = useState('disconnected')\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 // comlink.onStatus((status) => {\n // setStatus(status)\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 // setPresentationComlink(comlink)\n setComlink(comlink)\n // eslint-disable-next-line no-console\n // console.log('setting comlink', comlink)\n return () => {\n // eslint-disable-next-line no-console\n // console.log('stopping comlink')\n stop()\n }\n }, [])\n\n // @TODO come back to this later\n // const handleEnableDraftMode = useEffectEvent(async (signal: AbortSignal) => {\n // if (signal.aborted) return\n // const {secret} = await (presentationComlink?.fetch(\n // {\n // type: 'loader/fetch-preview-url-secret' as const,\n // data: {projectId, dataset},\n // },\n // {signal},\n // ) || {secret: null})\n // if (signal.aborted) return\n // const error = await handleDraftModeAction(secret!)\n // // eslint-disable-next-line no-console\n // // @TODO call another server action here that can tell us if draft mode is actually enabled\n // if (error) {\n // // @TODO use sonnet or whatever to push a toast with the error\n // // eslint-disable-next-line no-console\n // console.error('Error enabling draft mode', error)\n // return\n // }\n // // console.log('Draft mode enabled?', {enabled})\n // if (signal.aborted) return\n // router.refresh()\n // })\n // const connected = status === 'connected'\n // useEffect(() => {\n // if (connected && !draftModeEnabled) {\n // const controller = new AbortController()\n // handleEnableDraftMode(controller.signal).catch((reason) => {\n // // eslint-disable-next-line no-console\n // console.error('Failed to enable draft mode', reason)\n // return handleEnableDraftMode(controller.signal)\n // })\n // return () => {\n // controller.abort()\n // }\n // }\n // return undefined\n // }, [connected, draftModeEnabled, handleEnableDraftMode])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;AAgBA,SAAS,oBAAoB,OAMA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAO1B,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,CAED,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAGD,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAMD,IAAIA;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAE5B,aAAW,QAAQ;AAGnB,eAAa;AAGX,SAAM;;IAEP,EAAE,CAAC;AA0CN,QAAO;;AAET,oBAAoB,cAAc;AAElC,IAAA,8BAAe"}
@@ -1,10 +1,9 @@
1
1
  import { r as comlinkListeners, t as comlink } from "./context.js";
2
- import "@sanity/client";
2
+ import { use, useCallback, useEffect, useEffectEvent, useState, useSyncExternalStore } from "react";
3
3
  import { stegaEncodeSourceMap } from "@sanity/client/stega";
4
- import { Fragment, jsx } from "react/jsx-runtime";
5
- import { use, useCallback, useEffect, useState, useSyncExternalStore } from "react";
6
4
  import { dequal } from "dequal/lite";
7
- import { useEffectEvent } from "use-effect-event";
5
+ import { Fragment, jsx } from "react/jsx-runtime";
6
+ import "@sanity/client";
8
7
  const LISTEN_HEARTBEAT_INTERVAL = 1e4;
9
8
  function SanityLiveStream(props) {
10
9
  const { query, dataset, params = {}, perspective, projectId, stega } = props;
@@ -1 +1 @@
1
- {"version":3,"file":"SanityLiveStream.js","names":["comlink","comlinkSnapshot","children"],"sources":["../src/live/client-components/live-stream/SanityLiveStream.tsx"],"sourcesContent":["import {\n type ClientPerspective,\n type ContentSourceMap,\n type InitializedClientConfig,\n type QueryParams,\n} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {use, useCallback, useEffect, useState, useSyncExternalStore} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {comlinkListeners, comlink as comlinkSnapshot} from '../../hooks/context'\n\n/**\n * @public\n */\nexport interface SanityLiveStreamProps\n extends Pick<InitializedClientConfig, 'projectId' | 'dataset'> {\n query: string\n params?: QueryParams\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n initial: Promise<React.ReactNode>\n children: (result: {\n data: unknown\n sourceMap: ContentSourceMap | null\n tags: string[]\n }) => Promise<React.ReactNode>\n}\n\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * @public\n */\nexport default function SanityLiveStream(props: SanityLiveStreamProps): React.JSX.Element | null {\n const {query, dataset, params = {}, perspective, projectId, stega} = props\n\n const subscribe = useCallback((listener: () => void) => {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n }, [])\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n const [children, setChildren] = useState<React.ReactNode | undefined>(undefined)\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n comlink.post('loader/query-listen', {\n projectId: projectId!,\n dataset: dataset!,\n perspective: perspective! as ClientPerspective,\n query,\n params: params!,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n const {result, resultSourceMap, tags} = event\n const data = stega\n ? stegaEncodeSourceMap(result, resultSourceMap, {enabled: true, studioUrl: '/'})\n : result\n // eslint-disable-next-line no-console\n // console.log('server function streaming is disabled', {\n // startTransition,\n // setPromise,\n // data,\n // resultSourceMap,\n // tags,\n // })\n // console.log('rendering with server action')\n // startTransition(() =>\n // setPromise(\n // props.children({\n // data,\n // sourceMap: resultSourceMap!,\n // tags: tags || [],\n // }) as Promise<React.JSX.Element>,\n // ),\n // )\n // eslint-disable-next-line no-console\n console.groupCollapsed('rendering with server action')\n ;(\n props.children({\n data,\n sourceMap: resultSourceMap!,\n tags: tags || [],\n }) as Promise<React.JSX.Element>\n )\n .then(\n (children) => {\n // eslint-disable-next-line no-console\n console.log('setChildren(children)')\n // startTransition(() => setChildren(children))\n setChildren(children)\n },\n (reason: unknown) => {\n // eslint-disable-next-line no-console\n console.error('rendering with server action: render children error', reason)\n },\n )\n // eslint-disable-next-line no-console\n .finally(() => console.groupEnd())\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n if (!comlink ||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,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,KAAI,CAACA,aAAW,aAAa,KAAA,EAC3B,QAAO,IAAI,MAAM,QAAQ;AAG3B,QAAO,oBAAA,UAAA,EAAG,UAAA,CAAY"}
1
+ {"version":3,"file":"SanityLiveStream.js","names":["comlink","comlinkSnapshot","children"],"sources":["../src/live/client-components/live-stream/SanityLiveStream.tsx"],"sourcesContent":["import {\n type ClientPerspective,\n type ContentSourceMap,\n type InitializedClientConfig,\n type QueryParams,\n} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {use, useCallback, useEffect, useState, useSyncExternalStore, useEffectEvent} from 'react'\nimport {comlinkListeners, comlink as comlinkSnapshot} from '../../hooks/context'\n\n/**\n * @public\n */\nexport interface SanityLiveStreamProps extends Pick<\n InitializedClientConfig,\n 'projectId' | 'dataset'\n> {\n query: string\n params?: QueryParams\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n initial: Promise<React.ReactNode>\n children: (result: {\n data: unknown\n sourceMap: ContentSourceMap | null\n tags: string[]\n }) => Promise<React.ReactNode>\n}\n\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * @public\n */\nexport default function SanityLiveStream(props: SanityLiveStreamProps): React.JSX.Element | null {\n const {query, dataset, params = {}, perspective, projectId, stega} = props\n\n const subscribe = useCallback((listener: () => void) => {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n }, [])\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n const [children, setChildren] = useState<React.ReactNode | undefined>(undefined)\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n comlink.post('loader/query-listen', {\n projectId: projectId!,\n dataset: dataset!,\n perspective: perspective! as ClientPerspective,\n query,\n params: params!,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n const {result, resultSourceMap, tags} = event\n const data = stega\n ? stegaEncodeSourceMap(result, resultSourceMap, {enabled: true, studioUrl: '/'})\n : result\n // eslint-disable-next-line no-console\n // console.log('server function streaming is disabled', {\n // startTransition,\n // setPromise,\n // data,\n // resultSourceMap,\n // tags,\n // })\n // console.log('rendering with server action')\n // startTransition(() =>\n // setPromise(\n // props.children({\n // data,\n // sourceMap: resultSourceMap!,\n // tags: tags || [],\n // }) as Promise<React.JSX.Element>,\n // ),\n // )\n // eslint-disable-next-line no-console\n console.groupCollapsed('rendering with server action')\n ;(\n props.children({\n data,\n sourceMap: resultSourceMap!,\n tags: tags || [],\n }) as Promise<React.JSX.Element>\n )\n .then(\n (children) => {\n // eslint-disable-next-line no-console\n console.log('setChildren(children)')\n // startTransition(() => setChildren(children))\n setChildren(children)\n },\n (reason: unknown) => {\n // eslint-disable-next-line no-console\n console.error('rendering with server action: render children error', reason)\n },\n )\n // eslint-disable-next-line no-console\n .finally(() => console.groupEnd())\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n if (!comlink || children === undefined) {\n return use(props.initial) as React.JSX.Element\n }\n\n return <>{children}</>\n}\n"],"mappings":";;;;;;AA+BA,MAAM,4BAA4B;AAKlC,SAAwB,iBAAiB,OAAwD;CAC/F,MAAM,EAAC,OAAO,SAAS,SAAS,EAAE,EAAE,aAAa,WAAW,UAAS;CAOrE,MAAMA,YAAU,qBALE,aAAa,a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from "next/navigation";
3
2
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
3
  import { VisualEditing as VisualEditing$1 } from "@sanity/visual-editing/react";
4
+ import { jsx } from "react/jsx-runtime";
5
5
  import { revalidateRootLayout } from "next-sanity/visual-editing/server-actions";
6
6
  function pathHasPrefix(path, prefix) {
7
7
  if (typeof path !== "string") return false;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","names":[],"sources":["../src/experimental/constants.ts"],"sourcesContent":[],"mappings":";cAAa,yBAAA;AAAA,cACA,qBAAA,GADA,KAAA"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":";;;;;;AAkBA;AACS,KADG,sBAAA,GACH,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAAA;EACE,KAAA,EADF,WACE;EAAsB,MAAA,CAAA,EAAtB,WAAsB,GAAR,OAAQ,CAAA,WAAA,CAAA;EAAR;;;;;;EAoBnB,IAAA,CAAA,EAAA,MAAA,EAAA;EAAA,WAAA,CAAA,EAZU,OAYV,CAZkB,iBAYlB,EAAA,KAAA,CAAA;EASN,KAAY,CAAA,EAAA,OAAA;EACH;;;EACgB,GAAA,CAAA,EAAA,KAAA;EAQD;;;;;EAgBA,UAAM,CAAA,EAAA,MAAA;CAAd,EAAA,GAnCV,OAmCU,CAAA;EAAR,IAAA,EAlCA,YAkCA,CAlCa,WAkCb,CAAA;EAGF,SAAM,EApCC,gBAoCD,GAAA,IAAA;EAAA,IAAA,EAAA,MAAA,EAAA;AAKZ,CAAA,CAAA;;;;AA0D4C,KA5FhC,2BAAA,GA4FgC,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EAM5C,KAAiB,EAjGR,WAiGQ;EAuCjB,MAAgB,CAAA,EAvIL,WAuIK,GAvIS,OAuIT,CAvIiB,WAuIjB,CAAA;EAAmB;;;;;;;gBA/HnB,QAAQ;;;;;;;;;;;;;UAad,aAAa;eACR;;QAEP,QAAQ,QAAQ,KAAA,CAAM;MAGxB,KAAA,CAAM;;;;UAKK,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAoDI;;;;;8BAMS,cAAc;;;;;UAM3B,uBAAA;;;;UAIP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmCM,UAAA,SAAmB;;;;;eAKpB;;;;;cAKD,KAAA,CAAM,cAAc;;;;oBAId"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/draft-mode/define-enable-draft-mode.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;AAciB,UAdA,4BAAA,CAcA;EACA,MAAA,EAdP,YAcO;EAAoB;;;AAoBrC;;;;;;;;UArBiB,eAAA;iBACA,YAAY,QAAQ;;;;;;;;;;;;;;;;;;;iBAoBrB,qBAAA,UAA+B,+BAA+B"}
@@ -1,6 +1,6 @@
1
- import { cookies, draftMode } from "next/headers";
2
- import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
3
1
  import { validatePreviewUrl } from "@sanity/preview-url-secret";
2
+ import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
3
+ import { cookies, draftMode } from "next/headers";
4
4
  import { redirect } from "next/navigation";
5
5
  function defineEnableDraftMode(options) {
6
6
  const { client } = options;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live.d.ts","names":[],"sources":["../../../src/experimental/types.ts","../../../src/experimental/client-components/live.tsx"],"sourcesContent":[],"mappings":";;;;UAEiB,kBAAA,SAA2B,KAC1C;;;;AADF;;UCgCiB,eAAA;UACP;EADV,gBAAiB,EAAA,OAAA;EACP,cAAA,CAAA,EAAA,OAAA;EAYW,cAAA,CAAA,EAAA,OAAA;EAED,kBAAA,CAAA,EAAA,OAAA;EAAmC,UAAA,EAAA,MAAA,GAAA,SAAA;EAAwB;;;;EAE1C,OAAA,CAAA,EAAA,CAAA,KAAA,EAAA,OAAA,EAAA,GAAA,IAAA;kBAsCb,CAAA,EAAA,MAAA,GAAkB,KAAA;qBA1CrB;uCAED,mCAAmC,wBAAwB,gBACxE;qCAC8B,QAAQ;;;;;iBAsCrB,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
@@ -1,14 +1,13 @@
1
1
  "use client";
2
- import { t as isCorsOriginError } from "../../isCorsOriginError.js";
2
+ import { d as setEnvironment, f as setPerspective } from "../../context.js";
3
3
  import { t as sanitizePerspective } from "../../utils.js";
4
4
  import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
5
- import { d as setEnvironment, f as setPerspective } from "../../context.js";
6
- import { createClient } from "@sanity/client";
7
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { t as isCorsOriginError } from "../../isCorsOriginError.js";
8
6
  import { useRouter } from "next/navigation";
9
- import { useEffect, useMemo, useRef, useState } from "react";
7
+ import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
10
8
  import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
11
- import { useEffectEvent } from "use-effect-event";
9
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
+ import { createClient } from "@sanity/client";
12
11
  import dynamic from "next/dynamic";
13
12
  const PresentationComlink = dynamic(() => import("../../PresentationComlink.js"), { ssr: false });
14
13
  const RefreshOnMount = dynamic(() => import("../../RefreshOnMount.js"), { ssr: false });
@@ -1 +1 @@
1
- {"version":3,"file":"live.js","names":[],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {setEnvironment, setPerspective} from '../../live/hooks/context'\nimport {isCorsOriginError} from '../../isCorsOriginError'\nimport type {SanityClientConfig} from '../types'\nimport {sanitizePerspective} from '../../live/utils'\nimport {PUBLISHED_SYNC_TAG_PREFIX, type DRAFT_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\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: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\n}\n\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\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,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\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 [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(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 // eslint-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 setLongPollingInterval(false)\n } else if (event.type === 'message') {\n revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\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 // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAyBD,SAAS,YAAY,OAAgB;AAEnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAKxB,SAAS,eAAe,OAAwB,kBAAkC;AAEhF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAQL,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WA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,eAAW,OAAO;;KAGtB,EAAC,QAAQ,WAAW,QAAO,CAC5B;AACD,eAAa;AACX,gBAAa,QAAQ;AACrB,cAAW,OAAO;;IAEnB,EAAE,CAAC;CAMN,MAAM,0BAA0B,OAAkD,KAAA,EAAU;AAC5F,iBAAgB;AACd,MAAI,CAAC,iBAAkB;AACvB,eAAa,wBAAwB,QAAQ;AAC7C,eAAa;AACX,2BAAwB,UAAU,iBAAiB;AAEjD,YAAQ,KAAK,iEAAiE;KAC9E;;IAEH,CAAC,iBAAiB,CAAC;AAKtB,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
1
+ {"version":3,"file":"live.js","names":[],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\nimport {setEnvironment, setPerspective} from '../../live/hooks/context'\nimport {isCorsOriginError} from '../../isCorsOriginError'\nimport type {SanityClientConfig} from '../types'\nimport {sanitizePerspective} from '../../live/utils'\nimport {PUBLISHED_SYNC_TAG_PREFIX, type DRAFT_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\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: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\n}\n\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\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,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\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 [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(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 // eslint-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 setLongPollingInterval(false)\n } else if (event.type === 'message') {\n revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\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 // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAyBD,SAAS,YAAY,OAAgB;AAEnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAKxB,SAAS,eAAe,OAAwB,kBAAkC;AAEhF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAQL,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBACA,gCACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;E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;;;AAeP;AAoBgB,KA1GJ,sBAAA,GA0GI,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAzGL,kBAyGK,CAzGc,WAyGd,CAAA,EAAA,GAxGX,OAwGW,CAAA;EAAmB,IAAA,EAvG3B,YAuG2B,CAvGd,WAuGc,EAAA,OAAA,CAAA;EAIpB;;;;aAtGF;;;;;;;;;UAUI,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4CI;;;;;wCAQD,mCAAmC,wBAAwB,gBACxE;;;;sCAS+B,QAAQ;;;;;UAM7B,uBAAA;;;;UAIP;;;;;;;;;;;;;;;iBAgBM,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
@@ -1,14 +1,14 @@
1
1
  import { t as sanitizePerspective } from "../utils.js";
2
2
  import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../constants.js";
3
- import { stegaEncodeSourceMap } from "@sanity/client/stega";
4
- import { preconnect } from "react-dom";
5
- import { cookies, draftMode } from "next/headers";
6
3
  import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
4
+ import { cookies, draftMode } from "next/headers";
5
+ import { stegaEncodeSourceMap } from "@sanity/client/stega";
7
6
  import { jsx } from "react/jsx-runtime";
8
7
  import "server-only";
9
8
  import { createClient } from "next-sanity";
10
9
  import SanityLiveClientComponent from "next-sanity/experimental/client-components/live";
11
10
  import { cacheLife, cacheTag, updateTag } from "next/cache";
11
+ import { preconnect } from "react-dom";
12
12
  async function resolvePerspectiveFromCookies({ cookies: jar }) {
13
13
  return jar.has(perspectiveCookieName) ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, "drafts") : "drafts";
14
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"live.js","names":["SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps>","SanityLiveServerComponent","resolveDraftModePerspective"],"sources":["../../src/experimental/live.tsx"],"sourcesContent":["// oxlint-disable-next-line no-unassigned-import\nimport 'server-only'\nimport {\n createClient,\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from 'next-sanity'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport SanityLiveClientComponent, {\n type SanityLiveProps,\n} from 'next-sanity/experimental/client-components/live'\nimport {cacheTag, cacheLife, updateTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {preconnect} from 'react-dom'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {sanitizePerspective} from '../live/utils'\nimport type {SanityClientConfig} from './types'\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport async function resolvePerspectiveFromCookies({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n\nasync function sanityCachedFetch<const QueryString extends string>(\n config: SanityClientConfig,\n {\n query,\n params = {},\n perspective,\n stega,\n requestTag,\n draftToken,\n customCacheTags = [],\n }: {\n query: QueryString\n params?: QueryParams\n perspective: Exclude<ClientPerspective, 'raw'>\n stega: boolean\n requestTag: string\n draftToken?: string | false | undefined\n customCacheTags?: string[]\n },\n): Promise<{\n data: ClientReturn<QueryString, unknown>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}> {\n 'use cache: remote'\n\n const client = createClient({...config, useCdn: true})\n const useCdn = perspective === 'published'\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n resultSourceMap: stega ? 'withKeyArraySelector' : undefined, // @TODO allow passing csm for non-stega use\n stega: false,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? config.token : draftToken || config.token, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n /**\n * Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short\n */\n cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityFetchOptions<QueryString extends string> {\n query: QueryString\n params?: QueryParams\n /**\n * @defaultValue 'published'\n */\n perspective?: Exclude<ClientPerspective, 'raw'>\n /**\n * Enables stega encoding of the data, this is typically only used in draft mode in conjunction with `perspective: 'drafts'` and with `@sanity/visual-editing` setup.\n * @defaultValue `false`\n */\n stega?: boolean\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 /**\n * Custom cache tags that can be used with next's `revalidateTag` and `updateTag` functions for custom webhook on-demand revalidation.\n */\n tags?: string[]\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(\n options: SanityFetchOptions<QueryString>,\n) => Promise<{\n data: ClientReturn<QueryString, unknown>\n /**\n * The Content Source Map can be used for custom setups like `encodeSourceMap` for `data-sanity` attributes, or `stegaEncodeSourceMap` for stega encoding in your own way.\n * The Content Source Map is only fetched by default in draft mode, if `stega` is `true`. Otherwise your client configuration will need to have `resultSourceMap: 'withKeyArraySelector' | true`\n */\n sourceMap: ContentSourceMap | null\n /**\n * The cache tags used with `next/cache`, useful for debugging.\n */\n tags: string[]\n}>\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * @defaultValue `false`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * @defaultValue `false`\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * @defaultValue `false`\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 * 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 // @TODO remove, replace with onLiveEvent\n revalidateSyncTags?: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n\n // @TODO add\n // decide how to handle a live event coming in\n // onLiveEvent?: (event: LiveEvent, mode: 'production' | 'preview) => void\n\n /**\n * Control how the draft mode perspective is resolved, by default it resolves from the `sanity-preview-perspective` cookie.\n */\n resolveDraftModePerspective?: () => Promise<ClientPerspective>\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\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\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = 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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-console\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 {\n token: originalToken,\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n stega: stegaConfig,\n } = client.config()\n\n const sanityFetch: DefinedSanityFetchType = function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega = false,\n perspective = 'published',\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n requestTag?: string\n }) {\n return sanityCachedFetch(\n {\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n token: originalToken,\n },\n {\n query,\n params,\n perspective,\n stega,\n requestTag,\n draftToken: serverToken,\n customCacheTags,\n },\n ).then(({data, sourceMap, tags}) => ({\n data:\n stega && sourceMap\n ? stegaEncodeSourceMap(data, sourceMap, {...stegaConfig, enabled: true})\n : data,\n sourceMap,\n tags,\n }))\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = function SanityLive(props) {\n const {\n // perspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags = expireTags,\n } = props\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\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 preconnect(origin)\n\n return (\n <SanityLiveServerComponent\n config={{projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix}}\n requestTag={requestTag}\n browserToken={browserToken}\n // origin={origin}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={\n props.resolveDraftModePerspective ?? resolveDraftModePerspective\n }\n />\n )\n }\n\n return {sanityFetch, SanityLive}\n}\n\ninterface SanityLiveServerComponentProps\n extends Omit<SanityLiveProps, 'draftModeEnabled' | 'token' | 'draftModePerspective'> {\n browserToken: string | false | undefined\n // origin: string\n // perspective?: Exclude<ClientPerspective, 'raw'>\n}\n\nconst SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps> =\n async function SanityLiveServerComponent(props) {\n // 'use cache'\n // @TODO should this be 'max' instead?, or configured by changing the default cache profile?\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n const {\n config,\n requestTag,\n intervalOnGoAway,\n onError,\n onGoAway,\n refreshOnFocus,\n refreshOnMount,\n refreshOnReconnect,\n revalidateSyncTags,\n browserToken,\n // origin,\n // perspective,\n resolveDraftModePerspective,\n } = props\n\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 // preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n ...config,\n token: typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined,\n }}\n requestTag={requestTag}\n draftModeEnabled={isDraftModeEnabled}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n )\n }\n\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nasync function expireTags(_tags: unknown): Promise<void> {\n 'use server'\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n\nasync function resolveDraftModePerspective(): Promise<ClientPerspective> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookies({cookies: jar})\n }\n return 'published'\n}\n\n// revalidateSyncTags => actionUpdateTags\n// router.refresh() => actionRefresh\n"],"mappings":";;;;;;;;;;;AA2BA,eAAsB,8BAA8B,EAClD,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE;;AAGN,eAAe,kBACb,QACA,EACE,OACA,SAAS,EAAE,EACX,aACA,OACA,YACA,YACA,kBAAkB,EAAE,IAcrB;AACD;CAEA,MAAM,SAAS,aAAa;EAAC,GAAG;EAAQ,QAAQ;EAAK,CAAC;CACtD,MAAM,SAAS,gBAAgB;CAE/B,MAAM,EAAC,QAAQ,iBAAiB,aAAY,MAAM,OAAO,MAAM,OAAO,QAAQ;EAC5E,gBAAgB;EAChB,aAAa;EACb;EACA;EACA,iBAAiB,QAAQ,yBAAyB,KAAA;EAClD,OAAO;EACP,WAAW,SAAS,YAAY,KAAA;EAChC,KAAK;EACL,OAAO,gBAAgB,cAAc,OAAO,QAAQ,cAAc,OAAO;EAC1E,CAAC;CACF,MAAM,OAAO,CACX,GAAG,iBACH,IAAI,YAAY,EAAE,EAAE,KACjB,QACC,GAAG,gBAAgB,cAAc,4BAA4B,wBAAwB,MACxF,CACF;AAID,UAAS,GAAG,KAAK;AAIjB,WAAU,EA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AAI,MAAM,CAAC;AAGlD,cAAW,OAAO;AAElB,UACE,oBAAC,2BAAA;IACC,QAAQ;KAAC,WAAA;KAAW,SAAA;KAAS,SAAA;KAAS,YAAA;KAAY,oBAAA;KAAoB,kBAAA;KAAiB;IAC3E;IACE;IAEE;IACA;IACI;IACX;IACC;IACQ;IACE;IACpB,6BACE,MAAM,+BAA+B;KAEvC;;EAI0B;;AAUlC,MAAMA,4BACJ,eAAeC,4BAA0B,OAAO;CAQ9C,MAAM,EACJ,QACA,YACA,kBACA,SACA,UACA,gBACA,gBACA,oBACA,oBACA,cAGA,6BAAA,kCACE;CAEJ,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;AAKzD,QACE,oBAAC,2BAAA;EACC,QAAQ;GACN,GAAG;GACH,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;GAChF;EACW;EACZ,kBAAkB;EACF;EACA;EACI;EACX;EACC;EACQ;EACE;EACpB,6BAA6BC;GAC7B;;AAOR,eAAe,WAAW,OAA+B;AACvD;AAIA,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAEhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG;;AAGhE,eAAe,8BAA0D;AACvE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,8BAA8B,EAAC,SAD1B,MAAM,SAAS,EACwB,CAAC;AAEtD,QAAO"}
1
+ {"version":3,"file":"live.js","names":["SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps>","SanityLiveServerComponent","resolveDraftModePerspective"],"sources":["../../src/experimental/live.tsx"],"sourcesContent":["// oxlint-disable-next-line no-unassigned-import\nimport 'server-only'\nimport {\n createClient,\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from 'next-sanity'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport SanityLiveClientComponent, {\n type SanityLiveProps,\n} from 'next-sanity/experimental/client-components/live'\nimport {cacheTag, cacheLife, updateTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {preconnect} from 'react-dom'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {sanitizePerspective} from '../live/utils'\nimport type {SanityClientConfig} from './types'\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport async function resolvePerspectiveFromCookies({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n\nasync function sanityCachedFetch<const QueryString extends string>(\n config: SanityClientConfig,\n {\n query,\n params = {},\n perspective,\n stega,\n requestTag,\n draftToken,\n customCacheTags = [],\n }: {\n query: QueryString\n params?: QueryParams\n perspective: Exclude<ClientPerspective, 'raw'>\n stega: boolean\n requestTag: string\n draftToken?: string | false | undefined\n customCacheTags?: string[]\n },\n): Promise<{\n data: ClientReturn<QueryString, unknown>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}> {\n 'use cache: remote'\n\n const client = createClient({...config, useCdn: true})\n const useCdn = perspective === 'published'\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n resultSourceMap: stega ? 'withKeyArraySelector' : undefined, // @TODO allow passing csm for non-stega use\n stega: false,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? config.token : draftToken || config.token, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n /**\n * Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short\n */\n cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityFetchOptions<QueryString extends string> {\n query: QueryString\n params?: QueryParams\n /**\n * @defaultValue 'published'\n */\n perspective?: Exclude<ClientPerspective, 'raw'>\n /**\n * Enables stega encoding of the data, this is typically only used in draft mode in conjunction with `perspective: 'drafts'` and with `@sanity/visual-editing` setup.\n * @defaultValue `false`\n */\n stega?: boolean\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 /**\n * Custom cache tags that can be used with next's `revalidateTag` and `updateTag` functions for custom webhook on-demand revalidation.\n */\n tags?: string[]\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(\n options: SanityFetchOptions<QueryString>,\n) => Promise<{\n data: ClientReturn<QueryString, unknown>\n /**\n * The Content Source Map can be used for custom setups like `encodeSourceMap` for `data-sanity` attributes, or `stegaEncodeSourceMap` for stega encoding in your own way.\n * The Content Source Map is only fetched by default in draft mode, if `stega` is `true`. Otherwise your client configuration will need to have `resultSourceMap: 'withKeyArraySelector' | true`\n */\n sourceMap: ContentSourceMap | null\n /**\n * The cache tags used with `next/cache`, useful for debugging.\n */\n tags: string[]\n}>\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * @defaultValue `false`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * @defaultValue `false`\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * @defaultValue `false`\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 * 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 // @TODO remove, replace with onLiveEvent\n revalidateSyncTags?: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n\n // @TODO add\n // decide how to handle a live event coming in\n // onLiveEvent?: (event: LiveEvent, mode: 'production' | 'preview) => void\n\n /**\n * Control how the draft mode perspective is resolved, by default it resolves from the `sanity-preview-perspective` cookie.\n */\n resolveDraftModePerspective?: () => Promise<ClientPerspective>\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\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\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = 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 // eslint-disable-next-line no-console\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 // eslint-disable-next-line no-console\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 {\n token: originalToken,\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n stega: stegaConfig,\n } = client.config()\n\n const sanityFetch: DefinedSanityFetchType = function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega = false,\n perspective = 'published',\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n requestTag?: string\n }) {\n return sanityCachedFetch(\n {\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n token: originalToken,\n },\n {\n query,\n params,\n perspective,\n stega,\n requestTag,\n draftToken: serverToken,\n customCacheTags,\n },\n ).then(({data, sourceMap, tags}) => ({\n data:\n stega && sourceMap\n ? stegaEncodeSourceMap(data, sourceMap, {...stegaConfig, enabled: true})\n : data,\n sourceMap,\n tags,\n }))\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = function SanityLive(props) {\n const {\n // perspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags = expireTags,\n } = props\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\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 preconnect(origin)\n\n return (\n <SanityLiveServerComponent\n config={{projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix}}\n requestTag={requestTag}\n browserToken={browserToken}\n // origin={origin}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={\n props.resolveDraftModePerspective ?? resolveDraftModePerspective\n }\n />\n )\n }\n\n return {sanityFetch, SanityLive}\n}\n\ninterface SanityLiveServerComponentProps extends Omit<\n SanityLiveProps,\n 'draftModeEnabled' | 'token' | 'draftModePerspective'\n> {\n browserToken: string | false | undefined\n // origin: string\n // perspective?: Exclude<ClientPerspective, 'raw'>\n}\n\nconst SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps> =\n async function SanityLiveServerComponent(props) {\n // 'use cache'\n // @TODO should this be 'max' instead?, or configured by changing the default cache profile?\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n const {\n config,\n requestTag,\n intervalOnGoAway,\n onError,\n onGoAway,\n refreshOnFocus,\n refreshOnMount,\n refreshOnReconnect,\n revalidateSyncTags,\n browserToken,\n // origin,\n // perspective,\n resolveDraftModePerspective,\n } = props\n\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 // preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n ...config,\n token: typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined,\n }}\n requestTag={requestTag}\n draftModeEnabled={isDraftModeEnabled}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n )\n }\n\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nasync function expireTags(_tags: unknown): Promise<void> {\n 'use server'\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n\nasync function resolveDraftModePerspective(): Promise<ClientPerspective> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookies({cookies: jar})\n }\n return 'published'\n}\n\n// revalidateSyncTags => actionUpdateTags\n// router.refresh() => actionRefresh\n"],"mappings":";;;;;;;;;;;AA2BA,eAAsB,8BAA8B,EAClD,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE;;AAGN,eAAe,kBACb,QACA,EACE,OACA,SAAS,EAAE,EACX,aACA,OACA,YACA,YACA,kBAAkB,EAAE,IAcrB;AACD;CAEA,MAAM,SAAS,aAAa;EAAC,GAAG;EAAQ,QAAQ;EAAK,CAAC;CACtD,MAAM,SAAS,gBAAgB;CAE/B,MAAM,EAAC,QAAQ,iBAAiB,aAAY,MAAM,OAAO,MAAM,OAAO,QAAQ;EAC5E,gBAAgB;EAChB,aAAa;EACb;EACA;EACA,iBAAiB,QAAQ,yBAAyB,KAAA;EAClD,OAAO;EACP,WAAW,SAAS,YAAY,KAAA;EAChC,KAAK;EACL,OAAO,gBAAgB,cAAc,OAAO,QAAQ,cAAc,OAAO;EAC1E,CAAC;CACF,MAAM,OAAO,CACX,GAAG,iBACH,IAAI,YAAY,EAAE,EAAE,KACjB,QACC,GAAG,gBAAgB,cAAc,4BAA4B,wBAAwB,MACxF,CACF;AAID,UAAS,GAAG,K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,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAGlD,cAAW,OAAO;AAElB,UACE,oBAAC,2BAAA;IACC,QAAQ;KAAC,WAAA;KAAW,SAAA;KAAS,SAAA;KAAS,YAAA;KAAY,oBAAA;KAAoB,kBAAA;KAAiB;IAC3E;IACE;IAEE;IACA;IACI;IACX;IACC;IACQ;IACE;IACpB,6BACE,MAAM,+BAA+B;KAEvC;;EAI0B;;AAYlC,MAAMA,4BACJ,eAAeC,4BAA0B,OAAO;CAQ9C,MAAM,EACJ,QACA,YACA,kBACA,SACA,UACA,gBACA,gBACA,oBACA,oBACA,cAGA,6BAAA,kCACE;CAEJ,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;AAKzD,QACE,oBAAC,2BAAA;EACC,QAAQ;GACN,GAAG;GACH,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;GAChF;EACW;EACZ,kBAAkB;EACF;EACA;EACI;EACX;EACC;EACQ;EACE;EACpB,6BAA6BC;GAC7B;;AAOR,eAAe,WAAW,OAA+B;AACvD;AAIA,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAEhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG;;AAGhE,eAAe,8BAA0D;AACvE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,8BAA8B,EAAC,SAD1B,MAAM,SAAS,EACwB,CAAC;AAEtD,QAAO"}
@@ -1,7 +1,7 @@
1
- import { ClientPerspective, ClientPerspective as ClientPerspective$1, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
2
1
  import "@sanity/comlink";
3
2
  import "@sanity/presentation-comlink";
4
3
  import { useOptimistic } from "@sanity/visual-editing/react";
4
+ import { ClientPerspective, ClientPerspective as ClientPerspective$1, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
5
5
 
6
6
  //#region src/live/hooks/context.d.ts
7
7
 
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":["perspectiveListeners: Set<() => void>","perspective: DraftPerspective","environmentListeners: Set<() => void>","environment: DraftEnvironment","comlinkListeners: Set<() => void>","comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null","comlinkProjectId: string | null","comlinkDataset: string | null"],"sources":["../../src/live/hooks/context.ts","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAUA;AAmBA;;KAnBY,gBAAA,4BAA4C;AEExD;;;;ACKgB,KHYJ,gBAAA,GGZI,UAAA,GAAA,qBAAA,GAAA,qBAAA,GAAA,MAAA,GAAA,QAAA,GAAA,SAAA;;;;;;;;AHPhB;AAmBA;;;;ACTgB,iBAAA,uBAAA,CAAA,CAA2B,EAAA,gBAAA;AAmB3C;;;;AC3BA;;iBD2BgB,uBAAA,CAAA,GAA2B;;;;;;;;;AD7B3C;AAmBA;;;iBEjBgB,qBAAA,CAAA;;;;;;;;;AFFhB;AAmBA;;;;ACTA;AAmBA;;;iBEtBgB,gBAAA,CAAA;;;;KCHJ,mCAAA;;;;AJJZ,CAAA;AAmBA;KIRY;QACJ,aAAa;aACR;EHHb,WAAgB,EGID,mBHJC;AAmBhB,CAAA;KGZY,0DACR,sCACA,kCAAkC;;;AFjBtC;;;;ACKA;;iBCiEgB;SACP;EArET,MAAY,CAAA,EAsED,WAtEC,GAsEa,OAtEb,CAsEqB,WAtErB,CAAA;EAOZ,KAAY,CAAA,EAAA,OAAA;CACS,CAAA,EAgEjB,2BAhEiB,CAgEW,WAhEX,CAAA"}
@@ -1,9 +1,8 @@
1
1
  "use client";
2
2
  import { a as environment, c as perspectiveListeners, i as comlinkProjectId, n as comlinkDataset, o as environmentListeners, r as comlinkListeners, s as perspective, t as comlink } from "../context.js";
3
+ import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
3
4
  import { stegaEncodeSourceMap } from "@sanity/client/stega";
4
- import { useCallback, useEffect, useMemo, useReducer, useSyncExternalStore } from "react";
5
5
  import { dequal } from "dequal/lite";
6
- import { useEffectEvent } from "use-effect-event";
7
6
  import { useOptimistic } from "@sanity/visual-editing/react";
8
7
  function useDraftModeEnvironment() {
9
8
  return useSyncExternalStore(useCallback((listener) => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["environment","environment","initialState: UsePresentationQueryReturnsInactive","EMPTY_QUERY_PARAMS: QueryParams","comlink","comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {useCallback, useSyncExternalStore} from 'react'\nimport {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type DraftEnvironment,\n type DraftPerspective,\n} from './context'\n\n/**\n * Reports the current draft mode environment.\n * Use it to determine how to adapt the UI based on wether:\n * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.\n * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.\n * - Your app is live previewing drafts in a standalone context.\n * - Your app is previewing drafts, but not live.\n * - Your app is not previewing anything (that could be detected).\n * @public\n */\nexport function useDraftModeEnvironment(): DraftEnvironment {\n const subscribe = useCallback((listener: () => void) => {\n environmentListeners.add(listener)\n return () => environmentListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => environment,\n () => 'checking',\n )\n}\n\n/**\n * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.\n * If the hook is used outside Draft Mode it will resolve to `'unknown'`.\n * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.\n * @public\n */\nexport function useDraftModePerspective(): DraftPerspective {\n const subscribe = useCallback((listener: () => void) => {\n perspectiveListeners.add(listener)\n return () => perspectiveListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => perspective,\n () => 'checking',\n )\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' || environment === 'presentation-window'\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' ||\n environment === 'presentation-window' ||\n environment === 'live'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from './context'\nimport {useDraftModePerspective} from './useDraftMode'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? (state.sourceMap as ContentSourceMap | null)\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useDraftModePerspective()\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n // eslint-disable-next-line no-console\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === 'checking' || perspective === 'unknown') {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,0BAA4C;AAM1D,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;AASH,SAAgB,0BAA4C;AAM1D,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;ACrCH,SAAgB,wBAAwC;CACtD,MAAMA,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBAAyBA,kBAAgB;;ACC/D,SAAgB,mBAAmC;CACjD,MAAMC,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBACdA,kBAAgB,yBAChBA,kBAAgB;;ACcxB,SAAS,QACP,OACA,EAAC,MAAM,WACmC;AAC1C,SAAQ,MAAR;EACE,KAAK,eACH,QAAO,OAAO,OAAO,QAAQ,GACz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,mBAAmB;IACpC,aAAa,MAAM;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
1
+ {"version":3,"file":"index.js","names":["environment","environment","initialState: UsePresentationQueryReturnsInactive","EMPTY_QUERY_PARAMS: QueryParams","comlink","comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {useCallback, useSyncExternalStore} from 'react'\nimport {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type DraftEnvironment,\n type DraftPerspective,\n} from './context'\n\n/**\n * Reports the current draft mode environment.\n * Use it to determine how to adapt the UI based on wether:\n * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.\n * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.\n * - Your app is live previewing drafts in a standalone context.\n * - Your app is previewing drafts, but not live.\n * - Your app is not previewing anything (that could be detected).\n * @public\n */\nexport function useDraftModeEnvironment(): DraftEnvironment {\n const subscribe = useCallback((listener: () => void) => {\n environmentListeners.add(listener)\n return () => environmentListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => environment,\n () => 'checking',\n )\n}\n\n/**\n * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.\n * If the hook is used outside Draft Mode it will resolve to `'unknown'`.\n * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.\n * @public\n */\nexport function useDraftModePerspective(): DraftPerspective {\n const subscribe = useCallback((listener: () => void) => {\n perspectiveListeners.add(listener)\n return () => perspectiveListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => perspective,\n () => 'checking',\n )\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' || environment === 'presentation-window'\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' ||\n environment === 'presentation-window' ||\n environment === 'live'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from './context'\nimport {useDraftModePerspective} from './useDraftMode'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? (state.sourceMap as ContentSourceMap | null)\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useDraftModePerspective()\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n // eslint-disable-next-line no-console\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === 'checking' || perspective === 'unknown') {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,0BAA4C;AAM1D,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;AASH,SAAgB,0BAA4C;AAM1D,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;ACrCH,SAAgB,wBAAwC;CACtD,MAAMA,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBAAyBA,kBAAgB;;ACC/D,SAAgB,mBAAmC;CACjD,MAAMC,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBACdA,kBAAgB,yBAChBA,kBAAgB;;ACaxB,SAAS,QACP,OACA,EAAC,MAAM,WACmC;AAC1C,SAAQ,MAAR;EACE,KAAK,eACH,QAAO,OAAO,OAAO,QAAQ,GACzB,QACA;GACE,GAAG;GACH,MA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M;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":["imageLoader: ImageLoader"],"sources":["../../src/image/Image.tsx","../../src/image/imageLoader.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAcgB,UAdC,UAAA,SAAmB,IAcM,CAdD,YAcW,EAAA,QAAA,GAAA,KAAA,CAAA,CAAA;;;;EChBpD,MAAaA,CAAAA,EAAAA,KAAAA;;;;;;;;;iBDgBG,KAAA,QAAa,aAAa,KAAA,CAAM,GAAA,CAAI;;;;;AAdpD;AAcgB,cChBHA,WDgBgB,EChBH,WDgBsB"}
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { jsx } from "react/jsx-runtime";
3
2
  import NextImage from "next/image";
3
+ import { jsx } from "react/jsx-runtime";
4
4
  const imageLoader = ({ src, width, quality }) => {
5
5
  const url = new URL(src);
6
6
  url.searchParams.set("auto", "format");
@@ -15,7 +15,7 @@ const imageLoader = ({ src, width, quality }) => {
15
15
  return url.href;
16
16
  };
17
17
  function Image(props) {
18
- const { loader, src,...rest } = props;
18
+ const { loader, src, ...rest } = props;
19
19
  if (loader) throw new TypeError("The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.");
20
20
  let srcUrl;
21
21
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["imageLoader: ImageLoader","srcUrl: URL"],"sources":["../../src/image/imageLoader.ts","../../src/image/Image.tsx"],"sourcesContent":["import type {ImageLoader} from 'next/image'\n\n/**\n * @alpha\n */\nexport const imageLoader: ImageLoader = ({src, width, quality}) => {\n const url = new URL(src)\n url.searchParams.set('auto', 'format')\n if (!url.searchParams.has('fit')) {\n url.searchParams.set('fit', url.searchParams.has('h') ? 'min' : 'max')\n }\n if (url.searchParams.has('h') && url.searchParams.has('w')) {\n const originalHeight = parseInt(url.searchParams.get('h')!, 10)\n const originalWidth = parseInt(url.searchParams.get('w')!, 10)\n url.searchParams.set('h', Math.round((originalHeight / originalWidth) * width).toString())\n }\n url.searchParams.set('w', width.toString())\n if (quality) {\n url.searchParams.set('q', quality.toString())\n }\n return url.href\n}\n","import NextImage, {type ImageProps as NextImageProps} from 'next/image'\n\nimport {imageLoader} from './imageLoader'\n\n/**\n * @alpha\n */\nexport interface ImageProps extends Omit<NextImageProps, 'loader' | 'src'> {\n /**\n * The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.\n */\n loader?: never\n /**\n * Must be a string that is a valid URL to an image on the Sanity Image CDN.\n */\n src: string\n}\n\n/**\n * @alpha\n */\nexport function Image(props: ImageProps): React.JSX.Element {\n const {loader, src, ...rest} = props\n if (loader) {\n throw new TypeError(\n 'The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.',\n )\n }\n let srcUrl: URL\n try {\n srcUrl = new URL(src)\n if (props.height) {\n srcUrl.searchParams.set('h', `${props.height}`)\n }\n if (props.width) {\n srcUrl.searchParams.set('w', `${props.width}`)\n }\n } catch (err) {\n throw new TypeError('The `src` prop must be a valid URL to an image on the Sanity Image CDN.', {\n cause: err,\n })\n }\n return <NextImage {...rest} src={srcUrl.toString()} loader={imageLoader} />\n}\n"],"mappings":";;;AAKA,MAAaA,eAA4B,EAAC,KAAK,OAAO,cAAa;CACjE,MAAM,MAAM,IAAI,IAAI,IAAI;AACxB,KAAI,aAAa,IAAI,QAAQ,SAAS;AACtC,KAAI,CAAC,IAAI,aAAa,IAAI,MAAM,CAC9B,KAAI,aAAa,IAAI,OAAO,IAAI,aAAa,IAAI,IAAI,GAAG,QAAQ,MAAM;AAExE,KAAI,IAAI,aAAa,IAAI,IAAI,IAAI,IAAI,aAAa,IAAI,IAAI,EAAE;EAC1D,MAAM,iBAAiB,SAAS,IAAI,aAAa,IAAI,IAAI,EAAG,GAAG;EAC/D,MAAM,gBAAgB,SAAS,IAAI,aAAa,IAAI,IAAI,EAAG,GAAG;AAC9D,MAAI,aAAa,IAAI,KAAK,KAAK,MAAO,iBAAiB,gBAAiB,MAAM,CAAC,UAAU,CAAC;;AAE5F,KAAI,aAAa,IAAI,KAAK,MAAM,UAAU,CAAC;AAC3C,KAAI,QACF,KAAI,aAAa,IAAI,KAAK,QAAQ,UAAU,CAAC;AAE/C,QAAO,IAAI;;ACCb,SAAgB,MAAM,OAAsC;CAC1D,MAAM,EAAC,QAAQ,IAAK,GAAG,SAAQ;AAC/B,KAAI,OACF,OAAM,IAAI,UACR,8GACD;CAEH,IAAIC;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,IAAI;AACrB,MAAI,MAAM,OACR,QAAO,aAAa,IAAI,KAAK,GAAG,MAAM,SAAS;AAEjD,MAAI,MAAM,MACR,QAAO,aAAa,IAAI,KAAK,GAAG,MAAM,QAAQ;UAEzC,KAAK;AACZ,QAAM,IAAI,UAAU,2EAA2E,EAC7F,OAAO,KACR,CAAC;;AAEJ,QAAO,oBAAC,WAAA;EAAU,GAAI;EAAM,KAAK,OAAO,UAAU;EAAE,QAAQ;GAAe"}
1
+ {"version":3,"file":"index.js","names":["imageLoader: ImageLoader","srcUrl: URL"],"sources":["../../src/image/imageLoader.ts","../../src/image/Image.tsx"],"sourcesContent":["import type {ImageLoader} from 'next/image'\n\n/**\n * @alpha\n */\nexport const imageLoader: ImageLoader = ({src, width, quality}) => {\n const url = new URL(src)\n url.searchParams.set('auto', 'format')\n if (!url.searchParams.has('fit')) {\n url.searchParams.set('fit', url.searchParams.has('h') ? 'min' : 'max')\n }\n if (url.searchParams.has('h') && url.searchParams.has('w')) {\n const originalHeight = parseInt(url.searchParams.get('h')!, 10)\n const originalWidth = parseInt(url.searchParams.get('w')!, 10)\n url.searchParams.set('h', Math.round((originalHeight / originalWidth) * width).toString())\n }\n url.searchParams.set('w', width.toString())\n if (quality) {\n url.searchParams.set('q', quality.toString())\n }\n return url.href\n}\n","import NextImage, {type ImageProps as NextImageProps} from 'next/image'\n\nimport {imageLoader} from './imageLoader'\n\n/**\n * @alpha\n */\nexport interface ImageProps extends Omit<NextImageProps, 'loader' | 'src'> {\n /**\n * The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.\n */\n loader?: never\n /**\n * Must be a string that is a valid URL to an image on the Sanity Image CDN.\n */\n src: string\n}\n\n/**\n * @alpha\n */\nexport function Image(props: ImageProps): React.JSX.Element {\n const {loader, src, ...rest} = props\n if (loader) {\n throw new TypeError(\n 'The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.',\n )\n }\n let srcUrl: URL\n try {\n srcUrl = new URL(src)\n if (props.height) {\n srcUrl.searchParams.set('h', `${props.height}`)\n }\n if (props.width) {\n srcUrl.searchParams.set('w', `${props.width}`)\n }\n } catch (err) {\n throw new TypeError('The `src` prop must be a valid URL to an image on the Sanity Image CDN.', {\n cause: err,\n })\n }\n return <NextImage {...rest} src={srcUrl.toString()} loader={imageLoader} />\n}\n"],"mappings":";;;AAKA,MAAaA,eAA4B,EAAC,KAAK,OAAO,cAAa;CACjE,MAAM,MAAM,IAAI,IAAI,IAAI;AACxB,KAAI,aAAa,IAAI,QAAQ,SAAS;AACtC,KAAI,CAAC,IAAI,aAAa,IAAI,MAAM,CAC9B,KAAI,aAAa,IAAI,OAAO,IAAI,aAAa,IAAI,IAAI,GAAG,QAAQ,MAAM;AAExE,KAAI,IAAI,aAAa,IAAI,IAAI,IAAI,IAAI,aAAa,IAAI,IAAI,EAAE;EAC1D,MAAM,iBAAiB,SAAS,IAAI,aAAa,IAAI,IAAI,EAAG,GAAG;EAC/D,MAAM,gBAAgB,SAAS,IAAI,aAAa,IAAI,IAAI,EAAG,GAAG;AAC9D,MAAI,aAAa,IAAI,KAAK,KAAK,MAAO,iBAAiB,gBAAiB,MAAM,CAAC,UAAU,CAAC;;AAE5F,KAAI,aAAa,IAAI,KAAK,MAAM,UAAU,CAAC;AAC3C,KAAI,QACF,KAAI,aAAa,IAAI,KAAK,QAAQ,UAAU,CAAC;AAE/C,QAAO,IAAI;;ACCb,SAAgB,MAAM,OAAsC;CAC1D,MAAM,EAAC,QAAQ,KAAK,GAAG,SAAQ;AAC/B,KAAI,OACF,OAAM,IAAI,UACR,8GACD;CAEH,IAAIC;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,IAAI;AACrB,MAAI,MAAM,OACR,QAAO,aAAa,IAAI,KAAK,GAAG,MAAM,SAAS;AAEjD,MAAI,MAAM,MACR,QAAO,aAAa,IAAI,KAAK,GAAG,MAAM,QAAQ;UAEzC,KAAK;AACZ,QAAM,IAAI,UAAU,2EAA2E,EAC7F,OAAO,KACR,CAAC;;AAEJ,QAAO,oBAAC,WAAA;EAAU,GAAI;EAAM,KAAK,OAAO,UAAU;EAAE,QAAQ;GAAe"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
3
2
  import { stegaClean } from "@sanity/client/stega";
3
+ import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
4
4
  import { CreateDataAttribute, CreateDataAttributeProps, createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
5
5
  import groq, { defineQuery } from "groq";
6
6
  export * from "@sanity/client";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
- import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
3
2
  import { stegaClean } from "@sanity/client/stega";
3
+ import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
4
4
  import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
5
5
  import groq, { defineQuery } from "groq";
6
6
  export * from "@portabletext/react";
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/isCorsOriginError.ts"],"sourcesContent":[],"mappings":";;;;iBAGgB,iBAAA,2BAA4C"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/client-components/live/SanityLive.tsx"],"sourcesContent":[],"mappings":";;;;;;AAwBA;AACE,UADe,eAAA,SAAwB,IACvC,CAAA,uBAAA,EAAA,WAAA,GAAA,SAAA,GAAA,SAAA,GAAA,YAAA,GAAA,oBAAA,GAAA,OAAA,GAAA,kBAAA,CAAA,CAAA;EAWuB,gBAAA,EAAA,OAAA;EAWJ,oBAAA,CAAA,EAXI,iBAWJ;EACS,cAAA,CAAA,EAAA,OAAA;EAAc,cAAA,CAAA,EAAA,OAAA;EAxBH,kBAAA,CAAA,EAAA,OAAA;EAAA,UAAA,EAAA,MAAA,GAAA,SAAA;EA8DzC;;;;;;qBAvCqB;8BACS,cAAc;;;;;iBAsC5B,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
@@ -1,12 +1,11 @@
1
1
  "use client";
2
- import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
3
2
  import { d as setEnvironment, f as setPerspective } from "../../../context.js";
4
- import { createClient } from "@sanity/client";
5
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
6
4
  import { useRouter } from "next/navigation";
7
- import { useEffect, useMemo, useRef, useState } from "react";
5
+ import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
8
6
  import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
9
- import { useEffectEvent } from "use-effect-event";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ import { createClient } from "@sanity/client";
10
9
  import dynamic from "next/dynamic";
11
10
  import { revalidateSyncTags } from "next-sanity/live/server-actions";
12
11
  const PresentationComlink = dynamic(() => import("../../../PresentationComlink2.js"), { ssr: false });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["defaultRevalidateSyncTags"],"sources":["../../../../src/live/client-components/live/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 {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState} from 'react'\nimport {useEffectEvent} from 'use-effect-event'\nimport {setEnvironment, setPerspective} from '../../hooks/context'\nimport {isCorsOriginError} from '../../../isCorsOriginError'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'), {ssr: false})\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'), {ssr: false})\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'), {ssr: false})\n\n/**\n * @public\n */\nexport interface SanityLiveProps\n 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\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\n/**\n * @public\n */\nexport function 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 } = 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 [longPollingInterval, setLongPollingInterval] = 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 // eslint-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 setLongPollingInterval(false)\n } else if (event.type === 'message') {\n revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n useEffect(() => {\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).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])\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 // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\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 {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\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ACpB,eAAW,OAAO;;KAGtB,EAAC,QAAQ,WAAW,QAAO,CAC5B;AACD,eAAa;AACX,gBAAa,QAAQ;AACrB,cAAW,OAAO;;IAEnB,EAAE,CAAC;CAMN,MAAM,0BAA0B,OAAkD,KAAA,EAAU;AAC5F,iBAAgB;AACd,MAAI,CAAC,iBAAkB;AACvB,eAAa,wBAAwB,QAAQ;AAC7C,eAAa;AACX,2BAAwB,UAAU,iBAAiB;AAEjD,YAAQ,KAAK,iEAAiE;KAC9E;;IAEH,CAAC,iBAAiB,CAAC;AAKtB,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eACnB,oBAAC,qBAAA;GACY;GACF;GAES;GACI;IACtB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
1
+ {"version":3,"file":"index.js","names":["defaultRevalidateSyncTags"],"sources":["../../../../src/live/client-components/live/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 {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/server-actions'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\nimport {setEnvironment, setPerspective} from '../../hooks/context'\nimport {isCorsOriginError} from '../../../isCorsOriginError'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'), {ssr: false})\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'), {ssr: false})\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'), {ssr: false})\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\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\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 /* eslint-enable no-console */\n}\n\n/**\n * @public\n */\nexport function 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 } = 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 [longPollingInterval, setLongPollingInterval] = 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 // eslint-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 setLongPollingInterval(false)\n } else if (event.type === 'message') {\n revalidateSyncTags(event.tags).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n useEffect(() => {\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).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])\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 // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\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 {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;AAgBA,MAAM,sBAAsB,cAAc,OAAO,qCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,+BAAqB,EAAC,KAAK,OAAM,CAAC;AAC9E,MAAM,iBAAiB,cAAc,OAAO,+BAAqB,EAAC,KAAK,OAAM,CAAC;AAC9E,MAAM,qBAAqB,cAAc,OAAO,mCAAyB,EAAC,KAAK,OAAM,CAAC;AAgCtF,SAAS,YAAY,OAAgB;AAEnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAKxB,SAAS,eAAe,OAAwB,kBAAkC;AAEhF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAQL,SAAgB,WAAW,OAAkD;CAC3E,MAAM,EACJ,WACA,SACA,SACA,YACA,oBACA,OACA,kBAEA,k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AAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/client-components/live-stream/SanityLiveStream.tsx","../../../../src/live/client-components/live-stream/SanityLiveStreamLazy.tsx"],"sourcesContent":[],"mappings":";;;;;;AAeA;AACE,UADe,qBAAA,SAA8B,IAC7C,CAAA,uBAAA,EAAA,WAAA,GAAA,SAAA,CAAA,CAAA;EAIS,KAAA,EAAA,MAAA;EACa,MAAA,CAAA,EADb,WACa;EAAR,WAAA,CAAA,EAAA,OAAA,CAAQ,iBAAR,EAAA,KAAA,CAAA;EAEG,KAAA,CAAM,EAAA,OAAA;EAAd,OAAA,EAAA,OAAA,CAAQ,KAAA,CAAM,SAAd,CAAA;EAGI,QAAA,EAAA,CAAA,MAAA,EAAA;IAEC,IAAA,EAAM,OAAA;IAAd,SAAA,EAFO,gBAEP,GAAA,IAAA;IAbuC,IAAA,EAAA,MAAA,EAAA;EAAA,CAAA,EAAA,GAavC,OAbuC,CAa/B,KAAA,CAAM,SAbyB,CAAA;;;;iBCJ/B,mCAAA,QAA2C,wBAAwB,KAAA,CAAM"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/server-actions/index.ts"],"sourcesContent":[],"mappings":";;;iBAQsB,kBAAA,OAAyB,YAAY;iBAUrC,oBAAA,cAAkC,oBAAoB"}
@@ -1,7 +1,7 @@
1
1
  "use server";
2
2
  import { t as sanitizePerspective } from "../../utils.js";
3
- import { cookies, draftMode } from "next/headers";
4
3
  import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
4
+ import { cookies, draftMode } from "next/headers";
5
5
  import { revalidateTag } from "next/cache";
6
6
  async function revalidateSyncTags(tags) {
7
7
  await revalidateTag("sanity:fetch-sync-tags", "max");
package/dist/live.js CHANGED
@@ -1,12 +1,12 @@
1
- import { t as isCorsOriginError } from "./isCorsOriginError.js";
2
1
  import { t as sanitizePerspective } from "./utils.js";
3
- import "@sanity/client";
2
+ import { t as isCorsOriginError } from "./isCorsOriginError.js";
3
+ import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
4
+ import { cookies, draftMode } from "next/headers";
5
+ import { jsx } from "react/jsx-runtime";
4
6
  import { preconnect, prefetchDNS } from "react-dom";
7
+ import "@sanity/client";
5
8
  import SanityLiveClientComponent from "next-sanity/live/client-components/live";
6
9
  import SanityLiveStreamClientComponent from "next-sanity/live/client-components/live-stream";
7
- import { cookies, draftMode } from "next/headers";
8
- import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
9
- import { jsx } from "react/jsx-runtime";
10
10
  async function resolveCookiePerspective() {
11
11
  return (await draftMode()).isEnabled ? (await cookies()).has(perspectiveCookieName) ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, "drafts") : "drafts" : "published";
12
12
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live.server-only.d.ts","names":[],"sources":["../src/live.server-only.ts"],"sourcesContent":[],"mappings":";;;;;;;AAUgB,iBAAA,UAAA,CAAA,OAAA,EAAoB,uBAApB,CAAA,EAAA;EAAoB,WAAA,EACrB,sBADqB;EACrB,UAAA,EACD,KAAA,CAAM,aADL,CACmB,sBADnB,CAAA;EACmB,gBAAA,EACd,2BADc;CAApB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/studio/client-component/NextStudio.tsx","../../../src/studio/client-component/NextStudioLazy.tsx"],"sourcesContent":[],"mappings":";;;;UASiB,eAAA,SAAwB;EAAzC,QAAiB,CAAA,EACJ,KAAA,CAAM,SADF;;;;ACKjB;;;;;;;;;;;;;iBAAgB,6BAAA,QAAqC,kBAAkB,KAAA,CAAM"}
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { jsx } from "react/jsx-runtime";
3
2
  import { Suspense, lazy } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
4
  const NextStudioClientComponent = lazy(() => import("../../NextStudio.js"));
5
5
  function NextStudioLazyClientComponent(props) {
6
6
  return /* @__PURE__ */ jsx(Suspense, {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/studio/head.tsx","../../src/studio/NextStudioLayout.tsx","../../src/studio/NextStudioNoScript.tsx","../../src/studio/NextStudioWithBridge.tsx"],"sourcesContent":[],"mappings":";;;;;;;AAoBA;AAyBA;;;;AC5CA;AAaA;;;;;;;;ACOA;cFDa;;;EGVb,WAAgB,EAAA,MAAA;;;;;;;;;;;;;;;;;;;;cHmCH;;;;;;;UC5CI,qBAAA;YACL,KAAA,CAAM;ADkBlB;AAyBA;cC/Ba;;GAAgC,0BAAwB,KAAA,CAAM,GAAA,CAAI;;;;cCOlE,0BAAyB,KAAA,CAAM,GAAA,CAAI;;;iBCXhC,oBAAA,QAA4B,oBAAkB,KAAA,CAAM,GAAA,CAAI"}
@@ -1,6 +1,6 @@
1
1
  import { n as NextStudioLayout, t as NextStudioNoScript } from "../NextStudioNoScript.js";
2
- import { preloadModule } from "react-dom";
3
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { preloadModule } from "react-dom";
4
4
  import { NextStudio } from "next-sanity/studio/client-component";
5
5
  const viewport = {
6
6
  width: "device-width",
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/client-component/VisualEditing.tsx","../../../src/visual-editing/client-component/VisualEditingLazy.tsx"],"sourcesContent":[],"mappings":";;;;;;AAgBA;UAAiB,kBAAA,SAA2B,KAAK;;;ACFjD;;;;;;;;;;;;;;;;;;;;;iBAAgB,gCAAA,QAAwC,qBAAqB,KAAA,CAAM"}
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { jsx } from "react/jsx-runtime";
3
2
  import { Suspense, lazy } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
4
  const VisualEditingClientComponent = lazy(() => import("../../VisualEditing.js"));
5
5
  function VisualEditingLazyClientComponent(props) {
6
6
  return /* @__PURE__ */ jsx(Suspense, {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":[],"mappings":";;;;;;AAMA;iBAAgB,aAAA,QAAqB,uBAAqB,KAAA,CAAM"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/visual-editing/server-actions/index.ts"],"sourcesContent":[],"mappings":";iBAIsB,oBAAA,CAAA,GAAwB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/webhook/index.ts"],"sourcesContent":[],"mappings":";;;;;KAKY;EAAZ;AAaA;;EACO,gBAAA,EAAA,OAAA,GAAA,IAAA;EAGe,IAAA,EAZd,CAYc,GAAA,IAAA;CAAX;;;;;;iBAJW,iBAAiB,qBAChC,gFAGJ,QAAQ,WAAW"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "11.7.0-canary.2",
3
+ "version": "12.0.0",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "sanity",
@@ -49,46 +49,6 @@
49
49
  "main": "./dist/index.js",
50
50
  "module": "./dist/index.js",
51
51
  "types": "./dist/index.d.ts",
52
- "typesVersions": {
53
- "*": {
54
- "draft-mode": [
55
- "./dist/draft-mode/index.d.ts"
56
- ],
57
- "hooks": [
58
- "./dist/hooks/index.d.ts"
59
- ],
60
- "live": [
61
- "./dist/live.d.ts"
62
- ],
63
- "experimental/live": [
64
- "./dist/experimental/live.d.ts"
65
- ],
66
- "experimental/client-components/live": [
67
- "./dist/experimental/client-components/live.d.ts"
68
- ],
69
- "image": [
70
- "./dist/image/index.d.ts"
71
- ],
72
- "studio": [
73
- "./dist/studio/index.d.ts"
74
- ],
75
- "studio/client-component": [
76
- "./dist/studio/client-component/index.d.ts"
77
- ],
78
- "visual-editing": [
79
- "./dist/visual-editing/index.d.ts"
80
- ],
81
- "visual-editing/client-component": [
82
- "./dist/visual-editing/client-component/index.d.ts"
83
- ],
84
- "visual-editing/server-actions": [
85
- "./dist/visual-editing/server-actions/index.d.ts"
86
- ],
87
- "webhook": [
88
- "./dist/webhook/index.d.ts"
89
- ]
90
- }
91
- },
92
52
  "files": [
93
53
  "dist",
94
54
  "src",
@@ -99,43 +59,42 @@
99
59
  ],
100
60
  "browserslist": "extends @sanity/browserslist-config",
101
61
  "dependencies": {
102
- "@portabletext/react": "^4.0.3",
103
- "@sanity/client": "^7.12.0",
104
- "@sanity/comlink": "^4.0.0",
105
- "@sanity/presentation-comlink": "^2.0.0",
106
- "@sanity/preview-url-secret": "^2.1.15",
107
- "@sanity/visual-editing": "5.0.0-canary.2",
62
+ "@portabletext/react": "^6.0.0",
63
+ "@sanity/client": "^7.13.2",
64
+ "@sanity/comlink": "^4.0.1",
65
+ "@sanity/presentation-comlink": "^2.0.1",
66
+ "@sanity/preview-url-secret": "^4.0.0",
67
+ "@sanity/visual-editing": "^5.0.0",
108
68
  "dequal": "^2.0.3",
109
- "groq": "^4.12.0",
69
+ "groq": "^5.0.0",
110
70
  "history": "^5.3.0",
111
- "server-only": "^0.0.1",
112
- "use-effect-event": "^2.0.3"
71
+ "server-only": "^0.0.1"
113
72
  },
114
73
  "devDependencies": {
115
74
  "@sanity/browserslist-config": "^1.0.5",
116
- "@sanity/pkg-utils": "^8.1.28",
117
- "@sanity/types": "^4.12.0",
75
+ "@sanity/pkg-utils": "^10.2.1",
76
+ "@sanity/tsconfig": "^2.1.0",
77
+ "@sanity/types": "^5.0.0",
118
78
  "@sanity/webhook": "4.0.4",
119
- "@types/node": "^24",
120
- "@types/react": "^19.1.8",
121
- "@types/react-dom": "^19.1.6",
122
- "@vitest/coverage-v8": "^4.0.6",
123
- "next": "16.0.1-canary.5",
124
- "publint": "^0.3.15",
125
- "react": "^19.2.0",
126
- "react-dom": "^19.2.0",
79
+ "@types/node": "^24.10.4",
80
+ "@types/react": "^19.2.7",
81
+ "@types/react-dom": "^19.2.3",
82
+ "@vitest/coverage-v8": "^4.0.16",
83
+ "next": "16.1.0-canary.29",
84
+ "publint": "^0.3.16",
85
+ "react": "^19.2.3",
86
+ "react-dom": "^19.2.3",
127
87
  "styled-components": "^6.1.19",
128
- "tsdown": "0.15.12",
88
+ "tsdown": "0.18.0",
129
89
  "typescript": "5.9.3",
130
- "vite-tsconfig-paths": "^5.1.4",
131
- "vitest": "^4.0.6"
90
+ "vitest": "^4.0.16"
132
91
  },
133
92
  "peerDependencies": {
134
- "@sanity/client": "^7.12.0",
135
- "next": "^15.1.0-0 || ^16.0.0-0",
136
- "react": "^18.3 || ^19",
137
- "react-dom": "^18.3 || ^19",
138
- "sanity": "^4.12.0",
93
+ "@sanity/client": "^7.13.2",
94
+ "next": "^16.0.0-0",
95
+ "react": "^19.2.3",
96
+ "react-dom": "^19.2.3",
97
+ "sanity": "^5.0.0",
139
98
  "styled-components": "^6.1"
140
99
  },
141
100
  "engines": {
@@ -7,8 +7,7 @@ import {
7
7
  type LoaderNodeMsg,
8
8
  } from '@sanity/presentation-comlink'
9
9
  import {useRouter} from 'next/navigation'
10
- import {startTransition, useEffect} from 'react'
11
- import {useEffectEvent} from 'use-effect-event'
10
+ import {startTransition, useEffect, useEffectEvent} from 'react'
12
11
  import {
13
12
  setComlink,
14
13
  setComlinkClientConfig,
@@ -10,8 +10,7 @@ import {
10
10
  import {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'
11
11
  import dynamic from 'next/dynamic'
12
12
  import {useRouter} from 'next/navigation'
13
- import {useEffect, useMemo, useRef, useState} from 'react'
14
- import {useEffectEvent} from 'use-effect-event'
13
+ import {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'
15
14
  import {setEnvironment, setPerspective} from '../../live/hooks/context'
16
15
  import {isCorsOriginError} from '../../isCorsOriginError'
17
16
  import type {SanityClientConfig} from '../types'
@@ -361,8 +361,10 @@ export function defineLive(config: DefineSanityLiveOptions): {
361
361
  return {sanityFetch, SanityLive}
362
362
  }
363
363
 
364
- interface SanityLiveServerComponentProps
365
- extends Omit<SanityLiveProps, 'draftModeEnabled' | 'token' | 'draftModePerspective'> {
364
+ interface SanityLiveServerComponentProps extends Omit<
365
+ SanityLiveProps,
366
+ 'draftModeEnabled' | 'token' | 'draftModePerspective'
367
+ > {
366
368
  browserToken: string | false | undefined
367
369
  // origin: string
368
370
  // perspective?: Exclude<ClientPerspective, 'raw'>
@@ -1,13 +1,12 @@
1
1
  import type {InitializedClientConfig} from '@sanity/client'
2
2
 
3
- export interface SanityClientConfig
4
- extends Pick<
5
- InitializedClientConfig,
6
- | 'projectId'
7
- | 'dataset'
8
- | 'apiHost'
9
- | 'apiVersion'
10
- | 'useProjectHostname'
11
- | 'token'
12
- | 'requestTagPrefix'
13
- > {}
3
+ export interface SanityClientConfig extends Pick<
4
+ InitializedClientConfig,
5
+ | 'projectId'
6
+ | 'dataset'
7
+ | 'apiHost'
8
+ | 'apiVersion'
9
+ | 'useProjectHostname'
10
+ | 'token'
11
+ | 'requestTagPrefix'
12
+ > {}
@@ -11,11 +11,7 @@ import {
11
11
  type LoaderNodeMsg,
12
12
  } from '@sanity/presentation-comlink'
13
13
  import {useRouter} from 'next/navigation'
14
- import {
15
- useEffect,
16
- // useState
17
- } from 'react'
18
- import {useEffectEvent} from 'use-effect-event'
14
+ import {useEffect, useEffectEvent} from 'react'
19
15
  import {setComlink, setComlinkClientConfig} from '../../hooks/context'
20
16
 
21
17
  function PresentationComlink(props: {
@@ -10,8 +10,7 @@ import {revalidateSyncTags as defaultRevalidateSyncTags} from 'next-sanity/live/
10
10
  import {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'
11
11
  import dynamic from 'next/dynamic'
12
12
  import {useRouter} from 'next/navigation'
13
- import {useEffect, useMemo, useRef, useState} from 'react'
14
- import {useEffectEvent} from 'use-effect-event'
13
+ import {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'
15
14
  import {setEnvironment, setPerspective} from '../../hooks/context'
16
15
  import {isCorsOriginError} from '../../../isCorsOriginError'
17
16
 
@@ -23,17 +22,16 @@ const RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'), {ssr: f
23
22
  /**
24
23
  * @public
25
24
  */
26
- export interface SanityLiveProps
27
- extends Pick<
28
- InitializedClientConfig,
29
- | 'projectId'
30
- | 'dataset'
31
- | 'apiHost'
32
- | 'apiVersion'
33
- | 'useProjectHostname'
34
- | 'token'
35
- | 'requestTagPrefix'
36
- > {
25
+ export interface SanityLiveProps extends Pick<
26
+ InitializedClientConfig,
27
+ | 'projectId'
28
+ | 'dataset'
29
+ | 'apiHost'
30
+ | 'apiVersion'
31
+ | 'useProjectHostname'
32
+ | 'token'
33
+ | 'requestTagPrefix'
34
+ > {
37
35
  // handleDraftModeAction: (secret: string) => Promise<void | string>
38
36
  draftModeEnabled: boolean
39
37
  draftModePerspective?: ClientPerspective
@@ -7,15 +7,16 @@ import {
7
7
  import {stegaEncodeSourceMap} from '@sanity/client/stega'
8
8
  import type {LoaderControllerMsg} from '@sanity/presentation-comlink'
9
9
  import {dequal} from 'dequal/lite'
10
- import {use, useCallback, useEffect, useState, useSyncExternalStore} from 'react'
11
- import {useEffectEvent} from 'use-effect-event'
10
+ import {use, useCallback, useEffect, useState, useSyncExternalStore, useEffectEvent} from 'react'
12
11
  import {comlinkListeners, comlink as comlinkSnapshot} from '../../hooks/context'
13
12
 
14
13
  /**
15
14
  * @public
16
15
  */
17
- export interface SanityLiveStreamProps
18
- extends Pick<InitializedClientConfig, 'projectId' | 'dataset'> {
16
+ export interface SanityLiveStreamProps extends Pick<
17
+ InitializedClientConfig,
18
+ 'projectId' | 'dataset'
19
+ > {
19
20
  query: string
20
21
  params?: QueryParams
21
22
  perspective?: Exclude<ClientPerspective, 'raw'>
@@ -2,8 +2,7 @@ import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} fro
2
2
  import {stegaEncodeSourceMap} from '@sanity/client/stega'
3
3
  import type {LoaderControllerMsg} from '@sanity/presentation-comlink'
4
4
  import {dequal} from 'dequal/lite'
5
- import {useEffect, useMemo, useReducer, useSyncExternalStore} from 'react'
6
- import {useEffectEvent} from 'use-effect-event'
5
+ import {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'
7
6
  import {
8
7
  comlinkDataset,
9
8
  comlinkListeners,