next-sanity 13.0.0-cache-components.9 → 13.0.0-cache-components.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NextStudioNoScript.js.map +1 -1
- package/dist/PresentationComlink.js +6 -6
- package/dist/PresentationComlink.js.map +1 -1
- package/dist/PresentationComlink2.js +7 -7
- package/dist/PresentationComlink2.js.map +1 -1
- package/dist/context.js +29 -0
- package/dist/context.js.map +1 -0
- package/dist/defineLive.d.ts +142 -1
- package/dist/defineLive.d.ts.map +1 -1
- package/dist/experimental/client-components/live.js +5 -5
- package/dist/experimental/client-components/live.js.map +1 -1
- package/dist/hooks/index.d.ts +4 -1
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +1 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/image/index.d.ts.map +1 -1
- package/dist/image/index.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/isCorsOriginError.d.ts +5 -0
- package/dist/isCorsOriginError.d.ts.map +1 -0
- package/dist/isCorsOriginError.js +6 -0
- package/dist/isCorsOriginError.js.map +1 -0
- package/dist/live/client-components/live/index.js +2 -2
- package/dist/live/server-actions/index.js +1 -1
- package/dist/live.d.ts +3 -5
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js +1 -1
- package/dist/live.js.map +1 -1
- package/dist/live.next-js.d.ts +3 -5
- package/dist/live.next-js.d.ts.map +1 -1
- package/dist/live.next-js.js +3 -3
- package/dist/live.next-js.js.map +1 -1
- package/dist/live.react-server.d.ts +3 -5
- package/dist/live.react-server.js +3 -3
- package/dist/resolvePerspectiveFromCookies.js +8 -0
- package/dist/resolvePerspectiveFromCookies.js.map +1 -0
- package/dist/sanitizePerspective.js +14 -0
- package/dist/sanitizePerspective.js.map +1 -0
- package/dist/visual-editing/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NextStudioNoScript.js","names":[
|
|
1
|
+
{"version":3,"file":"NextStudioNoScript.js","names":[],"sources":["../src/studio/NextStudioLayout.tsx","../src/studio/NextStudioNoScript.tsx"],"sourcesContent":["/** @public */\nexport interface NextStudioLayoutProps {\n children: React.ReactNode\n}\n\nconst style = {\n height: '100vh',\n maxHeight: '100dvh',\n overscrollBehavior: 'none',\n WebkitFontSmoothing: 'antialiased',\n overflow: 'auto',\n} satisfies React.CSSProperties\n\n/** @public */\nexport const NextStudioLayout = ({children}: NextStudioLayoutProps): React.JSX.Element => {\n return (\n <div id=\"sanity\" data-ui=\"NextStudioLayout\" style={style}>\n {children}\n </div>\n )\n}\n","const styles: Record<'outer' | 'inner', React.CSSProperties> = {\n outer: {\n position: 'absolute',\n top: 0,\n right: 0,\n left: 0,\n bottom: 0,\n background: '#fff',\n zIndex: 1,\n },\n inner: {\n position: 'absolute',\n top: '50%',\n left: '50%',\n transform: 'translate(-50%, -50%)',\n textAlign: 'center',\n fontFamily: 'helvetica, arial, sans-serif',\n },\n}\n\n/** @internal */\nexport const NextStudioNoScript = (): React.JSX.Element => (\n <noscript>\n <div style={styles.outer}>\n <div style={styles.inner}>\n <h1>JavaScript disabled</h1>\n <p>\n Please <a href=\"https://www.enable-javascript.com/\">enable JavaScript</a> in your browser\n and reload the page to proceed.\n </p>\n </div>\n </div>\n </noscript>\n)\n"],"mappings":";AAKA,MAAM,QAAQ;CACZ,QAAQ;CACR,WAAW;CACX,oBAAoB;CACpB,qBAAqB;CACrB,UAAU;CACX;AAGD,MAAa,oBAAoB,EAAC,eAAwD;AACxF,QACE,oBAAC,OAAA;EAAI,IAAG;EAAS,WAAQ;EAA0B;EAChD;GACG;;AClBV,MAAM,SAAyD;CAC7D,OAAO;EACL,UAAU;EACV,KAAK;EACL,OAAO;EACP,MAAM;EACN,QAAQ;EACR,YAAY;EACZ,QAAQ;EACT;CACD,OAAO;EACL,UAAU;EACV,KAAK;EACL,MAAM;EACN,WAAW;EACX,WAAW;EACX,YAAY;EACb;CACF;AAGD,MAAa,2BACX,oBAAC,YAAA,EAAA,UACC,oBAAC,OAAA;CAAI,OAAO,OAAO;WACjB,qBAAC,OAAA;EAAI,OAAO,OAAO;aACjB,oBAAC,MAAA,EAAA,UAAG,uBAAA,CAAwB,EAC5B,qBAAC,KAAA,EAAA,UAAA;GAAE;GACM,oBAAC,KAAA;IAAE,MAAK;cAAqC;KAAqB;;MAEvE,CAAA;GACA;EACF,EAAA,CACG"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { f as setPerspective, l as setComlink, s as perspective, u as setComlinkClientConfig } from "./context.js";
|
|
2
|
+
import { t as sanitizePerspective } from "./sanitizePerspective.js";
|
|
1
3
|
import { useRouter } from "next/navigation";
|
|
2
|
-
import { perspective, setComlink, setComlinkClientConfig, setPerspective } from "#client-components/context";
|
|
3
4
|
import { startTransition, useEffect, useEffectEvent } from "react";
|
|
4
|
-
import { sanitizePerspective } from "#live/sanitizePerspective";
|
|
5
5
|
import { createCompatibilityActors } from "@sanity/presentation-comlink";
|
|
6
6
|
import { setPerspectiveCookie } from "next-sanity/live/server-actions";
|
|
7
7
|
import { createNode, createNodeMachine } from "@sanity/comlink";
|
|
@@ -22,18 +22,18 @@ function PresentationComlink(props) {
|
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
24
|
useEffect(() => {
|
|
25
|
-
const comlink
|
|
25
|
+
const comlink = createNode({
|
|
26
26
|
name: "loaders",
|
|
27
27
|
connectTo: "presentation"
|
|
28
28
|
}, createNodeMachine().provide({ actors: createCompatibilityActors() }));
|
|
29
29
|
let controller;
|
|
30
|
-
comlink
|
|
30
|
+
comlink.on("loader/perspective", (data) => {
|
|
31
31
|
controller?.abort();
|
|
32
32
|
controller = new AbortController();
|
|
33
33
|
handlePerspectiveChange(data.perspective, controller.signal);
|
|
34
34
|
});
|
|
35
|
-
const stop = comlink
|
|
36
|
-
setComlink(comlink
|
|
35
|
+
const stop = comlink.start();
|
|
36
|
+
setComlink(comlink);
|
|
37
37
|
return () => {
|
|
38
38
|
stop();
|
|
39
39
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PresentationComlink.js","names":[
|
|
1
|
+
{"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/experimental/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n setComlink,\n setComlinkClientConfig,\n setPerspective,\n perspective,\n} from '#client-components/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 {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {startTransition, useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n draftModeEnabled: boolean\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled} = props\n const router = useRouter()\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (_perspective: ClientPerspective, signal: AbortSignal) => {\n const nextPerspective = sanitizePerspective(_perspective, 'drafts')\n if (draftModeEnabled && perspective.toString() !== nextPerspective.toString()) {\n setPerspective(nextPerspective)\n startTransition(() =>\n setPerspectiveCookie(nextPerspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) =>\n console.error('Failed to set the preview perspective cookie', reason),\n ),\n )\n }\n },\n )\n\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n }\n }, [])\n\n return null\n}\n"],"mappings":";;;;;;;AAmBA,SAAwB,oBAAoB,OAIf;CAC3B,MAAM,EAAC,WAAW,SAAS,qBAAoB;CAC/C,MAAM,SAAS,WAAW;AAE1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,cAAiC,WAAwB;EACxD,MAAM,kBAAkB,oBAAoB,cAAc,SAAS;AACnE,MAAI,oBAAoB,YAAY,UAAU,KAAK,gBAAgB,UAAU,EAAE;AAC7E,kBAAe,gBAAgB;AAC/B,yBACE,qBAAqB,gBAAgB,CAClC,WAAW;AACV,QAAI,OAAO,QAAS;AACpB,WAAO,SAAS;KAChB,CACD,OAAO,WACN,QAAQ,MAAM,gDAAgD,OAAO,CACtE,CACJ;;GAGN;AAED,iBAAgB;EACd,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAED,IAAI;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;;IAEP,EAAE,CAAC;AAEN,QAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { l as setComlink, u as setComlinkClientConfig } from "./context.js";
|
|
1
2
|
import { useRouter } from "next/navigation";
|
|
2
|
-
import { setComlink, setComlinkClientConfig } from "#client-components/context";
|
|
3
3
|
import { useEffect, useEffectEvent } from "react";
|
|
4
4
|
import { createCompatibilityActors } from "@sanity/presentation-comlink";
|
|
5
5
|
import { setPerspectiveCookie } from "next-sanity/live/server-actions";
|
|
@@ -10,25 +10,25 @@ function PresentationComlink(props) {
|
|
|
10
10
|
useEffect(() => {
|
|
11
11
|
setComlinkClientConfig(projectId, dataset);
|
|
12
12
|
}, [dataset, projectId]);
|
|
13
|
-
const handlePerspectiveChange = useEffectEvent((perspective
|
|
14
|
-
if (draftModeEnabled && perspective
|
|
13
|
+
const handlePerspectiveChange = useEffectEvent((perspective, signal) => {
|
|
14
|
+
if (draftModeEnabled && perspective !== draftModePerspective) setPerspectiveCookie(perspective).then(() => {
|
|
15
15
|
if (signal.aborted) return;
|
|
16
16
|
router.refresh();
|
|
17
17
|
}).catch((reason) => console.error("Failed to set the preview perspective cookie", reason));
|
|
18
18
|
});
|
|
19
19
|
useEffect(() => {
|
|
20
|
-
const comlink
|
|
20
|
+
const comlink = createNode({
|
|
21
21
|
name: "loaders",
|
|
22
22
|
connectTo: "presentation"
|
|
23
23
|
}, createNodeMachine().provide({ actors: createCompatibilityActors() }));
|
|
24
24
|
let controller;
|
|
25
|
-
comlink
|
|
25
|
+
comlink.on("loader/perspective", (data) => {
|
|
26
26
|
controller?.abort();
|
|
27
27
|
controller = new AbortController();
|
|
28
28
|
handlePerspectiveChange(data.perspective, controller.signal);
|
|
29
29
|
});
|
|
30
|
-
const stop = comlink
|
|
31
|
-
setComlink(comlink
|
|
30
|
+
const stop = comlink.start();
|
|
31
|
+
setComlink(comlink);
|
|
32
32
|
return () => {
|
|
33
33
|
stop();
|
|
34
34
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PresentationComlink2.js","names":[
|
|
1
|
+
{"version":3,"file":"PresentationComlink2.js","names":[],"sources":["../src/live/client-components/live/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {\n createNode,\n createNodeMachine,\n // type Node,\n} from '@sanity/comlink'\nimport {setComlink, setComlinkClientConfig} from '#client-components/context'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {setPerspectiveCookie} from 'next-sanity/live/server-actions'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useEffectEvent} from 'react'\n\nfunction PresentationComlink(props: {\n projectId: string\n dataset: string\n // handleDraftModeAction: (secret: string) => Promise<void | string>\n draftModeEnabled: boolean\n draftModePerspective: ClientPerspective\n}): React.JSX.Element | null {\n const {projectId, dataset, draftModeEnabled, draftModePerspective} = props\n const router = useRouter()\n\n // const [presentationComlink, setPresentationComlink] = useState<Node<\n // LoaderControllerMsg,\n // LoaderNodeMsg\n // > | null>(null)\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent(\n (perspective: ClientPerspective, signal: AbortSignal) => {\n if (draftModeEnabled && perspective !== draftModePerspective) {\n setPerspectiveCookie(perspective)\n .then(() => {\n if (signal.aborted) return\n router.refresh()\n })\n .catch((reason) => console.error('Failed to set the preview perspective cookie', reason))\n }\n },\n )\n\n // const [status, setStatus] = useState('disconnected')\n useEffect(() => {\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n // comlink.onStatus((status) => {\n // setStatus(status)\n // })\n\n let controller: AbortController | undefined\n comlink.on('loader/perspective', (data) => {\n controller?.abort()\n controller = new AbortController()\n handlePerspectiveChange(data.perspective, controller.signal)\n })\n\n const stop = comlink.start()\n // setPresentationComlink(comlink)\n setComlink(comlink)\n // console.log('setting comlink', comlink)\n return () => {\n // console.log('stopping comlink')\n stop()\n }\n }, [])\n\n // @TODO come back to this later\n // const handleEnableDraftMode = useEffectEvent(async (signal: AbortSignal) => {\n // if (signal.aborted) return\n // const {secret} = await (presentationComlink?.fetch(\n // {\n // type: 'loader/fetch-preview-url-secret' as const,\n // data: {projectId, dataset},\n // },\n // {signal},\n // ) || {secret: null})\n // if (signal.aborted) return\n // const error = await handleDraftModeAction(secret!)\n // // eslint-disable-next-line no-console\n // // @TODO call another server action here that can tell us if draft mode is actually enabled\n // if (error) {\n // // @TODO use sonnet or whatever to push a toast with the error\n // // eslint-disable-next-line no-console\n // console.error('Error enabling draft mode', error)\n // return\n // }\n // // console.log('Draft mode enabled?', {enabled})\n // if (signal.aborted) return\n // router.refresh()\n // })\n // const connected = status === 'connected'\n // useEffect(() => {\n // if (connected && !draftModeEnabled) {\n // const controller = new AbortController()\n // handleEnableDraftMode(controller.signal).catch((reason) => {\n // // eslint-disable-next-line no-console\n // console.error('Failed to enable draft mode', reason)\n // return handleEnableDraftMode(controller.signal)\n // })\n // return () => {\n // controller.abort()\n // }\n // }\n // return undefined\n // }, [connected, draftModeEnabled, handleEnableDraftMode])\n\n return null\n}\nPresentationComlink.displayName = 'PresentationComlink'\n\nexport default PresentationComlink\n"],"mappings":";;;;;;AAiBA,SAAS,oBAAoB,OAMA;CAC3B,MAAM,EAAC,WAAW,SAAS,kBAAkB,yBAAwB;CACrE,MAAM,SAAS,WAAW;AAO1B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAC7B,aAAgC,WAAwB;AACvD,MAAI,oBAAoB,gBAAgB,qBACtC,sBAAqB,YAAY,CAC9B,WAAW;AACV,OAAI,OAAO,QAAS;AACpB,UAAO,SAAS;IAChB,CACD,OAAO,WAAW,QAAQ,MAAM,gDAAgD,OAAO,CAAC;GAGhG;AAGD,iBAAgB;EACd,MAAM,UAAU,WACd;GACE,MAAM;GACN,WAAW;GACZ,EACD,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;EAMD,IAAI;AACJ,UAAQ,GAAG,uBAAuB,SAAS;AACzC,eAAY,OAAO;AACnB,gBAAa,IAAI,iBAAiB;AAClC,2BAAwB,KAAK,aAAa,WAAW,OAAO;IAC5D;EAEF,MAAM,OAAO,QAAQ,OAAO;AAE5B,aAAW,QAAQ;AAEnB,eAAa;AAEX,SAAM;;IAEP,EAAE,CAAC;AA0CN,QAAO;;AAET,oBAAoB,cAAc;AAElC,IAAA,8BAAe"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
const comlinkListeners = /* @__PURE__ */ new Set();
|
|
15
|
+
let comlink = null;
|
|
16
|
+
let comlinkProjectId = null;
|
|
17
|
+
let comlinkDataset = null;
|
|
18
|
+
function setComlink(nextComlink) {
|
|
19
|
+
comlink = nextComlink;
|
|
20
|
+
for (const onComlinkChange of comlinkListeners) onComlinkChange();
|
|
21
|
+
}
|
|
22
|
+
function setComlinkClientConfig(nextComlinkProjectId, nextComlinkDataset) {
|
|
23
|
+
comlinkProjectId = nextComlinkProjectId;
|
|
24
|
+
comlinkDataset = nextComlinkDataset;
|
|
25
|
+
for (const onComlinkChange of comlinkListeners) onComlinkChange();
|
|
26
|
+
}
|
|
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 };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/shared/client-components/context.tsx"],"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"}
|
package/dist/defineLive.d.ts
CHANGED
|
@@ -1,4 +1,145 @@
|
|
|
1
|
+
import { cookies } from "next/headers";
|
|
1
2
|
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "@sanity/client";
|
|
3
|
+
import { ClientPerspective as ClientPerspective$1, ClientReturn as ClientReturn$1, ContentSourceMap as ContentSourceMap$1, LiveEventGoAway as LiveEventGoAway$1, QueryParams as QueryParams$1, SanityClient as SanityClient$1 } from "next-sanity";
|
|
4
|
+
type ResolvePerspectiveFromCookies = (options: {
|
|
5
|
+
/**
|
|
6
|
+
* You must await the cookies() function from next/headers
|
|
7
|
+
* and pass it here.
|
|
8
|
+
* Example:
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { cookies } from 'next/headers'
|
|
11
|
+
*
|
|
12
|
+
* const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
16
|
+
}) => Promise<Exclude<ClientPerspective, "raw">>;
|
|
17
|
+
/**
|
|
18
|
+
* Resolves the perspective from the cookie that is set by `import { defineEnableDraftMode } from "next-sanity/draft-mode"`
|
|
19
|
+
* @public
|
|
20
|
+
*/
|
|
21
|
+
declare const resolvePerspectiveFromCookies: ({
|
|
22
|
+
cookies: jar
|
|
23
|
+
}: {
|
|
24
|
+
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
25
|
+
}) => Promise<Exclude<ClientPerspective, "raw">>;
|
|
26
|
+
/**
|
|
27
|
+
* Perspectives supported by Sanity Live.
|
|
28
|
+
* Using the legacy `'raw'` perspective is not supported and leads to undefined behavior.
|
|
29
|
+
*/
|
|
30
|
+
type PerspectiveType = Exclude<ClientPerspective$1, "raw">;
|
|
31
|
+
/**
|
|
32
|
+
* TODO: docs
|
|
33
|
+
*/
|
|
34
|
+
type DefinedFetchType = <const QueryString extends string>(options: {
|
|
35
|
+
query: QueryString;
|
|
36
|
+
params?: QueryParams$1;
|
|
37
|
+
/**
|
|
38
|
+
* @defaultValue 'published'
|
|
39
|
+
*/
|
|
40
|
+
perspective?: PerspectiveType;
|
|
41
|
+
/**
|
|
42
|
+
* Enables stega encoding of the data, this is typically only used in draft mode in conjunction with `perspective: 'drafts'` and with `@sanity/visual-editing` setup.
|
|
43
|
+
* @defaultValue `false`
|
|
44
|
+
*/
|
|
45
|
+
stega?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Custom cache tags that can be used with next's `updateTag` functions for custom `read-your-write` server actions,
|
|
48
|
+
* for example a like button that uses client.mutate to update a document and then immediately shows the result.
|
|
49
|
+
*/
|
|
50
|
+
tags?: string[];
|
|
51
|
+
/**
|
|
52
|
+
* This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.
|
|
53
|
+
* @see https://www.sanity.io/docs/reference-api-request-tags
|
|
54
|
+
* @defaultValue 'next-loader.fetch'
|
|
55
|
+
*/
|
|
56
|
+
requestTag?: string;
|
|
57
|
+
}) => Promise<{
|
|
58
|
+
data: ClientReturn$1<QueryString, unknown>;
|
|
59
|
+
sourceMap: ContentSourceMap$1 | null;
|
|
60
|
+
tags: string[];
|
|
61
|
+
}>;
|
|
62
|
+
interface DefinedLiveProps {
|
|
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.
|
|
66
|
+
*/
|
|
67
|
+
perspective?: PerspectiveType;
|
|
68
|
+
/**
|
|
69
|
+
* TODO: If Presentation Tool is present this event will fire with the current `perspective` stack used in the
|
|
70
|
+
* Sanity Studio global perspective menu. The default event handler will store this state in a cookie,
|
|
71
|
+
* which can be read with `resolvePerspectiveFromCookies` and used to ensure data fetching in the preview
|
|
72
|
+
* matches the perspective and content viewed in the Studio, allowing you to quickly switch and preview different perspectives.
|
|
73
|
+
*/
|
|
74
|
+
onStudioPerspective?: (perspective: PerspectiveType) => void;
|
|
75
|
+
/**
|
|
76
|
+
* Automatic refresh of RSC when the component <SanityLive /> is mounted.
|
|
77
|
+
* @defaultValue `false`
|
|
78
|
+
*/
|
|
79
|
+
refreshOnMount?: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Automatically refresh when window gets focused
|
|
82
|
+
* @defaultValue `false`
|
|
83
|
+
*/
|
|
84
|
+
refreshOnFocus?: boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Automatically refresh when the browser regains a network connection (via navigator.onLine)
|
|
87
|
+
* @defaultValue `false`
|
|
88
|
+
*/
|
|
89
|
+
refreshOnReconnect?: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.
|
|
92
|
+
* This typically happens if the connection limit is reached, or if the connection is idle for too long.
|
|
93
|
+
* To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.
|
|
94
|
+
* You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.
|
|
95
|
+
* @defaultValue `30_000` 30 seconds interval
|
|
96
|
+
*/
|
|
97
|
+
intervalOnGoAway?: number | false;
|
|
98
|
+
/**
|
|
99
|
+
* This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.
|
|
100
|
+
* @see https://www.sanity.io/docs/reference-api-request-tags
|
|
101
|
+
* @defaultValue 'next-loader.live'
|
|
102
|
+
*/
|
|
103
|
+
requestTag?: string;
|
|
104
|
+
/**
|
|
105
|
+
* Handle errors from the Live Events subscription.
|
|
106
|
+
* By default it's reported using `console.error`, you can override this prop to handle it in your own way.
|
|
107
|
+
*/
|
|
108
|
+
onError?: (error: unknown) => void;
|
|
109
|
+
/**
|
|
110
|
+
* Handle the `goaway` event if the connection is rejected/closed.
|
|
111
|
+
* `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.
|
|
112
|
+
* When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.
|
|
113
|
+
* If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.
|
|
114
|
+
*/
|
|
115
|
+
onGoAway?: (event: LiveEventGoAway$1, intervalOnGoAway: number | false) => void;
|
|
116
|
+
/**
|
|
117
|
+
* TODO: docs, this handles events for published content only, and can be used to revalidate content for all your users when in presentation tool
|
|
118
|
+
*/
|
|
119
|
+
onChange?: (tags: string[]) => Promise<void | "refresh">;
|
|
120
|
+
/**
|
|
121
|
+
* TODO: docs, this handles events for all changes, published, drafts and even version documents in content releases.
|
|
122
|
+
* It's only used when `browserToken` is provided, and the `perspective` prop is other than `"published"`.
|
|
123
|
+
* 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.
|
|
124
|
+
*/
|
|
125
|
+
onChangeIncludingDrafts?: (tags: string[]) => Promise<void | "refresh">;
|
|
126
|
+
}
|
|
127
|
+
interface LiveOptions {
|
|
128
|
+
/**
|
|
129
|
+
* Required for `fetch()` and `<Live>` to work
|
|
130
|
+
*/
|
|
131
|
+
client: SanityClient$1;
|
|
132
|
+
/**
|
|
133
|
+
* Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.
|
|
134
|
+
* This token is never shared with the browser, unless you reuse it in `browserToken`..
|
|
135
|
+
*/
|
|
136
|
+
serverToken?: string | false;
|
|
137
|
+
/**
|
|
138
|
+
* Optional. This token is shared with the browser when `<Live>` is given a `perspective` prop other than `"published"`, and should only have access to query published documents.
|
|
139
|
+
* It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.
|
|
140
|
+
*/
|
|
141
|
+
browserToken?: string | false;
|
|
142
|
+
}
|
|
2
143
|
/**
|
|
3
144
|
* @public
|
|
4
145
|
*/
|
|
@@ -123,5 +264,5 @@ declare function defineLive(config: DefineSanityLiveOptions): {
|
|
|
123
264
|
*/
|
|
124
265
|
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
125
266
|
};
|
|
126
|
-
export { defineLive as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
|
|
267
|
+
export { DefinedFetchType as a, PerspectiveType as c, defineLive as i, ResolvePerspectiveFromCookies as l, DefinedSanityFetchType as n, DefinedLiveProps as o, DefinedSanityLiveProps as r, LiveOptions as s, DefineSanityLiveOptions as t, resolvePerspectiveFromCookies as u };
|
|
127
268
|
//# sourceMappingURL=defineLive.d.ts.map
|
package/dist/defineLive.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/shared/live/resolvePerspectiveFromCookies.ts","../src/shared/live/types.ts","../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":";;;KAMY,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,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CEKc,WFLd,CAAA;EAAR;;;;;AAOX;EACW,IAAA,CAAA,EAAA,MAAA,EAAA;EAE0B,WAAA,CAAA,EEGrB,OFHqB,CEGb,iBFHa,EAAA,KAAA,CAAA;EAAlB,KAAA,CAAA,EAAA,OAAA;EAAR;;;;;;ACdX,CAAA,EAAA,GCyBM,ODzBM,CAAA;EAKZ,IAAY,ECqBJ,YDrBI,CCqBS,WDrBT,CAAA;EACH,SAAA,ECqBI,gBDrBJ,GAAA,IAAA;EACE,IAAA,EAAA,MAAA,EAAA;CAIK,CAAA;;;;AAiBV,UCMW,sBAAA,CDNX;EAAA;AAMN;;;;EA+DiC,cAAA,CAAA,EAAA,OAAA;EAOe;;AAGhD;;ACpGA;EACS,cAAA,CAAA,EAAA,OAAA;EACE;;;;;EAiBU,kBAAA,CAAA,EAAA,OAAA;EAAb;;;;AAQR;;;EAqD4C,gBAAA,CAAA,EAAA,MAAA,GAAA,KAAA;EAAA;AAM5C;AAgCA;;;EAQkC,UAAA,CAAA,EAAA,MAAA;EAApB;;;;;;;;;;;qBApDO;;;;;8BAMS,cAAc;;;;;UAM3B,uBAAA;;;;UAIP;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4BM,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { d as setEnvironment, f as setPerspective } from "../../context.js";
|
|
3
|
+
import { t as isCorsOriginError } from "../../isCorsOriginError.js";
|
|
4
|
+
import { t as sanitizePerspective } from "../../sanitizePerspective.js";
|
|
2
5
|
import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
3
6
|
import { useRouter } from "next/navigation";
|
|
4
|
-
import { setEnvironment, setPerspective } from "#client-components/context";
|
|
5
7
|
import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
|
6
8
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
7
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
8
|
-
import { sanitizePerspective } from "#live/sanitizePerspective";
|
|
9
9
|
import { createClient } from "@sanity/client";
|
|
10
10
|
import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
|
|
11
11
|
import { expireTags } from "next-sanity/live/server-actions";
|
|
@@ -103,10 +103,10 @@ function SanityLive(props) {
|
|
|
103
103
|
return;
|
|
104
104
|
}
|
|
105
105
|
const controller = new AbortController();
|
|
106
|
-
resolveDraftModePerspective().then((perspective
|
|
106
|
+
resolveDraftModePerspective().then((perspective) => {
|
|
107
107
|
if (controller.signal.aborted) return;
|
|
108
108
|
setResolvedInitialPerspective(true);
|
|
109
|
-
setPerspective(sanitizePerspective(perspective
|
|
109
|
+
setPerspective(sanitizePerspective(perspective, "drafts"));
|
|
110
110
|
}).catch((err) => {
|
|
111
111
|
if (controller.signal.aborted) return;
|
|
112
112
|
console.error("Failed to resolve draft mode perspective", err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":["revalidateSyncTags","perspective"],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {setEnvironment, setPerspective} from '#client-components/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {expireTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\n\nimport type {SanityClientConfig} from '../types'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags?: (tags: string[]) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\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\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags = expireTags,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n void revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnRecon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B,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
|
|
1
|
+
{"version":3,"file":"live.js","names":["revalidateSyncTags"],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {setEnvironment, setPerspective} from '#client-components/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {expireTags} from 'next-sanity/live/server-actions'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\n\nimport type {SanityClientConfig} from '../types'\n\nimport {PUBLISHED_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags?: (tags: string[]) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\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\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags = expireTags,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n void revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAA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kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { LiveEnvironment, LivePerspective } from "#client-components/context";
|
|
2
1
|
import { useOptimistic } from "@sanity/visual-editing/react";
|
|
3
2
|
import { ClientPerspective, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
|
|
3
|
+
import "@sanity/presentation-comlink";
|
|
4
|
+
import "@sanity/comlink";
|
|
5
|
+
type LivePerspective = "checking" | "unknown" | ClientPerspective;
|
|
6
|
+
type LiveEnvironment = "checking" | "presentation-iframe" | "presentation-window" | "live" | "static" | "unknown";
|
|
4
7
|
/**
|
|
5
8
|
* Reports the current draft mode environment.
|
|
6
9
|
* Use it to determine how to adapt the UI based on wether:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/shared/client-components/context.tsx","../../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"}
|
package/dist/hooks/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
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
3
|
import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
|
|
4
4
|
import { stegaEncodeSourceMap } from "@sanity/client/stega";
|
|
5
5
|
import { dequal } from "dequal/lite";
|
package/dist/hooks/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["environment","environment","initialState: UsePresentationQueryReturnsInactive","EMPTY_QUERY_PARAMS: QueryParams","comlink","comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type LiveEnvironment,\n type LivePerspective,\n} from '#client-components/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 '#client-components/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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U,qBACd,iBACM,sBACA,KACP;CAID,MAAMC,gBAAc,yBAAyB;CAC7C,MAAM,uBAAuB,gBAAgB,cAAiD;AAE5F,MAAI,CAAC,aAAa,CAAC,WAAW,CAACA,eAAa;AAC1C,WAAQ,KAAK,wEAAwE;IACnF;IACA;IACA,aAAA;IACD,CAAC;AACF;;AAGF,MAAIA,kBAAgB,cAAcA,kBAAgB,UAChD;AAEF,YAAQ,KAAK,uBAAuB;GAClC;GACA;GACA,aAAA;GACA;GACA;GACA,WAAW;GACZ,CAAC;GACF;CACF,MAAM,oBAAoB,gBACvB,UAA+E;AAC9E,MACE,OACE;GACE;GACA;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,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["environment","environment","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 '#client-components/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 '#client-components/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;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MAAMC,gBAAc,yBAAyB;CAC7C,MAAM,uBAAuB,gBAAgB,cAAiD;AAE5F,MAAI,CAAC,aAAa,CAAC,WAAW,CAACA,eAAa;AAC1C,WAAQ,KAAK,wEAAwE;IACnF;IACA;IACA,aAAA;IACD,CAAC;AACF;;AAGF,MAAIA,kBAAgB,cAAcA,kBAAgB,UAChD;AAEF,YAAQ,KAAK,uBAAuB;GAClC;GACA;GACA,aAAA;GACA;GACA;GACA,WAAW;GACZ,CAAC;GACF;CACF,MAAM,oBAAoB,gBACvB,UAA+E;AAC9E,MACE,OACE;GACE;GACA;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,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/image/Image.tsx","../../src/image/imageLoader.ts"],"sourcesContent":[],"mappings":";;AAOA;AAcA;UAdiB,UAAA,SAAmB,KAAK;ECFzC;;;;;;;;;;;;iBDgBgB,KAAA,QAAa,aAAa,KAAA,CAAM,GAAA,CAAI;;AAdpD;AAcA;cChBa,aAAa"}
|
package/dist/image/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/image/imageLoader.ts","../../src/image/Image.tsx"],"sourcesContent":["import type {ImageLoader} from 'next/image'\n\n/**\n * @alpha\n */\nexport const imageLoader: ImageLoader = ({src, width, quality}) => {\n const url = new URL(src)\n url.searchParams.set('auto', 'format')\n if (!url.searchParams.has('fit')) {\n url.searchParams.set('fit', url.searchParams.has('h') ? 'min' : 'max')\n }\n if (url.searchParams.has('h') && url.searchParams.has('w')) {\n const originalHeight = parseInt(url.searchParams.get('h')!, 10)\n const originalWidth = parseInt(url.searchParams.get('w')!, 10)\n url.searchParams.set('h', Math.round((originalHeight / originalWidth) * width).toString())\n }\n url.searchParams.set('w', width.toString())\n if (quality) {\n url.searchParams.set('q', quality.toString())\n }\n return url.href\n}\n","import NextImage, {type ImageProps as NextImageProps} from 'next/image'\n\nimport {imageLoader} from './imageLoader'\n\n/**\n * @alpha\n */\nexport interface ImageProps extends Omit<NextImageProps, 'loader' | 'src'> {\n /**\n * The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.\n */\n loader?: never\n /**\n * Must be a string that is a valid URL to an image on the Sanity Image CDN.\n */\n src: string\n}\n\n/**\n * @alpha\n */\nexport function Image(props: ImageProps): React.JSX.Element {\n const {loader, src, ...rest} = props\n if (loader) {\n throw new TypeError(\n 'The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.',\n )\n }\n let srcUrl: URL\n try {\n srcUrl = new URL(src)\n if (props.height) {\n srcUrl.searchParams.set('h', `${props.height}`)\n }\n if (props.width) {\n srcUrl.searchParams.set('w', `${props.width}`)\n }\n } catch (err) {\n throw new TypeError('The `src` prop must be a valid URL to an image on the Sanity Image CDN.', {\n cause: err,\n })\n }\n return <NextImage {...rest} src={srcUrl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
|
|
1
2
|
import { stegaClean } from "@sanity/client/stega";
|
|
2
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
3
3
|
import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
|
|
4
4
|
import { CreateDataAttribute, CreateDataAttributeProps, createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
|
|
5
5
|
import groq, { defineQuery } from "groq";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
1
2
|
import { stegaClean } from "@sanity/client/stega";
|
|
2
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
3
3
|
import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
|
|
4
4
|
import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
|
|
5
5
|
import groq, { defineQuery } from "groq";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/shared/live/isCorsOriginError.ts"],"sourcesContent":[],"mappings":";;AAGgB,iBAAA,iBAAA,CAA4C,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IAAA,eAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isCorsOriginError.js","names":[],"sources":["../src/shared/live/isCorsOriginError.ts"],"sourcesContent":["import type {CorsOriginError} from '@sanity/client'\n\n/** @public */\nexport function isCorsOriginError(error: unknown): error is CorsOriginError {\n return error instanceof Error && error.name === 'CorsOriginError'\n}\n\nexport type {CorsOriginError}\n"],"mappings":"AAGA,SAAgB,kBAAkB,OAA0C;AAC1E,QAAO,iBAAiB,SAAS,MAAM,SAAS"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { d as setEnvironment, f as setPerspective } from "../../../context.js";
|
|
3
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
2
4
|
import { useRouter } from "next/navigation";
|
|
3
|
-
import { setEnvironment, setPerspective } from "#client-components/context";
|
|
4
5
|
import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
|
5
6
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
7
7
|
import { createClient } from "@sanity/client";
|
|
8
8
|
import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
|
|
9
9
|
import { revalidateSyncTags } from "next-sanity/live/server-actions";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use server";
|
|
2
|
+
import { t as sanitizePerspective } from "../../sanitizePerspective.js";
|
|
2
3
|
import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
3
4
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
4
5
|
import { cookies, draftMode } from "next/headers";
|
|
5
|
-
import { sanitizePerspective } from "#live/sanitizePerspective";
|
|
6
6
|
import { revalidateTag, updateTag } from "next/cache";
|
|
7
7
|
async function revalidateSyncTags(tags) {
|
|
8
8
|
revalidateTag("sanity:fetch-sync-tags", "max");
|
package/dist/live.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { ResolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
|
|
4
|
-
import { DefinedFetchType, DefinedLiveProps, PerspectiveType as LivePerspective } from "#live/types";
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { a as DefinedFetchType, c as PerspectiveType, l as ResolvePerspectiveFromCookies, n as DefinedSanityFetchType, o as DefinedLiveProps, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
|
|
5
3
|
/**
|
|
6
4
|
* @public
|
|
7
5
|
*/
|
|
@@ -22,5 +20,5 @@ declare function defineLive(_config: DefineSanityLiveOptions): {
|
|
|
22
20
|
* @public
|
|
23
21
|
*/
|
|
24
22
|
declare const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies;
|
|
25
|
-
export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
23
|
+
export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
26
24
|
//# sourceMappingURL=live.d.ts.map
|
package/dist/live.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.d.ts","names":[
|
|
1
|
+
{"version":3,"file":"live.d.ts","names":[],"sources":["../src/live.tsx"],"sourcesContent":[],"mappings":";;;;;AAsBc,iBAFE,UAAA,CAEF,OAAA,EAFsB,uBAEtB,CAAA,EAAA;EAIC,KAAA,EALN,gBAKM;EAImB,IAAA,EAR1B,KAAA,CAAM,aAQoB,CARN,gBAQM,CAAA;EAApB;;AASd;eAbe;;;;cAID,KAAA,CAAM,cAAc;;;;;;cASrB,+BAA+B"}
|
package/dist/live.js
CHANGED
package/dist/live.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":[
|
|
1
|
+
{"version":3,"file":"live.js","names":[],"sources":["../src/live.tsx"],"sourcesContent":["// This is the fallback export condition for `import 'next-sanity/live'`,\n// it should have the same type definitions as the other conditions so that userland don't have to worry about setting the right\n// `customCondition` in their `tsconfig.json` in order to get accurate typings.\n// The implementation here though should all throw errors, as importing this file means userland made a mistake and somehow a client component is\n// trying to pull in something it shouldn't.\n\nimport type {ResolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport type {DefinedFetchType, DefinedLiveProps} from '#live/types'\n\nimport type {\n DefineSanityLiveOptions,\n DefinedSanityFetchType,\n DefinedSanityLiveProps,\n} from './live/defineLive'\n\nexport {isCorsOriginError} from '#live/isCorsOriginError'\n\n/**\n * @public\n */\nexport function defineLive(_config: DefineSanityLiveOptions): {\n fetch: DefinedFetchType\n Live: React.ComponentType<DefinedLiveProps>\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} {\n throw new Error(`defineLive can't be imported by a client component`)\n}\n\n/**\n * Resolves the perspective from the cookie that is set by `import { defineEnableDraftMode } from \"next-sanity/draft-mode\"`\n * @public\n */\nexport const resolvePerspectiveFromCookies: ResolvePerspectiveFromCookies = () => {\n throw new Error(`resolvePerspectiveFromCookies can't be imported by a client component`)\n}\n\nexport type {PerspectiveType as LivePerspective} from '#live/types'\n"],"mappings":";AAoBA,SAAgB,WAAW,SAWzB;AACA,OAAM,IAAI,MAAM,qDAAqD;;AAOvE,MAAa,sCAAqE;AAChF,OAAM,IAAI,MAAM,wEAAwE"}
|
package/dist/live.next-js.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { resolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
|
|
4
|
-
import { DefinedFetchType, DefinedLiveProps, LiveOptions, PerspectiveType as LivePerspective } from "#live/types";
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { a as DefinedFetchType, c as PerspectiveType, n as DefinedSanityFetchType, o as DefinedLiveProps, r as DefinedSanityLiveProps, s as LiveOptions, u as resolvePerspectiveFromCookies } from "./defineLive.js";
|
|
5
3
|
declare function defineLive(config: LiveOptions): {
|
|
6
4
|
fetch: DefinedFetchType;
|
|
7
5
|
Live: React.ComponentType<DefinedLiveProps>;
|
|
@@ -14,5 +12,5 @@ declare function defineLive(config: LiveOptions): {
|
|
|
14
12
|
*/
|
|
15
13
|
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
16
14
|
};
|
|
17
|
-
export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
15
|
+
export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
18
16
|
//# sourceMappingURL=live.next-js.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.next-js.d.ts","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"live.next-js.d.ts","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":[],"mappings":";;iBAagB,UAAA,SAAmB;EAAnC,KAAgB,EACP,gBADO;EAAmB,IAAA,EAE3B,KAAA,CAAM,aAFqB,CAEP,gBAFO,CAAA;EAC1B;;;EAKM,WAAA,EAAA,sBAAA;EAImB;;;cAApB,KAAA,CAAM,cAAc"}
|
package/dist/live.next-js.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
1
2
|
import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "./constants.js";
|
|
3
|
+
import { t as resolvePerspectiveFromCookies } from "./resolvePerspectiveFromCookies.js";
|
|
2
4
|
import { cookies, draftMode } from "next/headers";
|
|
3
5
|
import { Suspense } from "react";
|
|
4
6
|
import { jsx } from "react/jsx-runtime";
|
|
5
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
6
|
-
import { resolvePerspectiveFromCookies, resolvePerspectiveFromCookies as resolvePerspectiveFromCookies$1 } from "#live/resolvePerspectiveFromCookies";
|
|
7
7
|
import SanityLiveClientComponent from "next-sanity/experimental/client-components/live";
|
|
8
8
|
import { cacheTag } from "next/cache";
|
|
9
9
|
import { preconnect } from "react-dom";
|
|
@@ -78,7 +78,7 @@ function defineLive(config) {
|
|
|
78
78
|
}
|
|
79
79
|
async function resolveDraftModePerspective() {
|
|
80
80
|
"use server";
|
|
81
|
-
if ((await draftMode()).isEnabled) return resolvePerspectiveFromCookies
|
|
81
|
+
if ((await draftMode()).isEnabled) return resolvePerspectiveFromCookies({ cookies: await cookies() });
|
|
82
82
|
return "published";
|
|
83
83
|
}
|
|
84
84
|
export { defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
package/dist/live.next-js.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.next-js.js","names":[
|
|
1
|
+
{"version":3,"file":"live.next-js.js","names":[],"sources":["../src/experimental/live.tsx"],"sourcesContent":["import type {DefinedFetchType, DefinedLiveProps, LiveOptions, PerspectiveType} from '#live/types'\n\nimport {resolvePerspectiveFromCookies} from '#live/resolvePerspectiveFromCookies'\nimport SanityLiveClientComponent from 'next-sanity/experimental/client-components/live'\nimport {cacheTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {Suspense} from 'react'\nimport {preconnect} from 'react-dom'\n\nimport type {DefinedSanityFetchType, DefinedSanityLiveProps} from '../live/defineLive'\n\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\nexport function defineLive(config: LiveOptions): {\n fetch: DefinedFetchType\n Live: React.ComponentType<DefinedLiveProps>\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} {\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 */\n // cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n\n // return sanityCachedFetch(\n // {\n // apiHost,\n // apiVersion,\n // useProjectHostname,\n // dataset,\n // projectId,\n // requestTagPrefix,\n // token: originalToken,\n // },\n // {\n // query,\n // params,\n // perspective,\n // stega,\n // requestTag,\n // draftToken: serverToken,\n // customCacheTags,\n // },\n // ).then(({data, sourceMap, tags}) => ({\n // data:\n // stega && sourceMap\n // ? stegaEncodeSourceMap(data, sourceMap, {...stegaConfig, enabled: true})\n // : data,\n // sourceMap,\n // tags,\n // }))\n }\n\n const Live: React.ComponentType<DefinedLiveProps> = function Live(props) {\n const {\n perspective = 'published',\n onChange,\n onChangeIncludingDrafts,\n onStudioPerspective,\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 if (onChangeIncludingDrafts) {\n console.warn('`onChangeIncludingDrafts` is not implemented yet')\n }\n if (onStudioPerspective) {\n console.warn('`onStudioPerspective` is not implemented yet')\n }\n\n const includeDrafts = typeof browserToken === 'string' && perspective !== 'published'\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n preconnect(origin)\n\n return (\n <Suspense>\n <SanityLiveClientComponent\n config={{\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n requestTagPrefix,\n token: includeDrafts ? browserToken : undefined,\n }}\n requestTag={requestTag}\n // origin={origin}\n draftModeEnabled={includeDrafts}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={onChange}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n </Suspense>\n )\n }\n\n return {\n fetch,\n Live,\n sanityFetch: () => {\n throw new Error(\n '`defineLive().sanityFetch` is not available when `cacheComponents: true`, use `defineLive().fetch` instead',\n )\n },\n SanityLive: () => {\n throw new Error(\n '`defineLive().SanityLive` is not available when `cacheComponents: true`, use `defineLive().Live` instead',\n )\n },\n }\n}\n\nasync function resolveDraftModePerspective(): Promise<PerspectiveType> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookies({cookies: jar})\n }\n return 'published'\n}\n\n// revalidateSyncTags => actionUpdateTags\n// router.refresh() => actionRefresh\n"],"mappings":";;;;;;;;;AAaA,SAAgB,WAAW,QAWzB;CACA,MAAM,EAAC,QAAQ,SAAS,aAAa,iBAAgB;AAErD,KAAI,CAAC,QACH,O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Q;GACjB,MAAM,EAAC,WAAU,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,CAAC;AAGlD,cAAW,OAAO;AAElB,UACE,oBAAC,UAAA,EAAA,UACC,oBAAC,2BAAA;IACC,QAAQ;KACN;KACA;KACA;KACA;KACA;KACA;KACA,OAAO,gBAAgB,eAAe,KAAA;KACvC;IACW;IAEZ,kBAAkB;IACF;IACA;IACI;IACX;IACC;IACQ;IAClB,oBAAoB;IACS;KAC7B,EAAA,CACO;;EAOb,mBAAmB;AACjB,SAAM,IAAI,MACR,6GACD;;EAEH,kBAAkB;AAChB,SAAM,IAAI,MACR,2GACD;;EAEJ;;AAGH,eAAe,8BAAwD;AACrE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,8BAA8B,EAAC,SAD1B,MAAM,SAAS,EACwB,CAAC;AAEtD,QAAO"}
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { PerspectiveType as LivePerspective } from "#live/types";
|
|
5
|
-
export { type LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { c as PerspectiveType, i as defineLive, u as resolvePerspectiveFromCookies } from "./defineLive.js";
|
|
3
|
+
export { type PerspectiveType as LivePerspective, defineLive, isCorsOriginError, resolvePerspectiveFromCookies };
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { t as sanitizePerspective } from "./sanitizePerspective.js";
|
|
3
|
+
import { t as resolvePerspectiveFromCookies } from "./resolvePerspectiveFromCookies.js";
|
|
1
4
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
2
5
|
import { cookies, draftMode } from "next/headers";
|
|
3
6
|
import { jsx } from "react/jsx-runtime";
|
|
4
|
-
import { isCorsOriginError } from "#live/isCorsOriginError";
|
|
5
|
-
import { sanitizePerspective } from "#live/sanitizePerspective";
|
|
6
7
|
import "@sanity/client";
|
|
7
|
-
import { resolvePerspectiveFromCookies } from "#live/resolvePerspectiveFromCookies";
|
|
8
8
|
import { preconnect, prefetchDNS } from "react-dom";
|
|
9
9
|
import SanityLiveClientComponent from "next-sanity/live/client-components/live";
|
|
10
10
|
async function resolveCookiePerspective() {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { t as sanitizePerspective } from "./sanitizePerspective.js";
|
|
2
|
+
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
3
|
+
const resolvePerspectiveFromCookies = async function resolvePerspectiveFromCookies$1({ cookies: jar }) {
|
|
4
|
+
return jar.has(perspectiveCookieName) ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, "drafts") : "drafts";
|
|
5
|
+
};
|
|
6
|
+
export { resolvePerspectiveFromCookies as t };
|
|
7
|
+
|
|
8
|
+
//# sourceMappingURL=resolvePerspectiveFromCookies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolvePerspectiveFromCookies.js","names":["resolvePerspectiveFromCookies"],"sources":["../src/shared/live/resolvePerspectiveFromCookies.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {cookies} from 'next/headers'\n\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\n\nexport type ResolvePerspectiveFromCookies = (options: {\n /**\n * You must await the cookies() function from next/headers\n * and pass it here.\n * Example:\n * ```ts\n * import { cookies } from 'next/headers'\n *\n * const perspective = await resolvePerspectiveFromCookies({cookies: await cookies()})\n * ```\n */\n cookies: Awaited<ReturnType<typeof cookies>>\n}) => Promise<Exclude<ClientPerspective, 'raw'>>\n\n/**\n * Resolves the perspective from the cookie that is set by `import { defineEnableDraftMode } from \"next-sanity/draft-mode\"`\n * @public\n */\nexport const resolvePerspectiveFromCookies = async function resolvePerspectiveFromCookies({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n"],"mappings":";;AAwBA,MAAa,gCAAgC,eAAeA,gCAA8B,EACxF,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { validateApiPerspective } from "@sanity/client";
|
|
2
|
+
function sanitizePerspective(_perspective, fallback) {
|
|
3
|
+
const perspective = typeof _perspective === "string" && _perspective.includes(",") ? _perspective.split(",") : _perspective;
|
|
4
|
+
try {
|
|
5
|
+
validateApiPerspective(perspective);
|
|
6
|
+
return perspective === "raw" ? fallback : perspective;
|
|
7
|
+
} catch (err) {
|
|
8
|
+
console.warn(`Invalid perspective:`, _perspective, perspective, err);
|
|
9
|
+
return fallback;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export { sanitizePerspective as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=sanitizePerspective.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sanitizePerspective.js","names":[],"sources":["../src/shared/live/sanitizePerspective.ts"],"sourcesContent":["import {validateApiPerspective, type ClientPerspective} from '@sanity/client'\n\nexport function sanitizePerspective(\n _perspective: unknown,\n fallback: 'drafts' | 'published',\n): Exclude<ClientPerspective, 'raw'> {\n const perspective =\n typeof _perspective === 'string' && _perspective.includes(',')\n ? _perspective.split(',')\n : _perspective\n try {\n validateApiPerspective(perspective)\n return perspective === 'raw' ? fallback : perspective\n } catch (err) {\n console.warn(`Invalid perspective:`, _perspective, perspective, err)\n return fallback\n }\n}\n"],"mappings":";AAEA,SAAgB,oBACd,cACA,UACmC;CACnC,MAAM,cACJ,OAAO,iBAAiB,YAAY,aAAa,SAAS,IAAI,GAC1D,aAAa,MAAM,IAAI,GACvB;AACN,KAAI;AACF,yBAAuB,YAAY;AACnC,SAAO,gBAAgB,QAAQ,WAAW;UACnC,KAAK;AACZ,UAAQ,KAAK,wBAAwB,cAAc,aAAa,IAAI;AACpE,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":["import type {VisualEditingProps} from 'next-sanity/visual-editing/client-component'\n\nimport VisualEditingComponent from 'next-sanity/visual-editing/client-component'\n\n/**\n * @public\n */\nexport function VisualEditing(props: VisualEditingProps): React.ReactElement {\n let autoBasePath: string | undefined\n if (typeof props.basePath !== 'string') {\n try {\n autoBasePath = process.env['__NEXT_ROUTER_BASEPATH']\n if (autoBasePath) {\n // oxlint-disable-next-line no-console\n console.log(\n `Detected next basePath as ${JSON.stringify(autoBasePath)} by reading \"process.env.__NEXT_ROUTER_BASEPATH\". If this is incorrect then you can set it manually with the basePath prop on the <VisualEditing /> component.`,\n )\n }\n } catch (err) {\n console.error('Failed detecting basePath', err)\n }\n }\n let autoTrailingSlash: boolean | undefined\n if (typeof props.trailingSlash !== 'boolean') {\n try {\n autoTrailingSlash = Boolean(process.env['__NEXT_TRAILING_SLASH'])\n if (autoTrailingSlash) {\n // oxlint-disable-next-line no-console\n console.log(\n `Detected next trailingSlash as ${JSON.stringify(autoTrailingSlash)} by reading \"process.env.__NEXT_TRAILING_SLASH\". If this is incorrect then you can set it manually with the trailingSlash prop on the <VisualEditing /> component.`,\n )\n }\n } catch (err) {\n console.error('Failed detecting trailingSlash', err)\n }\n }\n return (\n <VisualEditingComponent\n {...props}\n basePath={props.basePath ?? autoBasePath}\n trailingSlash={props.trailingSlash ?? autoTrailingSlash}\n />\n )\n}\n\nexport type {VisualEditingProps} from 'next-sanity/visual-editing/client-component'\n"],"mappings":";;AAOA,SAAgB,cAAc,OAA+C;CAC3E,IAAI;AACJ,KAAI,OAAO,MAAM,aAAa,SAC5B,KAAI;AACF,iBAAe,QAAQ,IAAI;AAC3B,MAAI,aAEF,SAAQ,IACN,6BAA6B,KAAK,UAAU,aAAa,CAAC,gKAC3D;UAEI,KAAK;AACZ,UAAQ,MAAM,6BAA6B,IAAI;;CAGnD,IAAI;AACJ,KAAI,OAAO,MAAM,kBAAkB,UACjC,KAAI;AACF,sBAAoB,QAAQ,QAAQ,IAAI,yBAAyB;AACjE,MAAI,kBAEF,SAAQ,IACN,kCAAkC,KAAK,UAAU,kBAAkB,CAAC,oKACrE;UAEI,KAAK;AACZ,UAAQ,MAAM,kCAAkC,IAAI;;AAGxD,QACE,oBAAC,wBAAA;EACC,GAAI;EACJ,UAAU,MAAM,YAAY;EAC5B,eAAe,MAAM,iBAAiB;GACtC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
|
-
"version": "13.0.0-cache-components.
|
|
3
|
+
"version": "13.0.0-cache-components.10",
|
|
4
4
|
"description": "Sanity.io toolkit for Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"live",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"react": "^19.2.3",
|
|
79
79
|
"react-dom": "^19.2.3",
|
|
80
80
|
"styled-components": "^6.1.19",
|
|
81
|
-
"tsdown": "0.
|
|
81
|
+
"tsdown": "0.19.0-beta.1",
|
|
82
82
|
"typescript": "5.9.3",
|
|
83
83
|
"vitest": "^4.0.16"
|
|
84
84
|
},
|