next-sanity 10.0.8 → 10.0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "10.0.8",
3
+ "version": "10.0.10",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "sanity",
@@ -28,62 +28,43 @@
28
28
  ".": {
29
29
  "source": "./src/index.ts",
30
30
  "edge-light": "./dist/index.edge-light.js",
31
- "import": "./dist/index.js",
32
- "require": "./dist/index.cjs",
33
31
  "default": "./dist/index.js"
34
32
  },
35
33
  "./draft-mode": {
36
34
  "source": "./src/draft-mode/index.ts",
37
- "import": "./dist/draft-mode.js",
38
- "require": "./dist/draft-mode.cjs",
39
35
  "default": "./dist/draft-mode.js"
40
36
  },
41
37
  "./hooks": {
42
38
  "source": "./src/hooks/index.ts",
43
- "import": "./dist/hooks.js",
44
- "require": "./dist/hooks.cjs",
45
39
  "default": "./dist/hooks.js"
46
40
  },
47
41
  "./image": {
48
42
  "source": "./src/image/index.ts",
49
- "import": "./dist/image.js",
50
- "require": "./dist/image.cjs",
51
43
  "default": "./dist/image.js"
52
44
  },
53
45
  "./studio": {
54
46
  "source": "./src/studio/index.ts",
55
- "import": "./dist/studio.js",
56
- "require": "./dist/studio.cjs",
57
47
  "default": "./dist/studio.js"
58
48
  },
59
49
  "./studio/client-component": {
60
50
  "source": "./src/studio/client-component/index.ts",
61
- "import": "./dist/studio/client-component.js",
62
- "require": "./dist/studio/client-component.cjs",
63
51
  "default": "./dist/studio/client-component.js"
64
52
  },
65
53
  "./visual-editing/client-component": {
66
54
  "source": "./src/visual-editing/client-component/index.ts",
67
- "import": "./dist/visual-editing/client-component.js",
68
- "require": "./dist/visual-editing/client-component.cjs",
69
55
  "default": "./dist/visual-editing/client-component.js"
70
56
  },
71
57
  "./visual-editing/server-actions": {
72
58
  "source": "./src/visual-editing/server-actions/index.ts",
73
- "import": "./dist/visual-editing/server-actions.js",
74
- "require": "./dist/visual-editing/server-actions.cjs",
75
59
  "default": "./dist/visual-editing/server-actions.js"
76
60
  },
77
61
  "./webhook": {
78
62
  "source": "./src/webhook/index.ts",
79
- "import": "./dist/webhook.js",
80
- "require": "./dist/webhook.cjs",
81
63
  "default": "./dist/webhook.js"
82
64
  },
83
65
  "./package.json": "./package.json"
84
66
  },
85
- "main": "./dist/index.cjs",
86
- "module": "./dist/index.js",
67
+ "main": "./dist/index.js",
87
68
  "types": "./dist/index.d.ts",
