next-sanity 11.5.5 → 11.5.7-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NextStudio.js +1 -1
- package/dist/NextStudioNoScript.js +1 -1
- package/dist/PresentationComlink.js +2 -2
- package/dist/PresentationComlink2.js +1 -1
- package/dist/SanityLiveStream.js +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/context.js +1 -1
- package/dist/defineLive.d.ts +1 -1
- package/dist/experimental/client-components/live.d.ts +1 -1
- package/dist/experimental/client-components/live.js +4 -4
- package/dist/experimental/live.d.ts +1 -1
- package/dist/experimental/live.js +16 -6
- package/dist/experimental/live.js.map +1 -1
- package/dist/hooks/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/isCorsOriginError.d.ts +1 -1
- package/dist/isCorsOriginError.js +1 -1
- package/dist/live/client-components/live/index.js +2 -2
- package/dist/live/server-actions/index.js +1 -1
- package/dist/live.d.ts +2 -2
- package/dist/live.js +2 -2
- package/dist/live.server-only.d.ts +2 -2
- package/dist/live.server-only.js +1 -1
- package/dist/studio/index.js +1 -1
- package/dist/utils.js +1 -1
- package/package.json +9 -9
- package/src/experimental/live.tsx +18 -3
package/dist/NextStudio.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NextStudioLayout, NextStudioNoScript } from "./NextStudioNoScript.js";
|
|
1
|
+
import { n as NextStudioLayout, t as NextStudioNoScript } from "./NextStudioNoScript.js";
|
|
2
2
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { useMemo, useSyncExternalStore } from "react";
|
|
4
4
|
import { Studio } from "sanity";
|
|
@@ -47,6 +47,6 @@ const NextStudioNoScript = () => /* @__PURE__ */ jsx("noscript", { children: /*
|
|
|
47
47
|
] })]
|
|
48
48
|
})
|
|
49
49
|
}) });
|
|
50
|
-
export { NextStudioLayout, NextStudioNoScript };
|
|
50
|
+
export { NextStudioLayout as n, NextStudioNoScript as t };
|
|
51
51
|
|
|
52
52
|
//# sourceMappingURL=NextStudioNoScript.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { sanitizePerspective } from "./utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { t as sanitizePerspective } from "./utils.js";
|
|
2
|
+
import { f as setPerspective, l as setComlink, s as perspective, u as setComlinkClientConfig } from "./context.js";
|
|
3
3
|
import { useRouter } from "next/navigation";
|
|
4
4
|
import { startTransition, useEffect } from "react";
|
|
5
5
|
import { createNode, createNodeMachine } from "@sanity/comlink";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { setComlink, setComlinkClientConfig } from "./context.js";
|
|
1
|
+
import { l as setComlink, u as setComlinkClientConfig } from "./context.js";
|
|
2
2
|
import { useRouter } from "next/navigation";
|
|
3
3
|
import { useEffect } from "react";
|
|
4
4
|
import { createNode, createNodeMachine } from "@sanity/comlink";
|
package/dist/SanityLiveStream.js
CHANGED
package/dist/constants.d.ts
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
declare const PUBLISHED_SYNC_TAG_PREFIX = "sp:";
|
|
3
3
|
declare const DRAFT_SYNC_TAG_PREFIX = "sd:";
|
|
4
4
|
//#endregion
|
|
5
|
-
export {
|
|
5
|
+
export { PUBLISHED_SYNC_TAG_PREFIX as n, DRAFT_SYNC_TAG_PREFIX as t };
|
|
6
6
|
//# sourceMappingURL=constants.d.ts.map
|
package/dist/constants.js
CHANGED
package/dist/context.js
CHANGED
|
@@ -26,6 +26,6 @@ function setComlinkClientConfig(nextComlinkProjectId, nextComlinkDataset) {
|
|
|
26
26
|
comlinkDataset = nextComlinkDataset;
|
|
27
27
|
for (const onComlinkChange of comlinkListeners) onComlinkChange();
|
|
28
28
|
}
|
|
29
|
-
export {
|
|
29
|
+
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 };
|
|
30
30
|
|
|
31
31
|
//# sourceMappingURL=context.js.map
|
package/dist/defineLive.d.ts
CHANGED
|
@@ -175,5 +175,5 @@ declare function defineLive(config: DefineSanityLiveOptions): {
|
|
|
175
175
|
SanityLiveStream: DefinedSanityLiveStreamType;
|
|
176
176
|
};
|
|
177
177
|
//#endregion
|
|
178
|
-
export {
|
|
178
|
+
export { defineLive as a, DefinedSanityLiveStreamType as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
|
|
179
179
|
//# sourceMappingURL=defineLive.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
2
2
|
import { ClientPerspective, InitializedClientConfig, LiveEventGoAway, SyncTag } from "@sanity/client";
|
|
3
3
|
|
|
4
4
|
//#region src/experimental/types.d.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { isCorsOriginError } from "../../isCorsOriginError.js";
|
|
3
|
-
import { sanitizePerspective } from "../../utils.js";
|
|
4
|
-
import { PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
5
|
-
import { setEnvironment, setPerspective } from "../../context.js";
|
|
2
|
+
import { t as isCorsOriginError } from "../../isCorsOriginError.js";
|
|
3
|
+
import { t as sanitizePerspective } from "../../utils.js";
|
|
4
|
+
import { n as PUBLISHED_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
5
|
+
import { d as setEnvironment, f as setPerspective } from "../../context.js";
|
|
6
6
|
import { createClient } from "@sanity/client";
|
|
7
7
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
8
8
|
import { useRouter } from "next/navigation";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../constants.js";
|
|
2
2
|
import { cookies } from "next/headers";
|
|
3
3
|
import "server-only";
|
|
4
4
|
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "next-sanity";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { sanitizePerspective } from "../utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { t as sanitizePerspective } from "../utils.js";
|
|
2
|
+
import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../constants.js";
|
|
3
3
|
import { stegaEncodeSourceMap } from "@sanity/client/stega";
|
|
4
4
|
import { preconnect } from "react-dom";
|
|
5
5
|
import { cookies, draftMode } from "next/headers";
|
|
@@ -8,17 +8,26 @@ import { jsx } from "react/jsx-runtime";
|
|
|
8
8
|
import "server-only";
|
|
9
9
|
import { createClient } from "next-sanity";
|
|
10
10
|
import SanityLiveClientComponent from "next-sanity/experimental/client-components/live";
|
|
11
|
-
import { cacheTag, updateTag } from "next/cache";
|
|
11
|
+
import { cacheLife, cacheTag, updateTag } from "next/cache";
|
|
12
12
|
async function resolvePerspectiveFromCookie({ cookies: jar }) {
|
|
13
13
|
return jar.has(perspectiveCookieName) ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, "drafts") : "drafts";
|
|
14
14
|
}
|
|
15
15
|
async function sanityCachedFetch(config, { query, params = {}, perspective, stega, requestTag, draftToken, customCacheTags = [] }) {
|
|
16
|
-
"use cache";
|
|
16
|
+
"use cache: remote";
|
|
17
17
|
const client = createClient({
|
|
18
18
|
...config,
|
|
19
19
|
useCdn: true
|
|
20
20
|
});
|
|
21
21
|
const useCdn = perspective === "published";
|
|
22
|
+
console.log("sanityCachedFetch", {
|
|
23
|
+
query,
|
|
24
|
+
params,
|
|
25
|
+
perspective,
|
|
26
|
+
stega,
|
|
27
|
+
requestTag,
|
|
28
|
+
draftToken,
|
|
29
|
+
customCacheTags
|
|
30
|
+
});
|
|
22
31
|
const { result, resultSourceMap, syncTags } = await client.fetch(query, params, {
|
|
23
32
|
filterResponse: false,
|
|
24
33
|
returnQuery: false,
|
|
@@ -31,6 +40,7 @@ async function sanityCachedFetch(config, { query, params = {}, perspective, steg
|
|
|
31
40
|
});
|
|
32
41
|
const tags = [...customCacheTags, ...(syncTags || []).map((tag) => `${perspective === "published" ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`)];
|
|
33
42
|
cacheTag(...tags);
|
|
43
|
+
cacheLife({ revalidate: 3600 * 24 * 90 });
|
|
34
44
|
return {
|
|
35
45
|
data: result,
|
|
36
46
|
sourceMap: resultSourceMap || null,
|
|
@@ -69,7 +79,8 @@ function defineLive(config) {
|
|
|
69
79
|
stega,
|
|
70
80
|
requestTag,
|
|
71
81
|
draftToken: serverToken,
|
|
72
|
-
customCacheTags
|
|
82
|
+
customCacheTags,
|
|
83
|
+
client
|
|
73
84
|
});
|
|
74
85
|
return {
|
|
75
86
|
data: stega && sourceMap ? stegaEncodeSourceMap(_data, sourceMap, {
|
|
@@ -110,7 +121,6 @@ function defineLive(config) {
|
|
|
110
121
|
};
|
|
111
122
|
}
|
|
112
123
|
const SanityLiveServerComponent = async function SanityLiveServerComponent$1(props) {
|
|
113
|
-
"use cache";
|
|
114
124
|
const { config, requestTag, intervalOnGoAway, onError, onGoAway, refreshOnFocus, refreshOnMount, refreshOnReconnect, revalidateSyncTags, browserToken, resolveDraftModePerspective: resolveDraftModePerspective$1 } = props;
|
|
115
125
|
const { isEnabled: isDraftModeEnabled } = await draftMode();
|
|
116
126
|
return /* @__PURE__ */ jsx(SanityLiveClientComponent, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":["SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps>","SanityLiveServerComponent","resolveDraftModePerspective"],"sources":["../../src/experimental/live.tsx"],"sourcesContent":["// oxlint-disable-next-line no-unassigned-import\nimport 'server-only'\nimport {\n createClient,\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from 'next-sanity'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport SanityLiveClientComponent, {\n type SanityLiveProps,\n} from 'next-sanity/experimental/client-components/live'\nimport {cacheTag, updateTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {preconnect} from 'react-dom'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {sanitizePerspective} from '../live/utils'\nimport type {SanityClientConfig} from './types'\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport async function resolvePerspectiveFromCookie({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n\nasync function sanityCachedFetch<const QueryString extends string>(\n config: SanityClientConfig,\n {\n query,\n params = {},\n perspective,\n stega,\n requestTag,\n draftToken,\n customCacheTags = [],\n }: {\n query: QueryString\n params?: QueryParams\n perspective: Exclude<ClientPerspective, 'raw'>\n stega: boolean\n requestTag: string\n draftToken?: string | false | undefined\n customCacheTags?: string[]\n },\n): Promise<{\n data: ClientReturn<QueryString, unknown>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}> {\n 'use cache'\n\n const client = createClient({...config, useCdn: true})\n const useCdn = perspective === 'published'\n /**\n * The default cache profile isn't ideal for live content, as it has unnecessary time based background validation, as well as a too lazy client stale value\n * https://github.com/vercel/next.js/blob/8dd358002baf4244c0b2e38b5bda496daf60dacb/packages/next/cache.d.ts#L14-L26\n */\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n resultSourceMap: stega ? 'withKeyArraySelector' : undefined, // @TODO allow passing csm for non-stega use\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? config.token : draftToken || config.token, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n perspective?: Exclude<ClientPerspective, 'raw'>\n /**\n * Enables stega encoding of the data, this is typically only used in draft mode.\n * If `defineLive({..., stega: true})` is provided, then it defaults to `true` in Draft Mode.\n * If `defineLive({..., stega: false})` then it defaults to `false`.\n */\n stega?: boolean\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n /**\n * Custom cache tags that can be used with next's `revalidateTag` function for custom webhook on-demand revalidation.\n */\n tags?: string[]\n}) => Promise<{\n data: ClientReturn<QueryString, unknown>\n /**\n * The Content Source Map can be used for custom setups like `encodeSourceMap` for `data-sanity` attributes, or `stegaEncodeSourceMap` for stega encoding in your own way.\n * The Content Source Map is only fetched by default in draft mode, if `stega` is `true`. Otherwise your client configuration will need to have `resultSourceMap: 'withKeyArraySelector' | true`\n */\n sourceMap: ContentSourceMap | null\n /**\n * The perspective used to fetch the data, useful for debugging.\n */\n perspective: Exclude<ClientPerspective, 'raw'>\n /**\n * The cache tags used with `next/cache`, useful for debugging.\n */\n tags: string[]\n}>\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * @defaultValue `false`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * @defaultValue `false`\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * @defaultValue `false`\n */\n refreshOnReconnect?: boolean\n /**\n * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.\n * This typically happens if the connection limit is reached, or if the connection is idle for too long.\n * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.\n * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.\n * @defaultValue `30_000` 30 seconds interval\n */\n intervalOnGoAway?: number | false\n\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live'\n */\n requestTag?: string\n\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n\n /**\n * Handle the `goaway` event if the connection is rejected/closed.\n * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.\n * When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.\n * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.\n */\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n /**\n * Override how cache tags are invalidated, you need to pass a server action here.\n * You can also pass a `use client` function here, and have `router.refresh()` be called if the promise resolves to `'refresh'`.\n */\n // @TODO remove, replace with onLiveEvent\n revalidateSyncTags?: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n\n // @TODO add\n // decide how to handle a live event coming in\n // onLiveEvent?: (event: LiveEvent, mode: 'production' | 'preview) => void\n\n /**\n * Control how the draft mode perspective is resolved, by default it resolves from the `sanity-preview-perspective` cookie.\n */\n resolveDraftModePerspective?: () => Promise<ClientPerspective>\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true` if the client configuration has the `stega.studioUrl` property set, otherwise `false`\n */\n stega?: boolean\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n // eslint-disable-next-line no-console\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n // eslint-disable-next-line no-console\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken, stega: stegaConfig} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n const {stega: stegaEnabled = typeof client.config().stega.studioUrl !== 'undefined'} = config\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags: customCacheTags = [],\n perspective: _perspective,\n requestTag = 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? ((await draftMode()).isEnabled ? 'drafts' : 'published')\n\n const {apiHost, apiVersion, useProjectHostname, dataset, projectId, requestTagPrefix} =\n client.config()\n const {\n data: _data,\n sourceMap,\n tags,\n } = await sanityCachedFetch(\n {\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n token: originalToken,\n },\n {\n query,\n params: await params,\n perspective,\n stega,\n requestTag,\n draftToken: serverToken,\n customCacheTags,\n },\n )\n\n const data =\n stega && sourceMap\n ? stegaEncodeSourceMap(_data, sourceMap, {...stegaConfig, enabled: true})\n : _data\n\n return {data, sourceMap, tags, perspective}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = function SanityLive(props) {\n const {\n // perspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags = expireTags,\n } = props\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n preconnect(origin)\n\n return (\n <SanityLiveServerComponent\n config={{projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix}}\n requestTag={requestTag}\n browserToken={browserToken}\n // origin={origin}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={\n props.resolveDraftModePerspective ?? resolveDraftModePerspective\n }\n />\n )\n }\n\n return {sanityFetch, SanityLive}\n}\n\ninterface SanityLiveServerComponentProps\n extends Omit<SanityLiveProps, 'draftModeEnabled' | 'token' | 'draftModePerspective'> {\n browserToken: string | false | undefined\n // origin: string\n // perspective?: Exclude<ClientPerspective, 'raw'>\n}\n\nconst SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps> =\n async function SanityLiveServerComponent(props) {\n 'use cache'\n // @TODO should this be 'max' instead?, or configured by changing the default cache profile?\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n const {\n config,\n requestTag,\n intervalOnGoAway,\n onError,\n onGoAway,\n refreshOnFocus,\n refreshOnMount,\n refreshOnReconnect,\n revalidateSyncTags,\n browserToken,\n // origin,\n // perspective,\n resolveDraftModePerspective,\n } = props\n\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n // preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n ...config,\n token: typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined,\n }}\n requestTag={requestTag}\n draftModeEnabled={isDraftModeEnabled}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n )\n }\n\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nasync function expireTags(_tags: unknown): Promise<void> {\n 'use server'\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n\nasync function resolveDraftModePerspective(): Promise<ClientPerspective> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookie({cookies: jar})\n }\n return 'published'\n}\n\n/**\n * Add more stuff:\n * - sanityFetchMetadata: sanityFetch({query, params, stega: false, perspective: 'auto'})\n * - sanityFetchStaticParams: sanityFetch({query, params, stega: false, perspective: 'published', cacheMode: undefined})\n * - sanityFetchCached: sanityFetch({query, params, stega: 'opt-in',perspective: 'opt-in'}) useful for 'use cache' components, no unexpected magic, maybe this will be `sanityFetch` instead\n * - sanityFetchDynamic: sanityFetch({query, params, stega: 'auto', perspective: 'auto'}) just like sanityFetch of old, since `sanityFetch` will likely become opt-in\n */\n"],"mappings":";;;;;;;;;;;AA2BA,eAAsB,6BAA6B,EACjD,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,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,MAAM,EAAC,WAAW,uBAAsB,MAAM,WAAW;AAKzD,QACE,oBAAC,2BAAA;EACC,QAAQ;GACN,GAAG;GACH,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;GAChF;EACW;EACZ,kBAAkB;EACF;EACA;EACI;EACX;EACC;EACQ;EACE;EACpB,6BAA6BC;GAC7B;;AAOR,eAAe,WAAW,OAA+B;AACvD;AAIA,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAEhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG;;AAGhE,eAAe,8BAA0D;AACvE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,6BAA6B,EAAC,SADzB,MAAM,SAAS,EACuB,CAAC;AAErD,QAAO"}
|
|
1
|
+
{"version":3,"file":"live.js","names":["SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps>","SanityLiveServerComponent","resolveDraftModePerspective"],"sources":["../../src/experimental/live.tsx"],"sourcesContent":["// oxlint-disable-next-line no-unassigned-import\nimport 'server-only'\nimport {\n createClient,\n type ClientPerspective,\n type ClientReturn,\n type ContentSourceMap,\n type LiveEventGoAway,\n type QueryParams,\n type SanityClient,\n type SyncTag,\n} from 'next-sanity'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport SanityLiveClientComponent, {\n type SanityLiveProps,\n} from 'next-sanity/experimental/client-components/live'\nimport {cacheTag, cacheLife, updateTag} from 'next/cache'\nimport {draftMode, cookies} from 'next/headers'\nimport {preconnect} from 'react-dom'\nimport {perspectiveCookieName} from '@sanity/preview-url-secret/constants'\nimport {sanitizePerspective} from '../live/utils'\nimport type {SanityClientConfig} from './types'\nimport {DRAFT_SYNC_TAG_PREFIX, PUBLISHED_SYNC_TAG_PREFIX} from './constants'\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport async function resolvePerspectiveFromCookie({\n cookies: jar,\n}: {\n cookies: Awaited<ReturnType<typeof cookies>>\n}): Promise<Exclude<ClientPerspective, 'raw'>> {\n return jar.has(perspectiveCookieName)\n ? sanitizePerspective(jar.get(perspectiveCookieName)?.value, 'drafts')\n : 'drafts'\n}\n\nasync function sanityCachedFetch<const QueryString extends string>(\n config: SanityClientConfig,\n {\n query,\n params = {},\n perspective,\n stega,\n requestTag,\n draftToken,\n customCacheTags = [],\n }: {\n query: QueryString\n params?: QueryParams\n perspective: Exclude<ClientPerspective, 'raw'>\n stega: boolean\n requestTag: string\n draftToken?: string | false | undefined\n customCacheTags?: string[]\n },\n): Promise<{\n data: ClientReturn<QueryString, unknown>\n sourceMap: ContentSourceMap | null\n tags: string[]\n}> {\n 'use cache: remote'\n\n const client = createClient({...config, useCdn: true})\n const useCdn = perspective === 'published'\n /**\n * The default cache profile isn't ideal for live content, as it has unnecessary time based background validation, as well as a too lazy client stale value\n * https://github.com/vercel/next.js/blob/8dd358002baf4244c0b2e38b5bda496daf60dacb/packages/next/cache.d.ts#L14-L26\n */\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n console.log('sanityCachedFetch', {\n query,\n params,\n perspective,\n stega,\n requestTag,\n draftToken,\n customCacheTags,\n })\n\n const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {\n filterResponse: false,\n returnQuery: false,\n perspective,\n useCdn,\n resultSourceMap: stega ? 'withKeyArraySelector' : undefined, // @TODO allow passing csm for non-stega use\n cacheMode: useCdn ? 'noStale' : undefined,\n tag: requestTag,\n token: perspective === 'published' ? config.token : draftToken || config.token, // @TODO can pass undefined instead of config.token here?\n })\n const tags = [\n ...customCacheTags,\n ...(syncTags || []).map(\n (tag) =>\n `${perspective === 'published' ? PUBLISHED_SYNC_TAG_PREFIX : DRAFT_SYNC_TAG_PREFIX}${tag}`,\n ),\n ]\n /**\n * The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`\n */\n cacheTag(...tags)\n /**\n * Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short\n */\n cacheLife({revalidate: 60 * 60 * 24 * 90})\n\n return {data: result, sourceMap: resultSourceMap || null, tags}\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport type DefinedSanityFetchType = <const QueryString extends string>(options: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n perspective?: Exclude<ClientPerspective, 'raw'>\n /**\n * Enables stega encoding of the data, this is typically only used in draft mode.\n * If `defineLive({..., stega: true})` is provided, then it defaults to `true` in Draft Mode.\n * If `defineLive({..., stega: false})` then it defaults to `false`.\n */\n stega?: boolean\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.fetch'\n */\n requestTag?: string\n /**\n * Custom cache tags that can be used with next's `revalidateTag` function for custom webhook on-demand revalidation.\n */\n tags?: string[]\n}) => Promise<{\n data: ClientReturn<QueryString, unknown>\n /**\n * The Content Source Map can be used for custom setups like `encodeSourceMap` for `data-sanity` attributes, or `stegaEncodeSourceMap` for stega encoding in your own way.\n * The Content Source Map is only fetched by default in draft mode, if `stega` is `true`. Otherwise your client configuration will need to have `resultSourceMap: 'withKeyArraySelector' | true`\n */\n sourceMap: ContentSourceMap | null\n /**\n * The perspective used to fetch the data, useful for debugging.\n */\n perspective: Exclude<ClientPerspective, 'raw'>\n /**\n * The cache tags used with `next/cache`, useful for debugging.\n */\n tags: string[]\n}>\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefinedSanityLiveProps {\n /**\n * Automatic refresh of RSC when the component <SanityLive /> is mounted.\n * @defaultValue `false`\n */\n refreshOnMount?: boolean\n /**\n * Automatically refresh when window gets focused\n * @defaultValue `false`\n */\n refreshOnFocus?: boolean\n /**\n * Automatically refresh when the browser regains a network connection (via navigator.onLine)\n * @defaultValue `false`\n */\n refreshOnReconnect?: boolean\n /**\n * Automatically refresh on an interval when the Live Event API emits a `goaway` event, which indicates that the connection is rejected or closed.\n * This typically happens if the connection limit is reached, or if the connection is idle for too long.\n * To disable this long polling fallback behavior set `intervalOnGoAway` to `false` or `0`.\n * You can also use `onGoAway` to handle the `goaway` event in your own way, and read the reason why the event was emitted.\n * @defaultValue `30_000` 30 seconds interval\n */\n intervalOnGoAway?: number | false\n\n /**\n * This request tag is used to identify the request when viewing request logs from your Sanity Content Lake.\n * @see https://www.sanity.io/docs/reference-api-request-tags\n * @defaultValue 'next-loader.live'\n */\n requestTag?: string\n\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n\n /**\n * Handle the `goaway` event if the connection is rejected/closed.\n * `event.reason` will be a string of why the event was emitted, for example `'connection limit reached'`.\n * When this happens the `<SanityLive />` will fallback to long polling with a default interval of 30 seconds, providing your own `onGoAway` handler does not change this behavior.\n * If you want to disable long polling set `intervalOnGoAway` to `false` or `0`.\n */\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n\n /**\n * Override how cache tags are invalidated, you need to pass a server action here.\n * You can also pass a `use client` function here, and have `router.refresh()` be called if the promise resolves to `'refresh'`.\n */\n // @TODO remove, replace with onLiveEvent\n revalidateSyncTags?: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n\n // @TODO add\n // decide how to handle a live event coming in\n // onLiveEvent?: (event: LiveEvent, mode: 'production' | 'preview) => void\n\n /**\n * Control how the draft mode perspective is resolved, by default it resolves from the `sanity-preview-perspective` cookie.\n */\n resolveDraftModePerspective?: () => Promise<ClientPerspective>\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface DefineSanityLiveOptions {\n /**\n * Required for `sanityFetch` and `SanityLive` to work\n */\n client: SanityClient\n /**\n * Optional. If provided then the token needs to have permissions to query documents with `drafts.` prefixes in order for `perspective: 'drafts'` to work.\n * This token is not shared with the browser.\n */\n serverToken?: string | false\n /**\n * Optional. This token is shared with the browser, and should only have access to query published documents.\n * It is used to setup a `Live Draft Content` EventSource connection, and enables live previewing drafts stand-alone, outside of Presentation Tool.\n */\n browserToken?: string | false\n /**\n * Optional. Include stega encoding when draft mode is enabled.\n * @defaultValue `true` if the client configuration has the `stega.studioUrl` property set, otherwise `false`\n */\n stega?: boolean\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport function defineLive(config: DefineSanityLiveOptions): {\n /**\n * Use this function to fetch data from Sanity in your React Server Components.\n */\n sanityFetch: DefinedSanityFetchType\n /**\n * Render this in your root layout.tsx to make your page revalidate on new content live, automatically.\n */\n SanityLive: React.ComponentType<DefinedSanityLiveProps>\n} {\n const {client: _client, serverToken, browserToken} = config\n\n if (!_client) {\n throw new Error('`client` is required for `defineLive` to function')\n }\n\n if (process.env.NODE_ENV !== 'production' && !serverToken && serverToken !== false) {\n // eslint-disable-next-line no-console\n console.warn(\n 'No `serverToken` provided to `defineLive`. This means that only published content will be fetched and respond to live events. You can silence this warning by setting `serverToken: false`.',\n )\n }\n\n if (process.env.NODE_ENV !== 'production' && !browserToken && browserToken !== false) {\n // eslint-disable-next-line no-console\n console.warn(\n 'No `browserToken` provided to `defineLive`. This means that live previewing drafts will only work when using the Presentation Tool in your Sanity Studio. To support live previewing drafts stand-alone, provide a `browserToken`. It is shared with the browser so it should only have Viewer rights or lower. You can silence this warning by setting `browserToken: false`.',\n )\n }\n\n const client = _client.withConfig({allowReconfigure: false, useCdn: false})\n const {token: originalToken, stega: stegaConfig} = client.config()\n const studioUrlDefined = typeof client.config().stega.studioUrl !== 'undefined'\n const {stega: stegaEnabled = typeof client.config().stega.studioUrl !== 'undefined'} = config\n\n const sanityFetch: DefinedSanityFetchType = async function sanityFetch<\n const QueryString extends string,\n >({\n query,\n params = {},\n stega: _stega,\n tags: customCacheTags = [],\n perspective: _perspective,\n requestTag = 'next-loader.fetch',\n }: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n tags?: string[]\n perspective?: Exclude<ClientPerspective, 'raw'>\n requestTag?: string\n }) {\n const stega = _stega ?? (stegaEnabled && studioUrlDefined && (await draftMode()).isEnabled)\n const perspective = _perspective ?? ((await draftMode()).isEnabled ? 'drafts' : 'published')\n\n const {apiHost, apiVersion, useProjectHostname, dataset, projectId, requestTagPrefix} =\n client.config()\n const {\n data: _data,\n sourceMap,\n tags,\n } = await sanityCachedFetch(\n {\n apiHost,\n apiVersion,\n useProjectHostname,\n dataset,\n projectId,\n requestTagPrefix,\n token: originalToken,\n },\n {\n query,\n params: await params,\n perspective,\n stega,\n requestTag,\n draftToken: serverToken,\n customCacheTags,\n // @ts-expect-error - we are debugging\n client,\n },\n )\n\n const data =\n stega && sourceMap\n ? stegaEncodeSourceMap(_data, sourceMap, {...stegaConfig, enabled: true})\n : _data\n\n return {data, sourceMap, tags, perspective}\n }\n\n const SanityLive: React.ComponentType<DefinedSanityLiveProps> = function SanityLive(props) {\n const {\n // perspective,\n refreshOnMount = false,\n refreshOnFocus = false,\n refreshOnReconnect = false,\n requestTag,\n onError,\n onGoAway,\n intervalOnGoAway,\n revalidateSyncTags = expireTags,\n } = props\n\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix} =\n client.config()\n const {origin} = new URL(client.getUrl('', false))\n\n // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n preconnect(origin)\n\n return (\n <SanityLiveServerComponent\n config={{projectId, dataset, apiHost, apiVersion, useProjectHostname, requestTagPrefix}}\n requestTag={requestTag}\n browserToken={browserToken}\n // origin={origin}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={\n props.resolveDraftModePerspective ?? resolveDraftModePerspective\n }\n />\n )\n }\n\n return {sanityFetch, SanityLive}\n}\n\ninterface SanityLiveServerComponentProps\n extends Omit<SanityLiveProps, 'draftModeEnabled' | 'token' | 'draftModePerspective'> {\n browserToken: string | false | undefined\n // origin: string\n // perspective?: Exclude<ClientPerspective, 'raw'>\n}\n\nconst SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps> =\n async function SanityLiveServerComponent(props) {\n // 'use cache'\n // @TODO should this be 'max' instead?, or configured by changing the default cache profile?\n // cacheLife({\n // stale: Infinity,\n // revalidate: Infinity,\n // expire: Infinity,\n // })\n const {\n config,\n requestTag,\n intervalOnGoAway,\n onError,\n onGoAway,\n refreshOnFocus,\n refreshOnMount,\n refreshOnReconnect,\n revalidateSyncTags,\n browserToken,\n // origin,\n // perspective,\n resolveDraftModePerspective,\n } = props\n\n const {isEnabled: isDraftModeEnabled} = await draftMode()\n\n // // Preconnect to the Live Event API origin early, as the Sanity API is almost always on a different origin than the app\n // preconnect(origin)\n\n return (\n <SanityLiveClientComponent\n config={{\n ...config,\n token: typeof browserToken === 'string' && isDraftModeEnabled ? browserToken : undefined,\n }}\n requestTag={requestTag}\n draftModeEnabled={isDraftModeEnabled}\n refreshOnMount={refreshOnMount}\n refreshOnFocus={refreshOnFocus}\n refreshOnReconnect={refreshOnReconnect}\n onError={onError}\n onGoAway={onGoAway}\n intervalOnGoAway={intervalOnGoAway}\n revalidateSyncTags={revalidateSyncTags}\n resolveDraftModePerspective={resolveDraftModePerspective}\n />\n )\n }\n\n// @TODO expose parseTags function that returns the correct array of tags\n// we already have s1: prefixes, but they could change\n// use sp: for prod, sd: for draft, keep em short\nasync function expireTags(_tags: unknown): Promise<void> {\n 'use server'\n // @TODO Draft Mode bypasses cache anyway so we don't bother with expiring tags for draft content\n // const isDraftMode = (await draftMode()).isEnabled\n // const tags = _tags.map((tag) => `${isDraftMode ? 'drafts' : 'sanity'}:${tag}`)\n if (!Array.isArray(_tags)) {\n console.warn('<SanityLive /> `expireTags` called with non-array tags', _tags)\n return undefined\n }\n const tags = _tags.filter(\n (tag) => typeof tag === 'string' && tag.startsWith(PUBLISHED_SYNC_TAG_PREFIX),\n )\n if (!tags.length) {\n console.warn('<SanityLive /> `expireTags` called with no valid tags', _tags)\n return undefined\n }\n for (const tag of tags) {\n updateTag(tag)\n }\n console.log(`<SanityLive /> updated tags: ${tags.join(', ')}`)\n}\n\nasync function resolveDraftModePerspective(): Promise<ClientPerspective> {\n 'use server'\n if ((await draftMode()).isEnabled) {\n const jar = await cookies()\n return resolvePerspectiveFromCookie({cookies: jar})\n }\n return 'published'\n}\n\n/**\n * Add more stuff:\n * - sanityFetchMetadata: sanityFetch({query, params, stega: false, perspective: 'auto'})\n * - sanityFetchStaticParams: sanityFetch({query, params, stega: false, perspective: 'published', cacheMode: undefined})\n * - sanityFetchCached: sanityFetch({query, params, stega: 'opt-in',perspective: 'opt-in'}) useful for 'use cache' components, no unexpected magic, maybe this will be `sanityFetch` instead\n * - sanityFetchDynamic: sanityFetch({query, params, stega: 'auto', perspective: 'auto'}) just like sanityFetch of old, since `sanityFetch` will likely become opt-in\n */\n"],"mappings":";;;;;;;;;;;AA2BA,eAAsB,6BAA6B,EACjD,SAAS,OAGoC;AAC7C,QAAO,IAAI,IAAI,sBAAsB,GACjC,oBAAoB,IAAI,IAAI,sBAAsB,EAAE,OAAO,SAAS,GACpE;;AAGN,eAAe,kBACb,QACA,EACE,OACA,SAAS,EAAE,EACX,aACA,OACA,YACA,YACA,kBAAkB,EAAE,IAcrB;AACD;CAEA,MAAM,SAAS,aAAa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oBAAC,2BAAA;EACC,QAAQ;GACN,GAAG;GACH,OAAO,OAAO,iBAAiB,YAAY,qBAAqB,eAAe,KAAA;GAChF;EACW;EACZ,kBAAkB;EACF;EACA;EACI;EACX;EACC;EACQ;EACE;EACpB,6BAA6BC;GAC7B;;AAOR,eAAe,WAAW,OAA+B;AACvD;AAIA,KAAI,CAAC,MAAM,QAAQ,MAAM,EAAE;AACzB,UAAQ,KAAK,0DAA0D,MAAM;AAC7E;;CAEF,MAAM,OAAO,MAAM,QAChB,QAAQ,OAAO,QAAQ,YAAY,IAAI,WAAW,0BAA0B,CAC9E;AACD,KAAI,CAAC,KAAK,QAAQ;AAChB,UAAQ,KAAK,yDAAyD,MAAM;AAC5E;;AAEF,MAAK,MAAM,OAAO,KAChB,WAAU,IAAI;AAEhB,SAAQ,IAAI,gCAAgC,KAAK,KAAK,KAAK,GAAG;;AAGhE,eAAe,8BAA0D;AACvE;AACA,MAAK,MAAM,WAAW,EAAE,UAEtB,QAAO,6BAA6B,EAAC,SADzB,MAAM,SAAS,EACuB,CAAC;AAErD,QAAO"}
|
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 { stegaEncodeSourceMap } from "@sanity/client/stega";
|
|
4
4
|
import { useCallback, useEffect, useMemo, useReducer, useSyncExternalStore } from "react";
|
|
5
5
|
import { dequal } from "dequal/lite";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isCorsOriginError } from "./isCorsOriginError.js";
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
2
|
import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
|
|
3
3
|
import { stegaClean } from "@sanity/client/stega";
|
|
4
4
|
import { CreateDataAttribute, CreateDataAttributeProps, createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isCorsOriginError } from "./isCorsOriginError.js";
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
2
|
import { createClient, unstable__adapter, unstable__environment } from "@sanity/client";
|
|
3
3
|
import { stegaClean } from "@sanity/client/stega";
|
|
4
4
|
import { createDataAttribute } from "@sanity/visual-editing/create-data-attribute";
|
|
@@ -4,5 +4,5 @@ import { CorsOriginError as CorsOriginError$1 } from "@sanity/client";
|
|
|
4
4
|
/** @public */
|
|
5
5
|
declare function isCorsOriginError(error: unknown): error is CorsOriginError$1;
|
|
6
6
|
//#endregion
|
|
7
|
-
export { isCorsOriginError };
|
|
7
|
+
export { isCorsOriginError as t };
|
|
8
8
|
//# sourceMappingURL=isCorsOriginError.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
3
|
-
import { setEnvironment, setPerspective } from "../../../context.js";
|
|
2
|
+
import { t as isCorsOriginError } from "../../../isCorsOriginError.js";
|
|
3
|
+
import { d as setEnvironment, f as setPerspective } from "../../../context.js";
|
|
4
4
|
import { createClient } from "@sanity/client";
|
|
5
5
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
6
|
import { useRouter } from "next/navigation";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use server";
|
|
2
|
-
import { sanitizePerspective } from "../../utils.js";
|
|
2
|
+
import { t as sanitizePerspective } from "../../utils.js";
|
|
3
3
|
import { cookies, draftMode } from "next/headers";
|
|
4
4
|
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
|
|
5
5
|
import { revalidateTag } from "next/cache";
|
package/dist/live.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
-
import {
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { a as defineLive, i as DefinedSanityLiveStreamType, n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
|
|
3
3
|
export { type DefineSanityLiveOptions, type DefinedSanityFetchType, type DefinedSanityLiveProps, type DefinedSanityLiveStreamType, defineLive, isCorsOriginError };
|
package/dist/live.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
-
import { sanitizePerspective } from "./utils.js";
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { t as sanitizePerspective } from "./utils.js";
|
|
3
3
|
import "@sanity/client";
|
|
4
4
|
import { preconnect, prefetchDNS } from "react-dom";
|
|
5
5
|
import SanityLiveClientComponent from "next-sanity/live/client-components/live";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
-
import {
|
|
1
|
+
import { t as isCorsOriginError } from "./isCorsOriginError.js";
|
|
2
|
+
import { i as DefinedSanityLiveStreamType, n as DefinedSanityFetchType, r as DefinedSanityLiveProps, t as DefineSanityLiveOptions } from "./defineLive.js";
|
|
3
3
|
|
|
4
4
|
//#region src/live.server-only.d.ts
|
|
5
5
|
/**
|
package/dist/live.server-only.js
CHANGED
package/dist/studio/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NextStudioLayout, NextStudioNoScript } from "../NextStudioNoScript.js";
|
|
1
|
+
import { n as NextStudioLayout, t as NextStudioNoScript } from "../NextStudioNoScript.js";
|
|
2
2
|
import { preloadModule } from "react-dom";
|
|
3
3
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
4
|
import { NextStudio } from "next-sanity/studio/client-component";
|
package/dist/utils.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-sanity",
|
|
3
|
-
"version": "11.5.
|
|
3
|
+
"version": "11.5.7-canary.0",
|
|
4
4
|
"description": "Sanity.io toolkit for Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -100,27 +100,27 @@
|
|
|
100
100
|
"@sanity/comlink": "^3.1.1",
|
|
101
101
|
"@sanity/presentation-comlink": "^1.0.33",
|
|
102
102
|
"@sanity/preview-url-secret": "^2.1.15",
|
|
103
|
-
"@sanity/visual-editing": "^3.2.
|
|
103
|
+
"@sanity/visual-editing": "^3.2.4",
|
|
104
104
|
"dequal": "^2.0.3",
|
|
105
|
-
"groq": "^4.
|
|
105
|
+
"groq": "^4.11.0",
|
|
106
106
|
"history": "^5.3.0",
|
|
107
107
|
"server-only": "^0.0.1",
|
|
108
108
|
"use-effect-event": "^2.0.3"
|
|
109
109
|
},
|
|
110
110
|
"devDependencies": {
|
|
111
111
|
"@sanity/browserslist-config": "^1.0.5",
|
|
112
|
-
"@sanity/pkg-utils": "^8.1.
|
|
113
|
-
"@sanity/types": "^4.
|
|
112
|
+
"@sanity/pkg-utils": "^8.1.24",
|
|
113
|
+
"@sanity/types": "^4.11.0",
|
|
114
114
|
"@sanity/webhook": "4.0.4",
|
|
115
115
|
"@types/react": "^19.1.8",
|
|
116
116
|
"@types/react-dom": "^19.1.6",
|
|
117
117
|
"@vitest/coverage-v8": "^3.2.4",
|
|
118
|
-
"next": "^
|
|
119
|
-
"publint": "^0.3.
|
|
118
|
+
"next": "^16.0.0",
|
|
119
|
+
"publint": "^0.3.15",
|
|
120
120
|
"react": "^19.1.0",
|
|
121
121
|
"react-dom": "^19.1.0",
|
|
122
122
|
"styled-components": "^6.1.19",
|
|
123
|
-
"tsdown": "0.15.
|
|
123
|
+
"tsdown": "0.15.9",
|
|
124
124
|
"typescript": "5.9.3",
|
|
125
125
|
"vite-tsconfig-paths": "^5.1.4",
|
|
126
126
|
"vitest": "^3.2.4"
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"next": "^15.1.0-0 || ^16.0.0-0",
|
|
131
131
|
"react": "^18.3 || ^19",
|
|
132
132
|
"react-dom": "^18.3 || ^19",
|
|
133
|
-
"sanity": "^4.
|
|
133
|
+
"sanity": "^4.11.0",
|
|
134
134
|
"styled-components": "^6.1"
|
|
135
135
|
},
|
|
136
136
|
"engines": {
|
|
@@ -14,7 +14,7 @@ import {stegaEncodeSourceMap} from '@sanity/client/stega'
|
|
|
14
14
|
import SanityLiveClientComponent, {
|
|
15
15
|
type SanityLiveProps,
|
|
16
16
|
} from 'next-sanity/experimental/client-components/live'
|
|
17
|
-
import {cacheTag, updateTag} from 'next/cache'
|
|
17
|
+
import {cacheTag, cacheLife, updateTag} from 'next/cache'
|
|
18
18
|
import {draftMode, cookies} from 'next/headers'
|
|
19
19
|
import {preconnect} from 'react-dom'
|
|
20
20
|
import {perspectiveCookieName} from '@sanity/preview-url-secret/constants'
|
|
@@ -59,7 +59,7 @@ async function sanityCachedFetch<const QueryString extends string>(
|
|
|
59
59
|
sourceMap: ContentSourceMap | null
|
|
60
60
|
tags: string[]
|
|
61
61
|
}> {
|
|
62
|
-
'use cache'
|
|
62
|
+
'use cache: remote'
|
|
63
63
|
|
|
64
64
|
const client = createClient({...config, useCdn: true})
|
|
65
65
|
const useCdn = perspective === 'published'
|
|
@@ -72,6 +72,15 @@ async function sanityCachedFetch<const QueryString extends string>(
|
|
|
72
72
|
// revalidate: Infinity,
|
|
73
73
|
// expire: Infinity,
|
|
74
74
|
// })
|
|
75
|
+
console.log('sanityCachedFetch', {
|
|
76
|
+
query,
|
|
77
|
+
params,
|
|
78
|
+
perspective,
|
|
79
|
+
stega,
|
|
80
|
+
requestTag,
|
|
81
|
+
draftToken,
|
|
82
|
+
customCacheTags,
|
|
83
|
+
})
|
|
75
84
|
|
|
76
85
|
const {result, resultSourceMap, syncTags} = await client.fetch(query, params, {
|
|
77
86
|
filterResponse: false,
|
|
@@ -94,6 +103,10 @@ async function sanityCachedFetch<const QueryString extends string>(
|
|
|
94
103
|
* The tags used here, are expired later on in the `expireTags` Server Action with the `expireTag` function from `next/cache`
|
|
95
104
|
*/
|
|
96
105
|
cacheTag(...tags)
|
|
106
|
+
/**
|
|
107
|
+
* Sanity Live handles on-demand revalidation, so the default 15min time based revalidation is too short
|
|
108
|
+
*/
|
|
109
|
+
cacheLife({revalidate: 60 * 60 * 24 * 90})
|
|
97
110
|
|
|
98
111
|
return {data: result, sourceMap: resultSourceMap || null, tags}
|
|
99
112
|
}
|
|
@@ -313,6 +326,8 @@ export function defineLive(config: DefineSanityLiveOptions): {
|
|
|
313
326
|
requestTag,
|
|
314
327
|
draftToken: serverToken,
|
|
315
328
|
customCacheTags,
|
|
329
|
+
// @ts-expect-error - we are debugging
|
|
330
|
+
client,
|
|
316
331
|
},
|
|
317
332
|
)
|
|
318
333
|
|
|
@@ -376,7 +391,7 @@ interface SanityLiveServerComponentProps
|
|
|
376
391
|
|
|
377
392
|
const SanityLiveServerComponent: React.ComponentType<SanityLiveServerComponentProps> =
|
|
378
393
|
async function SanityLiveServerComponent(props) {
|
|
379
|
-
'use cache'
|
|
394
|
+
// 'use cache'
|
|
380
395
|
// @TODO should this be 'max' instead?, or configured by changing the default cache profile?
|
|
381
396
|
// cacheLife({
|
|
382
397
|
// stale: Infinity,
|