next-sanity 13.0.0-cache-components.17 → 13.0.0-cache-components.19

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.
@@ -0,0 +1,43 @@
1
+ import { n as PUBLISHED_SYNC_TAG_PREFIX } from "./constants.js";
2
+ import { useRouter } from "next/navigation";
3
+ import { useEffect, useEffectEvent, useState } from "react";
4
+ function LiveEvents(props) {
5
+ const { client, onEvent, intervalOnGoAway = 3e4, requestTag, onError, onGoAway } = props;
6
+ const [longPollingInterval, setLongPollingInterval] = useState(false);
7
+ const router = useRouter();
8
+ const handleLiveEvent = useEffectEvent((event) => {
9
+ if (process.env.NODE_ENV !== "production" && event.type === "welcome") {
10
+ console.info("<SanityLive> is connected and listening for live events to published content");
11
+ setLongPollingInterval(false);
12
+ } else if (event.type === "message") onEvent(event.tags.map((tag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}`)).then((result) => {
13
+ if (result === "refresh") router.refresh();
14
+ });
15
+ else if (event.type === "restart" || event.type === "reconnect") router.refresh();
16
+ else if (event.type === "goaway") {
17
+ onGoAway(event, intervalOnGoAway);
18
+ setLongPollingInterval(intervalOnGoAway);
19
+ }
20
+ });
21
+ useEffect(() => {
22
+ const subscription = client.live.events({ tag: requestTag }).subscribe({
23
+ next: handleLiveEvent,
24
+ error: onError
25
+ });
26
+ return () => subscription.unsubscribe();
27
+ }, [
28
+ client.live,
29
+ onError,
30
+ requestTag
31
+ ]);
32
+ useEffect(() => {
33
+ if (!longPollingInterval) return;
34
+ const interval = setInterval(() => router.refresh(), longPollingInterval);
35
+ return () => clearInterval(interval);
36
+ }, [longPollingInterval, router]);
37
+ return null;
38
+ }
39
+ LiveEvents.displayName = "LiveEvents";
40
+ var LiveEvents_default = LiveEvents;
41
+ export { LiveEvents_default as default };
42
+
43
+ //# sourceMappingURL=LiveEvents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LiveEvents.js","names":[],"sources":["../src/live/client-components/LiveEvents.tsx"],"sourcesContent":["import type {LiveEvent, LiveEventGoAway, SanityClient, SyncTag} from '@sanity/client'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX} from '#live/constants'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useState, useEffectEvent} from 'react'\n\ninterface LiveEventsProps {\n client: SanityClient\n onEvent: (tags: string[]) => Promise<void | 'refresh'>\n requestTag: string\n onError: (error: unknown) => void\n intervalOnGoAway: number | false\n onGoAway: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction LiveEvents(props: LiveEventsProps): null {\n const {client, onEvent, intervalOnGoAway = 30_000, requestTag, onError, onGoAway} = props\n\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info('<SanityLive> is connected and listening for live events to published content')\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 void onEvent(\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 useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: onError,\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag])\n\n /**\n * 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 null\n}\n\nLiveEvents.displayName = 'LiveEvents'\n\nexport default LiveEvents\n"],"mappings":";;;AAeA,SAAS,WAAW,OAA8B;CAChD,MAAM,EAAC,QAAQ,SAAS,mBAAmB,KAAQ,YAAY,SAAS,aAAY;CAEpF,MAAM,CAAC,qBAAqB,0BAA0B,SAAyB,MAAM;CAErF,MAAM,SAAS,WAAW;CAC1B,MAAM,kBAAkB,gBAAgB,UAAqB;AAC3D,MAAI,QAAQ,IAAI,aAAa,gBAAgB,MAAM,SAAS,WAAW;AAErE,WAAQ,KAAK,+EAA+E;AAE5F,0BAAuB,MAAM;aACpB,MAAM,SAAS,UACnB,SACH,MAAM,KAAK,KAAK,QAAiB,GAAG,4BAA4B,MAAe,CAChF,CAAC,MAAM,WAAW;AACjB,OAAI,WAAW,UAAW,QAAO,SAAS;IAC1C;WACO,MAAM,SAAS,aAAa,MAAM,SAAS,YACpD,QAAO,SAAS;WACP,MAAM,SAAS,UAAU;AAClC,YAAS,OAAO,iBAAiB;AACjC,0BAAuB,iBAAiB;;GAE1C;AACF,iBAAgB;EACd,MAAM,eAAe,OAAO,KAAK,OAAO,EAAC,KAAK,YAAW,CAAC,CAAC,UAAU;GACnE,MAAM;GACN,OAAO;GACR,CAAC;AACF,eAAa,aAAa,aAAa;IACtC;EAAC,OAAO;EAAM;EAAS;EAAW,CAAC;AAKtC,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QAAO;;AAGT,WAAW,cAAc;AAEzB,IAAA,qBAAe"}
@@ -0,0 +1,46 @@
1
+ import { t as DRAFT_SYNC_TAG_PREFIX } from "./constants.js";
2
+ import { useRouter } from "next/navigation";
3
+ import { useEffect, useEffectEvent, useState } from "react";
4
+ function LiveEventsIncludingDrafts(props) {
5
+ const { client, intervalOnGoAway, onError, onEvent, onGoAway, requestTag } = props;
6
+ const [longPollingInterval, setLongPollingInterval] = useState(false);
7
+ const router = useRouter();
8
+ const handleLiveEvent = useEffectEvent((event) => {
9
+ if (process.env.NODE_ENV !== "production" && event.type === "welcome") {
10
+ console.info("<SanityLive> is connected and listening for live events to all content including drafts and version documents in content releases");
11
+ setLongPollingInterval(false);
12
+ } else if (event.type === "message") onEvent(event.tags.map((tag) => `${DRAFT_SYNC_TAG_PREFIX}${tag}`)).then((result) => {
13
+ if (result === "refresh") router.refresh();
14
+ });
15
+ else if (event.type === "restart" || event.type === "reconnect") router.refresh();
16
+ else if (event.type === "goaway") {
17
+ onGoAway(event, intervalOnGoAway);
18
+ setLongPollingInterval(intervalOnGoAway);
19
+ }
20
+ });
21
+ useEffect(() => {
22
+ const subscription = client.live.events({
23
+ includeDrafts: true,
24
+ tag: requestTag
25
+ }).subscribe({
26
+ next: handleLiveEvent,
27
+ error: onError
28
+ });
29
+ return () => subscription.unsubscribe();
30
+ }, [
31
+ client.live,
32
+ onError,
33
+ requestTag
34
+ ]);
35
+ useEffect(() => {
36
+ if (!longPollingInterval) return;
37
+ const interval = setInterval(() => router.refresh(), longPollingInterval);
38
+ return () => clearInterval(interval);
39
+ }, [longPollingInterval, router]);
40
+ return null;
41
+ }
42
+ LiveEventsIncludingDrafts.displayName = "LiveEventsIncludingDrafts";
43
+ var LiveEventsIncludingDrafts_default = LiveEventsIncludingDrafts;
44
+ export { LiveEventsIncludingDrafts_default as default };
45
+
46
+ //# sourceMappingURL=LiveEventsIncludingDrafts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LiveEventsIncludingDrafts.js","names":[],"sources":["../src/live/client-components/LiveEventsIncludingDrafts.tsx"],"sourcesContent":["import type {LiveEvent, LiveEventGoAway, SanityClient, SyncTag} from '@sanity/client'\n\nimport {DRAFT_SYNC_TAG_PREFIX} from '#live/constants'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useState, useEffectEvent} from 'react'\n\ninterface LiveEventsIncludingDraftsProps {\n client: SanityClient\n onEvent: (tags: string[]) => Promise<void | 'refresh'>\n requestTag: string\n onError: (error: unknown) => void\n intervalOnGoAway: number | false\n onGoAway: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction LiveEventsIncludingDrafts(props: LiveEventsIncludingDraftsProps): null {\n const {client, intervalOnGoAway, onError, onEvent, onGoAway, requestTag} = props\n\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n '<SanityLive> is connected and listening for live events to all content including drafts and version documents in content releases',\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 void onEvent(\n event.tags.map((tag: SyncTag) => `${DRAFT_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 useEffect(() => {\n const subscription = client.live.events({includeDrafts: true, tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: onError,\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag])\n\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return null\n}\n\nLiveEventsIncludingDrafts.displayName = 'LiveEventsIncludingDrafts'\n\nexport default LiveEventsIncludingDrafts\n"],"mappings":";;;AAeA,SAAS,0BAA0B,OAA6C;CAC9E,MAAM,EAAC,QAAQ,kBAAkB,SAAS,SAAS,UAAU,eAAc;CAE3E,MAAM,CAAC,qBAAqB,0BAA0B,SAAyB,MAAM;CAErF,MAAM,SAAS,WAAW;CAC1B,MAAM,kBAAkB,gBAAgB,UAAqB;AAC3D,MAAI,QAAQ,IAAI,aAAa,gBAAgB,MAAM,SAAS,WAAW;AAErE,WAAQ,KACN,oIACD;AAED,0BAAuB,MAAM;aACpB,MAAM,SAAS,UACnB,SACH,MAAM,KAAK,KAAK,QAAiB,GAAG,wBAAwB,MAAe,CAC5E,CAAC,MAAM,WAAW;AACjB,OAAI,WAAW,UAAW,QAAO,SAAS;IAC1C;WACO,MAAM,SAAS,aAAa,MAAM,SAAS,YACpD,QAAO,SAAS;WACP,MAAM,SAAS,UAAU;AAClC,YAAS,OAAO,iBAAiB;AACjC,0BAAuB,iBAAiB;;GAE1C;AACF,iBAAgB;EACd,MAAM,eAAe,OAAO,KAAK,OAAO;GAAC,eAAe;GAAM,KAAK;GAAW,CAAC,CAAC,UAAU;GACxF,MAAM;GACN,OAAO;GACR,CAAC;AACF,eAAa,aAAa,aAAa;IACtC;EAAC,OAAO;EAAM;EAAS;EAAW,CAAC;AAEtC,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QAAO;;AAGT,0BAA0B,cAAc;AAExC,IAAA,oCAAe"}
@@ -1,4 +1,4 @@
1
- import { f as setPerspective, l as setComlink, u as setComlinkClientConfig } from "./context.js";
1
+ import { c as setComlinkPerspective, o as setComlink, s as setComlinkClientConfig } from "./context.js";
2
2
  import { t as sanitizePerspective } from "./sanitizePerspective.js";
3
3
  import { useEffect, useEffectEvent } from "react";
4
4
  import { createNode, createNodeMachine } from "@sanity/comlink";
@@ -9,7 +9,7 @@ function PresentationComlink(props) {
9
9
  setComlinkClientConfig(projectId, dataset);
10
10
  }, [dataset, projectId]);
11
11
  const handlePerspectiveChange = useEffectEvent((perspective) => {
12
- setPerspective(sanitizePerspective(perspective, "drafts"));
12
+ setComlinkPerspective(sanitizePerspective(perspective, "drafts"));
13
13
  });
14
14
  useEffect(() => {
15
15
  const controller = new AbortController();
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {setComlink, setComlinkClientConfig, setPerspective} from '#live/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n}): React.JSX.Element | null {\n const {projectId, dataset} = props\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent((perspective: ClientPerspective) => {\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n\n useEffect(() => {\n const controller = new AbortController()\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n comlink.on('loader/perspective', (data) => {\n if (controller.signal.aborted) return\n\n handlePerspectiveChange(data.perspective)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n controller.abort()\n }\n }, [])\n\n return null\n}\n\nPresentationComlink.displayName = 'PresentationComlink'\n"],"mappings":";;;;;AAYA,SAAwB,oBAAoB,OAGf;CAC3B,MAAM,EAAC,WAAW,YAAW;AAE7B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAAgB,gBAAmC;AACjF,iBAAe,oBAAoB,aAAa,SAAS,CAAC;GAC1D;AAEF,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;AAED,UAAQ,GAAG,uBAAuB,SAAS;AACzC,OAAI,WAAW,OAAO,QAAS;AAE/B,2BAAwB,KAAK,YAAY;IACzC;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;AACN,cAAW,OAAO;;IAEnB,EAAE,CAAC;AAEN,QAAO;;AAGT,oBAAoB,cAAc"}
1
+ {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {setComlink, setComlinkClientConfig, setComlinkPerspective} from '#live/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n}): React.JSX.Element | null {\n const {projectId, dataset} = props\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent((perspective: ClientPerspective) => {\n setComlinkPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n\n useEffect(() => {\n const controller = new AbortController()\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n comlink.on('loader/perspective', (data) => {\n if (controller.signal.aborted) return\n\n handlePerspectiveChange(data.perspective)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n controller.abort()\n }\n }, [])\n\n return null\n}\n\nPresentationComlink.displayName = 'PresentationComlink'\n"],"mappings":";;;;;AAYA,SAAwB,oBAAoB,OAGf;CAC3B,MAAM,EAAC,WAAW,YAAW;AAE7B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAAgB,gBAAmC;AACjF,wBAAsB,oBAAoB,aAAa,SAAS,CAAC;GACjE;AAEF,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;AAED,UAAQ,GAAG,uBAAuB,SAAS;AACzC,OAAI,WAAW,OAAO,QAAS;AAE/B,2BAAwB,KAAK,YAAY;IACzC;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;AACN,cAAW,OAAO;;IAEnB,EAAE,CAAC;AAEN,QAAO;;AAGT,oBAAoB,cAAc"}
@@ -1,12 +1,11 @@
1
- import { n as PUBLISHED_SYNC_TAG_PREFIX } from "./constants.js";
2
- import { d as setEnvironment } from "./context.js";
3
1
  import { t as isCorsOriginError } from "./isCorsOriginError.js";
4
- import { useRouter } from "next/navigation";
5
- import { useEffect, useEffectEvent, useMemo, useState } from "react";
2
+ import { useEffect, useMemo, useState } from "react";
6
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
4
  import { createClient } from "@sanity/client";
8
5
  import dynamic from "next/dynamic";
9
- import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
6
+ import { isMaybePresentation } from "@sanity/presentation-comlink";
7
+ const LiveEvents = dynamic(() => import("./LiveEvents.js"));
8
+ const LiveEventsIncludingDrafts = dynamic(() => import("./LiveEventsIncludingDrafts.js"));
10
9
  const PresentationComlink = dynamic(() => import("./PresentationComlink.js"));
11
10
  const RefreshOnMount = dynamic(() => import("./RefreshOnMount.js"));
12
11
  const RefreshOnFocus = dynamic(() => import("./RefreshOnFocus.js"));
@@ -20,7 +19,7 @@ function handleOnGoAway(event, intervalOnGoAway) {
20
19
  else console.error("Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:", event.reason);
21
20
  }
22
21
  function SanityLive(props) {
23
- const { config, onLiveEvent, perspective, refreshOnMount = false, refreshOnFocus = perspective !== "published" ? false : typeof window === "undefined" ? true : window.self === window.top, refreshOnReconnect = true, intervalOnGoAway = 3e4, requestTag, onError = handleError, onGoAway = handleOnGoAway } = props;
22
+ const { config, includeDrafts, onLiveEvent, onLiveEventIncludingDrafts, refreshOnMount = false, refreshOnFocus = false, refreshOnReconnect = true, intervalOnGoAway = 3e4, requestTag, onError = handleError, onGoAway = handleOnGoAway } = props;
24
23
  const { projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix } = config;
25
24
  const client = useMemo(() => createClient({
26
25
  projectId,
@@ -41,62 +40,37 @@ function SanityLive(props) {
41
40
  token,
42
41
  useProjectHostname
43
42
  ]);
44
- const [longPollingInterval, setLongPollingInterval] = useState(false);
45
- const router = useRouter();
46
- const handleLiveEvent = useEffectEvent((event) => {
47
- if (process.env.NODE_ENV !== "production" && event.type === "welcome") {
48
- console.info("Sanity is live with", token ? "automatic revalidation for draft content changes as well as published content" : perspective === "published" ? "automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool." : "automatic revalidation of published content");
49
- setLongPollingInterval(false);
50
- } else if (event.type === "message") onLiveEvent(event.tags.map((tag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}`)).then((result) => {
51
- if (result === "refresh") router.refresh();
52
- });
53
- else if (event.type === "restart" || event.type === "reconnect") router.refresh();
54
- else if (event.type === "goaway") {
55
- onGoAway(event, intervalOnGoAway);
56
- setLongPollingInterval(intervalOnGoAway);
57
- }
58
- });
59
- useEffect(() => {
60
- const subscription = client.live.events({
61
- includeDrafts: !!token,
62
- tag: requestTag
63
- }).subscribe({
64
- next: handleLiveEvent,
65
- error: (err) => {
66
- onError(err);
67
- }
68
- });
69
- return () => subscription.unsubscribe();
70
- }, [
71
- client.live,
72
- onError,
73
- requestTag,
74
- token
75
- ]);
76
43
  const [loadComlink, setLoadComlink] = useState(false);
77
44
  useEffect(() => {
78
45
  if (!isMaybePresentation()) return;
79
46
  const controller = new AbortController();
80
- const timeout = setTimeout(() => setEnvironment("live"), 3e3);
81
47
  window.addEventListener("message", ({ data }) => {
82
48
  if (data && typeof data === "object" && "domain" in data && data.domain === "sanity/channels" && "from" in data && data.from === "presentation") {
83
- clearTimeout(timeout);
84
- setEnvironment(isMaybePreviewWindow() ? "presentation-window" : "presentation-iframe");
85
49
  setLoadComlink(true);
86
50
  controller.abort();
87
51
  }
88
52
  }, { signal: controller.signal });
89
53
  return () => {
90
- clearTimeout(timeout);
91
54
  controller.abort();
92
55
  };
93
56
  }, []);
94
- useEffect(() => {
95
- if (!longPollingInterval) return;
96
- const interval = setInterval(() => router.refresh(), longPollingInterval);
97
- return () => clearInterval(interval);
98
- }, [longPollingInterval, router]);
99
57
  return /* @__PURE__ */ jsxs(Fragment, { children: [
58
+ onLiveEvent && /* @__PURE__ */ jsx(LiveEvents, {
59
+ client,
60
+ onEvent: onLiveEvent,
61
+ requestTag,
62
+ onError,
63
+ onGoAway,
64
+ intervalOnGoAway
65
+ }),
66
+ includeDrafts && onLiveEventIncludingDrafts && /* @__PURE__ */ jsx(LiveEventsIncludingDrafts, {
67
+ client,
68
+ onEvent: onLiveEventIncludingDrafts,
69
+ requestTag,
70
+ onError,
71
+ onGoAway,
72
+ intervalOnGoAway
73
+ }),
100
74
  loadComlink && /* @__PURE__ */ jsx(PresentationComlink, {
101
75
  projectId,
102
76
  dataset
@@ -1 +1 @@
1
- {"version":3,"file":"SanityLive.js","names":[],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {PUBLISHED_SYNC_TAG_PREFIX} from '#live/constants'\nimport {setEnvironment} from '#live/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useState, useEffectEvent} from 'react'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n /**\n * Setting this to 'published' opens one live event connection, setting it to any other value opens both the live event connections if needed\n */\n perspective: Exclude<ClientPerspective, 'raw'>\n\n onLiveEvent: (tags: string[]) => Promise<void | 'refresh'>\n onLiveEventIncludingDrafts: (tags: string[]) => Promise<void | 'refresh'>\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\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 intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n onLiveEvent,\n // onLiveEventIncludingDrafts,\n perspective,\n\n refreshOnMount = false,\n refreshOnFocus = perspective !== 'published'\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag,\n onError = handleError,\n onGoAway = handleOnGoAway,\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\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : perspective === 'published'\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 void onLiveEvent(\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 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 const [loadComlink, setLoadComlink] = useState(false)\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 * 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 {loadComlink && <PresentationComlink projectId={projectId!} dataset={dataset!} />}\n {refreshOnMount && <RefreshOnMount />}\n {refreshOnFocus && <RefreshOnFocus />}\n {refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;;AAgBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,qBAAqB,cAAc,OAA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":3,"file":"SanityLive.js","names":[],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {isCorsOriginError} from '#live/isCorsOriginError'\nimport {createClient, type InitializedClientConfig, type LiveEventGoAway} from '@sanity/client'\nimport {\n isMaybePresentation,\n // isMaybePreviewWindow\n} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useEffect, useMemo, useState} from 'react'\n\nconst LiveEvents = dynamic(() => import('./LiveEvents'))\nconst LiveEventsIncludingDrafts = dynamic(() => import('./LiveEventsIncludingDrafts'))\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n includeDrafts?: boolean\n\n onLiveEvent: (tags: string[]) => Promise<void | 'refresh'>\n onLiveEventIncludingDrafts: (tags: string[]) => Promise<void | 'refresh'>\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\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 intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n includeDrafts,\n onLiveEvent,\n onLiveEventIncludingDrafts,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag,\n onError = handleError,\n onGoAway = handleOnGoAway,\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\n const [loadComlink, setLoadComlink] = useState(false)\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 return (\n <>\n {onLiveEvent && (\n <LiveEvents\n client={client}\n onEvent={onLiveEvent}\n requestTag={requestTag}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )}\n {includeDrafts && onLiveEventIncludingDrafts && (\n <LiveEventsIncludingDrafts\n client={client}\n onEvent={onLiveEventIncludingDrafts}\n requestTag={requestTag}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )}\n {loadComlink && <PresentationComlink projectId={projectId!} dataset={dataset!} />}\n {refreshOnMount && <RefreshOnMount />}\n {refreshOnFocus && <RefreshOnFocus />}\n {refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;AASA,MAAM,aAAa,cAAc,OAAO,mBAAgB;AACxD,MAAM,4BAA4B,cAAc,OAAO,kCAA+B;AACtF,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AAkCxE,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAIxB,SAAS,eAAe,OAAwB,kBAAkC;AAChF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAIL,SAAS,WAAW,OAAkD;CACpE,MAAM,EACJ,QACA,eACA,aACA,4BACA,iBAAiB,OACjB,iBAAiB,OACjB,qBAAqB,MACrB,mBAAmB,KACnB,YACA,UAAU,aACV,WAAW,mBACT;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B;EACA,QAAQ;EACR;EACD,CAAC,EACJ;EAAC;EAAS;EAAY;EAAS;EAAW;EAAkB;EAAO;EAAmB,CACvF;CAED,MAAM,CAAC,aAAa,kBAAkB,SAAS,MAAM;AACrD,iBAAgB;AACd,MAAI,CAAC,qBAAqB,CAAE;EAC5B,MAAM,aAAa,IAAI,iBAAiB;AAGxC,SAAO,iBACL,YACC,EAAC,WAAiC;AACjC,OACE,QACA,OAAO,SAAS,YAChB,YAAY,QACZ,KAAK,WAAW,qBAChB,UAAU,QACV,KAAK,SAAS,gBACd;AAGA,mBAAe,KAAK;AACpB,eAAW,OAAO;;KAGtB,EAAC,QAAQ,WAAW,QAAO,CAC5B;AACD,eAAa;AAEX,cAAW,OAAO;;IAEnB,EAAE,CAAC;AAEN,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,eACC,oBAAC,YAAA;GACS;GACR,SAAS;GACG;GACH;GACC;GACQ;IAClB;EAEH,iBAAiB,8BAChB,oBAAC,2BAAA;GACS;GACR,SAAS;GACG;GACH;GACC;GACQ;IAClB;EAEH,eAAe,oBAAC,qBAAA;GAA+B;GAAqB;IAAY;EAChF,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACpC,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACpC,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KAC5C;;AAIP,WAAW,cAAc;AAEzB,IAAA,qBAAe"}
package/dist/context.js CHANGED
@@ -1,20 +1,8 @@
1
- const perspectiveListeners = /* @__PURE__ */ new Set();
2
- let perspective = "checking";
3
- function setPerspective(nextPerspective) {
4
- if (perspective.toString() === nextPerspective.toString()) return;
5
- perspective = nextPerspective;
6
- for (const onPerspectiveChange of perspectiveListeners) onPerspectiveChange();
7
- }
8
- const environmentListeners = /* @__PURE__ */ new Set();
9
- let environment = "checking";
10
- function setEnvironment(nextEnvironment) {
11
- environment = nextEnvironment;
12
- for (const onEnvironmentChange of environmentListeners) onEnvironmentChange();
13
- }
14
1
  const comlinkListeners = /* @__PURE__ */ new Set();
15
2
  let comlink = null;
16
3
  let comlinkProjectId = null;
17
4
  let comlinkDataset = null;
5
+ let comlinkPerspective = null;
18
6
  function setComlink(nextComlink) {
19
7
  comlink = nextComlink;
20
8
  for (const onComlinkChange of comlinkListeners) onComlinkChange();
@@ -24,6 +12,11 @@ function setComlinkClientConfig(nextComlinkProjectId, nextComlinkDataset) {
24
12
  comlinkDataset = nextComlinkDataset;
25
13
  for (const onComlinkChange of comlinkListeners) onComlinkChange();
26
14
  }
27
- export { environment as a, perspectiveListeners as c, setEnvironment as d, setPerspective as f, comlinkProjectId as i, setComlink as l, comlinkDataset as n, environmentListeners as o, comlinkListeners as r, perspective as s, comlink as t, setComlinkClientConfig as u };
15
+ function setComlinkPerspective(nextComlinkPerspective) {
16
+ if (comlinkPerspective?.toString() === nextComlinkPerspective?.toString()) return;
17
+ comlinkPerspective = nextComlinkPerspective;
18
+ for (const onComlinkChange of comlinkListeners) onComlinkChange();
19
+ }
20
+ export { comlinkProjectId as a, setComlinkPerspective as c, comlinkPerspective as i, comlinkDataset as n, setComlink as o, comlinkListeners as r, setComlinkClientConfig as s, comlink as t };
28
21
 
29
22
  //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../src/live/shared/context.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {Node} from '@sanity/comlink'\nimport type {LoaderControllerMsg, LoaderNodeMsg} from '@sanity/presentation-comlink'\n\nexport type LivePerspective = 'checking' | 'unknown' | ClientPerspective\n\nexport const perspectiveListeners: Set<() => void> = new Set()\nexport let perspective: LivePerspective = 'checking'\nexport function setPerspective(nextPerspective: LivePerspective): void {\n if (perspective.toString() === nextPerspective.toString()) return\n perspective = nextPerspective\n for (const onPerspectiveChange of perspectiveListeners) {\n onPerspectiveChange()\n }\n}\n\nexport type LiveEnvironment =\n | 'checking'\n | 'presentation-iframe'\n | 'presentation-window'\n | 'live'\n | 'static'\n | 'unknown'\n\nexport const environmentListeners: Set<() => void> = new Set()\nexport let environment: LiveEnvironment = 'checking'\nexport function setEnvironment(nextEnvironment: LiveEnvironment): void {\n environment = nextEnvironment\n for (const onEnvironmentChange of environmentListeners) {\n onEnvironmentChange()\n }\n}\n\nexport const comlinkListeners: Set<() => void> = new Set()\nexport let comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null = null\nexport let comlinkProjectId: string | null = null\nexport let comlinkDataset: string | null = null\nexport function setComlink(nextComlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null): void {\n comlink = nextComlink\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkClientConfig(\n nextComlinkProjectId: string | null,\n nextComlinkDataset: string | null,\n): void {\n comlinkProjectId = nextComlinkProjectId\n comlinkDataset = nextComlinkDataset\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\n"],"mappings":"AAMA,MAAa,uCAAwC,IAAI,KAAK;AAC9D,IAAW,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,KAAI,YAAY,UAAU,KAAK,gBAAgB,UAAU,CAAE;AAC3D,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAYzB,MAAa,uCAAwC,IAAI,KAAK;AAC9D,IAAW,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAIzB,MAAa,mCAAoC,IAAI,KAAK;AAC1D,IAAW,UAA2D;AACtE,IAAW,mBAAkC;AAC7C,IAAW,iBAAgC;AAC3C,SAAgB,WAAW,aAAoE;AAC7F,WAAU;AACV,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,uBACd,sBACA,oBACM;AACN,oBAAmB;AACnB,kBAAiB;AACjB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../src/live/shared/context.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {Node} from '@sanity/comlink'\nimport type {LoaderControllerMsg, LoaderNodeMsg} from '@sanity/presentation-comlink'\n\nexport const comlinkListeners: Set<() => void> = new Set()\nexport let comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null = null\nexport let comlinkProjectId: string | null = null\nexport let comlinkDataset: string | null = null\nexport let comlinkPerspective: ClientPerspective | null = null\nexport function setComlink(nextComlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null): void {\n comlink = nextComlink\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkClientConfig(\n nextComlinkProjectId: string | null,\n nextComlinkDataset: string | null,\n): void {\n comlinkProjectId = nextComlinkProjectId\n comlinkDataset = nextComlinkDataset\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkPerspective(nextComlinkPerspective: ClientPerspective | null): void {\n if (comlinkPerspective?.toString() === nextComlinkPerspective?.toString()) return\n comlinkPerspective = nextComlinkPerspective\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\n"],"mappings":"AAIA,MAAa,mCAAoC,IAAI,KAAK;AAC1D,IAAW,UAA2D;AACtE,IAAW,mBAAkC;AAC7C,IAAW,iBAAgC;AAC3C,IAAW,qBAA+C;AAC1D,SAAgB,WAAW,aAAoE;AAC7F,WAAU;AACV,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,uBACd,sBACA,oBACM;AACN,oBAAmB;AACnB,kBAAiB;AACjB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,sBAAsB,wBAAwD;AAC5F,KAAI,oBAAoB,UAAU,KAAK,wBAAwB,UAAU,CAAE;AAC3E,sBAAqB;AACrB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB"}
@@ -61,10 +61,9 @@ type DefinedFetchType = <const QueryString extends string>(options: {
61
61
  }>;
62
62
  interface DefinedLiveProps {
63
63
  /**
64
- * TODO: should match the `perspective` you give `defineLive().fetch()`, setting it to a value other than `"published"`
65
- * and with `browserToken` set will cause it to subscribe to draft content changes as well as published content.
64
+ * TODO: docs, settings this to `true` enables live events for draft content and requires `browserToken` to be set.
66
65
  */
67
- perspective?: PerspectiveType;
66
+ includeDrafts?: boolean;
68
67
  /**
69
68
  * Automatic refresh of RSC when the component <SanityLive /> is mounted.
70
69
  * @defaultValue `false`
@@ -109,13 +108,13 @@ interface DefinedLiveProps {
109
108
  /**
110
109
  * TODO: docs, this handles events for published content only, and can be used to revalidate content for all your users when in presentation tool
111
110
  */
112
- onChange?: (tags: string[]) => Promise<void | "refresh">;
111
+ onLiveEvent?: (tags: string[]) => Promise<void | "refresh">;
113
112
  /**
114
113
  * TODO: docs, this handles events for all changes, published, drafts and even version documents in content releases.
115
114
  * It's only used when `browserToken` is provided, and the `perspective` prop is other than `"published"`.
116
115
  * Wether you should just `refresh()` or use `updateTag` to expire tags depends on how you fetch draft content and wether it's cached or not.
117
116
  */
118
- onChangeIncludingDrafts?: (tags: string[]) => Promise<void | "refresh">;
117
+ onLiveEventIncludingDrafts?: (tags: string[]) => Promise<void | "refresh">;
119
118
  }
120
119
  interface LiveOptions {
121
120
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/shared/resolvePerspectiveFromCookies.ts","../src/live/shared/types.ts","../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":[],"mappings":";;;KAOY,6BAAA;;AAAZ;;;;;;;;AAkBA;EACW,OAAA,EARA,OAQA,CARQ,UAQR,CAAA,OAR0B,OAQ1B,CAAA,CAAA;CAE0B,EAAA,GAT/B,OAS+B,CATvB,OASuB,CATf,iBASe,EAAA,KAAA,CAAA,CAAA;;;;;AACjC,cAJS,6BAIT,EAAA,CAAA;EAAA,OAAA,EAHO;CAGP,EAAA;EAAA,OAAA,EADO,OACP,CADe,UACf,CAAA,OADiC,OACjC,CAAA,CAAA;MAAA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;AAKZ,CAAA,EAAA,GCkBM,ODlBM,CAAA;EACH,IAAA,ECkBD,YDlBC,CCkBY,WDlBZ,CAAA;EACE,SAAA,ECkBE,gBDlBF,GAAA,IAAA;EAIK,IAAA,EAAA,MAAA,EAAA;CAkBK,CAAA;;;;AADf,UCIW,sBAAA,SAA+B,gBDJ1C,CAAA;EAMN;;;EAuDiC,WAAA,CAAA,ECrDjB,eDqDiB;;;AAUjC;;AC9FY,UAqCK,uBAAA,CArCL;EACH;;;EACgB,MAAA,EAuCf,YAvCe;EAQD;;;;EAUX,WAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAFP;;AASN;AAUA;EAgCA,YAAgB,CAAA,EAAA,MAAA,GAAA,KAAA;EAAmB;;;EAQrB,YAAM,CAAA,EAAA;IAAA;;;;;;;;;;;;iBARJ,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
1
+ {"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/shared/resolvePerspectiveFromCookies.ts","../src/live/shared/types.ts","../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":[],"mappings":";;;KAOY,6BAAA;;AAAZ;;;;;;;;AAkBA;EACW,OAAA,EARA,OAQA,CARQ,UAQR,CAAA,OAR0B,OAQ1B,CAAA,CAAA;CAE0B,EAAA,GAT/B,OAS+B,CATvB,OASuB,CATf,iBASe,EAAA,KAAA,CAAA,CAAA;;;;;AACjC,cAJS,6BAIT,EAAA,CAAA;EAAA,OAAA,EAHO;CAGP,EAAA;EAAA,OAAA,EADO,OACP,CADe,UACf,CAAA,OADiC,OACjC,CAAA,CAAA;MAAA,QAAQ,QAAQ;;;;AAtBpB;AAWqC,KCJzB,eAAA,GAAkB,ODIO,CCJC,mBDID,EAAA,KAAA,CAAA;;;;AACvB,KCAF,gBAAA,GDAE,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAAA;EAAR,KAAA,ECCG,WDDH;EAAA,MAAA,CAAA,ECEK,aDFL;EAMN;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D,WAAA,CAAA,EC3DnC,eD2DmC;;AAGnD;;AC7FA;AACS,UAoCQ,uBAAA,CApCR;EACE;;;EAQa,MAAA,EA+Bd,YA/Bc;EAAR;;;;EAQV,WAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAAA;AASN;AAUA;AAgCA;EAAmC,YAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAIpB;;;EAIK,YAAA,CAAA,EAAA;;;;;;;;;;;;;iBARJ,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
@@ -1,38 +1,5 @@
1
1
  import { useOptimistic } from "@sanity/visual-editing/react";
2
2
  import { ClientPerspective, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
3
- import "@sanity/comlink";
4
- import "@sanity/presentation-comlink";
5
- type LivePerspective = "checking" | "unknown" | ClientPerspective;
6
- type LiveEnvironment = "checking" | "presentation-iframe" | "presentation-window" | "live" | "static" | "unknown";
7
- /**
8
- * Reports the current draft mode environment.
9
- * Use it to determine how to adapt the UI based on wether:
10
- * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.
11
- * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.
12
- * - Your app is live previewing drafts in a standalone context.
13
- * - Your app is previewing drafts, but not live.
14
- * - Your app is not previewing anything (that could be detected).
15
- * @public
16
- */
17
- declare function useDraftModeEnvironment(): LiveEnvironment;
18
- /**
19
- * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.
20
- * If the hook is used outside Draft Mode it will resolve to `'unknown'`.
21
- * 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.
22
- * @public
23
- */
24
- declare function useDraftModePerspective(): LivePerspective;
25
- /**
26
- * Detects if the application is being previewed inside Sanity Presentation Tool.
27
- * Presentation Tool can open the application in an iframe, or in a new window.
28
- * When in this context there are some UI you usually don't want to show,
29
- * for example a Draft Mode toggle, or a "Viewing draft content" indicators, these are unnecessary and add clutter to
30
- * the editorial experience.
31
- * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,
32
- * then `true` if it is, and `false` otherwise.
33
- * @public
34
- */
35
- declare function useIsPresentationTool(): boolean | null;
36
3
  /**
37
4
  * Detects if the application is considered to be in a "Live Preview" mode.
38
5
  * Live Preview means that the application is either:
@@ -49,6 +16,7 @@ declare function useIsPresentationTool(): boolean | null;
49
16
  * @public
50
17
  */
51
18
  declare function useIsLivePreview(): boolean | null;
19
+ declare function useLiveEnvironment(): null;
52
20
  /** @alpha */
53
21
  type UsePresentationQueryReturnsInactive = {
54
22
  data: null;
@@ -75,5 +43,18 @@ declare function usePresentationQuery<const QueryString extends string>(props: {
75
43
  params?: QueryParams | Promise<QueryParams>;
76
44
  stega?: boolean;
77
45
  }): UsePresentationQueryReturns<QueryString>;
78
- export { UsePresentationQueryReturns, UsePresentationQueryReturnsActive, UsePresentationQueryReturnsInactive, useDraftModeEnvironment, useDraftModePerspective, useIsLivePreview, useIsPresentationTool, useOptimistic, usePresentationQuery };
46
+ /**
47
+ * Detects if the application is being previewed inside Sanity Presentation Tool.
48
+ * Presentation Tool can open the application in an iframe, or in a new window.
49
+ * When in this context there are some UI you usually don't want to show,
50
+ * for example a Draft Mode toggle, or a "Viewing draft content" indicators, these are unnecessary and add clutter to
51
+ * the editorial experience.
52
+ * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,
53
+ * then `true` if it is, and `false` otherwise.
54
+ * @public
55
+ */
56
+ declare function useIsPresentationTool(): boolean | null;
57
+ type VisualEditingEnvironment = null | "unknown" | "presentation-iframe" | "presentation-window" | "standalone";
58
+ declare function useVisualEditingEnvironment(): VisualEditingEnvironment;
59
+ export { UsePresentationQueryReturns, UsePresentationQueryReturnsActive, UsePresentationQueryReturnsInactive, useIsLivePreview, useIsPresentationTool, useLiveEnvironment, useOptimistic, usePresentationQuery, useVisualEditingEnvironment };
79
60
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/live/shared/context.ts","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;;;KAIY,eAAA,4BAA2C;KAY3C,eAAA;;;;;AAZZ;AAYA;;ACIA;AAmBA;;AC3BgB,iBDQA,uBAAA,CAAA,CCRA,EDQ2B,eCR3B;;ACKhB;;ACDA;AAOA;;AACQ,iBHeQ,uBAAA,CAAA,CGfR,EHemC,eGfnC;;;;;;AJpBR;AAYA;;ACIA;AAmBA;iBC3BgB,qBAAA,CAAA;;;;;;AFRhB;AAYA;;ACIA;AAmBA;;AC3BA;;ACKA;;ACDY,iBDCI,gBAAA,CAAA,CCDJ,EAAA,OAAA,GAAA,IAAA;;KAAA,mCAAA;;;EJZZ,WAAY,EAAA,IAAA;AAYZ,CAAA;;ACIgB,KGGJ,iCHH+B,CAAA,oBAAA,MAAA,CAAA,GAAA;EAmB3C,IAAgB,EGfR,YHeQ,CGfK,WHeL,CAAA;aGdH;EFbb,WAAgB,EEcD,iBFdC;;ACKA,KCYJ,2BDZI,CAAA,oBAAA,MAAA,CAAA,GCaZ,mCDbY,GCcZ,iCDdY,CCcsB,WDdtB,CAAA;;ACDhB;AAOA;;;;;;AAMY,iBAyDI,oBAzDJ,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EACR,KAAA,EAyDK,WAzDL;EACkC,MAAA,CAAA,EAyD3B,WAzD2B,GAyDb,OAzDa,CAyDL,WAzDK,CAAA;EAAlC,KAAA,CAAA,EAAA,OAAA;CAAA,CAAA,EA2DA,2BA3DA,CA2D4B,WA3D5B,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/hooks/useIsLivePreview.ts","../../src/live/hooks/useLiveEnvironment.ts","../../src/live/hooks/usePresentationQuery.ts","../../src/visual-editing/hooks/useIsPresentationTool.ts","../../src/visual-editing/hooks/useVisualEditingEnvironment.ts"],"sourcesContent":[],"mappings":";;;;;AAeA;;ACfA;;ACeA;AAOA;;;;;;AAMA;AACI,iBFdY,gBAAA,CAAA,CEcZ,EAAA,OAAA,GAAA,IAAA;iBD7BY,kBAAA,CAAA;;KCeJ,mCAAA;EFAZ,IAAgB,EAAA,IAAA;;ECfhB,WAAgB,EAAA,IAAA;;ACehB;AAOY,KAAA,iCAAA,CAAA,oBAAA,MAAA,CAAA,GAAA;EACS,IAAA,EAAb,YAAa,CAAA,WAAA,CAAA;EAAb,SAAA,EACK,gBADL,GAAA,IAAA;EACK,WAAA,EACE,iBADF;CACE;AAAA,KAGH,2BAHG,CAAA,oBAAA,MAAA,CAAA,GAIX,mCAJW,GAKX,iCALW,CAKuB,WALvB,CAAA;AAGf;;;;;AAyDA;;;AAEiC,iBAFjB,oBAEiB,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EAAR,KAAA,EADhB,WACgB;EAEO,MAAA,CAAA,EAFrB,WAEqB,GAFP,OAEO,CAFC,WAED,CAAA;EAA5B,KAAA,CAAA,EAAA,OAAA;CAAA,CAAA,EAAA,2BAAA,CAA4B,WAA5B,CAAA;;;;AF1EJ;;ACfA;;ACeA;AAOA;;AACQ,iBCbQ,qBAAA,CAAA,CDaR,EAAA,OAAA,GAAA,IAAA;KEvBH,wBAAA;iBAOW,2BAAA,CAAA,GAA+B"}
@@ -1,28 +1,16 @@
1
1
  "use client";
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";
2
+ import { a as comlinkProjectId, i as comlinkPerspective, n as comlinkDataset, r as comlinkListeners, t as comlink } from "../context.js";
4
3
  import { stegaEncodeSourceMap } from "@sanity/client/stega";
5
4
  import { dequal } from "dequal/lite";
5
+ import { useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
6
6
  import { useOptimistic } from "@sanity/visual-editing/react";
7
- function useDraftModeEnvironment() {
8
- return useSyncExternalStore(useCallback((listener) => {
9
- environmentListeners.add(listener);
10
- return () => environmentListeners.delete(listener);
11
- }, []), () => environment, () => "checking");
12
- }
13
- function useDraftModePerspective() {
14
- return useSyncExternalStore(useCallback((listener) => {
15
- perspectiveListeners.add(listener);
16
- return () => perspectiveListeners.delete(listener);
17
- }, []), () => perspective, () => "checking");
18
- }
19
- function useIsPresentationTool() {
20
- const environment$1 = useDraftModeEnvironment();
21
- return environment$1 === "checking" ? null : environment$1 === "presentation-iframe" || environment$1 === "presentation-window";
22
- }
23
7
  function useIsLivePreview() {
24
- const environment$1 = useDraftModeEnvironment();
25
- return environment$1 === "checking" ? null : environment$1 === "presentation-iframe" || environment$1 === "presentation-window" || environment$1 === "live";
8
+ console.log("TODO: Implement useIsLivePreview");
9
+ return null;
10
+ }
11
+ function useLiveEnvironment() {
12
+ console.log("TODO: Implement useLiveEnvironment");
13
+ return null;
26
14
  }
27
15
  function reducer(state, { type, payload }) {
28
16
  switch (type) {
@@ -52,21 +40,21 @@ function usePresentationQuery(props) {
52
40
  const comlink$1 = useSyncExternalStore(subscribe, () => comlink, () => null);
53
41
  const projectId = useSyncExternalStore(subscribe, () => comlinkProjectId, () => null);
54
42
  const dataset = useSyncExternalStore(subscribe, () => comlinkDataset, () => null);
55
- const perspective$1 = useDraftModePerspective();
43
+ const perspective = useSyncExternalStore(subscribe, () => comlinkPerspective, () => null);
56
44
  const handleQueryHeartbeat = useEffectEvent((comlink$2) => {
57
- if (!projectId || !dataset || !perspective$1) {
45
+ if (!projectId || !dataset || !perspective) {
58
46
  console.warn("usePresentationQuery: projectId, dataset and perspective must be set", {
59
47
  projectId,
60
48
  dataset,
61
- perspective: perspective$1
49
+ perspective
62
50
  });
63
51
  return;
64
52
  }
65
- if (perspective$1 === "checking" || perspective$1 === "unknown") return;
53
+ if (perspective === null) return;
66
54
  comlink$2.post("loader/query-listen", {
67
55
  projectId,
68
56
  dataset,
69
- perspective: perspective$1,
57
+ perspective,
70
58
  query,
71
59
  params,
72
60
  heartbeat: LISTEN_HEARTBEAT_INTERVAL
@@ -112,6 +100,14 @@ function usePresentationQuery(props) {
112
100
  return state;
113
101
  }, [state, stega]);
114
102
  }
115
- export { useDraftModeEnvironment, useDraftModePerspective, useIsLivePreview, useIsPresentationTool, useOptimistic, usePresentationQuery };
103
+ function useIsPresentationTool() {
104
+ console.log("TODO: Implement useIsPresentationTool");
105
+ return null;
106
+ }
107
+ function useVisualEditingEnvironment() {
108
+ console.log("TODO: Implement useVisualEditingEnvironment");
109
+ return null;
110
+ }
111
+ export { useIsLivePreview, useIsPresentationTool, useLiveEnvironment, useOptimistic, usePresentationQuery, useVisualEditingEnvironment };
116
112
 
117
113
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["environment","environment","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 {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type LiveEnvironment,\n type LivePerspective,\n} from '#live/context'\nimport {useCallback, useSyncExternalStore} from 'react'\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(): LiveEnvironment {\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(): LivePerspective {\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 type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from '#live/context'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\n\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 ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\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 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,0BAA2C;AAMzD,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;AASH,SAAgB,0BAA2C;AAMzD,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;;ACexB,SAAS,QACP,OACA,EAAC,MAAM,WACmC;AAC1C,SAAQ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P,MAAM;GACN,SAAS;IACP,MAAM,MAAM;IACZ,WAAW,MAAM,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":["comlink","comlinkSnapshot"],"sources":["../../src/hooks/useIsLivePreview.ts","../../src/live/hooks/useLiveEnvironment.ts","../../src/live/hooks/usePresentationQuery.ts","../../src/visual-editing/hooks/useIsPresentationTool.ts","../../src/visual-editing/hooks/useVisualEditingEnvironment.ts"],"sourcesContent":["/**\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 // oxlint-disable-next-line no-console\n console.log('TODO: Implement useIsLivePreview')\n\n return null\n}\n","export function useLiveEnvironment(): null {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useLiveEnvironment')\n\n return null\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlinkPerspective,\n comlink as comlinkSnapshot,\n} from '#live/context'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\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 ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\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 = useSyncExternalStore(\n subscribe,\n () => comlinkPerspective,\n () => null,\n )\n\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 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 === null) {\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","/**\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 // oxlint-disable-next-line no-console\n console.log('TODO: Implement useIsPresentationTool')\n\n return null\n}\n","type VisualEditingEnvironment =\n | null\n | 'unknown'\n | 'presentation-iframe'\n | 'presentation-window'\n | 'standalone'\n\nexport function useVisualEditingEnvironment(): VisualEditingEnvironment {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useVisualEditingEnvironment')\n\n return null\n}\n"],"mappings":";;;;;;AAeA,SAAgB,mBAAmC;AAEjD,SAAQ,IAAI,mCAAmC;AAE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GACA;GACA;GACD,EACD;GACE,WAAW,MAAM;GACjB,SAAS,MAAM;GACf,OAAO,MAAM;GACb,QAAQ,MAAM;GACf,CACF,CAED,UAAS;GACP,MAAM;GACN,SAAS;IACP,MAAM,MAAM;IACZ,WAAW,MAAM,mBAAmB;IACpC,aAAa,MAAM;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACD,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;;AC1LpB,SAAgB,wBAAwC;AAEtD,SAAQ,IAAI,wCAAwC;AAEpD,QAAO;;ACPT,SAAgB,8BAAwD;AAEtE,SAAQ,IAAI,8CAA8C;AAE1D,QAAO"}
@@ -1,11 +1,8 @@
1
- import { ClientPerspective, InitializedClientConfig, LiveEventGoAway } from "@sanity/client";
1
+ import { InitializedClientConfig, LiveEventGoAway } from "@sanity/client";
2
2
  interface SanityClientConfig extends Pick<InitializedClientConfig, "projectId" | "dataset" | "apiHost" | "apiVersion" | "useProjectHostname" | "token" | "requestTagPrefix"> {}
3
3
  interface SanityLiveProps {
4
4
  config: SanityClientConfig;
5
- /**
6
- * Setting this to 'published' opens one live event connection, setting it to any other value opens both the live event connections if needed
7
- */
8
- perspective: Exclude<ClientPerspective, "raw">;
5
+ includeDrafts?: boolean;
9
6
  onLiveEvent: (tags: string[]) => Promise<void | "refresh">;
10
7
  onLiveEventIncludingDrafts: (tags: string[]) => Promise<void | "refresh">;
11
8
  refreshOnMount?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"sourcesContent":[],"mappings":";UAqBU,kBAAA,SAA2B,KACnC;AADQ,UAWO,eAAA,CAXP;EAWV,MAAiB,EACP,kBADO;EACP;;;EAMyB,WAAA,EAFpB,OAEoB,CAFZ,iBAEY,EAAA,KAAA,CAAA;EACe,WAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GADf,OACe,CAAA,IAAA,GAAA,SAAA,CAAA;EAa7B,0BAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GAb6B,OAa7B,CAAA,IAAA,GAAA,SAAA,CAAA;EAAA,cAAA,CAAA,EAAA,OAAA;;EC7CrB,kBAA6C,CAAA,EAAA,OAAA;;;;;;;;qBD6CxB;;;AA3Cd;AAsBP;AACU,cCzBG,UDyBH,ECzBe,KAAA,CAAM,aDyBrB,CCzBmC,eDyBnC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"sourcesContent":[],"mappings":";UAgBU,kBAAA,SAA2B,KACnC;AADQ,UAWO,eAAA,CAXP;EAWV,MAAiB,EACP,kBADO;EACP,aAAA,CAAA,EAAA,OAAA;EAGyB,WAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GAAA,OAAA,CAAA,IAAA,GAAA,SAAA,CAAA;EACe,0BAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GAAA,OAAA,CAAA,IAAA,GAAA,SAAA,CAAA;EAa7B,cAAA,CAAA,EAAA,OAAA;EAAA,cAAA,CAAA,EAAA,OAAA;;ECrCrB,UAAa,EAAA,MAAgC;;;;;;;qBDqCxB;;;AA5C0D;AA0B/E;AACU,cCpBG,UDoBH,ECpBe,KAAA,CAAM,aDoBrB,CCpBmC,eDoBnC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":[],"mappings":";;iBAWgB,UAAA,SAAmB;EAAnC,WAAgB,EACD,sBADC;EAAmB,UAAA,EAErB,KAAA,CAAM,aAFe,CAED,sBAFC,CAAA;CACpB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":[],"mappings":";;iBAUgB,UAAA,SAAmB;EAAnC,WAAgB,EACD,sBADC;EAAmB,UAAA,EAErB,KAAA,CAAM,aAFe,CAED,sBAFC,CAAA;CACpB"}
@@ -1,7 +1,6 @@
1
1
  import { n as PUBLISHED_SYNC_TAG_PREFIX, r as revalidate, t as DRAFT_SYNC_TAG_PREFIX } from "../../../constants.js";
2
2
  import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
3
3
  import { t as resolvePerspectiveFromCookies } from "../../../resolvePerspectiveFromCookies.js";
4
- import { Suspense } from "react";
5
4
  import { jsx } from "react/jsx-runtime";
6
5
  import { SanityLive } from "next-sanity/live/client-components";
7
6
  import { actionLiveEvent, actionLiveEventIncludingDrafts } from "next-sanity/live/server-actions";
@@ -39,12 +38,12 @@ function defineLive(config) {
39
38
  };
40
39
  };
41
40
  const Live = function Live$1(props) {
42
- const { perspective = "published", onChange = actionLiveEvent, onChangeIncludingDrafts = actionLiveEventIncludingDrafts, refreshOnMount = false, refreshOnFocus = false, refreshOnReconnect = false, requestTag = "next-loader.live.cache-components", onError, onGoAway, intervalOnGoAway } = props;
43
- const includeDrafts = typeof browserToken === "string" && perspective !== "published";
41
+ const { includeDrafts = false, onLiveEvent = actionLiveEvent, onLiveEventIncludingDrafts = actionLiveEventIncludingDrafts, refreshOnMount = false, refreshOnFocus = false, refreshOnReconnect = false, requestTag = "next-loader.live.cache-components", onError, onGoAway, intervalOnGoAway } = props;
42
+ const shouldIncludeDrafts = typeof browserToken === "string" && includeDrafts;
44
43
  const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
45
44
  const { origin } = new URL(client.getUrl("", false));
46
45
  preconnect(origin);
47
- return /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(SanityLive, {
46
+ return /* @__PURE__ */ jsx(SanityLive, {
48
47
  config: {
49
48
  projectId,
50
49
  dataset,
@@ -52,11 +51,11 @@ function defineLive(config) {
52
51
  apiVersion,
53
52
  useProjectHostname,
54
53
  requestTagPrefix,
55
- token: includeDrafts ? browserToken : void 0
54
+ token: shouldIncludeDrafts ? browserToken : void 0
56
55
  },
57
- perspective,
58
- onLiveEvent: onChange,
59
- onLiveEventIncludingDrafts: onChangeIncludingDrafts,
56
+ includeDrafts: shouldIncludeDrafts,
57
+ onLiveEvent,
58
+ onLiveEventIncludingDrafts,
60
59
  requestTag,
61
60
  refreshOnMount,
62
61
  refreshOnFocus,
@@ -64,7 +63,7 @@ function defineLive(config) {
64
63
  onError,
65
64
  onGoAway,
66
65
  intervalOnGoAway
67
- }) });
66
+ });
68
67
  };
69
68
  Live.displayName = "SanityLiveServerComponent";
70
69
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fetch","Live","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions} from '#live/types'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX, revalidate} from '#live/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionLiveEvent, actionLiveEventIncludingDrafts} from 'next-sanity/live/server-actions'\nimport {cacheLife, cacheTag} from 'next/cache'\nimport {Suspense} from 'react'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../react-server/defineLive'\n\nexport function defineLive(config: LiveOptions): {\n sanityFetch: DefinedSanityFetchType\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 console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: true})\n const {token: originalToken} = client.config()\n\n const fetch: DefinedFetchType = async function fetch({\n query,\n params = {},\n perspective = 'published',\n stega = false,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\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 stega,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @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 * userland can still set a shorter revalidate time by calling `cacheLife` themselves.\n */\n cacheLife({revalidate})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n perspective = 'published',\n onChange = actionLiveEvent,\n onChangeIncludingDrafts = actionLiveEventIncludingDrafts,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n onError,\n onGoAway,\n intervalOnGoAway,\n } = props\n\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <Suspense>\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n perspective={perspective}\n onLiveEvent={onChange}\n onLiveEventIncludingDrafts={onChangeIncludingDrafts}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n </Suspense>\n )\n }\n Live.displayName = 'SanityLiveServerComponent'\n\n return {\n sanityFetch: fetch,\n SanityLive: Live,\n }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,WAAW,QAGzB;CACA,MAAM,EAAC,QAAQ,SAAS,aAAa,iBAAgB;AAErD,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAK,CAAC;CAC1E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAE9C,MAAM,QAA0B,eAAeA,QAAM,E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","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/next-js/defineLive.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions} from '#live/types'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX, revalidate} from '#live/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionLiveEvent, actionLiveEventIncludingDrafts} from 'next-sanity/live/server-actions'\nimport {cacheLife, cacheTag} from 'next/cache'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../react-server/defineLive'\n\nexport function defineLive(config: LiveOptions): {\n sanityFetch: DefinedSanityFetchType\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 console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: true})\n const {token: originalToken} = client.config()\n\n const fetch: DefinedFetchType = async function fetch({\n query,\n params = {},\n perspective = 'published',\n stega = false,\n tags: customCacheTags = [],\n requestTag = 'next-loader.fetch.cache-components',\n }) {\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 stega,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? originalToken : serverToken || originalToken, // @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 * userland can still set a shorter revalidate time by calling `cacheLife` themselves.\n */\n cacheLife({revalidate})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n includeDrafts = false,\n onLiveEvent = actionLiveEvent,\n onLiveEventIncludingDrafts = actionLiveEventIncludingDrafts,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag = 'next-loader.live.cache-components',\n onError,\n onGoAway,\n intervalOnGoAway,\n } = props\n\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n onLiveEvent={onLiveEvent}\n onLiveEventIncludingDrafts={onLiveEventIncludingDrafts}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )\n }\n Live.displayName = 'SanityLiveServerComponent'\n\n return {\n sanityFetch: fetch,\n SanityLive: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BAAiB,YAAY;EAEhE,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EAGjB,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAACC,YAAAA;GACC,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA,OAAO,sBAAsB,eAAe,KAAA;IAC7C;GACD,eAAe;GACF;GACe;GAChB;GACI;GACA;GACI;GACX;GACC;GACQ;IAClB;;AAGN,MAAK,cAAc;AAEnB,QAAO;EACL,aAAa;EACb,YAAY;EACb"}
@@ -57,10 +57,9 @@ function defineLive(config) {
57
57
  };
58
58
  };
59
59
  const SanityLive$1 = async function SanityLive$2(props) {
60
- const { onChange = actionLiveEvent, onChangeIncludingDrafts = actionLiveEventIncludingDrafts, refreshOnMount, refreshOnFocus, refreshOnReconnect, requestTag = "next-loader.live", onError, onGoAway, intervalOnGoAway, perspective: _perspective } = props;
60
+ const { includeDrafts = (await draftMode()).isEnabled, onLiveEvent: onChange = actionLiveEvent, onLiveEventIncludingDrafts: onChangeIncludingDrafts = actionLiveEventIncludingDrafts, refreshOnMount, refreshOnFocus, refreshOnReconnect, requestTag = "next-loader.live", onError, onGoAway, intervalOnGoAway, perspective: _perspective } = props;
61
61
  const { projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix } = client.config();
62
- const perspective = _perspective ?? await resolveCookiePerspective();
63
- const includeDrafts = typeof browserToken === "string" && perspective !== "published";
62
+ const shouldIncludeDrafts = typeof browserToken === "string" && includeDrafts;
64
63
  const { origin } = new URL(client.getUrl("", false));
65
64
  preconnect(origin);
66
65
  return /* @__PURE__ */ jsx(SanityLive, {
@@ -71,9 +70,9 @@ function defineLive(config) {
71
70
  apiVersion,
72
71
  useProjectHostname,
73
72
  requestTagPrefix,
74
- token: includeDrafts ? browserToken : void 0
73
+ token: shouldIncludeDrafts ? browserToken : void 0
75
74
  },
76
- perspective: await resolveCookiePerspective(),
75
+ includeDrafts: shouldIncludeDrafts,
77
76
  onLiveEvent: onChange,
78
77
  onLiveEventIncludingDrafts: onChangeIncludingDrafts,
79
78
  requestTag,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sanityFetch","tag","SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import type {DefinedLiveProps, PerspectiveType} from '#live/types'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type QueryParams,\n type SanityClient,\n} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionLiveEvent, actionLiveEventIncludingDrafts} from 'next-sanity/live/server-actions'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps extends DefinedLiveProps {\n /**\n * @defaultValue `automatically resolved`\n */\n perspective?: PerspectiveType\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * @deprecated use `fetch` instead, and define your own `sanityFetch` function with logic for when to toggle `stega` and `perspective`\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * @deprecated use `Live` instead, and define your own `SanityLive` component with logic for when to toggle `perspective`\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n // fetch: DefinedFetchType\n // Live: React.ComponentType<DefinedLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = ['sanity'],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n\n // fetch the tags first, with revalidate to 1s to ensure we get the latest tags, eventually\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n onChange = actionLiveEvent,\n onChangeIncludingDrafts = actionLiveEventIncludingDrafts,\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n requestTag = 'next-loader.live',\n onError,\n onGoAway,\n intervalOnGoAway,\n perspective: _perspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n perspective={await resolveCookiePerspective()}\n onLiveEvent={onChange}\n onLiveEventIncludingDrafts={onChangeIncludingDrafts}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {\n sanityFetch,\n SanityLive,\n }\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;AAwFA,SAAgB,WAAW,QAWzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAA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Aa,oBACb,SACA,UACA,kBACA,aAAa,iBACX;EACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,qBAClE,OAAO,QAAQ;EACjB,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;EACrE,MAAM,gBAAgB,OAAO,iBAAiB,YAAY,gBAAgB;EAG1E,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAClD,aAAW,OAAO;AAElB,SACE,oBAACC,YAAAA;GACC,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA,OAAO,gBAAgB,eAAe,KAAA;IACvC;GACD,aAAa,MAAM,0BAA0B;GAC7C,aAAa;GACb,4BAA4B;GAChB;GACI;GACA;GACI;GACX;GACC;GACQ;IAClB;;AAGN,cAAW,cAAc;AAEzB,QAAO;EACL;EACA,YAAA;EACD;;AAGH,eAAe,2BAAuE;AACpF,SAAQ,MAAM,WAAW,EAAE,aACtB,MAAM,SAAS,EAAE,IAAI,sBAAsB,GAC1C,qBAAqB,MAAM,SAAS,EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
1
+ {"version":3,"file":"index.js","names":["sanityFetch","tag","SanityLive","SanityLiveClientComponent"],"sources":["../../../../src/live/conditions/react-server/defineLive.tsx"],"sourcesContent":["import type {DefinedLiveProps, PerspectiveType} from '#live/types'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type QueryParams,\n type SanityClient,\n} from '@sanity/client'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {SanityLive as SanityLiveClientComponent} from 'next-sanity/live/client-components'\nimport {actionLiveEvent, actionLiveEventIncludingDrafts} from 'next-sanity/live/server-actions'\nimport {cookies, draftMode} from 'next/headers'\nimport {preconnect} from 'react-dom'\n\n/**\n * @public\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n /**\n * Add custom `next.tags` to the underlying fetch request.\n * @see https://nextjs.org/docs/app/api-reference/functions/fetch#optionsnexttags\n * This can be used in conjunction with custom fallback revalidation strategies, as well as with custom Server Actions that mutate data and want to render with fresh data right away (faster than the Live Event latency).\n * @defaultValue `['sanity']`\n */\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n}) => Promise<{\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}>\n\n/**\n * @public\n */\nexport interface DefinedSanityLiveProps extends DefinedLiveProps {\n /**\n * @defaultValue `automatically resolved`\n */\n perspective?: PerspectiveType\n}\n\n/**\n * @public\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Fetch options used by `sanityFetch`\n */\n fetchOptions?: {\n /**\n * Optional, enables time based revalidation in addition to the EventSource connection.\n * @defaultValue `false`\n */\n revalidate?: number | false\n }\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true`\n */\n stega?: boolean\n}\n\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * @deprecated use `fetch` instead, and define your own `sanityFetch` function with logic for when to toggle `stega` and `perspective`\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * @deprecated use `Live` instead, and define your own `SanityLive` component with logic for when to toggle `perspective`\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n // fetch: DefinedFetchType\n // Live: React.ComponentType<DefinedLiveProps>\n} {\n const {\n client: _client,\n serverToken,\n browserToken,\n fetchOptions,\n stega: stegaEnabled = true,\n } = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags = ['sanity'],\n perspective: _perspective,\n tag,\n requestTag = tag ?? 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n tag?: string\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? (await resolveCookiePerspective())\n const useCdn = perspective === 'published'\n const revalidate =\n fetchOptions?.revalidate !== undefined\n ? fetchOptions.revalidate\n : process.env.NODE_ENV === 'production'\n ? false\n : undefined\n\n // fetch the tags first, with revalidate to 1s to ensure we get the latest tags, eventually\n const {syncTags} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega: false,\n returnQuery: false,\n next: {revalidate, tags: [...tags, 'sanity:fetch-sync-tags']},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: [requestTag, 'fetch-sync-tags'].filter(Boolean).join('.'),\n })\n\n const cacheTags = [...tags, ...(syncTags?.map((tag) => `sanity:${tag}`) || [])]\n\n const {result, resultSourceMap} = await client.fetch(query, await params, {\n filterResponse: false,\n perspective: perspective as ClientPerspective,\n stega,\n token: perspective !== 'published' && serverToken ? serverToken : originalToken,\n next: {revalidate, tags: cacheTags},\n useCdn,\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n })\n return {data: result, sourceMap: resultSourceMap || null, tags: cacheTags}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = async function SanityLive(props) {\n const {\n includeDrafts = (await draftMode()).isEnabled,\n onLiveEvent: onChange = actionLiveEvent,\n onLiveEventIncludingDrafts: onChangeIncludingDrafts = actionLiveEventIncludingDrafts,\n refreshOnMount,\n refreshOnFocus,\n refreshOnReconnect,\n requestTag = 'next-loader.live',\n onError,\n onGoAway,\n intervalOnGoAway,\n perspective: _perspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const shouldIncludeDrafts = typeof browserToken === 'string' && includeDrafts\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n const {origin} = new URL(client.getUrl('', false))\n preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: shouldIncludeDrafts ? browserToken : undefined,\n }}\n includeDrafts={shouldIncludeDrafts}\n onLiveEvent={onChange}\n onLiveEventIncludingDrafts={onChangeIncludingDrafts}\n requestTag={requestTag}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n />\n )\n }\n SanityLive.displayName = 'SanityLiveServerComponent'\n\n return {\n sanityFetch,\n SanityLive,\n }\n}\n\nasync function resolveCookiePerspective(): Promise<Exclude<ClientPerspective, 'raw'>> {\n return (await draftMode()).isEnabled\n ? (await cookies()).has(perspectiveCookieName)\n ? sanitizePerspective((await cookies()).get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n : 'published'\n}\n"],"mappings":";;;;;;;;;AAwFA,SAAgB,WAAW,QAWzB;CACA,MAAM,EACJ,QAAQ,SACR,aACA,cACA,cACA,OAAO,eAAe,SACpB;AAEJ,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,oDAAoD;AAGtE,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,eAAe,gBAAgB,MAC3E,SAAQ,KACN,8LACD;AAGH,KAAI,QAAQ,IAAI,aAAa,gBAAgB,CAAC,gBAAgB,iBAAiB,MAC7E,SAAQ,KACN,iXACD;CAGH,MAAM,SAAS,QAAQ,WAAW;EAAC,kBAAkB;EAAO,QAAQ;EAAM,CAAC;CAC3E,MAAM,EAAC,OAAO,kBAAiB,OAAO,QAAQ;CAC9C,MAAM,mBAAmB,OAAO,OAAO,QAAQ,CAAC,MAAM,cAAc;CAEpE,MAAM,cAAsC,eAAeA,cAEzD,EACA,OACA,SAAS,EAAE,EACX,OAAO,QACP,OAAO,CAAC,SAAS,EACjB,aAAa,cACb,KACA,aAAa,OAAO,uBASnB;EACD,MAAM,QAAQ,WAAW,gBAAgB,qBAAqB,MAAM,WAAW,EAAE;EACjF,MAAM,cAAc,gBAAiB,MAAM,0BAA0B;EACrE,MAAM,SAAS,gBAAgB;EAC/B,MAAM,aACJ,cAAc,eAAe,KAAA,IACzB,aAAa,aACb,QAAQ,IAAI,aAAa,eACvB,QACA,KAAA;EAGR,MAAM,EAAC,aAAY,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;GACzD,gBAAgB;GACH;GACb,OAAO;GACP,aAAa;GACb,MAAM;IAAC;IAAY,MAAM,CAAC,GAAG,MAAM,yBAAyB;IAAC;GAC7D;GACA,WAA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EAAE,IAAI,sBAAsB,EAAE,OAAO,SAAS,GAClF,WACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "13.0.0-cache-components.17",
3
+ "version": "13.0.0-cache-components.19",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "live",
@@ -30,9 +30,9 @@
30
30
  "types": "./dist/index.d.ts",
31
31
  "imports": {
32
32
  "#env": {
33
- "next-js": "./src/env/next-js.ts",
34
- "react-server": "./src/env/react-server.ts",
35
- "default": "./src/env/default.ts"
33
+ "next-js": "./src/_env/next-js.ts",
34
+ "react-server": "./src/_env/react-server.ts",
35
+ "default": "./src/_env/default.ts"
36
36
  },
37
37
  "#live/*": "./src/live/shared/*.ts"
38
38
  },
@@ -68,7 +68,7 @@
68
68
  "@sanity/preview-url-secret": "^4.0.2",
69
69
  "@sanity/visual-editing": "^5.1.0",
70
70
  "dequal": "^2.0.3",
71
- "groq": "^5.2.0",
71
+ "groq": "^5.3.0",
72
72
  "history": "^5.3.0"
73
73
  },
74
74
  "devDependencies": {
@@ -76,7 +76,7 @@
76
76
  "@sanity/tsconfig": "^2.1.0",
77
77
  "@sanity/webhook": "4.0.4",
78
78
  "@types/js-yaml": "^4.0.9",
79
- "@types/node": "^24.10.7",
79
+ "@types/node": "^24.10.8",
80
80
  "@types/react": "^19.2.8",
81
81
  "@types/react-dom": "^19.2.3",
82
82
  "@vitejs/plugin-react": "^5.1.2",
@@ -97,7 +97,7 @@
97
97
  "next": "^16.0.0-0",
98
98
  "react": "^19.2.3",
99
99
  "react-dom": "^19.2.3",
100
- "sanity": "^5.2.0",
100
+ "sanity": "^5.3.0",
101
101
  "styled-components": "^6.1"
102
102
  },
103
103
  "browserslist": "extends @sanity/browserslist-config",