88
69
  "typesVersions": {
89
70
  "*": {
@@ -121,16 +102,16 @@
121
102
  "dependencies": {
122
103
  "@portabletext/react": "^3.2.1",
123
104
  "@sanity/client": "^7.8.2",
124
- "@sanity/next-loader": "^1.7.5",
105
+ "@sanity/next-loader": "^2.0.0",
125
106
  "@sanity/preview-url-secret": "^2.1.14",
126
107
  "@sanity/visual-editing": "^3.0.2",
127
- "groq": "^4.2.0",
108
+ "groq": "^4.3.0",
128
109
  "history": "^5.3.0"
129
110
  },
130
111
  "devDependencies": {
131
112
  "@sanity/browserslist-config": "^1.0.5",
132
113
  "@sanity/pkg-utils": "^7.11.0",
133
- "@sanity/types": "^4.2.0",
114
+ "@sanity/types": "^4.3.0",
134
115
  "@sanity/webhook": "4.0.4",
135
116
  "@types/react": "^19.1.8",
136
117
  "@types/react-dom": "^19.1.6",
@@ -148,7 +129,7 @@
148
129
  "next": "^15.1",
149
130
  "react": "^19",
150
131
  "react-dom": "^19",
151
- "sanity": "^4.2.0",
132
+ "sanity": "^4.3.0",
152
133
  "styled-components": "^6.1"
153
134
  },
154
135
  "engines": {
@@ -1,88 +0,0 @@
1
- "use strict";
2
- var jsxRuntime = require("react/jsx-runtime"), react = require("react"), sanity = require("sanity"), NextStudioNoScript = require("./NextStudioNoScript.cjs"), history = require("history"), navigation_js = require("next/navigation.js"), styledComponents = require("styled-components");
3
- function createHashHistoryForStudio() {
4
- const history$1 = history.createHashHistory();
5
- return {
6
- get action() {
7
- return history$1.action;
8
- },
9
- get location() {
10
- return history$1.location;
11
- },
12
- get createHref() {
13
- return history$1.createHref;
14
- },
15
- get push() {
16
- return history$1.push;
17
- },
18
- get replace() {
19
- return history$1.replace;
20
- },
21
- get go() {
22
- return history$1.go;
23
- },
24
- get back() {
25
- return history$1.back;
26
- },
27
- get forward() {
28
- return history$1.forward;
29
- },
30
- get block() {
31
- return history$1.block;
32
- },
33
- // Overriding listen to workaround a problem where native history provides history.listen(location => void), but the npm package is history.listen(({action, location}) => void)
34
- listen(listener) {
35
- return history$1.listen(({ location }) => {
36
- listener(location);
37
- });
38
- }
39
- };
40
- }
41
- function StyledComponentsRegistry({
42
- children,
43
- isMounted
44
- }) {
45
- const [styledComponentsStyleSheet] = react.useState(() => new styledComponents.ServerStyleSheet());
46
- return navigation_js.useServerInsertedHTML(() => {
47
- const styles = styledComponentsStyleSheet.getStyleElement();
48
- return styledComponentsStyleSheet.instance.clearTag(), /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: styles });
49
- }), isMounted ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children }) : /* @__PURE__ */ jsxRuntime.jsx(styledComponents.StyleSheetManager, { sheet: styledComponentsStyleSheet.instance, children });
50
- }
51
- function useIsMounted() {
52
- return react.useSyncExternalStore(
53
- emptySubscribe,
54
- () => !0,
55
- () => !1
56
- );
57
- }
58
- const emptySubscribe = () => () => {
59
- };
60
- function NextStudioComponent({
61
- children,
62
- config,
63
- unstable__noScript = !0,
64
- scheme,
65
- history: history2,
66
- ...props
67
- }) {
68
- const isMounted = useIsMounted(), unstableHistory = react.useMemo(() => {
69
- if (props.unstable_history && history2)
70
- throw new Error("Cannot use both `unstable_history` and `history` props at the same time");
71
- return isMounted && history2 === "hash" ? createHashHistoryForStudio() : props.unstable_history;
72
- }, [history2, isMounted, props.unstable_history]);
73
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
74
- unstable__noScript && /* @__PURE__ */ jsxRuntime.jsx(NextStudioNoScript.NextStudioNoScript, {}),
75
- /* @__PURE__ */ jsxRuntime.jsx(StyledComponentsRegistry, { isMounted, children: /* @__PURE__ */ jsxRuntime.jsx(NextStudioNoScript.NextStudioLayout, { children: history2 === "hash" && !isMounted ? null : children || /* @__PURE__ */ jsxRuntime.jsx(
76
- sanity.Studio,
77
- {
78
- config,
79
- scheme,
80
- unstable_globalStyles: !0,
81
- ...props,
82
- unstable_history: unstableHistory
83
- }
84
- ) }) })
85
- ] });
86
- }
87
- exports.default = NextStudioComponent;
88
- //# sourceMappingURL=NextStudio.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"NextStudio.cjs","sources":["../../src/studio/client-component/createHashHistoryForStudio.ts","../../src/studio/client-component/registry.tsx","../../src/studio/client-component/useIsMounted.ts","../../src/studio/client-component/NextStudio.tsx"],"sourcesContent":["import {createHashHistory, type History, type Listener} from 'history'\n\n/** @internal */\nexport function createHashHistoryForStudio(): History {\n const history = createHashHistory()\n return {\n get action() {\n return history.action\n },\n get location() {\n return history.location\n },\n get createHref() {\n return history.createHref\n },\n get push() {\n return history.push\n },\n get replace() {\n return history.replace\n },\n get go() {\n return history.go\n },\n get back() {\n return history.back\n },\n get forward() {\n return history.forward\n },\n get block() {\n return history.block\n },\n // Overriding listen to workaround a problem where native history provides history.listen(location => void), but the npm package is history.listen(({action, location}) => void)\n listen(listener: Listener) {\n // return history.listen(({ action, location }) => {\n return history.listen(({location}) => {\n // console.debug('history.listen', action, location)\n // @ts-expect-error -- working around a bug? in studio\n listener(location)\n })\n },\n }\n}\n","// https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components\nimport {useServerInsertedHTML} from 'next/navigation.js'\nimport {useState} from 'react'\nimport {ServerStyleSheet, StyleSheetManager} from 'styled-components'\n\nexport function StyledComponentsRegistry({\n children,\n isMounted,\n}: {\n children: React.ReactNode\n isMounted: boolean\n}): React.JSX.Element {\n // Only create stylesheet once with lazy initial state\n // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state\n const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())\n\n useServerInsertedHTML(() => {\n const styles = styledComponentsStyleSheet.getStyleElement()\n styledComponentsStyleSheet.instance.clearTag()\n return <>{styles}</>\n })\n\n if (isMounted) return <>{children}</>\n\n return (\n <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>{children}</StyleSheetManager>\n )\n}\n","import {useSyncExternalStore} from 'react'\n\n/** @internal */\nexport function useIsMounted(): boolean {\n return useSyncExternalStore(\n emptySubscribe,\n () => true,\n () => false,\n )\n}\n// eslint-disable-next-line no-empty-function\nconst emptySubscribe = () => () => {}\n","import {useMemo} from 'react'\nimport {Studio, type StudioProps} from 'sanity'\n\nimport {NextStudioLayout} from '../NextStudioLayout'\nimport {NextStudioNoScript} from '../NextStudioNoScript'\nimport {createHashHistoryForStudio} from './createHashHistoryForStudio'\nimport {StyledComponentsRegistry} from './registry'\nimport {useIsMounted} from './useIsMounted'\n\n/** @public */\nexport interface NextStudioProps extends StudioProps {\n children?: React.ReactNode\n /**\n * Render the <noscript> tag\n * @defaultValue true\n * @alpha\n */\n unstable__noScript?: boolean\n /**\n * The 'hash' option is new feature that is not yet stable for production, but is available for testing and its API won't change in a breaking way.\n * If 'hash' doesn't work for you, or if you want to use a memory based history, you can use the `unstable_history` prop instead.\n * @alpha\n * @defaultValue 'browser'\n */\n history?: 'browser' | 'hash'\n}\n/**\n * Override how the Studio renders by passing children.\n * This is useful for advanced use cases where you're using StudioProvider and StudioLayout instead of Studio:\n * ```\n * import {StudioProvider, StudioLayout} from 'sanity'\n * import {NextStudio} from 'next-sanity/studio'\n * <NextStudio config={config}>\n * <StudioProvider config={config}>\n * <CustomComponentThatUsesContextFromStudioProvider />\n * <StudioLayout />\n * </StudioProvider>\n * </NextStudio>\n * ```\n * @public\n */\nexport default function NextStudioComponent({\n children,\n config,\n unstable__noScript = true,\n scheme,\n history,\n ...props\n}: NextStudioProps): React.JSX.Element {\n const isMounted = useIsMounted()\n const unstableHistory = useMemo<typeof props.unstable_history>(() => {\n if (props.unstable_history && history) {\n throw new Error('Cannot use both `unstable_history` and `history` props at the same time')\n }\n\n if (isMounted && history === 'hash') {\n return createHashHistoryForStudio()\n }\n return props.unstable_history\n }, [history, isMounted, props.unstable_history])\n\n return (\n <>\n {unstable__noScript && <NextStudioNoScript />}\n <StyledComponentsRegistry isMounted={isMounted}>\n <NextStudioLayout>\n {history === 'hash' && !isMounted\n ? null\n : children || (\n <Studio\n config={config}\n scheme={scheme}\n unstable_globalStyles\n {...props}\n unstable_history={unstableHistory}\n />\n )}\n </NextStudioLayout>\n </StyledComponentsRegistry>\n </>\n )\n}\n"],"names":["history","createHashHistory","useState","ServerStyleSheet","useServerInsertedHTML","jsx","Fragment","StyleSheetManager","useSyncExternalStore","useMemo","jsxs","NextStudioNoScript","NextStudioLayout","Studio"],"mappings":";;AAGO,SAAS,6BAAsC;AACpD,QAAMA,YAAUC,QAAAA,kBAAA;AAChB,SAAO;AAAA,IACL,IAAI,SAAS;AACX,aAAOD,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,WAAW;AACb,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,aAAa;AACf,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,OAAO;AACT,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,UAAU;AACZ,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,KAAK;AACP,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,OAAO;AACT,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,UAAU;AACZ,aAAOA,UAAQ;AAAA,IACjB;AAAA,IACA,IAAI,QAAQ;AACV,aAAOA,UAAQ;AAAA,IACjB;AAAA;AAAA,IAEA,OAAO,UAAoB;AAEzB,aAAOA,UAAQ,OAAO,CAAC,EAAC,eAAc;AAGpC,iBA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BAAAA;AAAAA,MAACQ,OAAAA;AAAAA,MAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA,uBAAqB;AAAA,QACpB,GAAG;AAAA,QACJ,kBAAkB;AAAA,MAAA;AAAA,IAAA,GAG5B,EAAA,CACF;AAAA,EAAA,GACF;AAEJ;;"}
@@ -1,37 +0,0 @@
1
- "use strict";
2
- var jsxRuntime = require("react/jsx-runtime"), react = require("react");
3
- const style = {
4
- height: "100vh",
5
- maxHeight: "100dvh",
6
- overscrollBehavior: "none",
7
- WebkitFontSmoothing: "antialiased",
8
- overflow: "auto"
9
- }, NextStudioLayoutComponent = ({ children }) => /* @__PURE__ */ jsxRuntime.jsx("div", { id: "sanity", "data-ui": "NextStudioLayout", style, children }), NextStudioLayout = react.memo(NextStudioLayoutComponent), styles = {
10
- outer: {
11
- position: "absolute",
12
- top: 0,
13
- right: 0,
14
- left: 0,
15
- bottom: 0,
16
- background: "#fff",
17
- zIndex: 1
18
- },
19
- inner: {
20
- position: "absolute",
21
- top: "50%",
22
- left: "50%",
23
- transform: "translate(-50%, -50%)",
24
- textAlign: "center",
25
- fontFamily: "helvetica, arial, sans-serif"
26
- }
27
- }, NextStudioNoScript = () => /* @__PURE__ */ jsxRuntime.jsx("noscript", { children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: styles.outer, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { style: styles.inner, children: [
28
- /* @__PURE__ */ jsxRuntime.jsx("h1", { children: "JavaScript disabled" }),
29
- /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
30
- "Please ",
31
- /* @__PURE__ */ jsxRuntime.jsx("a", { href: "https://www.enable-javascript.com/", children: "enable JavaScript" }),
32
- " in your browser and reload the page to proceed."
33
- ] })
34
- ] }) }) });
35
- exports.NextStudioLayout = NextStudioLayout;
36
- exports.NextStudioNoScript = NextStudioNoScript;
37
- //# sourceMappingURL=NextStudioNoScript.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"NextStudioNoScript.cjs","sources":["../../src/studio/NextStudioLayout.tsx","../../src/studio/NextStudioNoScript.tsx"],"sourcesContent":["import {memo} from 'react'\n\n/** @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\nconst NextStudioLayoutComponent = ({children}: NextStudioLayoutProps) => {\n return (\n <div id=\"sanity\" data-ui=\"NextStudioLayout\" style={style}>\n {children}\n </div>\n )\n}\n\n/** @public */\nexport const NextStudioLayout = memo(NextStudioLayoutComponent)\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"],"names":["jsx","memo","jsxs"],"mappings":";;AAOA,MAAM,QAAQ;AAAA,EACZ,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,UAAU;AACZ,GAEM,4BAA4B,CAAC,EAAC,SAAA,MAEhCA,2BAAAA,IAAC,OAAA,EAAI,IAAG,UAAS,WAAQ,oBAAmB,OACzC,SAAA,CACH,GAKS,mBAAmBC,MAAAA,KAAK,yBAAyB,GCxBxD,SAAyD;AAAA,EAC7D,OAAO;AAAA,IACL,UAAU;AAAA,IACV,KAAK;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,QAAQ;AAAA,EAAA;AAAA,EAEV,OAAO;AAAA,IACL,UAAU;AAAA,IACV,KAAK;AAAA,IACL,MAAM;AAAA,IACN,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,EAAA;AAEhB,GAGa,qBAAqB,MAChCD,2BAAAA,IAAC,YAAA,EACC,UAAAA,2BAAAA,IAAC,OAAA,EAAI,OAAO,OAAO,OACjB,UAAAE,2BAAAA,KAAC,OAAA,EAAI,OAAO,OAAO,OACjB,UAAA;AAAA,EAAAF,2BAAAA,IAAC,QAAG,UAAA,sBAAA,CAAmB;AAAA,kCACtB,KAAA,EAAE,UAAA;AAAA,IAAA;AAAA,IACMA,2BAAAA,IAAC,KAAA,EAAE,MAAK,sCAAqC,UAAA,qBAAiB;AAAA,IAAI;AAAA,EAAA,EAAA,CAE3E;AAAA,EAAA,CACF,GACF,EAAA,CACF;;;"}
@@ -1,109 +0,0 @@
1
- "use strict";
2
- var jsxRuntime = require("react/jsx-runtime"), react$1 = require("@sanity/visual-editing/react"), navigation_js = require("next/navigation.js"), serverActions = require("next-sanity/visual-editing/server-actions"), react = require("react");
3
- function pathHasPrefix(path, prefix) {
4
- if (typeof path != "string")
5
- return !1;
6
- const { pathname } = parsePath(path);
7
- return pathname === prefix || pathname.startsWith(`${prefix}/`);
8
- }
9
- function parsePath(path) {
10
- const hashIndex = path.indexOf("#"), queryIndex = path.indexOf("?"), hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex);
11
- return hasQuery || hashIndex > -1 ? {
12
- pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),
13
- query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : void 0) : "",
14
- hash: hashIndex > -1 ? path.slice(hashIndex) : ""
15
- } : { pathname: path, query: "", hash: "" };
16
- }
17
- function addPathPrefix(path, prefix) {
18
- if (!path.startsWith("/") || !prefix)
19
- return path;
20
- if (path === "/" && prefix)
21
- return prefix;
22
- const { pathname, query, hash } = parsePath(path);
23
- return `${prefix}${pathname}${query}${hash}`;
24
- }
25
- function removePathPrefix(path, prefix) {
26
- if (!pathHasPrefix(path, prefix))
27
- return path;
28
- const withoutPrefix = path.slice(prefix.length);
29
- return withoutPrefix.startsWith("/") ? withoutPrefix : `/${withoutPrefix}`;
30
- }
31
- const normalizePathTrailingSlash = (path, trailingSlash) => {
32
- const { pathname, query, hash } = parsePath(path);
33
- return trailingSlash ? pathname.endsWith("/") ? `${pathname}${query}${hash}` : `${pathname}/${query}${hash}` : `${removeTrailingSlash(pathname)}${query}${hash}`;
34
- };
35
- function removeTrailingSlash(route) {
36
- return route.replace(/\/$/, "") || "/";
37
- }
38
- function VisualEditing(props) {
39
- const { basePath = "", plugins, components, refresh, trailingSlash = !1, zIndex } = props, router = navigation_js.useRouter(), routerRef = react.useRef(router), [navigate, setNavigate] = react.useState();
40
- react.useEffect(() => {
41
- routerRef.current = router;
42
- }, [router]);
43
- const history = react.useMemo(
44
- () => ({
45
- subscribe: (_navigate) => (setNavigate(() => _navigate), () => setNavigate(void 0)),
46
- update: (update) => {
47
- switch (update.type) {
48
- case "push":
49
- return routerRef.current.push(removePathPrefix(update.url, basePath));
50
- case "pop":
51
- return routerRef.current.back();
52
- case "replace":
53
- return routerRef.current.replace(removePathPrefix(update.url, basePath));
54
- default:
55
- throw new Error(`Unknown update type: ${update.type}`);
56
- }
57
- }
58
- }),
59
- [basePath]
60
- ), pathname = navigation_js.usePathname(), searchParams = navigation_js.useSearchParams();
61
- react.useEffect(() => {
62
- navigate && navigate({
63
- type: "push",
64
- url: normalizePathTrailingSlash(
65
- addPathPrefix(`${pathname}${searchParams?.size ? `?${searchParams}` : ""}`, basePath),
66
- trailingSlash
67
- )
68
- });
69
- }, [basePath, navigate, pathname, searchParams, trailingSlash]);
70
- const handleRefresh = react.useCallback(
71
- (payload) => {
72
- if (refresh) return refresh(payload);
73
- const manualFastRefresh = () => (console.debug(
74
- "Live preview is setup, calling router.refresh() to refresh the server components without refetching cached data"
75
- ), routerRef.current.refresh(), Promise.resolve()), manualFallbackRefresh = () => (console.debug(
76
- "No loaders in live mode detected, or preview kit setup, revalidating root layout"
77
- ), serverActions.revalidateRootLayout()), mutationFallbackRefresh = () => (console.debug(
78
- "No loaders in live mode detected, or preview kit setup, revalidating root layout"
79
- ), serverActions.revalidateRootLayout());
80
- switch (payload.source) {
81
- case "manual":
82
- return payload.livePreviewEnabled ? manualFastRefresh() : manualFallbackRefresh();
83
- case "mutation":
84
- return payload.livePreviewEnabled ? mutationFastRefresh() : mutationFallbackRefresh();
85
- default:
86
- throw new Error("Unknown refresh source", { cause: payload });
87
- }
88
- },
89
- [refresh]
90
- );
91
- return /* @__PURE__ */ jsxRuntime.jsx(
92
- react$1.VisualEditing,
93
- {
94
- plugins,
95
- components,
96
- history,
97
- portal: !0,
98
- refresh: handleRefresh,
99
- zIndex
100
- }
101
- );
102
- }
103
- function mutationFastRefresh() {
104
- return console.debug(
105
- "Live preview is setup, mutation is skipped assuming its handled by the live preview"
106
- ), !1;
107
- }
108
- exports.default = VisualEditing;
109
- //# sourceMappingURL=VisualEditing.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"VisualEditing.cjs","sources":["../../src/visual-editing/client-component/utils.ts","../../src/visual-editing/client-component/VisualEditing.tsx"],"sourcesContent":["/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nfunction pathHasPrefix(path: string, prefix: string): boolean {\n if (typeof path !== 'string') {\n return false\n }\n\n const {pathname} = parsePath(path)\n return pathname === prefix || pathname.startsWith(`${prefix}/`)\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/parse-path.ts#L6-L22\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nfunction parsePath(path: string): {\n pathname: string\n query: string\n hash: string\n} {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return {pathname: path, query: '', hash: ''}\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/add-path-prefix.ts#L3C1-L14C2\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string): string {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n // If the path is exactly '/' then return just the prefix\n if (path === '/' && prefix) {\n return prefix\n }\n\n const {pathname, query, hash} = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/remove-path-prefix.ts#L3-L39\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/client/normalize-trailing-slash.ts#L16\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string, trailingSlash: boolean): string => {\n const {pathname, query, hash} = parsePath(path)\n if (trailingSlash) {\n if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n }\n return `${pathname}/${query}${hash}`\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts#L8\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nfunction removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import {\n type HistoryAdapter,\n type HistoryAdapterNavigate,\n type HistoryRefresh,\n VisualEditing as VisualEditingComponent,\n type VisualEditingOptions,\n} from '@sanity/visual-editing/react'\nimport {usePathname, useRouter, useSearchParams} from 'next/navigation.js'\nimport {revalidateRootLayout} from 'next-sanity/visual-editing/server-actions'\nimport {useCallback, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {addPathPrefix, normalizePathTrailingSlash, removePathPrefix} from './utils'\n\n/**\n * @public\n */\nexport interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {\n /**\n * @deprecated The histoy adapter is already implemented\n */\n history?: never\n /**\n * If next.config.ts is configured with a basePath we try to configure it automatically,\n * you can disable this by setting basePath to ''.\n * @example basePath=\"/my-custom-base-path\"\n * @alpha experimental and may change without notice\n * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''\n */\n basePath?: string\n /**\n * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,\n * it can be controlled manually by passing a boolean.\n * @example trailingSlash={true}\n * @alpha experimental and may change without notice\n * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)\n */\n trailingSlash?: boolean\n}\n\nexport default function VisualEditing(props: VisualEditingProps): React.JSX.Element | null {\n const {basePath = '', plugins, components, refresh, trailingSlash = false, zIndex} = props\n\n const router = useRouter()\n const routerRef = useRef(router)\n const [navigate, setNavigate] = useState<HistoryAdapterNavigate | undefined>()\n\n useEffect(() => {\n routerRef.current = router\n }, [router])\n\n const history = useMemo<HistoryAdapter>(\n () => ({\n subscribe: (_navigate) => {\n setNavigate(() => _navigate)\n return () => setNavigate(undefined)\n },\n update: (update) => {\n switch (update.type) {\n case 'push':\n return routerRef.current.push(removePathPrefix(update.url, basePath))\n case 'pop':\n return routerRef.current.back()\n case 'replace':\n return routerRef.current.replace(removePathPrefix(update.url, basePath))\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n },\n }),\n [basePath],\n )\n\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n if (navigate) {\n navigate({\n type: 'push',\n url: normalizePathTrailingSlash(\n addPathPrefix(`${pathname}${searchParams?.size ? `?${searchParams}` : ''}`, basePath),\n trailingSlash,\n ),\n })\n }\n }, [basePath, navigate, pathname, searchParams, trailingSlash])\n\n const handleRefresh = useCallback(\n (payload: HistoryRefresh) => {\n if (refresh) return refresh(payload)\n\n const manualFastRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, calling router.refresh() to refresh the server components without refetching cached data',\n )\n routerRef.current.refresh()\n return Promise.resolve()\n }\n const manualFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n const mutationFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n switch (payload.source) {\n case 'manual':\n return payload.livePreviewEnabled ? manualFastRefresh() : manualFallbackRefresh()\n case 'mutation':\n return payload.livePreviewEnabled ? mutationFastRefresh() : mutationFallbackRefresh()\n default:\n throw new Error('Unknown refresh source', {cause: payload})\n }\n },\n [refresh],\n )\n\n return (\n <VisualEditingComponent\n plugins={plugins}\n components={components}\n history={history}\n portal\n refresh={handleRefresh}\n zIndex={zIndex}\n />\n )\n}\n\nfunction mutationFastRefresh(): false {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, mutation is skipped assuming its handled by the live preview',\n )\n return false\n}\n"],"names":["useRouter","useRef","useState","useEffect","useMemo","usePathname","useSearchParams","useCallback","revalidateRootLayout","jsx","VisualEditingComponent"],"mappings":";;AAQA,SAAS,cAAc,MAAc,QAAyB;AAC5D,MAAI,OAAO,QAAS;AAClB,WAAO;AAGT,QAAM,EAAC,SAAA,IAAY,UAAU,IAAI;AACjC,SAAO,aAAa,UAAU,SAAS,WAAW,GAAG,MAAM,GAAG;AAChE;AAQA,SAAS,UAAU,MAIjB;AACA,QAAM,YAAY,KAAK,QAAQ,GAAG,GAC5B,aAAa,KAAK,QAAQ,GAAG,GAC7B,WAAW,aAAa,OAAO,YAAY,KAAK,aAAa;AAEnE,SAAI,YAAY,YAAY,KACnB;AAAA,IACL,UAAU,KAAK,UAAU,GAAG,WAAW,aAAa,SAAS;AAAA,IAC7D,OAAO,WAAW,KAAK,UAAU,YAAY,YAAY,KAAK,YAAY,MAAS,IAAI;AAAA,IACvF,MAAM,YAAY,KAA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O,QAAQ,qBAAqB,oBAAA,IAAwB,wBAAA;AAAA,QAC9D;AACE,gBAAM,IAAI,MAAM,0BAA0B,EAAC,OAAO,SAAQ;AAAA,MAAA;AAAA,IAEhE;AAAA,IACA,CAAC,OAAO;AAAA,EAAA;AAGV,SACEC,2BAAAA;AAAAA,IAACC,QAAAA;AAAAA,IAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAM;AAAA,MACN,SAAS;AAAA,MACT;AAAA,IAAA;AAAA,EAAA;AAGN;AAEA,SAAS,sBAA6B;AAEpC,SAAA,QAAQ;AAAA,IACN;AAAA,EAAA,GAEK;AACT;;"}
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var previewUrlSecret = require("@sanity/preview-url-secret"), constants = require("@sanity/preview-url-secret/constants"), headers = require("next/headers"), navigation = require("next/navigation");
4
- function defineEnableDraftMode(options) {
5
- const { client } = options;
6
- return {
7
- GET: async (request) => {
8
- const {
9
- isValid,
10
- redirectTo = "/",
11
- studioPreviewPerspective
12
- } = await previewUrlSecret.validatePreviewUrl(client, request.url);
13
- if (!isValid)
14
- return new Response("Invalid secret", { status: 401 });
15
- const draftModeStore = await headers.draftMode();
16
- draftModeStore.isEnabled || draftModeStore.enable();
17
- const isSecure = process.env.NODE_ENV === "production" || (options.secureDevMode ?? !1), cookieStore = await headers.cookies(), cookie = cookieStore.get("__prerender_bypass");
18
- return cookieStore.set({
19
- name: "__prerender_bypass",
20
- value: cookie?.value,
21
- httpOnly: !0,
22
- path: "/",
23
- secure: isSecure,
24
- sameSite: isSecure ? "none" : "lax"
25
- }), studioPreviewPerspective && cookieStore.set({
26
- name: constants.perspectiveCookieName,
27
- value: studioPreviewPerspective,
28
- httpOnly: !0,
29
- path: "/",
30
- secure: isSecure,
31
- sameSite: isSecure ? "none" : "lax"
32
- }), navigation.redirect(redirectTo);
33
- }
34
- };
35
- }
36
- exports.defineEnableDraftMode = defineEnableDraftMode;
37
- //# sourceMappingURL=draft-mode.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"draft-mode.cjs","sources":["../src/draft-mode/define-enable-draft-mode.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {cookies, draftMode} from 'next/headers'\nimport {redirect} from 'next/navigation'\n\nimport type {SanityClient} from '../client'\n\n/**\n * @public\n */\nexport interface DefineEnableDraftModeOptions {\n client: SanityClient\n /**\n * Force secure cookies in development mode.\n * Enable this when using Next.js --experimental-https flag.\n * This option has no effect in production (cookies are always secure).\n * @defaultValue false\n */\n secureDevMode?: boolean\n}\n\n/**\n * @public\n */\nexport interface EnableDraftMode {\n GET: (request: Request) => Promise<Response>\n}\n\n/**\n * Sets up an API route for enabling draft mode, can be paired with the `previewUrl.previewMode.enable` in `sanity/presentation`.\n * Can also be used with `sanity-plugin-iframe-pane`.\n * @example\n * ```ts\n * // src/app/api/draft-mode/enable/route.ts\n *\n * import { defineEnableDraftMode } from \"next-sanity/draft-mode\";\n * import { client } from \"@/sanity/lib/client\";\n *\n * export const { GET } = defineEnableDraftMode({\n * client: client.withConfig({ token: process.env.SANITY_API_READ_TOKEN }),\n * });\n * ```\n *\n * @public\n */\nexport function defineEnableDraftMode(options: DefineEnableDraftModeOptions): EnableDraftMode {\n const {client} = options\n return {\n GET: async (request: Request) => {\n // eslint-disable-next-line no-warning-comments\n // @TODO check if already in draft mode at a much earlier stage, and skip validation\n\n const {\n isValid,\n redirectTo = '/',\n studioPreviewPerspective,\n } = await validatePreviewUrl(client, request.url)\n if (!isValid) {\n return new Response('Invalid secret', {status: 401})\n }\n\n const draftModeStore = await draftMode()\n\n // Let's enable draft mode if it's not already enabled\n if (!draftModeStore.isEnabled) {\n draftModeStore.enable()\n }\n\n const isProduction = process.env.NODE_ENV === 'production'\n\n // We can't auto-detect HTTPS in dev due to Next.js limitations,\n // so we need an explicit option\n const isSecure = isProduction || (options.secureDevMode ?? false)\n\n // Override cookie header for draft mode for usage in live-preview\n // https://github.com/vercel/next.js/issues/49927\n const cookieStore = await cookies()\n const cookie = cookieStore.get('__prerender_bypass')!\n cookieStore.set({\n name: '__prerender_bypass',\n value: cookie?.value,\n httpOnly: true,\n path: '/',\n secure: isSecure,\n sameSite: isSecure ? 'none' : 'lax',\n })\n\n if (studioPreviewPerspective) {\n cookieStore.set({\n name: perspectiveCookieName,\n value: studioPreviewPerspective,\n httpOnly: true,\n path: '/',\n secure: isSecure,\n sameSite: isSecure ? 'none' : 'lax',\n })\n }\n\n // the `redirect` function throws, and eventually returns a Promise<Response>. TSC doesn't \"see\" that so we have to tell it\n return redirect(redirectTo) as Promise<Response>\n },\n }\n}\n"],"names":["validatePreviewUrl","draftMode","cookies","perspectiveCookieName","redirect"],"mappings":";;;AA6CO,SAAS,sBAAsB,SAAwD;AAC5F,QAAM,EAAC,WAAU;AACjB,SAAO;AAAA,IACL,KAAK,OAAO,YAAqB;AAI/B,YAAM;AAAA,QACJ;AAAA,QACA,aAAa;AAAA,QACb;AAAA,MAAA,IACE,MAAMA,iBAAAA,mBAAmB,QAAQ,QAAQ,GAAG;AAChD,UAAI,CAAC;AACH,eAAO,IAAI,SAAS,kBAAkB,EAAC,QAAQ,KAAI;AAGrD,YAAM,iBAAiB,MAAMC,kBAAA;AAGxB,qBAAe,aAClB,eAAe,OAAA;AAOjB,YAAM,WAJe,QAAQ,IAAI,aAAa,iBAIZ,QAAQ,iBAAiB,KAIrD,cAAc,MAAMC,gBAAA,GACpB,SAAS,YAAY,IAAI,oBAAoB;AACnD,aAAA,YAAY,IAAI;AAAA,QACd,MAAM;AAAA,QACN,OAAO,QAAQ;AAAA,QACf,UAAU;AAAA,QACV,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,UAAU,WAAW,SAAS;AAAA,MAAA,CAC/B,GAEG,4BACF,YAAY,IAAI;AAAA,QACd,MAAMC,UAAAA;AAAAA,QACN,OAAO;AAAA,QACP,UAAU;AAAA,QACV,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,UAAU,WAAW,SAAS;AAAA,MAAA,CAC/B,GAIIC,WAAAA,SAAS,UAAU;AAAA,IAC5B;AAAA,EAAA;AAEJ;;"}
@@ -1,45 +0,0 @@
1
- import {SanityClient} from '@sanity/client'
2
-
3
- /**
4
- * Sets up an API route for enabling draft mode, can be paired with the `previewUrl.previewMode.enable` in `sanity/presentation`.
5
- * Can also be used with `sanity-plugin-iframe-pane`.
6
- * @example
7
- * ```ts
8
- * // src/app/api/draft-mode/enable/route.ts
9
- *
10
- * import { defineEnableDraftMode } from "next-sanity/draft-mode";
11
- * import { client } from "@/sanity/lib/client";
12
- *
13
- * export const { GET } = defineEnableDraftMode({
14
- * client: client.withConfig({ token: process.env.SANITY_API_READ_TOKEN }),
15
- * });
16
- * ```
17
- *
18
- * @public
19
- */
20
- export declare function defineEnableDraftMode(
21
- options: DefineEnableDraftModeOptions,
22
- ): EnableDraftMode
23
-
24
- /**
25
- * @public
26
- */
27
- export declare interface DefineEnableDraftModeOptions {
28
- client: SanityClient
29
- /**
30
- * Force secure cookies in development mode.
31
- * Enable this when using Next.js --experimental-https flag.
32
- * This option has no effect in production (cookies are always secure).
33
- * @defaultValue false
34
- */
35
- secureDevMode?: boolean
36
- }
37
-
38
- /**
39
- * @public
40
- */
41
- export declare interface EnableDraftMode {
42
- GET: (request: Request) => Promise<Response>
43
- }
44
-
45
- export {}
package/dist/hooks.cjs DELETED
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var hooks = require("@sanity/next-loader/hooks"), react = require("@sanity/visual-editing/react");
4
- Object.defineProperty(exports, "useOptimistic", {
5
- enumerable: !0,
6
- get: function() {
7
- return react.useOptimistic;
8
- }
9
- });
10
- Object.keys(hooks).forEach(function(k) {
11
- k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k) && Object.defineProperty(exports, k, {
12
- enumerable: !0,
13
- get: function() {
14
- return hooks[k];
15
- }
16
- });
17
- });
18
- //# sourceMappingURL=hooks.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hooks.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;"}
package/dist/hooks.d.cts DELETED
@@ -1,7 +0,0 @@
1
- import {useOptimistic} from '@sanity/visual-editing/react'
2
-
3
- export {useOptimistic}
4
-
5
- export * from '@sanity/next-loader/hooks'
6
-
7
- export {}
package/dist/image.cjs DELETED
@@ -1,35 +0,0 @@
1
- "use client";
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: !0 });
4
- var jsxRuntime = require("react/jsx-runtime"), NextImage = require("next/image");
5
- function _interopDefaultCompat(e) {
6
- return e && typeof e == "object" && "default" in e ? e : { default: e };
7
- }
8
- var NextImage__default = /* @__PURE__ */ _interopDefaultCompat(NextImage);
9
- const imageLoader = ({ src, width, quality }) => {
10
- const url = new URL(src);
11
- if (url.searchParams.set("auto", "format"), url.searchParams.has("fit") || url.searchParams.set("fit", url.searchParams.has("h") ? "min" : "max"), url.searchParams.has("h") && url.searchParams.has("w")) {
12
- const originalHeight = parseInt(url.searchParams.get("h"), 10), originalWidth = parseInt(url.searchParams.get("w"), 10);
13
- url.searchParams.set("h", Math.round(originalHeight / originalWidth * width).toString());
14
- }
15
- return url.searchParams.set("w", width.toString()), quality && url.searchParams.set("q", quality.toString()), url.href;
16
- };
17
- function Image(props) {
18
- const { loader, src, ...rest } = props;
19
- if (loader)
20
- throw new TypeError(
21
- "The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader."
22
- );
23
- let srcUrl;
24
- try {
25
- srcUrl = new URL(src), props.height && srcUrl.searchParams.set("h", `${props.height}`), props.width && srcUrl.searchParams.set("w", `${props.width}`);
26
- } catch (err) {
27
- throw new TypeError("The `src` prop must be a valid URL to an image on the Sanity Image CDN.", {
28
- cause: err
29
- });
30
- }
31
- return /* @__PURE__ */ jsxRuntime.jsx(NextImage__default.default, { ...rest, src: srcUrl.toString(), loader: imageLoader });
32
- }
33
- exports.Image = Image;
34
- exports.imageLoader = imageLoader;
35
- //# sourceMappingURL=image.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"image.cjs","sources":["../src/image/imageLoader.ts","../src/image/Image.tsx"],"sourcesContent":["import type {ImageLoader} from 'next/image'\n\n/**\n * @alpha\n */\nexport const 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}) satisfies ImageLoader\n","import NextImage, {type ImageProps as NextImageProps} from 'next/image'\n\nimport {imageLoader} from './imageLoader'\n\n/**\n * @alpha\n */\nexport interface ImageProps extends Omit<NextImageProps, 'loader' | 'src'> {\n /**\n * The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.\n */\n loader?: never\n /**\n * Must be a string that is a valid URL to an image on the Sanity Image CDN.\n */\n src: string\n}\n\n/**\n * @alpha\n */\nexport function Image(props: ImageProps): React.JSX.Element {\n const {loader, src, ...rest} = props\n if (loader) {\n throw new TypeError(\n 'The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.',\n )\n }\n let srcUrl: URL\n try {\n srcUrl = new URL(src)\n if (props.height) {\n srcUrl.searchParams.set('h', `${props.height}`)\n }\n if (props.width) {\n srcUrl.searchParams.set('w', `${props.width}`)\n }\n } catch (err) {\n throw new TypeError('The `src` prop must be a valid URL to an image on the Sanity Image CDN.', {\n cause: err,\n })\n }\n return <NextImage {...rest} src={srcUrl.toString()} loader={imageLoader} />\n}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
- import {ImageLoaderProps} from 'next/image'
2
- import {ImageProps as ImageProps_2} from 'next/image'
3
-
4
- /**
5
- * @alpha
6
- */
7
- declare function Image_2(props: ImageProps): React.JSX.Element
8
- export {Image_2 as Image}
9
-
10
- /**
11
- * @alpha
12
- */
13
- export declare const imageLoader: ({src, width, quality}: ImageLoaderProps) => string
14
-
15
- /**
16
- * @alpha
17
- */
18
- export declare interface ImageProps extends Omit<ImageProps_2, 'loader' | 'src'> {
19
- /**
20
- * The `loader` prop is not supported on `Image` components. Use `next/image` directly to use a custom loader.
21
- */
22
- loader?: never
23
- /**
24
- * Must be a string that is a valid URL to an image on the Sanity Image CDN.
25
- */
26
- src: string
27
- }
28
-
29
- export {}
package/dist/index.cjs DELETED
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var client = require("@sanity/client"), stega = require("@sanity/client/stega"), createDataAttribute = require("@sanity/visual-editing/create-data-attribute"), jsxRuntime = require("react/jsx-runtime"), VisualEditingComponent = require("next-sanity/visual-editing/client-component"), react = require("@portabletext/react"), nextLoader = require("@sanity/next-loader"), groq = require("groq");
4
- function _interopDefaultCompat(e) {
5
- return e && typeof e == "object" && "default" in e ? e : { default: e };
6
- }
7
- var VisualEditingComponent__default = /* @__PURE__ */ _interopDefaultCompat(VisualEditingComponent), groq__default = /* @__PURE__ */ _interopDefaultCompat(groq);
8
- function VisualEditing(props) {
9
- let autoBasePath;
10
- if (typeof props.basePath != "string")
11
- try {
12
- autoBasePath = process.env.__NEXT_ROUTER_BASEPATH, autoBasePath && console.log(
13
- `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.`
14
- );
15
- } catch (err) {
16
- console.error("Failed detecting basePath", err);
17
- }
18
- let autoTrailingSlash;
19
- if (typeof props.trailingSlash != "boolean")
20
- try {
21
- autoTrailingSlash = !!process.env.__NEXT_TRAILING_SLASH, autoTrailingSlash && console.log(
22
- `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.`
23
- );
24
- } catch (err) {
25
- console.error("Failed detecting trailingSlash", err);
26
- }
27
- return /* @__PURE__ */ jsxRuntime.jsx(
28
- VisualEditingComponent__default.default,
29
- {
30
- ...props,
31
- basePath: props.basePath ?? autoBasePath,
32
- trailingSlash: props.trailingSlash ?? autoTrailingSlash
33
- }
34
- );
35
- }
36
- Object.defineProperty(exports, "createClient", {
37
- enumerable: !0,
38
- get: function() {
39
- return client.createClient;
40
- }
41
- });
42
- Object.defineProperty(exports, "unstable__adapter", {
43
- enumerable: !0,
44
- get: function() {
45
- return client.unstable__adapter;
46
- }
47
- });
48
- Object.defineProperty(exports, "unstable__environment", {
49
- enumerable: !0,
50
- get: function() {
51
- return client.unstable__environment;
52
- }
53
- });
54
- Object.defineProperty(exports, "stegaClean", {
55
- enumerable: !0,
56
- get: function() {
57
- return stega.stegaClean;
58
- }
59
- });
60
- Object.defineProperty(exports, "createDataAttribute", {
61
- enumerable: !0,
62
- get: function() {
63
- return createDataAttribute.createDataAttribute;
64
- }
65
- });
66
- Object.defineProperty(exports, "defineQuery", {
67
- enumerable: !0,
68
- get: function() {
69
- return groq.defineQuery;
70
- }
71
- });
72
- Object.defineProperty(exports, "groq", {
73
- enumerable: !0,
74
- get: function() {
75
- return groq__default.default;
76
- }
77
- });
78
- exports.VisualEditing = VisualEditing;
79
- Object.keys(react).forEach(function(k) {
80
- k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k) && Object.defineProperty(exports, k, {
81
- enumerable: !0,
82
- get: function() {
83
- return react[k];
84
- }
85
- });
86
- });
87
- Object.keys(nextLoader).forEach(function(k) {
88
- k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k) && Object.defineProperty(exports, k, {
89
- enumerable: !0,
90
- get: function() {
91
- return nextLoader[k];
92
- }
93
- });
94
- });
95
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/visual-editing/index.tsx"],"sourcesContent":["import type {VisualEditingProps} from 'next-sanity/visual-editing/client-component'\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 // eslint-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 // eslint-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"],"names":["jsx","VisualEditingComponent"],"mappings":";;;;;;;AAMO,SAAS,cAAc,OAA+C;AAC3E,MAAI;AACJ,MAAI,OAAO,MAAM,YAAa;AAC5B,QAAI;AACF,qBAAe,QAAQ,IAAI,wBACvB,gBAEF,QAAQ;AAAA,QACN,6BAA6B,KAAK,UAAU,YAAY,CAAC;AAAA,MAAA;AAAA,IAG/D,SAAS,KAAK;AACZ,cAAQ,MAAM,6BAA6B,GAAG;AAAA,IAChD;AAEF,MAAI;AACJ,MAAI,OAAO,MAAM,iBAAkB;AACjC,QAAI;AACF,0BAAoB,CAAA,CAAQ,QAAQ,IAAI,uBACpC,qBAEF,QAAQ;AAAA,QACN,kCAAkC,KAAK,UAAU,iBAAiB,CAAC;AAAA,MAAA;AAAA,IAGzE,SAAS,KAAK;AACZ,cAAQ,MAAM,kCAAkC,GAAG;AAAA,IACrD;AAEF,SACEA,2BAAAA;AAAAA,IAACC,gCAAAA;AAAAA,IAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU,MAAM,YAAY;AAAA,MAC5B,eAAe,MAAM,iBAAiB;AAAA,IAAA;AAAA,EAAA;AAG5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.d.cts DELETED
@@ -1,41 +0,0 @@
1
- import {createClient} from '@sanity/client'
2
- import {CreateDataAttribute} from '@sanity/visual-editing/create-data-attribute'
3
- import {createDataAttribute} from '@sanity/visual-editing/create-data-attribute'
4
- import {CreateDataAttributeProps} from '@sanity/visual-editing/create-data-attribute'
5
- import {defineQuery} from 'groq'
6
- import {default as groq} from 'groq'
7
- import {stegaClean} from '@sanity/client/stega'
8
- import {unstable__adapter} from '@sanity/client'
9
- import {unstable__environment} from '@sanity/client'
10
- import {VisualEditingProps} from 'next-sanity/visual-editing/client-component'
11
-
12
- export {createClient}
13
-
14
- export {CreateDataAttribute}
15
-
16
- export {createDataAttribute}
17
-
18
- export {CreateDataAttributeProps}
19
-
20
- export {defineQuery}
21
-
22
- export {groq}
23
-
24
- export {stegaClean}
25
-
26
- export {unstable__adapter}
27
-
28
- export {unstable__environment}
29
-
30
- /**
31
- * @public
32
- */
33
- export declare function VisualEditing(props: VisualEditingProps): React.ReactElement
34
-
35
- export {VisualEditingProps}
36
-
37
- export * from '@portabletext/react'
38
- export * from '@sanity/client'
39
- export * from '@sanity/next-loader'
40
-
41
- export {}
@@ -1,12 +0,0 @@
1
- "use client";
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: !0 });
4
- var jsxRuntime = require("react/jsx-runtime"), react = require("react");
5
- const NextStudioClientComponent = react.lazy(() => Promise.resolve().then(function() {
6
- return require("../_chunks-cjs/NextStudio.cjs");
7
- }));
8
- function NextStudioLazyClientComponent(props) {
9
- return /* @__PURE__ */ jsxRuntime.jsx(react.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(NextStudioClientComponent, { ...props }) });
10
- }
11
- exports.NextStudio = NextStudioLazyClientComponent;
12
- //# sourceMappingURL=client-component.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-component.cjs","sources":["../../src/studio/client-component/NextStudioLazy.tsx"],"sourcesContent":["/**\n *\n * If pages router supported `next/dynamic` imports (it wants `next/dynamic.js`),\n * or if turbopack in app router allowed `next/dynamic.js` (it doesn't yet)\n * we could use `dynamic(() => import('...), {ssr: false})` here.\n * Since we can't, we need to use a lazy import and Suspense ourself.\n */\n\nimport {lazy, Suspense} from 'react'\n\nimport type {NextStudioProps} from './NextStudio'\n\nconst NextStudioClientComponent = lazy(() => import('./NextStudio'))\n\nexport function NextStudioLazyClientComponent(props: NextStudioProps): React.ReactNode {\n return (\n <Suspense fallback={null}>\n <NextStudioClientComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["lazy","jsx","Suspense"],"mappings":";;;;AAYA,MAAM,4BAA4BA,MAAAA,KAAK,MAAM,QAAA,QAAA,EAAA,KAAA,WAAA;AAAA,SAAA,QAAO,+BAAc;EAAC;AAE5D,SAAS,8BAA8B,OAAyC;AACrF,SACEC,+BAACC,MAAAA,YAAS,UAAU,MAClB,yCAAC,2BAAA,EAA2B,GAAG,OAAO,EAAA,CACxC;AAEJ;;"}
@@ -1,23 +0,0 @@
1
- import {StudioProps} from 'sanity'
2
-
3
- export declare function NextStudio(props: NextStudioProps): React.ReactNode
4
-
5
- /** @public */
6
- export declare interface NextStudioProps extends StudioProps {
7
- children?: React.ReactNode
8
- /**
9
- * Render the <noscript> tag
10
- * @defaultValue true
11
- * @alpha
12
- */
13
- unstable__noScript?: boolean
14
- /**
15
- * The 'hash' option is new feature that is not yet stable for production, but is available for testing and its API won't change in a breaking way.
16
- * If 'hash' doesn't work for you, or if you want to use a memory based history, you can use the `unstable_history` prop instead.
17
- * @alpha
18
- * @defaultValue 'browser'
19
- */
20
- history?: 'browser' | 'hash'
21
- }
22
-
23
- export {}
package/dist/studio.cjs DELETED
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var NextStudioNoScript = require("./_chunks-cjs/NextStudioNoScript.cjs"), jsxRuntime = require("react/jsx-runtime"), clientComponent = require("next-sanity/studio/client-component"), reactDom = require("react-dom");
4
- const viewport = {
5
- width: "device-width",
6
- initialScale: 1,
7
- // Studio implements display cutouts CSS (The iPhone Notch ™ ) and needs `viewport-fit=covered` for it to work correctly
8
- viewportFit: "cover"
9
- }, metadata = {
10
- referrer: "same-origin",
11
- robots: "noindex"
12
- }, bridgeScript = "https://core.sanity-cdn.com/bridge.js";
13
- function NextStudioWithBridge(props) {
14
- return reactDom.preloadModule(bridgeScript, { as: "script" }), /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
15
- /* @__PURE__ */ jsxRuntime.jsx("script", { src: bridgeScript, async: !0, type: "module", "data-sanity-core": !0 }),
16
- /* @__PURE__ */ jsxRuntime.jsx(clientComponent.NextStudio, { ...props })
17
- ] });
18
- }
19
- exports.NextStudioLayout = NextStudioNoScript.NextStudioLayout;
20
- exports.NextStudioNoScript = NextStudioNoScript.NextStudioNoScript;
21
- exports.NextStudio = NextStudioWithBridge;
22
- exports.metadata = metadata;
23
- exports.viewport = viewport;
24
- //# sourceMappingURL=studio.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"studio.cjs","sources":["../src/studio/head.tsx","../src/studio/NextStudioWithBridge.tsx"],"sourcesContent":["import type {Metadata, Viewport} from 'next'\n\n/**\n * In router segments (`/app/studio/[[...index]]/page.tsx`):\n * ```tsx\n * // If you don't want to change any defaults you can just re-export the viewport config directly:\n * export {viewport} from 'next-sanity/studio'\n *\n * // To customize the viewport config, spread it on the export:\n * import {viewport as studioViewport} from 'next-sanity/studio'\n * import type { Viewport } from 'next'\n *\n * export const viewport: Viewport = {\n * ...studioViewport,\n * // Overrides the viewport to resize behavior\n * interactiveWidget: 'resizes-content'\n * })\n * ```\n * @public\n */\nexport const viewport = {\n width: 'device-width' as const,\n initialScale: 1 as const,\n // Studio implements display cutouts CSS (The iPhone Notch ™ ) and needs `viewport-fit=covered` for it to work correctly\n viewportFit: 'cover',\n} satisfies Viewport\n\n/**\n * In router segments (`/app/studio/[[...index]]/page.tsx`):\n * ```tsx\n * // If you don't want to change any defaults you can just re-export the metadata directly:\n * export {metadata} from 'next-sanity/studio'\n *\n * // To customize the metadata, spread it on the export:\n * import {metadata as studioMetadata} from 'next-sanity/studio'\n * import type { Metadata } from 'next'\n *\n * export const metadata: Metadata = {\n * ...studioMetadata,\n * // Set another title\n * title: 'My Studio',\n * })\n * ```\n * @public\n */\nexport const metadata = {\n referrer: 'same-origin' as const,\n robots: 'noindex' as const,\n} satisfies Metadata\n","import {NextStudio, type NextStudioProps} from 'next-sanity/studio/client-component'\nimport {preloadModule} from 'react-dom'\n\n/**\n * Loads the bridge script the same way Sanity Studio does:\n * https://github.com/sanity-io/sanity/blob/bd5b1acb5015baaddd8d96c2abd1eaf579b3c904/packages/sanity/src/_internal/cli/server/renderDocument.tsx#L124-L139\n */\n\nconst bridgeScript = 'https://core.sanity-cdn.com/bridge.js'\n\nexport function NextStudioWithBridge(props: NextStudioProps): React.JSX.Element {\n preloadModule(bridgeScript, {as: 'script'})\n\n return (\n <>\n <script src={bridgeScript} async type=\"module\" data-sanity-core />\n <NextStudio {...props} />\n </>\n )\n}\n"],"names":["preloadModule","jsxs","Fragment","jsx","NextStudio"],"mappings":";;;AAoBO,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,cAAc;AAAA;AAAA,EAEd,aAAa;AACf,GAoBa,WAAW;AAAA,EACtB,UAAU;AAAA,EACV,QAAQ;AACV,GCxCM,eAAe;AAEd,SAAS,qBAAqB,OAA2C;AAC9E,SAAAA,SAAAA,cAAc,cAAc,EAAC,IAAI,SAAA,CAAS,GAGxCC,2BAAAA,KAAAC,qBAAA,EACE,UAAA;AAAA,IAAAC,2BAAAA,IAAC,UAAA,EAAO,KAAK,cAAc,OAAK,IAAC,MAAK,UAAS,oBAAgB,GAAA,CAAC;AAAA,IAChEA,+BAACC,gBAAAA,YAAA,EAAY,GAAG,MAAA,CAAO;AAAA,EAAA,GACzB;AAEJ;;;;;;"}
package/dist/studio.d.cts DELETED
@@ -1,69 +0,0 @@
1
- import {JSX} from 'react'
2
- import {MemoExoticComponent} from 'react'
3
- import {NextStudioProps} from 'next-sanity/studio/client-component'
4
-
5
- /**
6
- * In router segments (`/app/studio/[[...index]]/page.tsx`):
7
- * ```tsx
8
- * // If you don't want to change any defaults you can just re-export the metadata directly:
9
- * export {metadata} from 'next-sanity/studio'
10
- *
11
- * // To customize the metadata, spread it on the export:
12
- * import {metadata as studioMetadata} from 'next-sanity/studio'
13
- * import type { Metadata } from 'next'
14
- *
15
- * export const metadata: Metadata = {
16
- * ...studioMetadata,
17
- * // Set another title
18
- * title: 'My Studio',
19
- * })
20
- * ```
21
- * @public
22
- */
23
- export declare const metadata: {
24
- referrer: 'same-origin'
25
- robots: 'noindex'
26
- }
27
-
28
- export declare function NextStudio(props: NextStudioProps): React.JSX.Element
29
-
30
- /** @public */
31
- export declare const NextStudioLayout: MemoExoticComponent<
32
- ({children}: NextStudioLayoutProps) => JSX.Element
33
- >
34
-
35
- /** @public */
36
- export declare interface NextStudioLayoutProps {
37
- children: React.ReactNode
38
- }
39
-
40
- /** @internal */
41
- export declare const NextStudioNoScript: () => React.JSX.Element
42
-
43
- export {NextStudioProps}
44
-
45
- /**
46
- * In router segments (`/app/studio/[[...index]]/page.tsx`):
47
- * ```tsx
48
- * // If you don't want to change any defaults you can just re-export the viewport config directly:
49
- * export {viewport} from 'next-sanity/studio'
50
- *
51
- * // To customize the viewport config, spread it on the export:
52
- * import {viewport as studioViewport} from 'next-sanity/studio'
53
- * import type { Viewport } from 'next'
54
- *
55
- * export const viewport: Viewport = {
56
- * ...studioViewport,
57
- * // Overrides the viewport to resize behavior
58
- * interactiveWidget: 'resizes-content'
59
- * })
60
- * ```
61
- * @public
62
- */
63
- export declare const viewport: {
64
- width: 'device-width'
65
- initialScale: 1
66
- viewportFit: 'cover'
67
- }
68
-
69
- export {}
@@ -1,11 +0,0 @@
1
- "use client";
2
- "use strict";
3
- var jsxRuntime = require("react/jsx-runtime"), react = require("react");
4
- const VisualEditingClientComponent = react.lazy(() => Promise.resolve().then(function() {
5
- return require("../_chunks-cjs/VisualEditing.cjs");
6
- }));
7
- function VisualEditingLazyClientComponent(props) {
8
- return /* @__PURE__ */ jsxRuntime.jsx(react.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(VisualEditingClientComponent, { ...props }) });
9
- }
10
- module.exports = VisualEditingLazyClientComponent;
11
- //# sourceMappingURL=client-component.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-component.cjs","sources":["../../src/visual-editing/client-component/VisualEditingLazy.tsx"],"sourcesContent":["/**\n *\n * If pages router supported `next/dynamic` imports (it wants `next/dynamic.js`),\n * or if turbopack in app router allowed `next/dynamic.js` (it doesn't yet)\n * we could use `dynamic(() => import('...), {ssr: false})` here.\n * Since we can't, we need to use a lazy import and Suspense ourself.\n */\n\nimport {lazy, Suspense} from 'react'\n\nimport type {VisualEditingProps} from './VisualEditing'\n\nconst VisualEditingClientComponent = lazy(() => import('./VisualEditing'))\n\nexport function VisualEditingLazyClientComponent(props: VisualEditingProps): React.ReactNode {\n return (\n <Suspense fallback={null}>\n <VisualEditingClientComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["lazy","jsx","Suspense"],"mappings":";;;AAYA,MAAM,+BAA+BA,MAAAA,KAAK,MAAM,QAAA,QAAA,EAAA,KAAA,WAAA;AAAA,SAAA,QAAO,kCAAiB;EAAC;AAElE,SAAS,iCAAiC,OAA4C;AAC3F,SACEC,+BAACC,MAAAA,YAAS,UAAU,MAClB,yCAAC,8BAAA,EAA8B,GAAG,OAAO,EAAA,CAC3C;AAEJ;;"}
@@ -1,32 +0,0 @@
1
- import {VisualEditingOptions} from '@sanity/visual-editing/react'
2
-
3
- declare function VisualEditingLazyClientComponent(props: VisualEditingProps): React.ReactNode
4
- export default VisualEditingLazyClientComponent
5
-
6
- /**
7
- * @public
8
- */
9
- export declare interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {
10
- /**
11
- * @deprecated The histoy adapter is already implemented
12
- */
13
- history?: never
14
- /**
15
- * If next.config.ts is configured with a basePath we try to configure it automatically,
16
- * you can disable this by setting basePath to ''.
17
- * @example basePath="/my-custom-base-path"
18
- * @alpha experimental and may change without notice
19
- * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''
20
- */
21
- basePath?: string
22
- /**
23
- * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,
24
- * it can be controlled manually by passing a boolean.
25
- * @example trailingSlash={true}
26
- * @alpha experimental and may change without notice
27
- * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)
28
- */
29
- trailingSlash?: boolean
30
- }
31
-
32
- export {}
@@ -1,13 +0,0 @@
1
- "use server";
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: !0 });
4
- var cache_js = require("next/cache.js"), headers_js = require("next/headers.js");
5
- async function revalidateRootLayout() {
6
- if (!(await headers_js.draftMode()).isEnabled) {
7
- console.warn("Skipped revalidatePath request because draft mode is not enabled");
8
- return;
9
- }
10
- await cache_js.revalidatePath("/", "layout");
11
- }
12
- exports.revalidateRootLayout = revalidateRootLayout;
13
- //# sourceMappingURL=server-actions.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-actions.cjs","sources":["../../src/visual-editing/server-actions/index.ts"],"sourcesContent":["'use server'\nimport {revalidatePath} from 'next/cache.js'\nimport {draftMode} from 'next/headers.js'\n\nexport async function revalidateRootLayout(): Promise<void> {\n if (!(await draftMode()).isEnabled) {\n // eslint-disable-next-line no-console\n console.warn('Skipped revalidatePath request because draft mode is not enabled')\n return\n }\n await revalidatePath('/', 'layout')\n}\n"],"names":["draftMode","revalidatePath"],"mappings":";;;;AAIA,eAAsB,uBAAsC;AAC1D,MAAI,EAAE,MAAMA,qBAAA,GAAa,WAAW;AAElC,YAAQ,KAAK,kEAAkE;AAC/E;AAAA,EACF;AACA,QAAMC,SAAAA,eAAe,KAAK,QAAQ;AACpC;;"}
@@ -1,3 +0,0 @@
1
- export declare function revalidateRootLayout(): Promise<void>
2
-
3
- export {}
package/dist/webhook.cjs DELETED
@@ -1,81 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- class WebhookSignatureValueError extends Error {
4
- type = "WebhookSignatureValueError";
5
- statusCode = 401;
6
- }
7
- class WebhookSignatureFormatError extends Error {
8
- type = "WebhookSignatureFormatError";
9
- statusCode = 400;
10
- }
11
- function isSignatureError(error) {
12
- return typeof error == "object" && error !== null && "type" in error && ["WebhookSignatureValueError", "WebhookSignatureFormatError"].includes(
13
- error.type
14
- );
15
- }
16
- const MINIMUM_TIMESTAMP = 16094592e5, SIGNATURE_HEADER_REGEX = /^t=(\d+)[, ]+v1=([^, ]+)$/, SIGNATURE_HEADER_NAME = "sanity-webhook-signature";
17
- async function assertValidSignature(stringifiedPayload, signature, secret) {
18
- const { timestamp } = decodeSignatureHeader(signature), encoded = await encodeSignatureHeader(stringifiedPayload, timestamp, secret);
19
- if (signature !== encoded)
20
- throw new WebhookSignatureValueError("Signature is invalid");
21
- }
22
- async function isValidSignature(stringifiedPayload, signature, secret) {
23
- try {
24
- return await assertValidSignature(stringifiedPayload, signature, secret), !0;
25
- } catch (err) {
26
- if (isSignatureError(err))
27
- return !1;
28
- throw err;
29
- }
30
- }
31
- async function encodeSignatureHeader(stringifiedPayload, timestamp, secret) {
32
- const signature = await createHS256Signature(stringifiedPayload, timestamp, secret);
33
- return `t=${timestamp},v1=${signature}`;
34
- }
35
- function decodeSignatureHeader(signaturePayload) {
36
- if (!signaturePayload)
37
- throw new WebhookSignatureFormatError("Missing or empty signature header");
38
- const [, timestamp, hashedPayload] = signaturePayload.trim().match(SIGNATURE_HEADER_REGEX) || [];
39
- if (!timestamp || !hashedPayload)
40
- throw new WebhookSignatureFormatError("Invalid signature payload format");
41
- return {
42
- timestamp: parseInt(timestamp, 10),
43
- hashedPayload
44
- };
45
- }
46
- async function createHS256Signature(stringifiedPayload, timestamp, secret) {
47
- if (typeof crypto > "u")
48
- throw new TypeError(
49
- "The Web Crypto API is not available in this environment, either polyfill `globalThis.crypto` or downgrade to `@sanity/webhook@3` which uses the Node.js `crypto` module."
50
- );
51
- if (!secret || typeof secret != "string")
52
- throw new WebhookSignatureFormatError("Invalid secret provided");
53
- if (!stringifiedPayload)
54
- throw new WebhookSignatureFormatError("Can not create signature for empty payload");
55
- if (typeof stringifiedPayload != "string")
56
- throw new WebhookSignatureFormatError("Payload must be a JSON-encoded string");
57
- if (typeof timestamp != "number" || isNaN(timestamp) || timestamp < MINIMUM_TIMESTAMP)
58
- throw new WebhookSignatureFormatError(
59
- "Invalid signature timestamp, must be a unix timestamp with millisecond precision"
60
- );
61
- const enc = new TextEncoder(), key = await crypto.subtle.importKey(
62
- "raw",
63
- enc.encode(secret),
64
- { name: "HMAC", hash: "SHA-256" },
65
- !1,
66
- ["sign"]
67
- ), signaturePayload = `${timestamp}.${stringifiedPayload}`, signature = await crypto.subtle.sign("HMAC", key, enc.encode(signaturePayload)), signatureArray = Array.from(new Uint8Array(signature));
68
- return btoa(String.fromCharCode.apply(null, signatureArray)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
69
- }
70
- async function parseBody(req, secret, waitForContentLakeEventualConsistency = !0) {
71
- const signature = req.headers.get(SIGNATURE_HEADER_NAME);
72
- if (!signature)
73
- return console.error("Missing signature header"), { body: null, isValidSignature: null };
74
- const body = await req.text(), validSignature = secret ? await isValidSignature(body, signature, secret.trim()) : null;
75
- return validSignature !== !1 && waitForContentLakeEventualConsistency && await new Promise((resolve) => setTimeout(resolve, 3e3)), {
76
- body: body.trim() ? JSON.parse(body) : null,
77
- isValidSignature: validSignature
78
- };
79
- }
80
- exports.parseBody = parseBody;
81
- //# sourceMappingURL=webhook.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"webhook.cjs","sources":["../../../node_modules/.pnpm/@sanity+webhook@4.0.4/node_modules/@sanity/webhook/dist/index.mjs","../src/webhook/index.ts"],"sourcesContent":["class WebhookSignatureValueError extends Error {\n type = \"WebhookSignatureValueError\";\n statusCode = 401;\n}\nclass WebhookSignatureFormatError extends Error {\n type = \"WebhookSignatureFormatError\";\n statusCode = 400;\n}\nfunction isSignatureError(error) {\n return typeof error == \"object\" && error !== null && \"type\" in error && [\"WebhookSignatureValueError\", \"WebhookSignatureFormatError\"].includes(\n error.type\n );\n}\nconst MINIMUM_TIMESTAMP = 16094592e5, SIGNATURE_HEADER_REGEX = /^t=(\\d+)[, ]+v1=([^, ]+)$/, SIGNATURE_HEADER_NAME = \"sanity-webhook-signature\";\nasync function assertValidSignature(stringifiedPayload, signature, secret) {\n const { timestamp } = decodeSignatureHeader(signature), encoded = await encodeSignatureHeader(stringifiedPayload, timestamp, secret);\n if (signature !== encoded)\n throw new WebhookSignatureValueError(\"Signature is invalid\");\n}\nasync function isValidSignature(stringifiedPayload, signature, secret) {\n try {\n return await assertValidSignature(stringifiedPayload, signature, secret), !0;\n } catch (err) {\n if (isSignatureError(err))\n return !1;\n throw err;\n }\n}\nasync function assertValidRequest(request, secret) {\n const signature = request.headers[SIGNATURE_HEADER_NAME];\n if (Array.isArray(signature))\n throw new WebhookSignatureFormatError(\"Multiple signature headers received\");\n if (typeof signature != \"string\")\n throw new WebhookSignatureValueError(\"Request contained no signature header\");\n if (typeof request.body > \"u\")\n throw new WebhookSignatureFormatError(\"Request contained no parsed request body\");\n if (typeof request.body == \"string\" || Buffer.isBuffer(request.body))\n await assertValidSignature(request.body.toString(\"utf8\"), signature, secret);\n else\n throw new Error(\n \"[@sanity/webhook] `request.body` was not a string/buffer - this can lead to invalid signatures. See the [migration docs](https://github.com/sanity-io/webhook-toolkit#from-parsed-to-unparsed-body) for details on how to fix this.\"\n );\n}\nasync function isValidRequest(request, secret) {\n try {\n return await assertValidRequest(request, secret), !0;\n } catch (err) {\n if (isSignatureError(err))\n return !1;\n throw err;\n }\n}\nasync function encodeSignatureHeader(stringifiedPayload, timestamp, secret) {\n const signature = await createHS256Signature(stringifiedPayload, timestamp, secret);\n return `t=${timestamp},v1=${signature}`;\n}\nfunction decodeSignatureHeader(signaturePayload) {\n if (!signaturePayload)\n throw new WebhookSignatureFormatError(\"Missing or empty signature header\");\n const [, timestamp, hashedPayload] = signaturePayload.trim().match(SIGNATURE_HEADER_REGEX) || [];\n if (!timestamp || !hashedPayload)\n throw new WebhookSignatureFormatError(\"Invalid signature payload format\");\n return {\n timestamp: parseInt(timestamp, 10),\n hashedPayload\n };\n}\nasync function createHS256Signature(stringifiedPayload, timestamp, secret) {\n if (typeof crypto > \"u\")\n throw new TypeError(\n \"The Web Crypto API is not available in this environment, either polyfill `globalThis.crypto` or downgrade to `@sanity/webhook@3` which uses the Node.js `crypto` module.\"\n );\n if (!secret || typeof secret != \"string\")\n throw new WebhookSignatureFormatError(\"Invalid secret provided\");\n if (!stringifiedPayload)\n throw new WebhookSignatureFormatError(\"Can not create signature for empty payload\");\n if (typeof stringifiedPayload != \"string\")\n throw new WebhookSignatureFormatError(\"Payload must be a JSON-encoded string\");\n if (typeof timestamp != \"number\" || isNaN(timestamp) || timestamp < MINIMUM_TIMESTAMP)\n throw new WebhookSignatureFormatError(\n \"Invalid signature timestamp, must be a unix timestamp with millisecond precision\"\n );\n const enc = new TextEncoder(), key = await crypto.subtle.importKey(\n \"raw\",\n enc.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n !1,\n [\"sign\"]\n ), signaturePayload = `${timestamp}.${stringifiedPayload}`, signature = await crypto.subtle.sign(\"HMAC\", key, enc.encode(signaturePayload)), signatureArray = Array.from(new Uint8Array(signature));\n return btoa(String.fromCharCode.apply(null, signatureArray)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction requireSignedRequest(options) {\n const parseBody = typeof options.parseBody > \"u\" ? !0 : options.parseBody, respondOnError = typeof options.respondOnError > \"u\" ? !0 : options.respondOnError;\n return async function(request, response, next) {\n try {\n await assertValidRequest(request, options.secret), parseBody && typeof request.body == \"string\" && (request.body = JSON.parse(request.body)), next();\n } catch (err) {\n if (!respondOnError || !isSignatureError(err)) {\n next(err);\n return;\n }\n response.status(err.statusCode).json({ message: err.message });\n }\n };\n}\nexport {\n SIGNATURE_HEADER_NAME,\n WebhookSignatureFormatError,\n WebhookSignatureValueError,\n assertValidRequest,\n assertValidSignature,\n decodeSignatureHeader,\n encodeSignatureHeader,\n isSignatureError,\n isValidRequest,\n isValidSignature,\n requireSignedRequest\n};\n//# sourceMappingURL=index.mjs.map\n","import type {SanityDocument} from '@sanity/types'\nimport {isValidSignature, SIGNATURE_HEADER_NAME} from '@sanity/webhook'\nimport type {NextRequest} from 'next/server'\n\n/** @public */\nexport type ParsedBody<T> = {\n /**\n * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`\n */\n isValidSignature: boolean | null\n body: T | null\n}\n\n/**\n * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries\n * without worrying about getting stale data.\n * @public\n */\nexport async function parseBody<Body = SanityDocument>(\n req: NextRequest,\n secret?: string,\n waitForContentLakeEventualConsistency = true,\n): Promise<ParsedBody<Body>> {\n const signature = req.headers.get(SIGNATURE_HEADER_NAME)\n if (!signature) {\n console.error('Missing signature header')\n return {body: null, isValidSignature: null}\n }\n\n const body = await req.text()\n const validSignature = secret ? await isValidSignature(body, signature, secret.trim()) : null\n\n if (validSignature !== false && waitForContentLakeEventualConsistency) {\n await new Promise((resolve) => setTimeout(resolve, 3000))\n }\n\n return {\n body: body.trim() ? JSON.parse(body) : null,\n isValidSignature: validSignature,\n }\n}\n"],"names":[],"mappings":";;AAAA,MAAM,mCAAmC,MAAM;AAAA,EAC7C,OAAO;AAAA,EACP,aAAa;AACf;AACA,MAAM,oCAAoC,MAAM;AAAA,EAC9C,OAAO;AAAA,EACP,aAAa;AACf;AACA,SAAS,iBAAiB,OAAO;AAC/B,SAAO,OAAO,SAAS,YAAY,UAAU,QAAQ,UAAU,SAAS,CAAC,8BAA8B,6BAA6B,EAAE;AAAA,IACpI,MAAM;AAAA,EACV;AACA;AACA,MAAM,oBAAoB,YAAY,yBAAyB,6BAA6B,wBAAwB;AACpH,eAAe,qBAAqB,oBAAoB,WAAW,QAAQ;AACzE,QAAM,EAAE,UAAS,IAAK,sBAAsB,SAAS,GAAG,UAAU,MAAM,sBAAsB,oBAAoB,WAAW,MAAM;AACnI,MAAI,cAAc;AAChB,UAAM,IAAI,2BAA2B,sBAAsB;AAC/D;AACA,eAAe,iBAAiB,oBAAoB,WAAW,QAAQ;AACrE,MAAI;AACF,WAAO,MAAM,qBAAqB,oBAAoB,WAAW,MAAM,GAAG;AAAA,EAC5E,SAAS,KAAK;AACZ,QAAI,iBAAiB,GAAG;AACtB,aAAO;AACT,UAAM;AAAA,EACR;AACF;AAyBA,eAAe,sBAAsB,oBAAoB,WAAW,QAAQ;AAC1E,QAAM,YAAY,MAAM,qBAAqB,oBAAoB,WAAW,MAAM;AAClF,SAAO,KAAK,SAAS,OAAO,SAAS;AACvC;AACA,SAAS,sBAAsB,kBAAkB;AAC/C,MAAI,CAAC;AACH,UAAM,IAAI,4BAA4B,mCAAmC;AAC3E,QAA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0B,GACjC,EAAC,MAAM,MAAM,kBAAkB,KAAA;AAGxC,QAAM,OAAO,MAAM,IAAI,KAAA,GACjB,iBAAiB,SAAS,MAAM,iBAAiB,MAAM,WAAW,OAAO,KAAA,CAAM,IAAI;AAEzF,SAAI,mBAAmB,MAAS,yCAC9B,MAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC,GAGnD;AAAA,IACL,MAAM,KAAK,KAAA,IAAS,KAAK,MAAM,IAAI,IAAI;AAAA,IACvC,kBAAkB;AAAA,EAAA;AAEtB;;","x_google_ignoreList":[0]}
@@ -1,33 +0,0 @@
1
- import type {NextRequest} from 'next/server'
2
-
3
- /**
4
- * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries
5
- * without worrying about getting stale data.
6
- * @public
7
- */
8
- export declare function parseBody<Body = SanityDocument>(
9
- req: NextRequest,
10
- secret?: string,
11
- waitForContentLakeEventualConsistency?: boolean,
12
- ): Promise<ParsedBody<Body>>
13
-
14
- /** @public */
15
- export declare type ParsedBody<T> = {
16
- /**
17
- * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`
18
- */
19
- isValidSignature: boolean | null
20
- body: T | null
21
- }
22
-
23
- /** @public */
24
- declare interface SanityDocument {
25
- _id: string
26
- _type: string
27
- _createdAt: string
28
- _updatedAt: string
29
- _rev: string
30
- [key: string]: unknown
31
- }
32
-
33
- export {}