hydrogen-sanity 4.0.5 → 4.1.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 +41 -18
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/preview/route.cjs +1 -1
- package/dist/preview/route.cjs.map +1 -1
- package/dist/preview/route.js +1 -1
- package/dist/preview/route.js.map +1 -1
- package/package.json +19 -19
- package/src/loader.ts +7 -3
package/README.md
CHANGED
|
@@ -2,30 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
[Sanity.io](https://www.sanity.io) toolkit for [Hydrogen](https://hydrogen.shopify.dev/). Requires `@shopify/hydrogen >= 2023.7.0`.
|
|
4
4
|
|
|
5
|
-
- [
|
|
6
|
-
|
|
7
|
-
- [
|
|
8
|
-
|
|
9
|
-
- [
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
- [
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
- [
|
|
22
|
-
- [Release new version](#release-new-version)
|
|
5
|
+
- [Installation](#installation)
|
|
6
|
+
- [Usage](#usage)
|
|
7
|
+
- [Satisfy TypeScript](#satisfy-typescript)
|
|
8
|
+
- [Interacting with Sanity data](#interacting-with-sanity-data)
|
|
9
|
+
- [Preferred: Cached fetches using `loadQuery`](#preferred-cached-fetches-using-loadquery)
|
|
10
|
+
- [`loadQuery` Request Options](#loadquery-request-options)
|
|
11
|
+
- [Alternatively: Using `client` directly](#alternatively-using-client-directly)
|
|
12
|
+
- [Visual Editing](#visual-editing)
|
|
13
|
+
- [Enabling preview mode](#enabling-preview-mode)
|
|
14
|
+
- [Setup CORS for front-end domains](#setup-cors-for-front-end-domains)
|
|
15
|
+
- [Modify Content Security Policy for Studio domains](#modify-content-security-policy-for-studio-domains)
|
|
16
|
+
- [Setup Presentation Tool](#setup-presentation-tool)
|
|
17
|
+
- [Using `@sanity/client` instead of hydrogen-sanity](#using-sanityclient-instead-of-hydrogen-sanity)
|
|
18
|
+
- [Migration Guides](#migration-guides)
|
|
19
|
+
- [License](#license)
|
|
20
|
+
- [Develop \& test](#develop--test)
|
|
21
|
+
- [Release new version](#release-new-version)
|
|
23
22
|
|
|
24
23
|
**Features:**
|
|
25
24
|
|
|
26
25
|
- Cacheable queries to [Sanity API CDN](https://www.sanity.io/docs/api-cdn)
|
|
27
26
|
- Interactive live preview with [Visual Editing](https://www.sanity.io/docs/loaders-and-overlays)
|
|
28
27
|
|
|
28
|
+
> [!NOTE]
|
|
29
|
+
>
|
|
30
|
+
> If you'd prefer a self-paced course on how to use Sanity and Hydrogen, check out the [Sanity and Shopify with Hydrogen on Sanity Learn](https://www.sanity.io/learn/course/sanity-and-shopify-with-hydrogen).
|
|
31
|
+
|
|
29
32
|
> [!NOTE]
|
|
30
33
|
>
|
|
31
34
|
> Using this package isn't strictly required for working with Sanity in a Hydrogen storefront. If you'd like to use `@sanity/react-loader` and/or `@sanity/client` directly, see [Using `@sanity/client` directly](#using-sanityclient-directly) below.
|
|
@@ -195,9 +198,18 @@ const page = await context.sanity.loadQuery<HomePage>(query, params, {
|
|
|
195
198
|
// displayName: 'query Homepage'
|
|
196
199
|
// }
|
|
197
200
|
},
|
|
201
|
+
|
|
202
|
+
// ...as well as other request options
|
|
203
|
+
// tag: 'home',
|
|
204
|
+
// headers: {
|
|
205
|
+
// 'Accept-Encoding': 'br, gzip, *',
|
|
206
|
+
// },
|
|
198
207
|
})
|
|
199
208
|
```
|
|
200
209
|
|
|
210
|
+
> [!NOTE]
|
|
211
|
+
> You can learn more about request tagging in [the documentation](https://www.sanity.io/docs/reference-api-request-tags).
|
|
212
|
+
|
|
201
213
|
### Alternatively: Using `client` directly
|
|
202
214
|
|
|
203
215
|
The Sanity client (either instantiated from your configuration or passed through directly) is also available in your app's context. It is recommended to use `loadQuery` for data fetching; but the Sanity client can be used for mutations within actions, for example:
|
|
@@ -223,6 +235,10 @@ export async function action({context, request}: ActionFunctionArgs) {
|
|
|
223
235
|
|
|
224
236
|
Enable real-time, interactive live preview inside the Presentation tool of your Sanity Studio. `hydrogen-sanity` comes with a ready-to-use version of the `VisualEditing` component that's compatible with Hydrogen and Oxygen.
|
|
225
237
|
|
|
238
|
+
> [!NOTE]
|
|
239
|
+
>
|
|
240
|
+
> These instructions assume some familiarity with Sanity's Visual Editing concepts, like loaders and overlays. To learn more, please visit the [Visual Editing documentation](https://www.sanity.io/docs/introduction-to-visual-editing).
|
|
241
|
+
|
|
226
242
|
First set up your root route to enable preview mode across the entire application, if the preview session is active:
|
|
227
243
|
|
|
228
244
|
```tsx
|
|
@@ -268,6 +284,12 @@ For users to enter preview mode, they will need to visit a route that performs s
|
|
|
268
284
|
|
|
269
285
|
`hydrogen-sanity` comes with a preconfigured route for this purpose. It checks the value of a secret in the URL used by Presentation tool - and if valid - writes the `projectId` to the Hydrogen session.
|
|
270
286
|
|
|
287
|
+
> [!NOTE]
|
|
288
|
+
>
|
|
289
|
+
> By default, `hydrogen-sanity` will enable stega-encoded Content Source Maps when preview mode is enabled.
|
|
290
|
+
>
|
|
291
|
+
> You can learn more about Content Source Maps and working with stega-encoded strings in [the documentation](https://www.sanity.io/docs/stega).
|
|
292
|
+
|
|
271
293
|
Add this route to your project like below, or view the source to copy and modify it in your project.
|
|
272
294
|
|
|
273
295
|
```tsx
|
|
@@ -308,6 +330,7 @@ export default async function handleRequest(
|
|
|
308
330
|
// Include Sanity domains in the CSP
|
|
309
331
|
defaultSrc: ['https://cdn.sanity.io', 'https://lh3.googleusercontent.com'],
|
|
310
332
|
connectSrc: [`https://${projectId}.api.sanity.io`, `wss://${projectId}.api.sanity.io`],
|
|
333
|
+
// Consider using an environment variable here
|
|
311
334
|
frameAncestors: [`http://localhost:3333`, `'self'`],
|
|
312
335
|
})
|
|
313
336
|
|
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");function r(e,t){let n=e;return t&&(n+=JSON.stringify(t)),async function(e){const t=await(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(n)}const i=n.CacheLong(),a=t.createQueryStore({client:!1,ssr:!0});Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityLoader=function(t){const{withCache:o,preview:
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/client"),t=require("@sanity/react-loader"),n=require("@shopify/hydrogen");function r(e,t){let n=e;return t&&(n+=JSON.stringify(t)),async function(e){const t=await(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(n)}const i=n.CacheLong(),a=t.createQueryStore({client:!1,ssr:!0});Object.defineProperty(exports,"SanityClient",{enumerable:!0,get:function(){return e.SanityClient}}),Object.defineProperty(exports,"createClient",{enumerable:!0,get:function(){return e.createClient}}),exports.createSanityLoader=function(t){const{withCache:o,preview:c,strategy:s}=t;let l=t.client instanceof e.SanityClient?t.client:e.createClient(t.client);if("1"===l.config().apiVersion&&(l=l.withConfig({apiVersion:"v2022-03-07"})),c&&c.enabled){if(!c.token)throw new Error("Enabling preview mode requires a token.");const e=l.withConfig({useCdn:!1,token:c.token,perspective:"previewDrafts",stega:{...l.config().stega,enabled:!0,studioUrl:c.studioUrl}});a.setServerClient(e)}else a.setServerClient(l);return{async loadQuery(e,t,l){const u=c&&c.enabled?n.CacheNone():l?.hydrogen?.cache||s||i,d=await r(e,t);return await o(d,u,(async({addDebugData:n})=>{if("development"===process.env.NODE_ENV){n({displayName:l?.hydrogen?.debug?.displayName||"query Sanity"})}return await a.loadQuery(e,t,l)}))},client:l,preview:c}};//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/utils.ts","../src/loader.ts"],"sourcesContent":["import type {QueryParams, QueryWithoutParams} from './client'\n\n/**\n * Create an SHA-256 hash as a hex string\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string\n */\nexport async function sha256(message: string): Promise<string> {\n // encode as UTF-8\n const messageBuffer = await new TextEncoder().encode(message)\n // hash the message\n const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer)\n // convert bytes to hex string\n return Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Hash query and its parameters for use as cache key\n * NOTE: Oxygen deployment will break if the cache key is long or contains `\\n`\n */\nexport function hashQuery(\n query: string,\n params: QueryParams | QueryWithoutParams,\n): Promise<string> {\n let hash = query\n\n if (params) {\n hash += JSON.stringify(params)\n }\n\n return sha256(hash)\n}\n","/* eslint-disable no-return-await */\nimport {createQueryStore, type QueryResponseInitial} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type HydrogenSession, 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 type {CachingStrategy} from './types'\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'\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\ndeclare module '@shopify/remix-oxygen' {\n /**\n * Declare local additions to the Remix loader context.\n */\n export interface AppLoadContext {\n session: HydrogenSession\n sanity: SanityLoader\n }\n}\n\nconst queryStore = createQueryStore({client: false, ssr: true})\n\n/**\n * @public\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 /**\n * TODO: should this default to the latest API version?\n * Or at least warn if a version that doesn't support
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/utils.ts","../src/loader.ts"],"sourcesContent":["import type {QueryParams, QueryWithoutParams} from './client'\n\n/**\n * Create an SHA-256 hash as a hex string\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string\n */\nexport async function sha256(message: string): Promise<string> {\n // encode as UTF-8\n const messageBuffer = await new TextEncoder().encode(message)\n // hash the message\n const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer)\n // convert bytes to hex string\n return Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Hash query and its parameters for use as cache key\n * NOTE: Oxygen deployment will break if the cache key is long or contains `\\n`\n */\nexport function hashQuery(\n query: string,\n params: QueryParams | QueryWithoutParams,\n): Promise<string> {\n let hash = query\n\n if (params) {\n hash += JSON.stringify(params)\n }\n\n return sha256(hash)\n}\n","/* eslint-disable no-return-await */\nimport {createQueryStore, type QueryResponseInitial} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type HydrogenSession, 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 type {CachingStrategy} from './types'\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\ndeclare module '@shopify/remix-oxygen' {\n /**\n * Declare local additions to the Remix loader context.\n */\n export interface AppLoadContext {\n session: HydrogenSession\n sanity: SanityLoader\n }\n}\n\nconst queryStore = createQueryStore({client: false, ssr: true})\n\n/**\n * @public\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 /**\n * TODO: should this default to the latest API version?\n * Or at least warn if a version that doesn't support perspectives is used?\n */\n if (client.config().apiVersion === '1') {\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 queryStore.setServerClient(previewClient)\n } else {\n queryStore.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 queryStore.loadQuery<T>(query, params, loaderOptions)\n })\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["hashQuery","query","params","hash","JSON","stringify","async","message","messageBuffer","TextEncoder","encode","hashBuffer","crypto","subtle","digest","Array","from","Uint8Array","map","b","toString","padStart","join","sha256","DEFAULT_CACHE_STRATEGY","CacheLong","queryStore","createQueryStore","client","ssr","Object","defineProperty","exports","enumerable","get","SanityClient","createClient","createSanityLoader","options","withCache","preview","strategy","config","apiVersion","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","loaderOptions","cacheStrategy","CacheNone","hydrogen","cache","queryHash","addDebugData","process","env","NODE_ENV","displayName","debug"],"mappings":"qKAqBgB,SAAAA,EACdC,EACAC,GAEA,IAAIC,EAAOF,EAEX,OAAIC,IACFC,GAAQC,KAAKC,UAAUH,IAtB3BI,eAA6BC,GAE3B,MAAMC,QAAsB,IAAIC,aAAcC,OAAOH,GAE/CI,QAAmBC,OAAOC,OAAOC,OAAO,UAAWN,GAElD,OAAAO,MAAMC,KAAK,IAAIC,WAAWN,IAC9BO,KAAKC,GAAMA,EAAEC,SAAS,IAAIC,SAAS,EAAG,OACtCC,KAAK,GACV,CAgBSC,CAAOpB,EAChB,CCjBA,MAAMqB,EAAyBC,EAAAA,YAkFzBC,EAAaC,EAAAA,iBAAiB,CAACC,QAAQ,EAAOC,KAAK,IAwEzDC,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAN,EAAAO,YAAA,IAAAL,OAAAC,eAAAC,QAAA,eAAA,CAAAC,YAAA,EAAAC,IAAA,WAAA,OAAAN,EAAAQ,YAAA,IAAAJ,QAAAK,mBAnEO,SAA4BC,GACjC,MAAMC,UAACA,EAAAC,QAAWA,EAASC,SAAAA,GAAYH,EACnCV,IAAAA,EACFU,EAAQV,kBAAkBO,EAAAA,aAAeG,EAAQV,OAASQ,EAAAA,aAAaE,EAAQV,QAUjF,GAJmC,MAA/BA,EAAOc,SAASC,aAClBf,EAASA,EAAOgB,WAAW,CAACD,WAAY,iBAGtCH,GAAWA,EAAQK,QAAS,CAC9B,IAAKL,EAAQM,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBpB,EAAOgB,WAAW,CACtCK,QAAQ,EACRH,MAAON,EAAQM,MACfI,YAAa,gBACbC,MAAO,IACFvB,EAAOc,SAASS,MACnBN,SAAS,EACTO,UAAWZ,EAAQY,aAIvB1B,EAAW2B,gBAAgBL,EAC7B,MACEtB,EAAW2B,gBAAgBzB,GAGd,MAAA,CACb,eAAM0B,CACJrD,EACAC,EACAqD,GAGA,MAAMC,EACJhB,GAAWA,EAAQK,QACfY,EAAAA,YACAF,GAAeG,UAAUC,OAASlB,GAAYjB,EAE9CoC,QAAkB5D,EAAUC,EAAOC,GAEzC,aAAaqC,EAAUqB,EAAWJ,GAAelD,OAAQuD,mBAEnD,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBV,GAAeG,UAAUQ,OAAOD,aAAe,gBAKrE,CAEA,aAAavC,EAAW4B,UAAarD,EAAOC,EAAQqD,EAAa,GAErE,EAAA3B,OACAA,EACAY,UAIJ"}
|
package/dist/index.d.cts
CHANGED
|
@@ -50,7 +50,7 @@ declare type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' |
|
|
|
50
50
|
|
|
51
51
|
declare type LoadQueryOptions = Pick<
|
|
52
52
|
HydrogenResponseQueryOptions,
|
|
53
|
-
'perspective' | 'hydrogen' | 'useCdn' | 'stega'
|
|
53
|
+
'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
|
|
54
54
|
>
|
|
55
55
|
|
|
56
56
|
declare interface RequestInit_2 {
|
package/dist/index.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ declare type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' |
|
|
|
50
50
|
|
|
51
51
|
declare type LoadQueryOptions = Pick<
|
|
52
52
|
HydrogenResponseQueryOptions,
|
|
53
|
-
'perspective' | 'hydrogen' | 'useCdn' | 'stega'
|
|
53
|
+
'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
|
|
54
54
|
>
|
|
55
55
|
|
|
56
56
|
declare interface RequestInit_2 {
|
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{createQueryStore as r}from"@sanity/react-loader";import{CacheLong as a,CacheNone as o}from"@shopify/hydrogen";function
|
|
1
|
+
import{SanityClient as e,createClient as t}from"@sanity/client";import{SanityClient as n,createClient as i}from"@sanity/client";import{createQueryStore as r}from"@sanity/react-loader";import{CacheLong as a,CacheNone as o}from"@shopify/hydrogen";function s(e,t){let n=e;return t&&(n+=JSON.stringify(t)),async function(e){const t=await(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(n)}const c=a(),l=r({client:!1,ssr:!0});function d(n){const{withCache:i,preview:r,strategy:a}=n;let d=n.client instanceof e?n.client:t(n.client);if("1"===d.config().apiVersion&&(d=d.withConfig({apiVersion:"v2022-03-07"})),r&&r.enabled){if(!r.token)throw new Error("Enabling preview mode requires a token.");const e=d.withConfig({useCdn:!1,token:r.token,perspective:"previewDrafts",stega:{...d.config().stega,enabled:!0,studioUrl:r.studioUrl}});l.setServerClient(e)}else l.setServerClient(d);return{async loadQuery(e,t,n){const d=r&&r.enabled?o():n?.hydrogen?.cache||a||c,y=await s(e,t);return await i(y,d,(async({addDebugData:i})=>{if("development"===process.env.NODE_ENV){i({displayName:n?.hydrogen?.debug?.displayName||"query Sanity"})}return await l.loadQuery(e,t,n)}))},client:d,preview:r}}export{n as SanityClient,i as createClient,d as createSanityLoader};//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/utils.ts","../src/loader.ts"],"sourcesContent":["import type {QueryParams, QueryWithoutParams} from './client'\n\n/**\n * Create an SHA-256 hash as a hex string\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string\n */\nexport async function sha256(message: string): Promise<string> {\n // encode as UTF-8\n const messageBuffer = await new TextEncoder().encode(message)\n // hash the message\n const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer)\n // convert bytes to hex string\n return Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Hash query and its parameters for use as cache key\n * NOTE: Oxygen deployment will break if the cache key is long or contains `\\n`\n */\nexport function hashQuery(\n query: string,\n params: QueryParams | QueryWithoutParams,\n): Promise<string> {\n let hash = query\n\n if (params) {\n hash += JSON.stringify(params)\n }\n\n return sha256(hash)\n}\n","/* eslint-disable no-return-await */\nimport {createQueryStore, type QueryResponseInitial} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type HydrogenSession, 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 type {CachingStrategy} from './types'\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'\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\ndeclare module '@shopify/remix-oxygen' {\n /**\n * Declare local additions to the Remix loader context.\n */\n export interface AppLoadContext {\n session: HydrogenSession\n sanity: SanityLoader\n }\n}\n\nconst queryStore = createQueryStore({client: false, ssr: true})\n\n/**\n * @public\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 /**\n * TODO: should this default to the latest API version?\n * Or at least warn if a version that doesn't support
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/utils.ts","../src/loader.ts"],"sourcesContent":["import type {QueryParams, QueryWithoutParams} from './client'\n\n/**\n * Create an SHA-256 hash as a hex string\n * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string\n */\nexport async function sha256(message: string): Promise<string> {\n // encode as UTF-8\n const messageBuffer = await new TextEncoder().encode(message)\n // hash the message\n const hashBuffer = await crypto.subtle.digest('SHA-256', messageBuffer)\n // convert bytes to hex string\n return Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Hash query and its parameters for use as cache key\n * NOTE: Oxygen deployment will break if the cache key is long or contains `\\n`\n */\nexport function hashQuery(\n query: string,\n params: QueryParams | QueryWithoutParams,\n): Promise<string> {\n let hash = query\n\n if (params) {\n hash += JSON.stringify(params)\n }\n\n return sha256(hash)\n}\n","/* eslint-disable no-return-await */\nimport {createQueryStore, type QueryResponseInitial} from '@sanity/react-loader'\nimport {CacheLong, CacheNone, type HydrogenSession, 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 type {CachingStrategy} from './types'\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\ndeclare module '@shopify/remix-oxygen' {\n /**\n * Declare local additions to the Remix loader context.\n */\n export interface AppLoadContext {\n session: HydrogenSession\n sanity: SanityLoader\n }\n}\n\nconst queryStore = createQueryStore({client: false, ssr: true})\n\n/**\n * @public\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 /**\n * TODO: should this default to the latest API version?\n * Or at least warn if a version that doesn't support perspectives is used?\n */\n if (client.config().apiVersion === '1') {\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 queryStore.setServerClient(previewClient)\n } else {\n queryStore.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 queryStore.loadQuery<T>(query, params, loaderOptions)\n })\n },\n client,\n preview,\n }\n\n return sanity\n}\n"],"names":["hashQuery","query","params","hash","JSON","stringify","async","message","messageBuffer","TextEncoder","encode","hashBuffer","crypto","subtle","digest","Array","from","Uint8Array","map","b","toString","padStart","join","sha256","DEFAULT_CACHE_STRATEGY","CacheLong","queryStore","createQueryStore","client","ssr","createSanityLoader","options","withCache","preview","strategy","SanityClient","createClient","config","apiVersion","withConfig","enabled","token","Error","previewClient","useCdn","perspective","stega","studioUrl","setServerClient","loadQuery","loaderOptions","cacheStrategy","CacheNone","hydrogen","cache","queryHash","addDebugData","process","env","NODE_ENV","displayName","debug"],"mappings":"qPAqBgB,SAAAA,EACdC,EACAC,GAEA,IAAIC,EAAOF,EAEX,OAAIC,IACFC,GAAQC,KAAKC,UAAUH,IAtB3BI,eAA6BC,GAE3B,MAAMC,QAAsB,IAAIC,aAAcC,OAAOH,GAE/CI,QAAmBC,OAAOC,OAAOC,OAAO,UAAWN,GAElD,OAAAO,MAAMC,KAAK,IAAIC,WAAWN,IAC9BO,KAAKC,GAAMA,EAAEC,SAAS,IAAIC,SAAS,EAAG,OACtCC,KAAK,GACV,CAgBSC,CAAOpB,EAChB,CCjBA,MAAMqB,EAAyBC,IAkFzBC,EAAaC,EAAiB,CAACC,QAAQ,EAAOC,KAAK,IAKlD,SAASC,EAAmBC,GACjC,MAAMC,UAACA,EAAAC,QAAWA,EAASC,SAAAA,GAAYH,EACnC,IAAAH,EACFG,EAAQH,kBAAkBO,EAAeJ,EAAQH,OAASQ,EAAaL,EAAQH,QAUjF,GAJmC,MAA/BA,EAAOS,SAASC,aAClBV,EAASA,EAAOW,WAAW,CAACD,WAAY,iBAGtCL,GAAWA,EAAQO,QAAS,CAC9B,IAAKP,EAAQQ,MACL,MAAA,IAAIC,MAAM,2CAGZ,MAAAC,EAAgBf,EAAOW,WAAW,CACtCK,QAAQ,EACRH,MAAOR,EAAQQ,MACfI,YAAa,gBACbC,MAAO,IACFlB,EAAOS,SAASS,MACnBN,SAAS,EACTO,UAAWd,EAAQc,aAIvBrB,EAAWsB,gBAAgBL,EAC7B,MACEjB,EAAWsB,gBAAgBpB,GAGd,MAAA,CACb,eAAMqB,CACJhD,EACAC,EACAgD,GAGA,MAAMC,EACJlB,GAAWA,EAAQO,QACfY,IACAF,GAAeG,UAAUC,OAASpB,GAAYV,EAE9C+B,QAAkBvD,EAAUC,EAAOC,GAEzC,aAAa8B,EAAUuB,EAAWJ,GAAe7C,OAAQkD,mBAEnD,GAAyB,gBAAzBC,QAAQC,IAAIC,SAA4B,CAI7BH,EAAA,CACXI,YAHkBV,GAAeG,UAAUQ,OAAOD,aAAe,gBAKrE,CAEA,aAAalC,EAAWuB,UAAahD,EAAOC,EAAQgD,EAAa,GAErE,EACAtB,SACAK,UAIJ"}
|
package/dist/preview/route.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/preview-url-secret"),t=require("@shopify/remix-oxygen");exports.action=async({context:e,request:s})=>"POST"!==s.method?t.json({message:"Method not allowed"},405):(await e.session.unset("projectId"),t.redirect("/",{headers:{"Set-Cookie":await e.session.commit()}})),exports.loader=async({context:s,request:o})=>{
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@sanity/preview-url-secret"),t=require("@shopify/remix-oxygen");exports.action=async({context:e,request:s})=>"POST"!==s.method?t.json({message:"Method not allowed"},405):(await e.session.unset("projectId"),t.redirect("/",{headers:{"Set-Cookie":await e.session.commit()}})),exports.loader=async({context:s,request:o})=>{const{sanity:i}=s,r=i.client.config().projectId;if(!i.preview?.token||!r)throw new Response("Unable to enable preview mode. Please check your preview configuration",{status:500});const n=i.client.withConfig({useCdn:!1,token:i.preview.token}),{isValid:a,redirectTo:c="/"}=await e.validatePreviewUrl(n,o.url);if(!a)throw new Response("Invalid secret",{status:401});return await s.session.set("projectId",r),t.redirect(c,{headers:{"Set-Cookie":await s.session.commit()}})};//# sourceMappingURL=route.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.cjs","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\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 await context.session.unset('projectId')\n\n return redirect('/', {\n headers: {\n 'Set-Cookie': await context.session.commit(),\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 const {sanity} = context\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview?.token || !projectId) {\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\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 throw new Response('Invalid secret', {status: 401})\n }\n\n await context.session.set('projectId', projectId)\n\n return redirect(redirectTo, {\n headers: {\n 'Set-Cookie': await context.session.commit(),\n },\n })\n}\n"],"names":["Object","defineProperty","exports","value","previewUrlSecret","require","remixOxygen","action","async","context","request","method","json","message","session","unset","redirect","headers","commit","loader","
|
|
1
|
+
{"version":3,"file":"route.cjs","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\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 await context.session.unset('projectId')\n\n return redirect('/', {\n headers: {\n 'Set-Cookie': await context.session.commit(),\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 const {sanity} = context\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview?.token || !projectId) {\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\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 throw new Response('Invalid secret', {status: 401})\n }\n\n await context.session.set('projectId', projectId)\n\n return redirect(redirectTo, {\n headers: {\n 'Set-Cookie': await context.session.commit(),\n },\n })\n}\n"],"names":["Object","defineProperty","exports","value","previewUrlSecret","require","remixOxygen","action","async","context","request","method","json","message","session","unset","redirect","headers","commit","loader","sanity","projectId","client","config","preview","token","Response","status","clientWithToken","withConfig","useCdn","isValid","redirectTo","validatePreviewUrl","url","set"],"mappings":"aAMaA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,8BAAAC,EAAAD,QAAA,yBA6CbH,QAAAK,OA7CsCC,OAAQC,UAASC,aAC9B,SAAnBA,EAAQC,OACHC,EAAAA,KAAK,CAACC,QAAS,sBAAuB,YAGzCJ,EAAQK,QAAQC,MAAM,aAErBC,EAAAA,SAAS,IAAK,CACnBC,QAAS,CACP,mBAAoBR,EAAQK,QAAQI,aAoC1ChB,QAAAiB,OA5BsCX,OAAQC,UAASC,cAC/C,MAAAU,OAACA,GAAUX,EACXY,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,SAASC,QAAUJ,EACvB,MAAA,IAAIK,SAAS,yEAA0E,CAC3FC,OAAQ,MAIN,MAAAC,EAAkBR,EAAOE,OAAOO,WAAW,CAC/CC,QAAQ,EACRL,MAAOL,EAAOI,QAAQC,SAGlBM,QAACA,EAAAC,WAASA,EAAa,WAAaC,EAAAA,mBAAmBL,EAAiBlB,EAAQwB,KAEtF,IAAKH,EACH,MAAM,IAAIL,SAAS,iBAAkB,CAACC,OAAQ,MAGhD,aAAMlB,EAAQK,QAAQqB,IAAI,YAAad,GAEhCL,WAASgB,EAAY,CAC1Bf,QAAS,CACP,mBAAoBR,EAAQK,QAAQI,WAEvC"}
|
package/dist/preview/route.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validatePreviewUrl as e}from"@sanity/preview-url-secret";import{json as t,redirect as o}from"@shopify/remix-oxygen";const s=async({context:e,request:s})=>"POST"!==s.method?t({message:"Method not allowed"},405):(await e.session.unset("projectId"),o("/",{headers:{"Set-Cookie":await e.session.commit()}})),i=async({context:t,request:s})=>{
|
|
1
|
+
import{validatePreviewUrl as e}from"@sanity/preview-url-secret";import{json as t,redirect as o}from"@shopify/remix-oxygen";const s=async({context:e,request:s})=>"POST"!==s.method?t({message:"Method not allowed"},405):(await e.session.unset("projectId"),o("/",{headers:{"Set-Cookie":await e.session.commit()}})),i=async({context:t,request:s})=>{const{sanity:i}=t,n=i.client.config().projectId;if(!i.preview?.token||!n)throw new Response("Unable to enable preview mode. Please check your preview configuration",{status:500});const r=i.client.withConfig({useCdn:!1,token:i.preview.token}),{isValid:a,redirectTo:c="/"}=await e(r,s.url);if(!a)throw new Response("Invalid secret",{status:401});return await t.session.set("projectId",n),o(c,{headers:{"Set-Cookie":await t.session.commit()}})};export{s as action,i as loader};//# sourceMappingURL=route.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.js","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\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 await context.session.unset('projectId')\n\n return redirect('/', {\n headers: {\n 'Set-Cookie': await context.session.commit(),\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 const {sanity} = context\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview?.token || !projectId) {\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\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 throw new Response('Invalid secret', {status: 401})\n }\n\n await context.session.set('projectId', projectId)\n\n return redirect(redirectTo, {\n headers: {\n 'Set-Cookie': await context.session.commit(),\n },\n })\n}\n"],"names":["validatePreviewUrl","json","redirect","action","async","context","request","method","message","session","unset","headers","commit","loader","
|
|
1
|
+
{"version":3,"file":"route.js","sources":["../../src/preview/route.ts"],"sourcesContent":["import {validatePreviewUrl} from '@sanity/preview-url-secret'\nimport {type ActionFunction, json, type LoaderFunction, redirect} from '@shopify/remix-oxygen'\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 await context.session.unset('projectId')\n\n return redirect('/', {\n headers: {\n 'Set-Cookie': await context.session.commit(),\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 const {sanity} = context\n const projectId = sanity.client.config().projectId\n\n if (!sanity.preview?.token || !projectId) {\n throw new Response('Unable to enable preview mode. Please check your preview configuration', {\n status: 500,\n })\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 throw new Response('Invalid secret', {status: 401})\n }\n\n await context.session.set('projectId', projectId)\n\n return redirect(redirectTo, {\n headers: {\n 'Set-Cookie': await context.session.commit(),\n },\n })\n}\n"],"names":["validatePreviewUrl","json","redirect","action","async","context","request","method","message","session","unset","headers","commit","loader","sanity","projectId","client","config","preview","token","Response","status","clientWithToken","withConfig","useCdn","isValid","redirectTo","url","set"],"mappings":"6BAMaA,MAAA,4CAAAC,cAAAC,MAAA,wBAAA,MAAAC,EAAyBC,OAAQC,UAASC,aAC9B,SAAnBA,EAAQC,OACHN,EAAK,CAACO,QAAS,sBAAuB,YAGzCH,EAAQI,QAAQC,MAAM,aAErBR,EAAS,IAAK,CACnBS,QAAS,CACP,mBAAoBN,EAAQI,QAAQG,aAQ7BC,EAAyBT,OAAQC,UAASC,cAC/C,MAAAQ,OAACA,GAAUT,EACXU,EAAYD,EAAOE,OAAOC,SAASF,UAEzC,IAAKD,EAAOI,SAASC,QAAUJ,EACvB,MAAA,IAAIK,SAAS,yEAA0E,CAC3FC,OAAQ,MAIN,MAAAC,EAAkBR,EAAOE,OAAOO,WAAW,CAC/CC,QAAQ,EACRL,MAAOL,EAAOI,QAAQC,SAGlBM,QAACA,EAASC,WAAAA,EAAa,WAAa1B,EAAmBsB,EAAiBhB,EAAQqB,KAEtF,IAAKF,EACH,MAAM,IAAIL,SAAS,iBAAkB,CAACC,OAAQ,MAGhD,aAAMhB,EAAQI,QAAQmB,IAAI,YAAab,GAEhCb,EAASwB,EAAY,CAC1Bf,QAAS,CACP,mBAAoBN,EAAQI,QAAQG,WAEvC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hydrogen-sanity",
|
|
3
|
-
"version": "4.0
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "Sanity.io toolkit for Hydrogen",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -82,33 +82,33 @@
|
|
|
82
82
|
"watch": "pkg-utils watch --strict"
|
|
83
83
|
},
|
|
84
84
|
"dependencies": {
|
|
85
|
-
"@sanity/client": "^6.
|
|
86
|
-
"@sanity/preview-url-secret": "^1.6.
|
|
87
|
-
"@sanity/react-loader": "^1.
|
|
88
|
-
"@sanity/visual-editing": "^1.
|
|
89
|
-
"groq": "^3.
|
|
85
|
+
"@sanity/client": "^6.21.1",
|
|
86
|
+
"@sanity/preview-url-secret": "^1.6.19",
|
|
87
|
+
"@sanity/react-loader": "^1.10.5",
|
|
88
|
+
"@sanity/visual-editing": "^2.1.7",
|
|
89
|
+
"groq": "^3.52.4"
|
|
90
90
|
},
|
|
91
91
|
"devDependencies": {
|
|
92
|
-
"@sanity/pkg-utils": "^6.8
|
|
93
|
-
"@sanity/plugin-kit": "^4.0.
|
|
94
|
-
"@sanity/semantic-release-preset": "^4.1.
|
|
95
|
-
"@shopify/hydrogen": "~2024.
|
|
96
|
-
"@shopify/remix-oxygen": "^2.0.
|
|
97
|
-
"@types/react": "^18.3.
|
|
98
|
-
"@typescript-eslint/eslint-plugin": "^7.
|
|
99
|
-
"@typescript-eslint/parser": "^7.
|
|
92
|
+
"@sanity/pkg-utils": "^6.10.8",
|
|
93
|
+
"@sanity/plugin-kit": "^4.0.18",
|
|
94
|
+
"@sanity/semantic-release-preset": "^4.1.8",
|
|
95
|
+
"@shopify/hydrogen": "~2024.7.2",
|
|
96
|
+
"@shopify/remix-oxygen": "^2.0.5",
|
|
97
|
+
"@types/react": "^18.3.3",
|
|
98
|
+
"@typescript-eslint/eslint-plugin": "^7.16.1",
|
|
99
|
+
"@typescript-eslint/parser": "^7.16.1",
|
|
100
100
|
"eslint": "^8.57.0",
|
|
101
101
|
"eslint-config-prettier": "^9.1.0",
|
|
102
102
|
"eslint-config-sanity": "^7.1.2",
|
|
103
|
-
"eslint-plugin-prettier": "^5.1
|
|
104
|
-
"eslint-plugin-react": "^7.
|
|
103
|
+
"eslint-plugin-prettier": "^5.2.1",
|
|
104
|
+
"eslint-plugin-react": "^7.35.0",
|
|
105
105
|
"eslint-plugin-react-hooks": "^4.6.2",
|
|
106
|
-
"eslint-plugin-simple-import-sort": "^12.1.
|
|
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
|
-
"typescript": "^5.4
|
|
111
|
-
"vitest": "^
|
|
110
|
+
"typescript": "^5.5.4",
|
|
111
|
+
"vitest": "^2.0.5",
|
|
112
112
|
"vitest-github-actions-reporter": "^0.11.1"
|
|
113
113
|
},
|
|
114
114
|
"peerDependencies": {
|
package/src/loader.ts
CHANGED
|
@@ -65,7 +65,7 @@ type HydrogenResponseQueryOptions = Omit<ResponseQueryOptions, 'next' | 'cache'>
|
|
|
65
65
|
|
|
66
66
|
type LoadQueryOptions = Pick<
|
|
67
67
|
HydrogenResponseQueryOptions,
|
|
68
|
-
'perspective' | 'hydrogen' | 'useCdn' | 'stega'
|
|
68
|
+
'perspective' | 'hydrogen' | 'useCdn' | 'stega' | 'headers' | 'tag'
|
|
69
69
|
>
|
|
70
70
|
|
|
71
71
|
export type SanityLoader = {
|
|
@@ -107,7 +107,7 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
|
|
|
107
107
|
|
|
108
108
|
/**
|
|
109
109
|
* TODO: should this default to the latest API version?
|
|
110
|
-
* Or at least warn if a version that doesn't support
|
|
110
|
+
* Or at least warn if a version that doesn't support perspectives is used?
|
|
111
111
|
*/
|
|
112
112
|
if (client.config().apiVersion === '1') {
|
|
113
113
|
client = client.withConfig({apiVersion: 'v2022-03-07'})
|
|
@@ -122,7 +122,11 @@ export function createSanityLoader(options: CreateSanityLoaderOptions): SanityLo
|
|
|
122
122
|
useCdn: false,
|
|
123
123
|
token: preview.token,
|
|
124
124
|
perspective: 'previewDrafts' as const,
|
|
125
|
-
stega: {
|
|
125
|
+
stega: {
|
|
126
|
+
...client.config().stega,
|
|
127
|
+
enabled: true,
|
|
128
|
+
studioUrl: preview.studioUrl,
|
|
129
|
+
},
|
|
126
130
|
})
|
|
127
131
|
|
|
128
132
|
queryStore.setServerClient(previewClient)
|