hydrogen-sanity 4.2.0 → 4.3.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/README.md CHANGED
@@ -204,7 +204,12 @@ const page = await context.sanity.loadQuery<HomePage>(query, params, {
204
204
  // display in the subrequest profiler, you can pass that here:
205
205
  // debug: {
206
206
  // displayName: 'query Homepage'
207
- // }
207
+ // },
208
+
209
+ // You can also pass a function do determine whether or not to cache the response
210
+ // shouldCacheResult(value){
211
+ // return true
212
+ // },
208
213
  },
209
214
 
210
215
  // ...as well as other request options
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/client"),t=require("@sanity/react-loader"),n=require("@shopify/hydrogen"),i=require("./_chunks-cjs/utils.cjs");const r=n.CacheLong();const a=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityContext=function(a){const{cache:o,waitUntil:s=()=>Promise.resolve(),request:c,preview:l,defaultStrategy:u}=a,d=o?n.createWithCache({cache:o,waitUntil:s,request:c}):null;let p=a.client instanceof e.SanityClient?a.client:e.createClient(a.client);if("1"===p.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),p=p.withConfig({apiVersion:"v2022-03-07"})),l&&l.enabled){if(!l.token)throw new Error("Enabling preview mode requires a token.");const e=p.withConfig({useCdn:!1,token:l.token,perspective:"previewDrafts",stega:{...p.config().stega,enabled:!0,studioUrl:l.studioUrl}});t.setServerClient(e)}else t.setServerClient(p);return{async loadQuery(e,a,o){const s=l&&l.enabled?n.CacheNone():o?.hydrogen?.cache||u||r,c=await i.h(e,a);return await(d?d(c,s,(async({addDebugData:n})=>{if("development"===process.env.NODE_ENV){n({displayName:o?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,a,o)})):t.loadQuery(e,a,o))},client:p,preview:l}},exports.createSanityLoader=function(r){const{withCache:o,preview:s,strategy:c}=r;let l=r.client instanceof e.SanityClient?r.client:e.createClient(r.client);if("1"===l.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),l=l.withConfig({apiVersion:"v2022-03-07"})),s&&s.enabled){if(!s.token)throw new Error("Enabling preview mode requires a token.");const e=l.withConfig({useCdn:!1,token:s.token,perspective:"previewDrafts",stega:{...l.config().stega,enabled:!0,studioUrl:s.studioUrl}});t.setServerClient(e)}else t.setServerClient(l);return{async loadQuery(e,r,l){const u=s&&s.enabled?n.CacheNone():l?.hydrogen?.cache||c||a,d=await i.h(e,r);return await o(d,u,(async({addDebugData:n})=>{if("development"===process.env.NODE_ENV){n({displayName:l?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,r,l)}))},client:l,preview:s}};//# sourceMappingURL=index.cjs.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/client"),t=require("@sanity/react-loader"),n=require("@shopify/hydrogen"),i=require("./_chunks-cjs/utils.cjs");const r=n.CacheLong();const a=n.CacheLong();Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityContext=function(a){const{cache:o,waitUntil:s=()=>Promise.resolve(),request:c,preview:l,defaultStrategy:u}=a,d=o?n.createWithCache({cache:o,waitUntil:s,request:c}):null;let h=a.client instanceof e.SanityClient?a.client:e.createClient(a.client);if("1"===h.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),h=h.withConfig({apiVersion:"v2022-03-07"})),l&&l.enabled){if(!l.token)throw new Error("Enabling preview mode requires a token.");const e=h.withConfig({useCdn:!1,token:l.token,perspective:"previewDrafts",stega:{...h.config().stega,enabled:!0,studioUrl:l.studioUrl}});t.setServerClient(e)}else t.setServerClient(h);return{async loadQuery(e,a,o){if(!d)return await t.loadQuery(e,a,o);const s=l&&l.enabled?n.CacheNone():o?.hydrogen?.cache||u||r,c=await i.h(e,a),h=o?.hydrogen?.shouldCacheResult??(()=>!0),y=async function({addDebugData:n}){if("development"===process.env.NODE_ENV){n({displayName:o?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,a,o)};return await("run"in d?d.run({cacheKey:c,cacheStrategy:s,shouldCacheResult:h},y):d(c,s,y))},client:h,preview:l}},exports.createSanityLoader=function(r){const{withCache:o,preview:s,strategy:c}=r;let l=r.client instanceof e.SanityClient?r.client:e.createClient(r.client);if("1"===l.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),l=l.withConfig({apiVersion:"v2022-03-07"})),s&&s.enabled){if(!s.token)throw new Error("Enabling preview mode requires a token.");const e=l.withConfig({useCdn:!1,token:s.token,perspective:"previewDrafts",stega:{...l.config().stega,enabled:!0,studioUrl:s.studioUrl}});t.setServerClient(e)}else t.setServerClient(l);return{async loadQuery(e,r,l){const u=s&&s.enabled?n.CacheNone():l?.hydrogen?.cache||c||a,d=await i.h(e,r),h=l?.hydrogen?.shouldCacheResult??(()=>!0),y=async function({addDebugData:n}){if("development"===process.env.NODE_ENV){n({displayName:l?.hydrogen?.debug?.displayName||"query Sanity"})}return await t.loadQuery(e,r,l)};return await("run"in o?o.run({cacheKey:d,cacheStrategy:u,shouldCacheResult:h},y):o(d,u,y))},client:l,preview:s}};//# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, createWithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\ntype WaitUntil = (promise: Promise<unknown>) => void\n\nexport type CreateSanityContextOptions = {\n request: Request\n\n cache?: Cache | undefined\n waitUntil?: WaitUntil | undefined\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n defaultStrategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n>\n\nexport type SanityContext = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityContextOptions['preview']\n}\n\n/**\n * @public\n */\nexport function createSanityContext(options: CreateSanityContextOptions): SanityContext {\n const {cache, waitUntil = () => Promise.resolve(), request, preview, defaultStrategy} = options\n const withCache = cache ? createWithCache({cache, waitUntil, request}) : null\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await (withCache\n ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n })\n : loadQuery<T>(query, params, loaderOptions))\n },\n client,\n preview,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, type WithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\nexport type CreateSanityLoaderOptions = {\n /**\n * Cache control utility from `@shopify/hydrogen`.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching/third-party\n */\n withCache: WithCache\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n strategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n>\n\nexport type SanityLoader = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityLoaderOptions['preview']\n}\n\n/**\n * @deprecated Use `createSanityContext` instead\n */\nexport function createSanityLoader(options: CreateSanityLoaderOptions): SanityLoader {\n const {withCache, preview, strategy} = options\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || strategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n })\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["Object","defineProperty","exports","value","client","require","reactLoader","hydrogen","utils","DEFAULT_CACHE_STRATEGY","CacheLong","enumerable","get","SanityClient","createClient","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","queryHash","hashQuery","async","addDebug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AE1D,EAAAvC,OACAA,EACAkB,UAIJ"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheLong,\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\ntype WaitUntil = (promise: Promise<unknown>) => void\n\nexport type CreateSanityContextOptions = {\n request: Request\n\n cache?: Cache | undefined\n waitUntil?: WaitUntil | undefined\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n defaultStrategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n hydrogen?: {\n /**\n * Whether to cache the result of the query or not.\n * @defaultValue () => true\n */\n shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n }\n}\n\nexport type SanityContext = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityContextOptions['preview']\n}\n\n/**\n * @public\n */\nexport function createSanityContext(options: CreateSanityContextOptions): SanityContext {\n const {cache, waitUntil = () => Promise.resolve(), request, preview, defaultStrategy} = options\n const withCache = cache ? createWithCache({cache, waitUntil, request}) : null\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>> {\n if (!withCache) {\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n const runWithCache = async function runWithCache({\n addDebugData,\n }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n return await ('run' in withCache\n ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n : // @ts-expect-error for compatibility, remove in next major\n withCache(queryHash, cacheStrategy, runWithCache))\n },\n client,\n preview,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, type WithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\nexport type CreateSanityLoaderOptions = {\n /**\n * Cache control utility from `@shopify/hydrogen`.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching/third-party\n */\n withCache: WithCache\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n strategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n hydrogen?: {\n /**\n * Whether to cache the result of the query or not.\n * @defaultValue () => true\n */\n shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n }\n}\n\nexport type SanityLoader = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityLoaderOptions['preview']\n}\n\n/**\n * @deprecated Use `createSanityContext` instead\n */\nexport function createSanityLoader(options: CreateSanityLoaderOptions): SanityLoader {\n const {withCache, preview, strategy} = options\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || strategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n const runWithCache = async function runWithCache({\n addDebugData,\n }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n return await ('run' in withCache\n ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n : // @ts-expect-error for compatibility, remove in next major\n withCache(queryHash, cacheStrategy, runWithCache))\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["DEFAULT_CACHE_STRATEGY","CacheLong","Object","defineProperty","exports","enumerable","get","client","SanityClient","createClient","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","hydrogen","queryHash","hashQuery","shouldCacheResult","runWithCache","async","addDebugData","process","env","NODE_ENV","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"0MAmBA,MAAMA,EAAyBC,EAAAA,YCN/B,MAAMD,EAAyBC,EAAAA,YA8J/BC,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAC,YAAA,IAAAN,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAC,EAAAE,YAAA,IAAAL,QAAAM,oBDpEO,SAA6BC,GA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keyof RequestInit_3 ? RequestInit_3['hydrogen'] : never
80
80
  }
81
81
 
82
- declare type LoadQueryOptions = Pick<
82
+ declare type LoadQueryOptions<T> = Pick<
83
83
  HydrogenResponseQueryOptions,
84
84
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
85
- >
85
+ > & {
86
+ hydrogen?: {
87
+ /**
88
+ * Whether to cache the result of the query or not.
89
+ * @defaultValue () => true
90
+ */
91
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
92
+ }
93
+ }
86
94
 
87
- declare type LoadQueryOptions_2 = Pick<
95
+ declare type LoadQueryOptions_2<T> = Pick<
88
96
  HydrogenResponseQueryOptions_2,
89
97
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
90
- >
98
+ > & {
99
+ hydrogen?: {
100
+ /**
101
+ * Whether to cache the result of the query or not.
102
+ * @defaultValue () => true
103
+ */
104
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
105
+ }
106
+ }
91
107
 
92
108
  declare interface RequestInit_2 {
93
109
  hydrogen?: {
@@ -133,7 +149,7 @@ export declare type SanityContext = {
133
149
  loadQuery<T = any>(
134
150
  query: string,
135
151
  params?: QueryParams,
136
- options?: LoadQueryOptions,
152
+ options?: LoadQueryOptions<T>,
137
153
  ): Promise<QueryResponseInitial<T>>
138
154
  client: SanityClient
139
155
  preview?: CreateSanityContextOptions['preview']
@@ -147,7 +163,7 @@ export declare type SanityLoader = {
147
163
  loadQuery<T = any>(
148
164
  query: string,
149
165
  params?: QueryParams,
150
- options?: LoadQueryOptions_2,
166
+ options?: LoadQueryOptions_2<T>,
151
167
  ): Promise<QueryResponseInitial<T>>
152
168
  client: SanityClient
153
169
  preview?: CreateSanityLoaderOptions['preview']
package/dist/index.d.ts CHANGED
@@ -79,15 +79,31 @@ declare type HydrogenResponseQueryOptions_2 = Omit<ResponseQueryOptions, 'next'
79
79
  hydrogen?: 'hydrogen' extends keyof RequestInit_3 ? RequestInit_3['hydrogen'] : never
80
80
  }
81
81
 
82
- declare type LoadQueryOptions = Pick<
82
+ declare type LoadQueryOptions<T> = Pick<
83
83
  HydrogenResponseQueryOptions,
84
84
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
85
- >
85
+ > & {
86
+ hydrogen?: {
87
+ /**
88
+ * Whether to cache the result of the query or not.
89
+ * @defaultValue () => true
90
+ */
91
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
92
+ }
93
+ }
86
94
 
87
- declare type LoadQueryOptions_2 = Pick<
95
+ declare type LoadQueryOptions_2<T> = Pick<
88
96
  HydrogenResponseQueryOptions_2,
89
97
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
90
- >
98
+ > & {
99
+ hydrogen?: {
100
+ /**
101
+ * Whether to cache the result of the query or not.
102
+ * @defaultValue () => true
103
+ */
104
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
105
+ }
106
+ }
91
107
 
92
108
  declare interface RequestInit_2 {
93
109
  hydrogen?: {
@@ -133,7 +149,7 @@ export declare type SanityContext = {
133
149
  loadQuery<T = any>(
134
150
  query: string,
135
151
  params?: QueryParams,
136
- options?: LoadQueryOptions,
152
+ options?: LoadQueryOptions<T>,
137
153
  ): Promise<QueryResponseInitial<T>>
138
154
  client: SanityClient
139
155
  preview?: CreateSanityContextOptions['preview']
@@ -147,7 +163,7 @@ export declare type SanityLoader = {
147
163
  loadQuery<T = any>(
148
164
  query: string,
149
165
  params?: QueryParams,
150
- options?: LoadQueryOptions_2,
166
+ options?: LoadQueryOptions_2<T>,
151
167
  ): Promise<QueryResponseInitial<T>>
152
168
  client: SanityClient
153
169
  preview?: CreateSanityLoaderOptions['preview']
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SanityClient as e,createClient as t}from"@sanity/client";import{SanityClient as n,createClient as i}from"@sanity/client";import{setServerClient as a,loadQuery as o}from"@sanity/react-loader";import{CacheLong as r,createWithCache as s,CacheNone as c}from"@shopify/hydrogen";import{h as l}from"./_chunks-es/utils.js";const p=r();function d(n){const{cache:i,waitUntil:r=()=>Promise.resolve(),request:d,preview:u,defaultStrategy:g}=n,w=i?s({cache:i,waitUntil:r,request:d}):null;let h=n.client instanceof e?n.client:t(n.client);if("1"===h.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),h=h.withConfig({apiVersion:"v2022-03-07"})),u&&u.enabled){if(!u.token)throw new Error("Enabling preview mode requires a token.");const e=h.withConfig({useCdn:!1,token:u.token,perspective:"previewDrafts",stega:{...h.config().stega,enabled:!0,studioUrl:u.studioUrl}});a(e)}else a(h);return{async loadQuery(e,t,n){const i=u&&u.enabled?c():n?.hydrogen?.cache||g||p,a=await l(e,t);return await(w?w(a,i,(async({addDebugData:i})=>{if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)})):o(e,t,n))},client:h,preview:u}}const u=r();function g(n){const{withCache:i,preview:r,strategy:s}=n;let p=n.client instanceof e?n.client:t(n.client);if("1"===p.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),p=p.withConfig({apiVersion:"v2022-03-07"})),r&&r.enabled){if(!r.token)throw new Error("Enabling preview mode requires a token.");const e=p.withConfig({useCdn:!1,token:r.token,perspective:"previewDrafts",stega:{...p.config().stega,enabled:!0,studioUrl:r.studioUrl}});a(e)}else a(p);return{async loadQuery(e,t,n){const a=r&&r.enabled?c():n?.hydrogen?.cache||s||u,p=await l(e,t);return await i(p,a,(async({addDebugData:i})=>{if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)}))},client:p,preview:r}}export{n as SanityClient,i as createClient,d as createSanityContext,g as createSanityLoader};//# sourceMappingURL=index.js.map
1
+ import{SanityClient as e,createClient as t}from"@sanity/client";import{SanityClient as n,createClient as i}from"@sanity/client";import{setServerClient as a,loadQuery as o}from"@sanity/react-loader";import{CacheLong as r,createWithCache as s,CacheNone as c}from"@shopify/hydrogen";import{h as l}from"./_chunks-es/utils.js";const u=r();function h(n){const{cache:i,waitUntil:r=()=>Promise.resolve(),request:h,preview:d,defaultStrategy:p}=n,g=i?s({cache:i,waitUntil:r,request:h}):null;let y=n.client instanceof e?n.client:t(n.client);if("1"===y.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),y=y.withConfig({apiVersion:"v2022-03-07"})),d&&d.enabled){if(!d.token)throw new Error("Enabling preview mode requires a token.");const e=y.withConfig({useCdn:!1,token:d.token,perspective:"previewDrafts",stega:{...y.config().stega,enabled:!0,studioUrl:d.studioUrl}});a(e)}else a(y);return{async loadQuery(e,t,n){if(!g)return await o(e,t,n);const i=d&&d.enabled?c():n?.hydrogen?.cache||p||u,a=await l(e,t),r=n?.hydrogen?.shouldCacheResult??(()=>!0),s=async function({addDebugData:i}){if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)};return await("run"in g?g.run({cacheKey:a,cacheStrategy:i,shouldCacheResult:r},s):g(a,i,s))},client:y,preview:d}}const d=r();function p(n){const{withCache:i,preview:r,strategy:s}=n;let u=n.client instanceof e?n.client:t(n.client);if("1"===u.config().apiVersion&&(console.warn("No API version specified, defaulting to `v2022-03-07` which supports perspectives.\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog"),u=u.withConfig({apiVersion:"v2022-03-07"})),r&&r.enabled){if(!r.token)throw new Error("Enabling preview mode requires a token.");const e=u.withConfig({useCdn:!1,token:r.token,perspective:"previewDrafts",stega:{...u.config().stega,enabled:!0,studioUrl:r.studioUrl}});a(e)}else a(u);return{async loadQuery(e,t,n){const a=r&&r.enabled?c():n?.hydrogen?.cache||s||d,u=await l(e,t),h=n?.hydrogen?.shouldCacheResult??(()=>!0),p=async function({addDebugData:i}){if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await o(e,t,n)};return await("run"in i?i.run({cacheKey:u,cacheStrategy:a,shouldCacheResult:h},p):i(u,a,p))},client:u,preview:r}}export{n as SanityClient,i as createClient,h as createSanityContext,p as createSanityLoader};//# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, createWithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\ntype WaitUntil = (promise: Promise<unknown>) => void\n\nexport type CreateSanityContextOptions = {\n request: Request\n\n cache?: Cache | undefined\n waitUntil?: WaitUntil | undefined\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n defaultStrategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n>\n\nexport type SanityContext = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityContextOptions['preview']\n}\n\n/**\n * @public\n */\nexport function createSanityContext(options: CreateSanityContextOptions): SanityContext {\n const {cache, waitUntil = () => Promise.resolve(), request, preview, defaultStrategy} = options\n const withCache = cache ? createWithCache({cache, waitUntil, request}) : null\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await (withCache\n ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n })\n : loadQuery<T>(query, params, loaderOptions))\n },\n client,\n preview,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, type WithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\nexport type CreateSanityLoaderOptions = {\n /**\n * Cache control utility from `@shopify/hydrogen`.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching/third-party\n */\n withCache: WithCache\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n strategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n>\n\nexport type SanityLoader = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityLoaderOptions['preview']\n}\n\n/**\n * @deprecated Use `createSanityContext` instead\n */\nexport function createSanityLoader(options: CreateSanityLoaderOptions): SanityLoader {\n const {withCache, preview, strategy} = options\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || strategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n })\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["SanityClient","createClient","setServerClient","loadQuery","CacheLong","createWithCache","CacheNone","hashQuery","DEFAULT_CACHE_STRATEGY","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","client","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","query","params","loaderOptions","cacheStrategy","hydrogen","queryHash","async","addDebugData","process","env","NODE_ENV","displayName","debug","createSanityLoader","strategy"],"mappings":"uBAaAA,kBAAAC,MAAA,wCAAAD,kBAAAC,MAAA,2CAAAC,eAAAC,MAAA,2CAAAC,qBAAAC,eAAAC,MAAA,gCAAAC,MAAA,wBAAA,MAAMC,EAAyBJ,IA4ExB,SAASK,EAAoBC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQN,EAAgB,CAACM,QAAOC,YAAWG,YAAY,KACrE,IAAAI,EACFT,EAAQS,kBAAkBnB,EAAeU,EAAQS,OAASlB,EAAaS,EAAQS,QASjF,GAPmC,MAA/BA,EAAOC,SAASC,aAClBC,QAAQC,KACN,gLAEFJ,EAASA,EAAOK,WAAW,CAACH,WAAY,iBAGtCL,GAAWA,EAAQS,QAAS,CAC9B,IAAKT,EAAQU,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBT,EAAOK,WAAW,CACtCK,QAAQ,EACRH,MAAOV,EAAQU,MACfI,YAAa,gBACbC,MAAO,IACFZ,EAAOC,SAASW,MACnBN,SAAS,EACTO,UAAWhB,EAAQgB,aAIvB9B,EAAgB0B,EAClB,MACE1B,EAAgBiB,GAGH,MAAA,CACb,eAAMhB,CACJ8B,EACAC,EAC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aAAe,gBAKrE,CAEA,aAAazC,EAAa8B,EAAOC,EAAQC,EAAa,GAE1D,EACAhB,SACAH,UAIJ"}
1
+ {"version":3,"file":"index.js","sources":["../src/context.ts","../src/loader.ts"],"sourcesContent":["import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {\n CacheLong,\n CacheNone,\n type CachingStrategy,\n createWithCache,\n type WithCache,\n} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\ntype WaitUntil = (promise: Promise<unknown>) => void\n\nexport type CreateSanityContextOptions = {\n request: Request\n\n cache?: Cache | undefined\n waitUntil?: WaitUntil | undefined\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n defaultStrategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n hydrogen?: {\n /**\n * Whether to cache the result of the query or not.\n * @defaultValue () => true\n */\n shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n }\n}\n\nexport type SanityContext = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityContextOptions['preview']\n}\n\n/**\n * @public\n */\nexport function createSanityContext(options: CreateSanityContextOptions): SanityContext {\n const {cache, waitUntil = () => Promise.resolve(), request, preview, defaultStrategy} = options\n const withCache = cache ? createWithCache({cache, waitUntil, request}) : null\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>> {\n if (!withCache) {\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n const runWithCache = async function runWithCache({\n addDebugData,\n }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n return await ('run' in withCache\n ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n : // @ts-expect-error for compatibility, remove in next major\n withCache(queryHash, cacheStrategy, runWithCache))\n },\n client,\n preview,\n }\n\n return sanity\n}\n","import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type CachingStrategy, type WithCache} from '@shopify/hydrogen'\n\nimport {\n type ClientConfig,\n createClient,\n type QueryParams,\n type QueryWithoutParams,\n type ResponseQueryOptions,\n SanityClient,\n} from './client'\nimport {hashQuery} from './utils'\n\nconst DEFAULT_CACHE_STRATEGY = CacheLong()\n\nexport type CreateSanityLoaderOptions = {\n /**\n * Cache control utility from `@shopify/hydrogen`.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching/third-party\n */\n withCache: WithCache\n\n /**\n * Sanity client or configuration to use.\n */\n client: SanityClient | ClientConfig\n\n /**\n * The default caching strategy to use for `loadQuery` subrequests.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n *\n * Defaults to `CacheLong`\n */\n strategy?: CachingStrategy | null\n\n /**\n * Configuration for enabling preview mode.\n */\n preview?: {enabled: boolean; token: string; studioUrl: string}\n}\n\ninterface RequestInit {\n hydrogen?: {\n /**\n * The caching strategy to use for the subrequest.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/caching#caching-strategies\n */\n cache?: CachingStrategy\n\n /**\n * Optional debugging information to be displayed in the subrequest profiler.\n * @see https://shopify.dev/docs/custom-storefronts/hydrogen/debugging/subrequest-profiler#how-to-provide-more-debug-information-for-a-request\n */\n debug?: {\n displayName: string\n }\n }\n}\n\ntype HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'> & {\n hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never\n}\n\ntype LoadQueryOptions<T> = Pick<\n HydrogenResponseQueryOptions,\n 'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'\n> & {\n hydrogen?: {\n /**\n * Whether to cache the result of the query or not.\n * @defaultValue () => true\n */\n shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean\n }\n}\n\nexport type SanityLoader = {\n /**\n * Query Sanity using the loader.\n * @see https://www.sanity.io/docs/loaders\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadQuery<T = any>(\n query: string,\n params?: QueryParams,\n options?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>>\n\n client: SanityClient\n\n preview?: CreateSanityLoaderOptions['preview']\n}\n\n/**\n * @deprecated Use `createSanityContext` instead\n */\nexport function createSanityLoader(options: CreateSanityLoaderOptions): SanityLoader {\n const {withCache, preview, strategy} = options\n let client =\n options.client instanceof SanityClient ? options.client : createClient(options.client)\n\n if (client.config().apiVersion === '1') {\n console.warn(\n 'No API version specified, defaulting to `v2022-03-07` which supports perspectives.\\nYou can find the latest version in the Sanity changelog: https://www.sanity.io/changelog',\n )\n client = client.withConfig({apiVersion: 'v2022-03-07'})\n }\n\n if (preview && preview.enabled) {\n if (!preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n const previewClient = client.withConfig({\n useCdn: false,\n token: preview.token,\n perspective: 'previewDrafts' as const,\n stega: {\n ...client.config().stega,\n enabled: true,\n studioUrl: preview.studioUrl,\n },\n })\n\n setServerClient(previewClient)\n } else {\n setServerClient(client)\n }\n\n const sanity = {\n async loadQuery<T>(\n query: string,\n params: QueryParams | QueryWithoutParams,\n loaderOptions?: LoadQueryOptions<T>,\n ): Promise<QueryResponseInitial<T>> {\n // Don't store response if preview is enabled\n const cacheStrategy =\n preview && preview.enabled\n ? CacheNone()\n : loaderOptions?.hydrogen?.cache || strategy || DEFAULT_CACHE_STRATEGY\n\n const queryHash = await hashQuery(query, params)\n\n const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)\n\n const runWithCache = async function runWithCache({\n addDebugData,\n }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {\n // eslint-disable-next-line no-process-env\n if (process.env.NODE_ENV === 'development') {\n // Name displayed in the subrequest profiler\n const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'\n\n addDebugData({\n displayName,\n })\n }\n\n return await loadQuery<T>(query, params, loaderOptions)\n }\n\n return await ('run' in withCache\n ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)\n : // @ts-expect-error for compatibility, remove in next major\n withCache(queryHash, cacheStrategy, runWithCache))\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["DEFAULT_CACHE_STRATEGY","CacheLong","createSanityContext","options","cache","waitUntil","Promise","resolve","request","preview","defaultStrategy","withCache","createWithCache","client","SanityClient","createClient","config","apiVersion","console","warn","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","query","params","loaderOptions","cacheStrategy","CacheNone","hydrogen","queryHash","hashQuery","shouldCacheResult","runWithCache","async","addDebugData","process","env","NODE_ENV","displayName","debug","run","cacheKey","createSanityLoader","strategy"],"mappings":"kUAmBA,MAAMA,EAAyBC,IAoFxB,SAASC,EAAoBC,GAC5B,MAAAC,MAACA,YAAOC,EAAY,IAAMC,QAAQC,kBAAWC,UAASC,EAASC,gBAAAA,GAAmBP,EAClFQ,EAAYP,EAAQQ,EAAgB,CAACR,QAAOC,YAAWG,YAAY,KACrE,IAAAK,EACFV,EAAQU,kBAAkBC,EAAeX,EAAQU,OAASE,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,GAAWA,EAAQY,QAAS,CAC9B,IAAKZ,EAAQa,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBX,EAAOO,WAAW,CACtCK,QAAQ,EACRH,MAAOb,EAAQa,MACfI,YAAa,gBACbC,MAAO,IACFd,EAAOG,SAASW,MACnBN,SAAS,EACTO,UAAWnB,EAAQmB,aAIvBC,EAAgBL,EAClB,MACEK,EAAgBhB,GAGH,MAAA,CACb,eAAMiB,CACJC,EACAC,EACAC,GAGM,MAAAC,EACJzB,GAAWA,EAAQY,QACfc,IACAF,GAAeG,UAAUhC,OAAS+C,GAAYnD,EAE9CqC,QAAkBC,EAAUP,EAAOC,GAEnCO,EAAoBN,GAAeG,UAAUG,mBAAsB,MAAM,GAEzEC,EAAeC,gBAA4BC,aAC/CA,IAGI,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBb,GAAeG,UAAUW,OAAOD,aAAe,gBAIlE,CAGH,aAAahB,EAAaC,EAAOC,EAAQC,EAC3C,EAEO,aAAO,QAAStB,EACnBA,EAAUqC,IAAI,CAACC,SAAUZ,EAAWH,gBAAeK,qBAAoBC,GAEvE7B,EAAU0B,EAAWH,EAAeM,GAC1C,EACA3B,SACAJ,UAIJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"route.cjs","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport type {HydrogenSession} from '@shopify/hydrogen'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\n\nimport type {SanityContext} from '../context'\nimport {assertSession} from '../utils'\n\n/**\n * A `POST` request to this route will exit preview mode\n */\nexport const action: ActionFunction = async ({context, request}) => {\n if (request.method !== 'POST') {\n return json({message: 'Method not allowed'}, 405)\n }\n\n try {\n const {session} = context\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n // TODO: make this a callback? `onExitPreview`?\n await session.unset('projectId')\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect('/')\n } catch (error) {\n console.error(error)\n throw new Response('Unable to disable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n\n/**\n * A `GET` request to this route will enter preview mode\n */\nexport const loader: LoaderFunction = async ({context, request}) => {\n try {\n // TODO: to remove\n const {sanity, session} = context as {sanity: SanityContext; session: HydrogenSession}\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview) {\n return new Response('Preview mode is not enabled in this environment.', {status: 403})\n }\n\n if (!sanity.preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if (!projectId) {\n throw new Error('No `projectId` found in the client config.')\n }\n\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n const clientWithToken = sanity.client.withConfig({\n useCdn: false,\n token: sanity.preview.token,\n })\n\n const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, request.url)\n\n if (!isValid) {\n return new Response('Invalid secret', {status: 401})\n }\n\n // TODO: make this a callback? `onEnterPreview`?\n await session.set('projectId', projectId)\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect(redirectTo)\n } catch (error) {\n console.error(error)\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n"],"names":["exports","action","async","context","request","method","json","message","session","assertSession","Error","unset","redirect","error","console","Response","status","loader","sanity","projectId","client","config","preview","token","clientWithToken","withConfig","useCdn","isValid","redirectTo","validatePreviewUrl","url","set"],"mappings":"yLAiFAA,QAAAC,OAvEsCC,OAAQC,UAASC,cACrD,GAAuB,SAAnBA,EAAQC,OACV,OAAOC,EAAKA,KAAA,CAACC,QAAS,sBAAuB,KAG3C,IACI,MAAAC,QAACA,GAAWL,EACd,IAACM,IAAcD,GACX,MAAA,IAAIE,MAAM,iDAIlB,aAAMF,EAAQG,MAAM,aAGbC,EAAAA,SAAS,WACTC,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,0EAA2E,CAC5FC,OAAQ,KAEZ,GAkDFhB,QAAAiB,OA5CsCf,OAAQC,UAASC,cACjD,IAEI,MAAAc,OAACA,UAAQV,GAAWL,EACpBgB,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,QACV,OAAO,IAAIP,SAAS,mDAAoD,CAACC,OAAQ,MAG/E,IAACE,EAAOI,QAAQC,MACZ,MAAA,IAAIb,MAAM,2CAGlB,IAAKS,EACG,MAAA,IAAIT,MAAM,8CAGd,IAACD,IAAcD,GACX,MAAA,IAAIE,MAAM,iDAGZ,MAAAc,EAAkBN,EAAOE,OAAOK,WAAW,CAC/CC,QAAQ,EACRH,MAAOL,EAAOI,QAAQC,SAGlBI,QAACA,EAAAC,WAASA,EAAa,WAAaC,EAAAA,mBAAmBL,EAAiBpB,EAAQ0B,KAEtF,OAAKH,SAKCnB,EAAQuB,IAAI,YAAaZ,GAGxBP,EAAAA,SAASgB,IAPP,IAAIb,SAAS,iBAAkB,CAACC,OAAQ,YAQ1CH,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,yEAA0E,CAC3FC,OAAQ,KAEZ"}
1
+ {"version":3,"file":"route.cjs","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport type {HydrogenSession} from '@shopify/hydrogen'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\n\nimport type {SanityContext} from '../context'\nimport {assertSession} from '../utils'\n\n/**\n * A `POST` request to this route will exit preview mode\n */\nexport const action: ActionFunction = async ({context, request}) => {\n if (request.method !== 'POST') {\n return json({message: 'Method not allowed'}, 405)\n }\n\n try {\n const {session} = context\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n // TODO: make this a callback? `onExitPreview`?\n await session.unset('projectId')\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect('/')\n } catch (error) {\n console.error(error)\n throw new Response('Unable to disable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n\n/**\n * A `GET` request to this route will enter preview mode\n */\nexport const loader: LoaderFunction = async ({context, request}) => {\n try {\n // TODO: to remove\n const {sanity, session} = context as {sanity: SanityContext; session: HydrogenSession}\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview) {\n return new Response('Preview mode is not enabled in this environment.', {status: 403})\n }\n\n if (!sanity.preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if (!projectId) {\n throw new Error('No `projectId` found in the client config.')\n }\n\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n const clientWithToken = sanity.client.withConfig({\n useCdn: false,\n token: sanity.preview.token,\n })\n\n const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, request.url)\n\n if (!isValid) {\n return new Response('Invalid secret', {status: 401})\n }\n\n // TODO: make this a callback? `onEnterPreview`?\n await session.set('projectId', projectId)\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect(redirectTo)\n } catch (error) {\n console.error(error)\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n"],"names":["exports","action","async","context","request","method","json","message","session","assertSession","Error","unset","redirect","error","console","Response","status","loader","sanity","projectId","client","config","preview","token","clientWithToken","withConfig","useCdn","isValid","redirectTo","validatePreviewUrl","url","set"],"mappings":"yLAiFAA,QAAAC,OAvEsCC,OAAQC,UAASC,cACrD,GAAuB,SAAnBA,EAAQC,OACV,OAAOC,EAAKA,KAAA,CAACC,QAAS,sBAAuB,KAG3C,IACI,MAAAC,QAACA,GAAWL,EACd,IAACM,IAAcD,GACX,MAAA,IAAIE,MAAM,iDAIlB,aAAMF,EAAQG,MAAM,aAGbC,EAAAA,SAAS,WACTC,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,0EAA2E,CAC5FC,OAAQ,KACT,GAmDLhB,QAAAiB,OA5CsCf,OAAQC,UAASC,cACjD,IAEI,MAAAc,OAACA,UAAQV,GAAWL,EACpBgB,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,QACV,OAAO,IAAIP,SAAS,mDAAoD,CAACC,OAAQ,MAG/E,IAACE,EAAOI,QAAQC,MACZ,MAAA,IAAIb,MAAM,2CAGlB,IAAKS,EACG,MAAA,IAAIT,MAAM,8CAGd,IAACD,IAAcD,GACX,MAAA,IAAIE,MAAM,iDAGZ,MAAAc,EAAkBN,EAAOE,OAAOK,WAAW,CAC/CC,QAAQ,EACRH,MAAOL,EAAOI,QAAQC,SAGlBI,QAACA,EAAAC,WAASA,EAAa,WAAaC,qBAAmBL,EAAiBpB,EAAQ0B,KAEtF,OAAKH,SAKCnB,EAAQuB,IAAI,YAAaZ,GAGxBP,EAAAA,SAASgB,IAPP,IAAIb,SAAS,iBAAkB,CAACC,OAAQ,YAQ1CH,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,yEAA0E,CAC3FC,OAAQ,KACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"route.js","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport type {HydrogenSession} from '@shopify/hydrogen'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\n\nimport type {SanityContext} from '../context'\nimport {assertSession} from '../utils'\n\n/**\n * A `POST` request to this route will exit preview mode\n */\nexport const action: ActionFunction = async ({context, request}) => {\n if (request.method !== 'POST') {\n return json({message: 'Method not allowed'}, 405)\n }\n\n try {\n const {session} = context\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n // TODO: make this a callback? `onExitPreview`?\n await session.unset('projectId')\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect('/')\n } catch (error) {\n console.error(error)\n throw new Response('Unable to disable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n\n/**\n * A `GET` request to this route will enter preview mode\n */\nexport const loader: LoaderFunction = async ({context, request}) => {\n try {\n // TODO: to remove\n const {sanity, session} = context as {sanity: SanityContext; session: HydrogenSession}\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview) {\n return new Response('Preview mode is not enabled in this environment.', {status: 403})\n }\n\n if (!sanity.preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if (!projectId) {\n throw new Error('No `projectId` found in the client config.')\n }\n\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n const clientWithToken = sanity.client.withConfig({\n useCdn: false,\n token: sanity.preview.token,\n })\n\n const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, request.url)\n\n if (!isValid) {\n return new Response('Invalid secret', {status: 401})\n }\n\n // TODO: make this a callback? `onEnterPreview`?\n await session.set('projectId', projectId)\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect(redirectTo)\n } catch (error) {\n console.error(error)\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n"],"names":["action","async","context","request","method","json","message","session","assertSession","Error","unset","redirect","error","console","Response","status","loader","sanity","projectId","client","config","preview","token","clientWithToken","withConfig","useCdn","isValid","redirectTo","validatePreviewUrl","url","set"],"mappings":"sKAUO,MAAMA,EAAyBC,OAAQC,UAASC,cACrD,GAAuB,SAAnBA,EAAQC,OACV,OAAOC,EAAK,CAACC,QAAS,sBAAuB,KAG3C,IACI,MAAAC,QAACA,GAAWL,EACd,IAACM,EAAcD,GACX,MAAA,IAAIE,MAAM,iDAIlB,aAAMF,EAAQG,MAAM,aAGbC,EAAS,WACTC,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,0EAA2E,CAC5FC,OAAQ,KAEZ,GAMWC,EAAyBf,OAAQC,UAASC,cACjD,IAEI,MAAAc,OAACA,UAAQV,GAAWL,EACpBgB,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,QACV,OAAO,IAAIP,SAAS,mDAAoD,CAACC,OAAQ,MAG/E,IAACE,EAAOI,QAAQC,MACZ,MAAA,IAAIb,MAAM,2CAGlB,IAAKS,EACG,MAAA,IAAIT,MAAM,8CAGd,IAACD,EAAcD,GACX,MAAA,IAAIE,MAAM,iDAGZ,MAAAc,EAAkBN,EAAOE,OAAOK,WAAW,CAC/CC,QAAQ,EACRH,MAAOL,EAAOI,QAAQC,SAGlBI,QAACA,EAASC,WAAAA,EAAa,WAAaC,EAAmBL,EAAiBpB,EAAQ0B,KAEtF,OAAKH,SAKCnB,EAAQuB,IAAI,YAAaZ,GAGxBP,EAASgB,IAPP,IAAIb,SAAS,iBAAkB,CAACC,OAAQ,YAQ1CH,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,yEAA0E,CAC3FC,OAAQ,KAEZ"}
1
+ {"version":3,"file":"route.js","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport type {HydrogenSession} from '@shopify/hydrogen'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\n\nimport type {SanityContext} from '../context'\nimport {assertSession} from '../utils'\n\n/**\n * A `POST` request to this route will exit preview mode\n */\nexport const action: ActionFunction = async ({context, request}) => {\n if (request.method !== 'POST') {\n return json({message: 'Method not allowed'}, 405)\n }\n\n try {\n const {session} = context\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n // TODO: make this a callback? `onExitPreview`?\n await session.unset('projectId')\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect('/')\n } catch (error) {\n console.error(error)\n throw new Response('Unable to disable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n\n/**\n * A `GET` request to this route will enter preview mode\n */\nexport const loader: LoaderFunction = async ({context, request}) => {\n try {\n // TODO: to remove\n const {sanity, session} = context as {sanity: SanityContext; session: HydrogenSession}\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview) {\n return new Response('Preview mode is not enabled in this environment.', {status: 403})\n }\n\n if (!sanity.preview.token) {\n throw new Error('Enabling preview mode requires a token.')\n }\n\n if (!projectId) {\n throw new Error('No `projectId` found in the client config.')\n }\n\n if (!assertSession(session)) {\n throw new Error('Session is not an instance of HydrogenSession')\n }\n\n const clientWithToken = sanity.client.withConfig({\n useCdn: false,\n token: sanity.preview.token,\n })\n\n const {isValid, redirectTo = '/'} = await validatePreviewUrl(clientWithToken, request.url)\n\n if (!isValid) {\n return new Response('Invalid secret', {status: 401})\n }\n\n // TODO: make this a callback? `onEnterPreview`?\n await session.set('projectId', projectId)\n\n // TODO: confirm that the redirect and setting cookie has to happen here?\n return redirect(redirectTo)\n } catch (error) {\n console.error(error)\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\n }\n}\n"],"names":["action","async","context","request","method","json","message","session","assertSession","Error","unset","redirect","error","console","Response","status","loader","sanity","projectId","client","config","preview","token","clientWithToken","withConfig","useCdn","isValid","redirectTo","validatePreviewUrl","url","set"],"mappings":"sKAUO,MAAMA,EAAyBC,OAAQC,UAASC,cACrD,GAAuB,SAAnBA,EAAQC,OACV,OAAOC,EAAK,CAACC,QAAS,sBAAuB,KAG3C,IACI,MAAAC,QAACA,GAAWL,EACd,IAACM,EAAcD,GACX,MAAA,IAAIE,MAAM,iDAIlB,aAAMF,EAAQG,MAAM,aAGbC,EAAS,WACTC,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,0EAA2E,CAC5FC,OAAQ,KACT,GAOQC,EAAyBf,OAAQC,UAASC,cACjD,IAEI,MAAAc,OAACA,UAAQV,GAAWL,EACpBgB,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,QACV,OAAO,IAAIP,SAAS,mDAAoD,CAACC,OAAQ,MAG/E,IAACE,EAAOI,QAAQC,MACZ,MAAA,IAAIb,MAAM,2CAGlB,IAAKS,EACG,MAAA,IAAIT,MAAM,8CAGd,IAACD,EAAcD,GACX,MAAA,IAAIE,MAAM,iDAGZ,MAAAc,EAAkBN,EAAOE,OAAOK,WAAW,CAC/CC,QAAQ,EACRH,MAAOL,EAAOI,QAAQC,SAGlBI,QAACA,EAASC,WAAAA,EAAa,WAAaC,EAAmBL,EAAiBpB,EAAQ0B,KAEtF,OAAKH,SAKCnB,EAAQuB,IAAI,YAAaZ,GAGxBP,EAASgB,IAPP,IAAIb,SAAS,iBAAkB,CAACC,OAAQ,YAQ1CH,GACP,MAAAC,QAAQD,MAAMA,GACR,IAAIE,SAAS,yEAA0E,CAC3FC,OAAQ,KACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":["import type {VisualEditingProps} from '@sanity/visual-editing/remix'\nimport {lazy, type ReactElement, Suspense} from 'react'\n\n/**\n * Provide a consistent fallback to prevent hydration mismatch errors.\n */\nfunction VisualEditingFallback(): ReactElement {\n return <></>\n}\n\n/**\n * If server-side rendering, then return the fallback instead of the heavy dependency.\n * @see https://remix.run/docs/en/1.14.3/guides/constraints#browser-only-code-on-the-server\n */\nconst VisualEditingComponent =\n typeof document === 'undefined'\n ? VisualEditingFallback\n : lazy(\n () =>\n /**\n * `lazy` expects the component as the default export\n * @see https://react.dev/reference/react/lazy\n */\n import('./VisualEditing.client'),\n )\n\nexport function VisualEditing(props: VisualEditingProps): ReactElement {\n return (\n <Suspense>\n <VisualEditingComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["Object","defineProperty","exports","value","jsxRuntime","require","react","createDataAttribute","VisualEditingComponent","document","jsx","Fragment","lazy","Promise","resolve","then","enumerable","get","VisualEditing","props","Suspense","children"],"mappings":"aAMAA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,qBAAAC,EAAAD,QAAA,SAAAE,EAAAF,QAAA,gDAQA,MAAMG,SACGC,SAAa,IATtB,WACE,OAASL,EAAAM,IAAAC,WAAA,CAAA,EACX,EASMC,EAAAA,MACE,IAKEC,QAAAC,UAAAC,MAAA,WAAA,OAAAV,QAAO,0CAAwB,MASzCL,OAAAC,eAAAC,QAAA,sBAAA,CAAAc,YAAA,EAAAC,IAAA,WAAA,OAAAV,EAAAA,mBAAA,IAAAL,QAAAgB,cANO,SAAuBC,GAC5B,aACGC,WACC,CAAAC,SAAAX,EAAAA,IAACF,EAAwB,IAAGW,KAGlC"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":["import type {VisualEditingProps} from '@sanity/visual-editing/remix'\nimport {lazy, type ReactElement, Suspense} from 'react'\n\n/**\n * Provide a consistent fallback to prevent hydration mismatch errors.\n */\nfunction VisualEditingFallback(): ReactElement {\n return <></>\n}\n\n/**\n * If server-side rendering, then return the fallback instead of the heavy dependency.\n * @see https://remix.run/docs/en/1.14.3/guides/constraints#browser-only-code-on-the-server\n */\nconst VisualEditingComponent =\n typeof document === 'undefined'\n ? VisualEditingFallback\n : lazy(\n () =>\n /**\n * `lazy` expects the component as the default export\n * @see https://react.dev/reference/react/lazy\n */\n import('./VisualEditing.client'),\n )\n\nexport function VisualEditing(props: VisualEditingProps): ReactElement {\n return (\n <Suspense>\n <VisualEditingComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["Object","defineProperty","exports","value","jsxRuntime","require","react","createDataAttribute","VisualEditingComponent","document","jsx","Fragment","lazy","Promise","enumerable","get","VisualEditing","props","Suspense","children"],"mappings":"aAMAA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,qBAAAC,EAAAD,QAAA,SAAAE,EAAAF,QAAA,gDAQA,MAAMG,SACGC,SAAa,IATtB,WACE,OAASL,EAAAM,IAAAC,EAAAA,SAAA,GACX,EASMC,EAAAA,MACE,IAKEC,kDAAO,0CAAwB,MASzCb,OAAAC,eAAAC,QAAA,sBAAA,CAAAY,YAAA,EAAAC,IAAA,WAAA,OAAAR,EAAAA,mBAAA,IAAAL,QAAAc,cANO,SAAuBC,GAC5B,aACGC,WACC,CAAAC,SAAAT,EAAAA,IAACF,EAAwB,IAAGS,KAGlC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":["import type {VisualEditingProps} from '@sanity/visual-editing/remix'\nimport {lazy, type ReactElement, Suspense} from 'react'\n\n/**\n * Provide a consistent fallback to prevent hydration mismatch errors.\n */\nfunction VisualEditingFallback(): ReactElement {\n return <></>\n}\n\n/**\n * If server-side rendering, then return the fallback instead of the heavy dependency.\n * @see https://remix.run/docs/en/1.14.3/guides/constraints#browser-only-code-on-the-server\n */\nconst VisualEditingComponent =\n typeof document === 'undefined'\n ? VisualEditingFallback\n : lazy(\n () =>\n /**\n * `lazy` expects the component as the default export\n * @see https://react.dev/reference/react/lazy\n */\n import('./VisualEditing.client'),\n )\n\nexport function VisualEditing(props: VisualEditingProps): ReactElement {\n return (\n <Suspense>\n <VisualEditingComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["jsx","Fragment","lazy","Suspense","createDataAttribute","VisualEditingComponent","document","import","VisualEditing","props","children"],"mappings":"cAMAA,cAAAC,MAAA,mCAAAC,cAAAC,MAAA,sCAAAC,MAAA,+CAQA,MAAMC,SACGC,SAAa,IATtB,WACW,OAAAN,EAAAC,EAAA,CAAA,EACX,EASMC,GACE,IAKEK,OAAO,2CAGV,SAASC,EAAcC,YAEzBN,EACC,CAAAO,SAAAV,EAACK,EAAwB,IAAGI,KAGlC"}
1
+ {"version":3,"file":"index.js","sources":["../../src/visual-editing/VisualEditing.tsx"],"sourcesContent":["import type {VisualEditingProps} from '@sanity/visual-editing/remix'\nimport {lazy, type ReactElement, Suspense} from 'react'\n\n/**\n * Provide a consistent fallback to prevent hydration mismatch errors.\n */\nfunction VisualEditingFallback(): ReactElement {\n return <></>\n}\n\n/**\n * If server-side rendering, then return the fallback instead of the heavy dependency.\n * @see https://remix.run/docs/en/1.14.3/guides/constraints#browser-only-code-on-the-server\n */\nconst VisualEditingComponent =\n typeof document === 'undefined'\n ? VisualEditingFallback\n : lazy(\n () =>\n /**\n * `lazy` expects the component as the default export\n * @see https://react.dev/reference/react/lazy\n */\n import('./VisualEditing.client'),\n )\n\nexport function VisualEditing(props: VisualEditingProps): ReactElement {\n return (\n <Suspense>\n <VisualEditingComponent {...props} />\n </Suspense>\n )\n}\n"],"names":["jsx","Fragment","lazy","Suspense","createDataAttribute","VisualEditingComponent","document","import","VisualEditing","props","children"],"mappings":"cAMAA,cAAAC,MAAA,mCAAAC,cAAAC,MAAA,sCAAAC,MAAA,+CAQA,MAAMC,SACGC,SAAa,IATtB,WACW,OAAAN,EAAAC,EAAA,GACX,EASMC,GACE,IAKEK,OAAO,2CAGV,SAASC,EAAcC,YAEzBN,EACC,CAAAO,SAAAV,EAACK,EAAwB,IAAGI,KAGlC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hydrogen-sanity",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "description": "Sanity.io toolkit for Hydrogen",
5
5
  "keywords": [
6
6
  "sanity",
@@ -83,37 +83,37 @@
83
83
  },
84
84
  "dependencies": {
85
85
  "@sanity/client": "^6.22.2",
86
- "@sanity/preview-url-secret": "^1.6.21",
87
- "@sanity/react-loader": "^1.10.7",
88
- "@sanity/visual-editing": "^2.1.10",
89
- "groq": "^3.61.0"
86
+ "@sanity/preview-url-secret": "^2.0.0",
87
+ "@sanity/react-loader": "^1.10.14",
88
+ "@sanity/visual-editing": "^2.4.2",
89
+ "groq": "^3.62.3"
90
90
  },
91
91
  "devDependencies": {
92
- "@sanity/pkg-utils": "^6.11.4",
92
+ "@sanity/pkg-utils": "^6.11.8",
93
93
  "@sanity/plugin-kit": "^4.0.18",
94
94
  "@sanity/semantic-release-preset": "^4.1.8",
95
- "@shopify/hydrogen": "~2024.7.9",
96
- "@shopify/remix-oxygen": "^2.0.8",
97
- "@types/react": "^18.3.11",
95
+ "@shopify/hydrogen": "~2024.10.0",
96
+ "@shopify/remix-oxygen": "^2.0.9",
97
+ "@types/react": "^18.3.12",
98
98
  "@typescript-eslint/eslint-plugin": "^7.18.0",
99
99
  "@typescript-eslint/parser": "^7.18.0",
100
100
  "eslint": "^8.57.1",
101
101
  "eslint-config-prettier": "^9.1.0",
102
102
  "eslint-config-sanity": "^7.1.3",
103
103
  "eslint-plugin-prettier": "^5.2.1",
104
- "eslint-plugin-react": "^7.37.1",
104
+ "eslint-plugin-react": "^7.37.2",
105
105
  "eslint-plugin-react-hooks": "^4.6.2",
106
106
  "eslint-plugin-simple-import-sort": "^12.1.1",
107
107
  "react": "^18.3.1",
108
108
  "react-dom": "^18.3.1",
109
109
  "semantic-release": "^23.1.1",
110
110
  "typescript": "^5.6.3",
111
- "vitest": "^2.1.3",
111
+ "vitest": "^2.1.4",
112
112
  "vitest-github-actions-reporter": "^0.11.1"
113
113
  },
114
114
  "peerDependencies": {
115
115
  "@sanity/client": "^6.18.0",
116
- "@shopify/hydrogen": "^2023.7.0 || ~2024.1.0 || ~2024.4.0 || ~2024.7.0",
116
+ "@shopify/hydrogen": "^2023.7.0 || ~2024.1.0 || ~2024.4.0 || ~2024.7.0 || ~2024.10.0",
117
117
  "@shopify/remix-oxygen": "^1.0.0 || ^2.0.0",
118
118
  "groq": "^3.41.0",
119
119
  "react": "^18.0.0",
@@ -1,5 +1,5 @@
1
1
  import type {QueryStore} from '@sanity/react-loader'
2
- import {CacheShort, WithCache} from '@shopify/hydrogen'
2
+ import {CacheShort, type WithCache} from '@shopify/hydrogen'
3
3
  import groq from 'groq'
4
4
  import {beforeEach, describe, expect, it, vi} from 'vitest'
5
5
 
@@ -25,9 +25,11 @@ let withCache = vi.hoisted<WithCache | null>(() => null)
25
25
 
26
26
  vi.mock('@shopify/hydrogen', async (importOriginal) => {
27
27
  const module = await importOriginal<typeof import('@shopify/hydrogen')>()
28
- withCache = vi
29
- .fn()
30
- .mockImplementation(module.createWithCache({cache, waitUntil: () => Promise.resolve()}))
28
+ withCache = module.createWithCache({
29
+ cache,
30
+ waitUntil: () => Promise.resolve(),
31
+ request: new Request('https://example.com'),
32
+ })
31
33
 
32
34
  return {
33
35
  ...module,
@@ -37,17 +39,15 @@ vi.mock('@shopify/hydrogen', async (importOriginal) => {
37
39
 
38
40
  vi.mock('@sanity/react-loader', async (importOriginal) => {
39
41
  const module = await importOriginal<typeof import('@sanity/react-loader')>()
40
- const queryStore = module.createQueryStore({client: false, ssr: true})
41
42
 
42
43
  return {
43
44
  ...module,
44
- createQueryStore: vi.fn().mockReturnValue({
45
- ...queryStore,
46
- loadQuery,
47
- }),
45
+ loadQuery,
48
46
  }
49
47
  })
50
48
 
49
+ const runWithCache = vi.spyOn(withCache!, 'run')
50
+
51
51
  const client = createClient({projectId: 'my-project-id', dataset: 'my-dataset'})
52
52
 
53
53
  const query = groq`true`
@@ -77,8 +77,12 @@ describe('the Sanity request context', () => {
77
77
  })
78
78
 
79
79
  await contextWithDefaultStrategy.loadQuery<boolean>(query, params)
80
- expect(withCache).toHaveBeenCalledWith(hashedQuery, defaultStrategy, expect.any(Function))
81
- expect(cache.put).toHaveBeenCalled()
80
+ expect(runWithCache).toHaveBeenNthCalledWith(
81
+ 1,
82
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: defaultStrategy}),
83
+ expect.any(Function),
84
+ )
85
+ expect(cache.put).toHaveBeenCalledOnce()
82
86
  })
83
87
 
84
88
  it('queries should use the cache strategy passed in `loadQuery`', async () => {
@@ -86,8 +90,12 @@ describe('the Sanity request context', () => {
86
90
  await sanityContext.loadQuery<boolean>(query, params, {
87
91
  hydrogen: {cache: strategy},
88
92
  })
89
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
90
- expect(cache.put).toHaveBeenCalled()
93
+ expect(runWithCache).toHaveBeenNthCalledWith(
94
+ 1,
95
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
96
+ expect.any(Function),
97
+ )
98
+ expect(cache.put).toHaveBeenCalledOnce()
91
99
  })
92
100
  })
93
101
 
@@ -126,6 +134,6 @@ describe('when configured for preview', () => {
126
134
  it(`shouldn't cache queries`, async () => {
127
135
  await previewContext.loadQuery<boolean>(query)
128
136
  expect(loadQuery).toHaveBeenCalledOnce()
129
- expect(cache.put).not.toHaveBeenCalled()
137
+ expect(cache.put).not.toHaveBeenCalledOnce()
130
138
  })
131
139
  })
package/src/context.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import {loadQuery, type QueryResponseInitial, setServerClient} from '@sanity/react-loader'
2
- import {CacheLong, CacheNone, type CachingStrategy, createWithCache} from '@shopify/hydrogen'
2
+ import {
3
+ CacheLong,
4
+ CacheNone,
5
+ type CachingStrategy,
6
+ createWithCache,
7
+ type WithCache,
8
+ } from '@shopify/hydrogen'
3
9
 
4
10
  import {
5
11
  type ClientConfig,
@@ -62,10 +68,18 @@ type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'>
62
68
  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never
63
69
  }
64
70
 
65
- type LoadQueryOptions = Pick<
71
+ type LoadQueryOptions<T> = Pick<
66
72
  HydrogenResponseQueryOptions,
67
73
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
68
- >
74
+ > & {
75
+ hydrogen?: {
76
+ /**
77
+ * Whether to cache the result of the query or not.
78
+ * @defaultValue () => true
79
+ */
80
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
81
+ }
82
+ }
69
83
 
70
84
  export type SanityContext = {
71
85
  /**
@@ -76,7 +90,7 @@ export type SanityContext = {
76
90
  loadQuery<T = any>(
77
91
  query: string,
78
92
  params?: QueryParams,
79
- options?: LoadQueryOptions,
93
+ options?: LoadQueryOptions<T>,
80
94
  ): Promise<QueryResponseInitial<T>>
81
95
 
82
96
  client: SanityClient
@@ -125,8 +139,12 @@ export function createSanityContext(options: CreateSanityContextOptions): Sanity
125
139
  async loadQuery<T>(
126
140
  query: string,
127
141
  params: QueryParams | QueryWithoutParams,
128
- loaderOptions?: LoadQueryOptions,
142
+ loaderOptions?: LoadQueryOptions<T>,
129
143
  ): Promise<QueryResponseInitial<T>> {
144
+ if (!withCache) {
145
+ return await loadQuery<T>(query, params, loaderOptions)
146
+ }
147
+
130
148
  // Don't store response if preview is enabled
131
149
  const cacheStrategy =
132
150
  preview && preview.enabled
@@ -134,21 +152,28 @@ export function createSanityContext(options: CreateSanityContextOptions): Sanity
134
152
  : loaderOptions?.hydrogen?.cache || defaultStrategy || DEFAULT_CACHE_STRATEGY
135
153
 
136
154
  const queryHash = await hashQuery(query, params)
155
+ const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)
156
+
157
+ const runWithCache = async function runWithCache({
158
+ addDebugData,
159
+ }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {
160
+ // eslint-disable-next-line no-process-env
161
+ if (process.env.NODE_ENV === 'development') {
162
+ // Name displayed in the subrequest profiler
163
+ const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'
164
+
165
+ addDebugData({
166
+ displayName,
167
+ })
168
+ }
137
169
 
138
- return await (withCache
139
- ? withCache(queryHash, cacheStrategy, async ({addDebugData}) => {
140
- if (process.env.NODE_ENV === 'development') {
141
- // Name displayed in the subrequest profiler
142
- const displayName = loaderOptions?.hydrogen?.debug?.displayName || 'query Sanity'
143
-
144
- addDebugData({
145
- displayName,
146
- })
147
- }
170
+ return await loadQuery<T>(query, params, loaderOptions)
171
+ }
148
172
 
149
- return await loadQuery<T>(query, params, loaderOptions)
150
- })
151
- : loadQuery<T>(query, params, loaderOptions))
173
+ return await ('run' in withCache
174
+ ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)
175
+ : // @ts-expect-error for compatibility, remove in next major
176
+ withCache(queryHash, cacheStrategy, runWithCache))
152
177
  },
153
178
  client,
154
179
  preview,
@@ -11,14 +11,10 @@ const loadQuery = vi.hoisted<QueryStore['loadQuery']>(() => vi.fn().mockResolved
11
11
 
12
12
  vi.mock('@sanity/react-loader', async (importOriginal) => {
13
13
  const module = await importOriginal<typeof import('@sanity/react-loader')>()
14
- const queryStore = module.createQueryStore({client: false, ssr: true})
15
14
 
16
15
  return {
17
16
  ...module,
18
- createQueryStore: vi.fn().mockReturnValue({
19
- ...queryStore,
20
- loadQuery,
21
- }),
17
+ loadQuery,
22
18
  }
23
19
  })
24
20
 
@@ -37,8 +33,8 @@ function waitUntil() {
37
33
  return Promise.resolve()
38
34
  }
39
35
 
40
- type WithCache = ReturnType<typeof createWithCache>
41
- const withCache: WithCache = vi.fn().mockImplementation(createWithCache({cache, waitUntil}))
36
+ const withCache = createWithCache({cache, waitUntil, request: new Request('https://example.com')})
37
+ const runWithCache = vi.spyOn(withCache, 'run')
42
38
 
43
39
  const client = createClient({projectId: 'my-project-id', dataset: 'my-dataset'})
44
40
 
@@ -67,15 +63,23 @@ describe('the loader', () => {
67
63
  })
68
64
 
69
65
  await loaderWithDefaultStrategy.loadQuery<boolean>(query, params)
70
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
71
- expect(cache.put).toHaveBeenCalled()
66
+ expect(runWithCache).toHaveBeenNthCalledWith(
67
+ 1,
68
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
69
+ expect.any(Function),
70
+ )
71
+ expect(cache.put).toHaveBeenCalledOnce()
72
72
  })
73
73
 
74
74
  it('queries should use the cache strategy passed in `loadQuery`', async () => {
75
75
  const strategy = CacheShort()
76
76
  await loader.loadQuery<boolean>(query, params, {hydrogen: {cache: strategy}})
77
- expect(withCache).toHaveBeenCalledWith(hashedQuery, strategy, expect.any(Function))
78
- expect(cache.put).toHaveBeenCalled()
77
+ expect(runWithCache).toHaveBeenNthCalledWith(
78
+ 1,
79
+ expect.objectContaining({cacheKey: hashedQuery, cacheStrategy: strategy}),
80
+ expect.any(Function),
81
+ )
82
+ expect(cache.put).toHaveBeenCalledOnce()
79
83
  })
80
84
  })
81
85
 
@@ -112,6 +116,6 @@ describe('when configured for preview', () => {
112
116
  it(`shouldn't cache queries`, async () => {
113
117
  await previewLoader.loadQuery<boolean>(query)
114
118
  expect(loadQuery).toHaveBeenCalledOnce()
115
- expect(cache.put).not.toHaveBeenCalled()
119
+ expect(cache.put).not.toHaveBeenCalledOnce()
116
120
  })
117
121
  })
package/src/loader.ts CHANGED
@@ -61,10 +61,18 @@ type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'>
61
61
  hydrogen?: 'hydrogen' extends keyof RequestInit ? RequestInit['hydrogen'] : never
62
62
  }
63
63
 
64
- type LoadQueryOptions = Pick<
64
+ type LoadQueryOptions<T> = Pick<
65
65
  HydrogenResponseQueryOptions,
66
66
  'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
67
- >
67
+ > & {
68
+ hydrogen?: {
69
+ /**
70
+ * Whether to cache the result of the query or not.
71
+ * @defaultValue () => true
72
+ */
73
+ shouldCacheResult?: (value: QueryResponseInitial<T>) => boolean
74
+ }
75
+ }
68
76
 
69
77
  export type SanityLoader = {
70
78
  /**
@@ -75,7 +83,7 @@ export type SanityLoader = {
75
83
  loadQuery<T = any>(
76
84
  query: string,
77
85
  params?: QueryParams,
78
- options?: LoadQueryOptions,
86
+ options?: LoadQueryOptions<T>,
79
87
  ): Promise<QueryResponseInitial<T>>
80
88
 
81
89
  client: SanityClient
@@ -123,7 +131,7 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
123
131
  async loadQuery<T>(
124
132
  query: string,
125
133
  params: QueryParams | QueryWithoutParams,
126
- loaderOptions?: LoadQueryOptions,
134
+ loaderOptions?: LoadQueryOptions<T>,
127
135
  ): Promise<QueryResponseInitial<T>> {
128
136
  // Don't store response if preview is enabled
129
137
  const cacheStrategy =
@@ -133,7 +141,11 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
133
141
 
134
142
  const queryHash = await hashQuery(query, params)
135
143
 
136
- return await withCache(queryHash, cacheStrategy, async ({addDebugData}) => {
144
+ const shouldCacheResult = loaderOptions?.hydrogen?.shouldCacheResult ?? (() => true)
145
+
146
+ const runWithCache = async function runWithCache({
147
+ addDebugData,
148
+ }: Parameters<Parameters<WithCache['run']>[1]>[0]): Promise<QueryResponseInitial<T>> {
137
149
  // eslint-disable-next-line no-process-env
138
150
  if (process.env.NODE_ENV === 'development') {
139
151
  // Name displayed in the subrequest profiler
@@ -145,7 +157,12 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
145
157
  }
146
158
 
147
159
  return await loadQuery<T>(query, params, loaderOptions)
148
- })
160
+ }
161
+
162
+ return await ('run' in withCache
163
+ ? withCache.run({cacheKey: queryHash, cacheStrategy, shouldCacheResult}, runWithCache)
164
+ : // @ts-expect-error for compatibility, remove in next major
165
+ withCache(queryHash, cacheStrategy, runWithCache))
149
166
  },
150
167
  client,
151
168
  preview,
@@ -0,0 +1,61 @@
1
+ import type {HydrogenSession} from '@shopify/hydrogen'
2
+ import {describe, expect, it, vi} from 'vitest'
3
+
4
+ import {createSanityContext, type SanityContext} from '../context'
5
+ import {action, loader} from './route'
6
+
7
+ vi.mock('./client', {spy: true})
8
+
9
+ type AppLoadContext = {
10
+ session: HydrogenSession
11
+ sanity: SanityContext
12
+ }
13
+
14
+ class Session implements HydrogenSession {
15
+ #data = new Map()
16
+
17
+ get(key: string) {
18
+ return this.#data.get(key)
19
+ }
20
+
21
+ set(key: string, value: unknown) {
22
+ this.#data.set(key, value)
23
+ }
24
+
25
+ unset(key: string) {
26
+ this.#data.delete(key)
27
+ }
28
+
29
+ async commit() {
30
+ return JSON.stringify(this.#data)
31
+ }
32
+ }
33
+
34
+ describe('the preview route', () => {
35
+ const request = new Request('https://example.com')
36
+
37
+ const sanity = createSanityContext({
38
+ request,
39
+ client: {projectId: 'my-project-id', dataset: 'my-dataset'},
40
+ preview: {
41
+ enabled: true,
42
+ token: 'my-token',
43
+ studioUrl: 'https://example.com',
44
+ },
45
+ })
46
+
47
+ const context: AppLoadContext = {
48
+ session: new Session(),
49
+ sanity,
50
+ }
51
+
52
+ it('should enable preview mode', async () => {
53
+ const response = await loader({context, request, params: {}})
54
+ expect(response).toBeInstanceOf(Response)
55
+ })
56
+
57
+ it('should disable preview mode', async () => {
58
+ const response = await action({context, request, params: {}})
59
+ expect(response).toBeInstanceOf(Response)
60
+ })
61
+ })