@shopify/hydrogen 2026.10.2 → 2026.10.3
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 +3 -5
- package/dist/cli/index.mjs +2 -2
- package/dist/client/client.mjs +44 -9
- package/dist/client/client.mjs.map +1 -1
- package/dist/client/i18n-variables.d.mts +1 -1
- package/dist/client/i18n-variables.mjs +14 -6
- package/dist/client/i18n-variables.mjs.map +1 -1
- package/dist/client/types.d.mts +12 -6
- package/dist/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/core/cart/cart.mjs +1 -1
- package/dist/core/cart/cookie.mjs +6 -1
- package/dist/core/cart/cookie.mjs.map +1 -1
- package/dist/core/cart/form.d.mts +17 -5
- package/dist/core/cart/form.mjs +5 -0
- package/dist/core/cart/form.mjs.map +1 -1
- package/dist/core/cart/index.d.mts +1 -1
- package/dist/core/collection/url.mjs +8 -1
- package/dist/core/collection/url.mjs.map +1 -1
- package/dist/core/constants.mjs +2 -1
- package/dist/core/constants.mjs.map +1 -1
- package/dist/core/csp/index.d.mts +56 -0
- package/dist/core/csp/index.mjs +117 -0
- package/dist/core/csp/index.mjs.map +1 -0
- package/dist/core/csp/types.d.mts +52 -0
- package/dist/core/headers.mjs +2 -2
- package/dist/core/headers.mjs.map +1 -1
- package/dist/core/i18n/define.d.mts +54 -0
- package/dist/core/i18n/define.mjs +135 -0
- package/dist/core/i18n/define.mjs.map +1 -0
- package/dist/core/i18n/errors.d.mts +18 -0
- package/dist/core/i18n/errors.mjs +24 -0
- package/dist/core/i18n/errors.mjs.map +1 -0
- package/dist/core/i18n/href.d.mts +28 -0
- package/dist/core/i18n/href.mjs +45 -0
- package/dist/core/i18n/href.mjs.map +1 -0
- package/dist/core/i18n/locale.d.mts +21 -0
- package/dist/core/i18n/locale.mjs +36 -0
- package/dist/core/i18n/locale.mjs.map +1 -0
- package/dist/core/i18n/match.d.mts +37 -0
- package/dist/core/i18n/match.mjs +82 -0
- package/dist/core/i18n/match.mjs.map +1 -0
- package/dist/core/i18n/types.d.mts +80 -0
- package/dist/core/index.d.mts +14 -5
- package/dist/core/index.mjs +9 -2
- package/dist/core/predictive-search/index.d.mts +2 -2
- package/dist/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/core/predictive-search/url.d.mts +2 -2
- package/dist/core/predictive-search/url.mjs.map +1 -1
- package/dist/core/product/accept-variant-id.mjs +1 -1
- package/dist/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/core/request-context.d.mts +61 -35
- package/dist/core/request-context.mjs +11 -7
- package/dist/core/request-context.mjs.map +1 -1
- package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/core/request-routing/registered-routes.d.mts +10 -3
- package/dist/core/request-routing/registered-routes.mjs +13 -3
- package/dist/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/core/request-routing/route-types.d.mts +2 -2
- package/dist/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/core/shopify-scripts/constants.mjs +3 -1
- package/dist/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/core/shopify-scripts/global.mjs +13 -11
- package/dist/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/core/shopify-scripts/index.d.mts +1 -0
- package/dist/core/shopify-scripts/index.mjs +12 -9
- package/dist/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/core/shopify-scripts/types.d.mts +4 -2
- package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/core/standard-routes/build.d.mts +7 -2
- package/dist/core/standard-routes/build.mjs +10 -3
- package/dist/core/standard-routes/build.mjs.map +1 -1
- package/dist/core/standard-routes/match.mjs +11 -1
- package/dist/core/standard-routes/match.mjs.map +1 -1
- package/dist/core/standard-routes/path.mjs +14 -3
- package/dist/core/standard-routes/path.mjs.map +1 -1
- package/dist/core/standard-routes/types.d.mts +6 -1
- package/dist/core/url.mjs +5 -3
- package/dist/core/url.mjs.map +1 -1
- package/dist/customer-account/client.d.mts +14 -10
- package/dist/customer-account/client.mjs +4 -5
- package/dist/customer-account/client.mjs.map +1 -1
- package/dist/customer-account/graphql.d.mts +7 -1
- package/dist/customer-account/graphql.mjs +6 -7
- package/dist/customer-account/graphql.mjs.map +1 -1
- package/dist/customer-account/session.mjs +3 -4
- package/dist/customer-account/session.mjs.map +1 -1
- package/dist/development/client/client.mjs +44 -9
- package/dist/development/client/client.mjs.map +1 -1
- package/dist/development/client/i18n-variables.d.mts +1 -1
- package/dist/development/client/i18n-variables.mjs +13 -5
- package/dist/development/client/i18n-variables.mjs.map +1 -1
- package/dist/development/client/types.d.mts +12 -6
- package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/development/core/cart/cart.mjs +1 -1
- package/dist/development/core/cart/cookie.mjs +6 -1
- package/dist/development/core/cart/cookie.mjs.map +1 -1
- package/dist/development/core/cart/form.d.mts +17 -5
- package/dist/development/core/cart/form.mjs +5 -0
- package/dist/development/core/cart/form.mjs.map +1 -1
- package/dist/development/core/cart/index.d.mts +1 -1
- package/dist/development/core/cart/queries.d.mts +57 -57
- package/dist/development/core/collection/url.mjs +8 -1
- package/dist/development/core/collection/url.mjs.map +1 -1
- package/dist/development/core/constants.mjs +2 -1
- package/dist/development/core/constants.mjs.map +1 -1
- package/dist/development/core/csp/index.d.mts +56 -0
- package/dist/development/core/csp/index.mjs +128 -0
- package/dist/development/core/csp/index.mjs.map +1 -0
- package/dist/development/core/csp/types.d.mts +52 -0
- package/dist/development/core/development.d.mts +14 -5
- package/dist/development/core/development.mjs +9 -2
- package/dist/development/core/headers.mjs +2 -2
- package/dist/development/core/headers.mjs.map +1 -1
- package/dist/development/core/i18n/define.d.mts +54 -0
- package/dist/development/core/i18n/define.mjs +135 -0
- package/dist/development/core/i18n/define.mjs.map +1 -0
- package/dist/development/core/i18n/errors.d.mts +18 -0
- package/dist/development/core/i18n/errors.mjs +24 -0
- package/dist/development/core/i18n/errors.mjs.map +1 -0
- package/dist/development/core/i18n/href.d.mts +28 -0
- package/dist/development/core/i18n/href.mjs +45 -0
- package/dist/development/core/i18n/href.mjs.map +1 -0
- package/dist/development/core/i18n/locale.d.mts +21 -0
- package/dist/development/core/i18n/locale.mjs +36 -0
- package/dist/development/core/i18n/locale.mjs.map +1 -0
- package/dist/development/core/i18n/match.d.mts +37 -0
- package/dist/development/core/i18n/match.mjs +82 -0
- package/dist/development/core/i18n/match.mjs.map +1 -0
- package/dist/development/core/i18n/types.d.mts +80 -0
- package/dist/development/core/index.d.mts +13 -4
- package/dist/development/core/predictive-search/index.d.mts +2 -2
- package/dist/development/core/predictive-search/queries.d.mts +2 -2
- package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/development/core/predictive-search/url.d.mts +2 -2
- package/dist/development/core/predictive-search/url.mjs.map +1 -1
- package/dist/development/core/product/accept-variant-id.mjs +1 -1
- package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/development/core/request-context.d.mts +61 -35
- package/dist/development/core/request-context.mjs +11 -7
- package/dist/development/core/request-context.mjs.map +1 -1
- package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/development/core/request-routing/registered-routes.d.mts +10 -3
- package/dist/development/core/request-routing/registered-routes.mjs +13 -3
- package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/route-types.d.mts +2 -2
- package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/constants.mjs +3 -1
- package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/global.mjs +13 -11
- package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/development/core/shopify-scripts/index.d.mts +1 -0
- package/dist/development/core/shopify-scripts/index.mjs +12 -9
- package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/types.d.mts +4 -2
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/development/core/standard-routes/build.d.mts +7 -2
- package/dist/development/core/standard-routes/build.mjs +10 -3
- package/dist/development/core/standard-routes/build.mjs.map +1 -1
- package/dist/development/core/standard-routes/match.mjs +11 -1
- package/dist/development/core/standard-routes/match.mjs.map +1 -1
- package/dist/development/core/standard-routes/path.mjs +14 -3
- package/dist/development/core/standard-routes/path.mjs.map +1 -1
- package/dist/development/core/standard-routes/types.d.mts +6 -1
- package/dist/development/core/url.mjs +5 -3
- package/dist/development/core/url.mjs.map +1 -1
- package/dist/development/customer-account/session.mjs.map +1 -1
- package/dist/development/globals.d.mts +8 -4
- package/dist/development/graphql/type-resolver.d.mts +13 -1
- package/dist/development/react/index.d.mts +2 -2
- package/dist/globals.d.mts +8 -4
- package/dist/graphql/type-resolver.d.mts +13 -1
- package/dist/react/index.d.mts +2 -2
- package/dist/vite/index.mjs +1 -1
- package/dist/vue/shopify-scripts.d.mts +1 -1
- package/package.json +13 -3
- package/skills/hydrogen-analytics/SKILL.md +2 -2
- package/skills/hydrogen-analytics/references/react.md +2 -2
- package/skills/hydrogen-markets/SKILL.md +127 -93
- package/skills/hydrogen-markets/references/nextjs.md +77 -87
- package/skills/hydrogen-oxygen/references/react-router.md +1 -2
- package/skills/hydrogen-predictive-search/SKILL.md +18 -1
- package/skills/hydrogen-request-handlers/SKILL.md +23 -5
- package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
- package/skills/hydrogen-request-handlers/references/frameworks.md +8 -6
- package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
- package/skills/hydrogen-request-handlers/references/nuxt.md +7 -5
- package/skills/hydrogen-robots-txt/SKILL.md +87 -0
- package/skills/hydrogen-routing/SKILL.md +36 -14
- package/skills/hydrogen-setup/SKILL.md +2 -2
- package/skills/hydrogen-setup/references/analytics.md +5 -5
- package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
- package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
- package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
- package/skills/hydrogen-smoke-test/SKILL.md +9 -2
- package/skills/hydrogen-storefront-client/SKILL.md +27 -9
- package/skills/hydrogen-storefront-client/references/astro.md +8 -3
- package/skills/hydrogen-storefront-client/references/caching.md +2 -0
- package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
- package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
- package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
- package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
- package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
- package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
- package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
- package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
|
@@ -1,14 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { CountryCode as CountryCode$1, LanguageCode as LanguageCode$1 } from "../graphql/generated/storefront-api-types.mjs";
|
|
1
|
+
import { ShopifyCountryCode, ShopifyI18n, ShopifyLanguageCode, ShopifyLocale, ShopifyMatchedLocale } from "./i18n/types.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/core/request-context.d.ts
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
/** A country code that both the Storefront API and the Customer Account API accept. */
|
|
10
|
-
type ShopifyCountryCode = Extract<CountryCode$1, CountryCode>;
|
|
11
|
-
/** The language, country, and optional localized path prefix for a request. */
|
|
4
|
+
/**
|
|
5
|
+
* Deprecated: a fixed request locale with an optional path prefix. Removed in the next major release.
|
|
6
|
+
* @deprecated Pass a definition from `defineShopifyI18n` to `createShopifyRequestContext` instead. Use `ShopifyLocale` for `{language, country}` and `ShopifyMatchedLocale` for the resolved locale. Removed in the next major release.
|
|
7
|
+
*/
|
|
12
8
|
type I18nConfig = {
|
|
13
9
|
/** The request's language. */language: ShopifyLanguageCode; /** The request's country. */
|
|
14
10
|
country: ShopifyCountryCode;
|
|
@@ -17,24 +13,40 @@ type I18nConfig = {
|
|
|
17
13
|
*/
|
|
18
14
|
pathPrefix?: string;
|
|
19
15
|
};
|
|
20
|
-
|
|
21
|
-
type NormalizedI18nConfig<I18n extends I18nConfig = I18nConfig> = Omit<I18n, "pathPrefix"> & {
|
|
16
|
+
type NormalizedI18nConfig<TConfig extends I18nConfig> = Omit<TConfig, "pathPrefix"> & {
|
|
22
17
|
pathPrefix: string;
|
|
23
18
|
};
|
|
24
|
-
/** The
|
|
25
|
-
type
|
|
19
|
+
/** The locale a request context resolves: matched from a definition, or the legacy fixed locale. */
|
|
20
|
+
type RequestLocale<TI18n extends ShopifyI18n | I18nConfig> = TI18n extends ShopifyI18n ? ShopifyMatchedLocale<TI18n> : TI18n extends I18nConfig ? NormalizedI18nConfig<TI18n> : never;
|
|
21
|
+
/** The incoming request's headers, plus its method, abort signal, and URL when the framework provides them. */
|
|
22
|
+
type StorefrontRequest = Pick<Request, "headers"> & Partial<Pick<Request, "method" | "signal" | "url">>;
|
|
23
|
+
/** The incoming request and the storefront's i18n definition. */
|
|
24
|
+
type ShopifyRequestContextInputBase<TI18n extends ShopifyI18n = ShopifyI18n> = {
|
|
26
25
|
/**
|
|
27
26
|
* The incoming request from your framework. When the framework exposes no request, such as during prerendering, pass `{ headers: new Headers() }`.
|
|
28
27
|
*/
|
|
29
|
-
request: StorefrontRequest; /** The
|
|
30
|
-
i18n:
|
|
28
|
+
request: StorefrontRequest; /** The storefront's i18n definition from `defineShopifyI18n`. Hydrogen matches the request's locale against it. */
|
|
29
|
+
i18n: TI18n;
|
|
30
|
+
/**
|
|
31
|
+
* The locale to use instead of matching the request URL. The locale must be one of the definition's supported locales.
|
|
32
|
+
* Pass it when the request has no meaningful URL, such as during static rendering.
|
|
33
|
+
*/
|
|
34
|
+
locale?: ShopifyLocale;
|
|
31
35
|
};
|
|
32
|
-
type ShopifyRequestContextInput<
|
|
36
|
+
type ShopifyRequestContextInput<TI18n extends ShopifyI18n = ShopifyI18n> = ShopifyRequestContextInputBase<TI18n> & {
|
|
33
37
|
buyerIp?: never;
|
|
34
38
|
};
|
|
35
|
-
type ShopifyRequestContextWithBuyerIpInput<
|
|
39
|
+
type ShopifyRequestContextWithBuyerIpInput<TI18n extends ShopifyI18n = ShopifyI18n> = ShopifyRequestContextInputBase<TI18n> & {
|
|
36
40
|
buyerIp: string;
|
|
37
41
|
};
|
|
42
|
+
/**
|
|
43
|
+
* Deprecated: the request and a fixed locale, used for every request with no URL matching. Pass a definition from `defineShopifyI18n` as `i18n` instead. Removed in the next major release.
|
|
44
|
+
*/
|
|
45
|
+
type LegacyShopifyRequestContextInput<TConfig extends I18nConfig> = {
|
|
46
|
+
request: StorefrontRequest; /** Deprecated: the fixed `{language, country, pathPrefix}` for every request. */
|
|
47
|
+
i18n: TConfig;
|
|
48
|
+
locale?: never;
|
|
49
|
+
};
|
|
38
50
|
/** The fields and methods on every request context. */
|
|
39
51
|
type ShopifyRequestContextBase = {
|
|
40
52
|
/**
|
|
@@ -90,47 +102,61 @@ type ShopifyRequestContextBase = {
|
|
|
90
102
|
* @internal
|
|
91
103
|
*/
|
|
92
104
|
consumeStorefrontResponseHeaders(headers: Headers): void;
|
|
93
|
-
/**
|
|
94
|
-
* Marks the final response as private and uncacheable because the response holds customer data.
|
|
95
|
-
* The Customer Account API client and the customer session call the method for you.
|
|
96
|
-
* @internal
|
|
97
|
-
*/
|
|
98
|
-
markResponseAsPersonalized(reason: string): void;
|
|
99
105
|
/**
|
|
100
106
|
* Lets the final response set Shopify cookies before the customer has a Shopify session, and
|
|
101
107
|
* marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.
|
|
102
108
|
* @internal
|
|
103
109
|
*/
|
|
104
|
-
markResponseAsSessionEstablishing(reason: string): void; /**
|
|
105
|
-
i18n: NormalizedI18nConfig; /** Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin. */
|
|
110
|
+
markResponseAsSessionEstablishing(reason: string): void; /** Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin. */
|
|
106
111
|
getForwardedRequestHeaders(): Headers;
|
|
112
|
+
/**
|
|
113
|
+
* Marks the final response as private and uncacheable because the response holds customer data, such as a server-rendered cart. `applyResponseHeaders()` then sets `Cache-Control: private, no-store, max-age=0, must-revalidate` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. Call the method before `applyResponseHeaders()`, and only on requests whose response holds customer data, so other responses stay cacheable. Pass a short `reason` that names the customer data. The Customer Account API client and the customer session call the method for you.
|
|
114
|
+
*/
|
|
115
|
+
markResponseAsPersonalized(reason: string): void;
|
|
107
116
|
/**
|
|
108
117
|
* Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers.
|
|
109
118
|
*
|
|
110
|
-
* Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses
|
|
119
|
+
* Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses marked with `markResponseAsPersonalized()` private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`.
|
|
111
120
|
*/
|
|
112
121
|
applyResponseHeaders(headers: Headers): void;
|
|
113
122
|
};
|
|
114
123
|
/** The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request. */
|
|
115
|
-
type ShopifyRequestContext<
|
|
116
|
-
|
|
124
|
+
type ShopifyRequestContext<TI18n extends ShopifyI18n | I18nConfig = ShopifyI18n> = ShopifyRequestContextBase & {
|
|
125
|
+
/** The locale resolved for this request, with the path prefix it is served under. */locale: RequestLocale<TI18n>;
|
|
126
|
+
/**
|
|
127
|
+
* The locale resolved for this request.
|
|
128
|
+
* @deprecated Use `locale` instead. Removed in the next major release.
|
|
129
|
+
*/
|
|
130
|
+
i18n: RequestLocale<TI18n>;
|
|
117
131
|
};
|
|
118
132
|
/** A request context that includes the customer's IP address. Private Storefront API clients require this context. */
|
|
119
|
-
type ShopifyRequestContextWithBuyerIp<
|
|
133
|
+
type ShopifyRequestContextWithBuyerIp<TI18n extends ShopifyI18n | I18nConfig = ShopifyI18n> = ShopifyRequestContext<TI18n> & {
|
|
120
134
|
readonly buyerIp: string;
|
|
121
135
|
};
|
|
136
|
+
/**
|
|
137
|
+
* @deprecated Pass a definition from `defineShopifyI18n` as `i18n` instead of a fixed `{language, country, pathPrefix}`. Removed in the next major release.
|
|
138
|
+
*/
|
|
139
|
+
declare function createShopifyRequestContext<const TConfig extends I18nConfig>(input: LegacyShopifyRequestContextInput<TConfig> & {
|
|
140
|
+
buyerIp: string;
|
|
141
|
+
}): ShopifyRequestContextWithBuyerIp<TConfig>;
|
|
142
|
+
/**
|
|
143
|
+
* @deprecated Pass a definition from `defineShopifyI18n` as `i18n` instead of a fixed `{language, country, pathPrefix}`. Removed in the next major release.
|
|
144
|
+
*/
|
|
145
|
+
declare function createShopifyRequestContext<const TConfig extends I18nConfig>(input: LegacyShopifyRequestContextInput<TConfig> & {
|
|
146
|
+
buyerIp?: never;
|
|
147
|
+
}): ShopifyRequestContext<TConfig>;
|
|
122
148
|
/**
|
|
123
149
|
* Creates the context for one incoming request. Pass the same context to the Storefront API
|
|
124
|
-
* client, the Customer Account API client, and `handleShopifyRoutes`. The context
|
|
125
|
-
*
|
|
126
|
-
* headers to your response.
|
|
150
|
+
* client, the Customer Account API client, and `handleShopifyRoutes`. The context resolves the
|
|
151
|
+
* request's locale from your i18n definition, forwards the customer's cookies, locale, and privacy
|
|
152
|
+
* signal to Shopify, and adds Shopify's cookies and cache headers to your response.
|
|
127
153
|
*
|
|
128
|
-
* Call `applyResponseHeaders()` on each response that your app builds. Pass `buyerIp` with the customer's trusted IP address when you use a private Storefront API client. The function throws when `i18n`
|
|
154
|
+
* Call `applyResponseHeaders()` on each response that your app builds. Pass `buyerIp` with the customer's trusted IP address when you use a private Storefront API client. The function throws when `i18n` doesn't come from `defineShopifyI18n`, when `locale` isn't one of the definition's supported locales, and when `buyerIp` is an empty string.
|
|
129
155
|
*
|
|
130
156
|
* @publicDocs
|
|
131
157
|
*/
|
|
132
|
-
declare function createShopifyRequestContext<const
|
|
133
|
-
declare function createShopifyRequestContext<const
|
|
158
|
+
declare function createShopifyRequestContext<const TI18n extends ShopifyI18n>(input: ShopifyRequestContextWithBuyerIpInput<TI18n>): ShopifyRequestContextWithBuyerIp<TI18n>;
|
|
159
|
+
declare function createShopifyRequestContext<const TI18n extends ShopifyI18n>(input: ShopifyRequestContextInput<TI18n>): ShopifyRequestContext<TI18n>;
|
|
134
160
|
//#endregion
|
|
135
161
|
export { I18nConfig, ShopifyRequestContext, ShopifyRequestContextWithBuyerIp, createShopifyRequestContext };
|
|
136
162
|
//# sourceMappingURL=request-context.d.mts.map
|
|
@@ -1,28 +1,29 @@
|
|
|
1
1
|
import { normalizePathPrefix } from "./standard-routes/path.mjs";
|
|
2
|
+
import { matchLocale, resolveSupportedLocale } from "./i18n/match.mjs";
|
|
2
3
|
import { STOREFRONT_API_VERSION } from "./constants.mjs";
|
|
3
4
|
import { CONSENT_MANAGEMENT_HEADER, HYDROGEN_VERSION_HEADER, REQUEST_GROUP_ID_HEADER, SDK_VARIANT_HEADER, SDK_VARIANT_SOURCE_HEADER, SDK_VERSION_HEADER, SEC_GPC_HEADER, SHOPIFY_STOREFRONT_ORIGIN_HEADER, STOREFRONT_URL_HEADER, applyPrivateResponseCacheHeaders } from "./headers.mjs";
|
|
4
5
|
|
|
5
6
|
//#region src/core/request-context.ts
|
|
6
7
|
const SHOPIFY_ESSENTIAL_COOKIE = "_shopify_essential";
|
|
7
8
|
/**
|
|
8
|
-
* @param input The incoming request,
|
|
9
|
+
* @param input The incoming request, the storefront's i18n definition, and the customer's IP address for private Storefront API clients.
|
|
9
10
|
* @returns The context to pass to Hydrogen's API clients and route handlers for this request.
|
|
10
11
|
*/
|
|
11
12
|
function createShopifyRequestContext(input) {
|
|
12
13
|
const { request } = input;
|
|
13
|
-
if (!input.i18n?.country || !input.i18n?.language) throw new Error("i18n with country and language is required for Shopify request contexts.");
|
|
14
14
|
if (input.buyerIp !== void 0 && !input.buyerIp) throw new Error("buyerIp must be non-empty when provided");
|
|
15
15
|
const requestMethod = request.method?.toUpperCase();
|
|
16
|
-
const i18n = normalizeI18n(input.i18n);
|
|
17
16
|
const cookieHeader = request.headers.get("cookie") || void 0;
|
|
18
17
|
const hasEssentialCookie = parseCookieHeader(cookieHeader).has(SHOPIFY_ESSENTIAL_COOKIE);
|
|
19
18
|
const isConsentManagementRequest = request.headers.get(CONSENT_MANAGEMENT_HEADER) === "1";
|
|
20
19
|
const url = request.url ?? request.headers.get("x-storefront-url") ?? void 0;
|
|
21
20
|
const storefrontOrigin = getUrlOrigin(url);
|
|
21
|
+
const locale = resolveRequestLocale(input, url);
|
|
22
22
|
const context = {
|
|
23
23
|
...cookieHeader && { cookie: cookieHeader },
|
|
24
24
|
globalPrivacyControl: request.headers.get("Sec-GPC") ?? void 0,
|
|
25
|
-
|
|
25
|
+
locale,
|
|
26
|
+
i18n: locale,
|
|
26
27
|
...url && { url },
|
|
27
28
|
...storefrontOrigin && { storefrontOrigin },
|
|
28
29
|
...input.buyerIp && { buyerIp: input.buyerIp },
|
|
@@ -74,17 +75,20 @@ function createShopifyRequestContext(input) {
|
|
|
74
75
|
}
|
|
75
76
|
};
|
|
76
77
|
}
|
|
77
|
-
function
|
|
78
|
-
|
|
78
|
+
function resolveRequestLocale(input, url) {
|
|
79
|
+
const { i18n } = input;
|
|
80
|
+
if (i18n && "defaultLocale" in i18n && i18n.defaultLocale?.country && i18n.defaultLocale.language) return input.locale ? resolveSupportedLocale(input.locale, i18n) : matchLocale(url, i18n);
|
|
81
|
+
if (i18n && "country" in i18n && i18n.country && i18n.language) return {
|
|
79
82
|
...i18n,
|
|
80
83
|
pathPrefix: normalizePathPrefix(i18n.pathPrefix)
|
|
81
84
|
};
|
|
85
|
+
throw new Error("i18n from defineShopifyI18n (with a defaultLocale) is required for Shopify request contexts.");
|
|
82
86
|
}
|
|
83
87
|
function applyStorefrontRequestHeaders(context, headers) {
|
|
84
88
|
headers.set(SDK_VARIANT_HEADER, "hydrogen");
|
|
85
89
|
headers.set(SDK_VARIANT_SOURCE_HEADER, "kit");
|
|
86
90
|
headers.set(SDK_VERSION_HEADER, STOREFRONT_API_VERSION);
|
|
87
|
-
headers.set(HYDROGEN_VERSION_HEADER, "2026.10.
|
|
91
|
+
headers.set(HYDROGEN_VERSION_HEADER, "2026.10.3");
|
|
88
92
|
headers.set(REQUEST_GROUP_ID_HEADER, context.requestGroupId);
|
|
89
93
|
if (context.cookie) headers.set("cookie", context.cookie);
|
|
90
94
|
else headers.delete("cookie");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-context.mjs","names":[],"sources":["../../../src/core/request-context.ts"],"sourcesContent":["import type {\n CountryCode as CustomerAccountCountryCode,\n LanguageCode as CustomerAccountLanguageCode,\n} from \"../graphql/generated/customer-account-api-types\";\nimport type {\n CountryCode as StorefrontCountryCode,\n LanguageCode as StorefrontLanguageCode,\n} from \"../graphql/generated/storefront-api-types\";\nimport { STOREFRONT_API_VERSION } from \"./constants\";\nimport {\n applyPrivateResponseCacheHeaders,\n CONSENT_MANAGEMENT_HEADER,\n HYDROGEN_VERSION_HEADER,\n REQUEST_GROUP_ID_HEADER,\n SDK_VARIANT_HEADER,\n SDK_VARIANT_SOURCE_HEADER,\n SDK_VERSION_HEADER,\n SEC_GPC_HEADER,\n SHOPIFY_STOREFRONT_ORIGIN_HEADER,\n STOREFRONT_URL_HEADER,\n} from \"./headers\";\nimport { normalizePathPrefix } from \"./standard-routes/path\";\n\nconst SHOPIFY_ESSENTIAL_COOKIE = \"_shopify_essential\";\n\n/** The incoming request's headers, plus its method, abort signal, and URL when the framework provides them. */\ntype StorefrontRequest = Pick<Request, \"headers\"> &\n Partial<Pick<Request, \"method\" | \"signal\" | \"url\">>;\n\n/** A language code that both the Storefront API and the Customer Account API accept. */\nexport type ShopifyLanguageCode = Extract<StorefrontLanguageCode, CustomerAccountLanguageCode>;\n/** A country code that both the Storefront API and the Customer Account API accept. */\nexport type ShopifyCountryCode = Extract<StorefrontCountryCode, CustomerAccountCountryCode>;\n\n/** The language, country, and optional localized path prefix for a request. */\nexport type I18nConfig = {\n /** The request's language. */\n language: ShopifyLanguageCode;\n /** The request's country. */\n country: ShopifyCountryCode;\n /**\n * The URL prefix for localized routes, such as `/es-es`. Hydrogen adds the prefix to standard route redirects and product variant URLs.\n */\n pathPrefix?: string;\n};\n\n/** The request's locale, with a path prefix that starts with `/` or is an empty string. */\ntype NormalizedI18nConfig<I18n extends I18nConfig = I18nConfig> = Omit<I18n, \"pathPrefix\"> & {\n pathPrefix: string;\n};\n\n/** The incoming request and its locale. */\ntype ShopifyRequestContextInputBase<I18n extends I18nConfig = I18nConfig> = {\n /**\n * The incoming request from your framework. When the framework exposes no request, such as during prerendering, pass `{ headers: new Headers() }`.\n */\n request: StorefrontRequest;\n /** The request's language, country, and optional localized path prefix. */\n i18n: I18n;\n};\n\ntype ShopifyRequestContextInput<I18n extends I18nConfig = I18nConfig> =\n ShopifyRequestContextInputBase<I18n> & { buyerIp?: never };\n\ntype ShopifyRequestContextWithBuyerIpInput<I18n extends I18nConfig = I18nConfig> =\n ShopifyRequestContextInputBase<I18n> & { buyerIp: string };\n\n/** The fields and methods on every request context. */\ntype ShopifyRequestContextBase = {\n // -- Private fields --\n /**\n * A type-only marker. Create request contexts only with `createShopifyRequestContext`.\n * @internal\n */\n readonly __hydrogenShopifyRequestContextBrand: never;\n /**\n * The incoming request's `Cookie` header. Hydrogen forwards the header to the Storefront API.\n * @internal\n */\n cookie?: string;\n /**\n * The customer's trusted IP address. Private Storefront API clients require it.\n * @internal\n */\n readonly buyerIp?: string;\n /**\n * The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one.\n * @internal\n */\n requestGroupId: string;\n /**\n * The incoming request's abort signal. Hydrogen's API clients stop their requests when the signal aborts.\n * @internal\n */\n signal?: AbortSignal;\n /**\n * The incoming request's URL.\n * @internal\n */\n url?: string;\n /**\n * The origin of the incoming request's URL. Hydrogen forwards the origin to the Storefront API.\n * @internal\n */\n storefrontOrigin?: string;\n /**\n * Adds the Hydrogen SDK headers and the customer's cookie, privacy, and origin headers to a\n * Storefront API request. The Storefront API client and the API proxies call the method for you.\n * @internal\n */\n applyStorefrontRequestHeaders(headers: Headers): void;\n /**\n * Saves the cookies from the first Storefront API response that sets cookies. The Storefront API\n * client calls the method for you, and `applyResponseHeaders()` can add the cookies to your response.\n * @internal\n */\n captureSubrequestHeaders(headers: Headers): void;\n /**\n * Saves the cookies from a proxied Storefront API response and removes the `set-cookie` header\n * from that response. The API proxies in `handleShopifyRoutes` call the method for you.\n * @internal\n */\n consumeStorefrontResponseHeaders(headers: Headers): void;\n /**\n * Marks the final response as private and uncacheable because the response holds customer data.\n * The Customer Account API client and the customer session call the method for you.\n * @internal\n */\n markResponseAsPersonalized(reason: string): void;\n /**\n * Lets the final response set Shopify cookies before the customer has a Shopify session, and\n * marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.\n * @internal\n */\n markResponseAsSessionEstablishing(reason: string): void;\n\n // -- Public fields --\n /** The request's language, country, and path prefix. The path prefix starts with `/` and has no trailing slash, or is an empty string when you don't set one. */\n i18n: NormalizedI18nConfig;\n /** Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin. */\n getForwardedRequestHeaders(): Headers;\n /**\n * Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers.\n *\n * Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses that hold customer data private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`.\n */\n applyResponseHeaders(headers: Headers): void;\n};\n\n/** The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request. */\nexport type ShopifyRequestContext<I18n extends I18nConfig = I18nConfig> =\n ShopifyRequestContextBase & {\n i18n: NormalizedI18nConfig<I18n>;\n };\n\n/** A request context that includes the customer's IP address. Private Storefront API clients require this context. */\nexport type ShopifyRequestContextWithBuyerIp<I18n extends I18nConfig = I18nConfig> =\n ShopifyRequestContext<I18n> & { readonly buyerIp: string };\n\n/** The values that the request context reads from the incoming request. */\ntype Context<I18n extends I18nConfig = I18nConfig> = {\n /** The incoming request's `Cookie` header. */\n cookie?: string;\n /** The incoming request's `Sec-GPC` header value, which carries the customer's Global Privacy Control signal. */\n globalPrivacyControl?: string;\n /** The customer's trusted IP address. */\n buyerIp?: string;\n /** The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one. */\n requestGroupId: string;\n /** The incoming request's abort signal. */\n signal?: AbortSignal;\n /** The incoming request's URL. */\n url?: string;\n /** The origin of the incoming request's URL. */\n storefrontOrigin?: string;\n /** The request's language, country, and path prefix. */\n i18n: NormalizedI18nConfig<I18n>;\n /** Whether the incoming request asks for an HTML document. */\n documentRequest?: boolean;\n};\n\n/**\n * Creates the context for one incoming request. Pass the same context to the Storefront API\n * client, the Customer Account API client, and `handleShopifyRoutes`. The context forwards the\n * customer's cookies, locale, and privacy signal to Shopify, and adds Shopify's cookies and cache\n * headers to your response.\n *\n * Call `applyResponseHeaders()` on each response that your app builds. Pass `buyerIp` with the customer's trusted IP address when you use a private Storefront API client. The function throws when `i18n` lacks a country or language, and when `buyerIp` is an empty string.\n *\n * @publicDocs\n */\nexport function createShopifyRequestContext<const I18n extends I18nConfig>(\n input: ShopifyRequestContextWithBuyerIpInput<I18n>,\n): ShopifyRequestContextWithBuyerIp<I18n>;\nexport function createShopifyRequestContext<const I18n extends I18nConfig>(\n input: ShopifyRequestContextInput<I18n>,\n): ShopifyRequestContext<I18n>;\n/**\n * @param input The incoming request, its locale, and the customer's IP address for private Storefront API clients.\n * @returns The context to pass to Hydrogen's API clients and route handlers for this request.\n */\nexport function createShopifyRequestContext<const I18n extends I18nConfig>(\n input: ShopifyRequestContextInputBase<I18n> & { buyerIp?: string },\n): ShopifyRequestContext<I18n> {\n const { request } = input;\n\n if (!input.i18n?.country || !input.i18n?.language) {\n throw new Error(\"i18n with country and language is required for Shopify request contexts.\");\n }\n\n if (input.buyerIp !== undefined && !input.buyerIp) {\n throw new Error(\"buyerIp must be non-empty when provided\");\n }\n\n const requestMethod = request.method?.toUpperCase();\n const i18n = normalizeI18n(input.i18n);\n const cookieHeader = request.headers.get(\"cookie\") || undefined;\n const inboundCookies = parseCookieHeader(cookieHeader);\n const hasEssentialCookie = inboundCookies.has(SHOPIFY_ESSENTIAL_COOKIE);\n const isConsentManagementRequest = request.headers.get(CONSENT_MANAGEMENT_HEADER) === \"1\";\n const url = request.url ?? request.headers.get(STOREFRONT_URL_HEADER) ?? undefined;\n const storefrontOrigin = getUrlOrigin(url);\n const context = {\n ...(cookieHeader && { cookie: cookieHeader }),\n globalPrivacyControl: request.headers.get(SEC_GPC_HEADER) ?? undefined,\n i18n,\n ...(url && { url }),\n ...(storefrontOrigin && { storefrontOrigin }),\n ...(input.buyerIp && { buyerIp: input.buyerIp }),\n requestGroupId:\n request.headers.get(REQUEST_GROUP_ID_HEADER) ??\n request.headers.get(\"x-request-id\") ??\n request.headers.get(\"request-id\") ??\n crypto.randomUUID(),\n ...(isDocumentRequest(request) && { documentRequest: true }),\n ...(request.signal && { signal: request.signal }),\n } as Context<I18n>;\n\n let capturedCookies: string[] | undefined;\n let personalizedResponseReason: string | undefined;\n let sessionEstablishingReason: string | undefined;\n\n const captureSubrequestHeaders = (headers: Headers): void => {\n // Capture the first fresh response cookies to increase the\n // chance of returning them from the main server response. The main response\n // needs headers set at send time, while the body can stream later, so this\n // may not be used if subrequests finish after the main response is sent.\n const cookies = headers.getSetCookie();\n if (cookies.length > 0) capturedCookies ??= cookies;\n };\n\n return {\n ...context,\n getForwardedRequestHeaders() {\n const headers = new Headers(request.headers);\n applyStorefrontRequestHeaders(context, headers);\n if (context.url) headers.set(STOREFRONT_URL_HEADER, context.url);\n return headers;\n },\n applyStorefrontRequestHeaders(headers) {\n applyStorefrontRequestHeaders(context, headers);\n },\n captureSubrequestHeaders,\n consumeStorefrontResponseHeaders(headers) {\n captureSubrequestHeaders(headers);\n headers.delete(\"set-cookie\");\n },\n markResponseAsPersonalized(reason) {\n personalizedResponseReason ??= reason;\n },\n markResponseAsSessionEstablishing(reason) {\n sessionEstablishingReason ??= reason;\n },\n applyResponseHeaders(headers) {\n headers.set(\"powered-by\", \"Shopify, Hydrogen\");\n\n // Documents may be shared or streamed, so they must not carry buyer-specific state.\n const isDocumentResponse =\n context.documentRequest || (headers.get(\"content-type\")?.startsWith(\"text/html\") ?? false);\n\n // Keep GET and HEAD responses cacheable, and fail closed when the request method is unknown.\n // Cold sessions may only be established by the explicitly marked consent request.\n const mayReturnShopifyState =\n requestMethod !== undefined &&\n requestMethod !== \"GET\" &&\n requestMethod !== \"HEAD\" &&\n !isDocumentResponse &&\n (hasEssentialCookie ||\n isConsentManagementRequest ||\n sessionEstablishingReason !== undefined);\n\n // Replay cookies captured from fresh SFAPI and proxy responses when allowed.\n if (capturedCookies && mayReturnShopifyState) {\n const existingSetCookies = new Set(headers.getSetCookie());\n for (const value of capturedCookies) {\n if (existingSetCookies.has(value)) continue;\n headers.append(\"set-cookie\", value);\n existingSetCookies.add(value);\n }\n }\n\n // Consent/session responses can contain private state in the body without setting cookies.\n if (\n personalizedResponseReason ||\n isConsentManagementRequest ||\n sessionEstablishingReason !== undefined ||\n headers.has(\"set-cookie\")\n ) {\n applyPrivateResponseCacheHeaders(headers);\n }\n },\n } as ShopifyRequestContext<I18n>;\n}\n\nfunction normalizeI18n<I18n extends I18nConfig>(i18n: I18n): NormalizedI18nConfig<I18n> {\n return {\n ...i18n,\n pathPrefix: normalizePathPrefix(i18n.pathPrefix),\n } as NormalizedI18nConfig<I18n>;\n}\n\nfunction applyStorefrontRequestHeaders(context: Context, headers: Headers): void {\n headers.set(SDK_VARIANT_HEADER, \"hydrogen\");\n headers.set(SDK_VARIANT_SOURCE_HEADER, \"kit\");\n headers.set(SDK_VERSION_HEADER, STOREFRONT_API_VERSION);\n headers.set(HYDROGEN_VERSION_HEADER, __HYDROGEN_VERSION__);\n headers.set(REQUEST_GROUP_ID_HEADER, context.requestGroupId);\n\n if (context.cookie) headers.set(\"cookie\", context.cookie);\n else headers.delete(\"cookie\");\n if (context.globalPrivacyControl !== undefined) {\n headers.set(SEC_GPC_HEADER, context.globalPrivacyControl);\n } else headers.delete(SEC_GPC_HEADER);\n if (context.storefrontOrigin) {\n headers.set(SHOPIFY_STOREFRONT_ORIGIN_HEADER, context.storefrontOrigin);\n } else headers.delete(SHOPIFY_STOREFRONT_ORIGIN_HEADER);\n}\n\nfunction getUrlOrigin(url: string | undefined): string | undefined {\n if (!url) return undefined;\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction isDocumentRequest(request: StorefrontRequest): boolean {\n if (request.method && request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n\n const destination = request.headers.get(\"sec-fetch-dest\");\n if (destination === \"document\") return true;\n\n return request.headers.get(\"accept\")?.includes(\"text/html\") ?? false;\n}\n\nfunction parseCookieHeader(cookieHeader: string | undefined): Map<string, string> {\n const cookies = new Map<string, string>();\n if (!cookieHeader) return cookies;\n\n for (const cookie of cookieHeader.split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator < 0) continue;\n\n const name = cookie.slice(0, separator).trim();\n if (!cookies.has(name)) cookies.set(name, cookie.slice(separator + 1));\n }\n\n return cookies;\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"request-context.mjs","names":[],"sources":["../../../src/core/request-context.ts"],"sourcesContent":["import { STOREFRONT_API_VERSION } from \"./constants\";\nimport {\n applyPrivateResponseCacheHeaders,\n CONSENT_MANAGEMENT_HEADER,\n HYDROGEN_VERSION_HEADER,\n REQUEST_GROUP_ID_HEADER,\n SDK_VARIANT_HEADER,\n SDK_VARIANT_SOURCE_HEADER,\n SDK_VERSION_HEADER,\n SEC_GPC_HEADER,\n SHOPIFY_STOREFRONT_ORIGIN_HEADER,\n STOREFRONT_URL_HEADER,\n} from \"./headers\";\nimport { matchLocale, resolveSupportedLocale } from \"./i18n/match\";\nimport type {\n ShopifyCountryCode,\n ShopifyI18n,\n ShopifyLanguageCode,\n ShopifyLocale,\n ShopifyMatchedLocale,\n} from \"./i18n/types\";\nimport { normalizePathPrefix } from \"./standard-routes/path\";\n\nexport type { ShopifyCountryCode, ShopifyLanguageCode } from \"./i18n/types\";\n\n/**\n * Deprecated: a fixed request locale with an optional path prefix. Removed in the next major release.\n * @deprecated Pass a definition from `defineShopifyI18n` to `createShopifyRequestContext` instead. Use `ShopifyLocale` for `{language, country}` and `ShopifyMatchedLocale` for the resolved locale. Removed in the next major release.\n */\nexport type I18nConfig = {\n /** The request's language. */\n language: ShopifyLanguageCode;\n /** The request's country. */\n country: ShopifyCountryCode;\n /**\n * The URL prefix for localized routes, such as `/es-es`. Hydrogen adds the prefix to standard route redirects and product variant URLs.\n */\n pathPrefix?: string;\n};\n\ntype NormalizedI18nConfig<TConfig extends I18nConfig> = Omit<TConfig, \"pathPrefix\"> & {\n pathPrefix: string;\n};\n\n/** The locale a request context resolves: matched from a definition, or the legacy fixed locale. */\ntype RequestLocale<TI18n extends ShopifyI18n | I18nConfig> = TI18n extends ShopifyI18n\n ? ShopifyMatchedLocale<TI18n>\n : TI18n extends I18nConfig\n ? NormalizedI18nConfig<TI18n>\n : never;\n\nconst SHOPIFY_ESSENTIAL_COOKIE = \"_shopify_essential\";\n\n/** The incoming request's headers, plus its method, abort signal, and URL when the framework provides them. */\ntype StorefrontRequest = Pick<Request, \"headers\"> &\n Partial<Pick<Request, \"method\" | \"signal\" | \"url\">>;\n\n/** The incoming request and the storefront's i18n definition. */\ntype ShopifyRequestContextInputBase<TI18n extends ShopifyI18n = ShopifyI18n> = {\n /**\n * The incoming request from your framework. When the framework exposes no request, such as during prerendering, pass `{ headers: new Headers() }`.\n */\n request: StorefrontRequest;\n /** The storefront's i18n definition from `defineShopifyI18n`. Hydrogen matches the request's locale against it. */\n i18n: TI18n;\n /**\n * The locale to use instead of matching the request URL. The locale must be one of the definition's supported locales.\n * Pass it when the request has no meaningful URL, such as during static rendering.\n */\n locale?: ShopifyLocale;\n};\n\ntype ShopifyRequestContextInput<TI18n extends ShopifyI18n = ShopifyI18n> =\n ShopifyRequestContextInputBase<TI18n> & { buyerIp?: never };\n\ntype ShopifyRequestContextWithBuyerIpInput<TI18n extends ShopifyI18n = ShopifyI18n> =\n ShopifyRequestContextInputBase<TI18n> & { buyerIp: string };\n\n/**\n * Deprecated: the request and a fixed locale, used for every request with no URL matching. Pass a definition from `defineShopifyI18n` as `i18n` instead. Removed in the next major release.\n */\ntype LegacyShopifyRequestContextInput<TConfig extends I18nConfig> = {\n request: StorefrontRequest;\n /** Deprecated: the fixed `{language, country, pathPrefix}` for every request. */\n i18n: TConfig;\n locale?: never;\n};\n\ntype RequestContextInput =\n | ShopifyRequestContextInputBase\n | LegacyShopifyRequestContextInput<I18nConfig>;\n\n/** The fields and methods on every request context. */\ntype ShopifyRequestContextBase = {\n // -- Private fields --\n /**\n * A type-only marker. Create request contexts only with `createShopifyRequestContext`.\n * @internal\n */\n readonly __hydrogenShopifyRequestContextBrand: never;\n /**\n * The incoming request's `Cookie` header. Hydrogen forwards the header to the Storefront API.\n * @internal\n */\n cookie?: string;\n /**\n * The customer's trusted IP address. Private Storefront API clients require it.\n * @internal\n */\n readonly buyerIp?: string;\n /**\n * The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one.\n * @internal\n */\n requestGroupId: string;\n /**\n * The incoming request's abort signal. Hydrogen's API clients stop their requests when the signal aborts.\n * @internal\n */\n signal?: AbortSignal;\n /**\n * The incoming request's URL.\n * @internal\n */\n url?: string;\n /**\n * The origin of the incoming request's URL. Hydrogen forwards the origin to the Storefront API.\n * @internal\n */\n storefrontOrigin?: string;\n /**\n * Adds the Hydrogen SDK headers and the customer's cookie, privacy, and origin headers to a\n * Storefront API request. The Storefront API client and the API proxies call the method for you.\n * @internal\n */\n applyStorefrontRequestHeaders(headers: Headers): void;\n /**\n * Saves the cookies from the first Storefront API response that sets cookies. The Storefront API\n * client calls the method for you, and `applyResponseHeaders()` can add the cookies to your response.\n * @internal\n */\n captureSubrequestHeaders(headers: Headers): void;\n /**\n * Saves the cookies from a proxied Storefront API response and removes the `set-cookie` header\n * from that response. The API proxies in `handleShopifyRoutes` call the method for you.\n * @internal\n */\n consumeStorefrontResponseHeaders(headers: Headers): void;\n /**\n * Lets the final response set Shopify cookies before the customer has a Shopify session, and\n * marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.\n * @internal\n */\n markResponseAsSessionEstablishing(reason: string): void;\n\n // -- Public fields --\n /** Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin. */\n getForwardedRequestHeaders(): Headers;\n /**\n * Marks the final response as private and uncacheable because the response holds customer data, such as a server-rendered cart. `applyResponseHeaders()` then sets `Cache-Control: private, no-store, max-age=0, must-revalidate` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. Call the method before `applyResponseHeaders()`, and only on requests whose response holds customer data, so other responses stay cacheable. Pass a short `reason` that names the customer data. The Customer Account API client and the customer session call the method for you.\n */\n markResponseAsPersonalized(reason: string): void;\n /**\n * Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers.\n *\n * Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses marked with `markResponseAsPersonalized()` private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`.\n */\n applyResponseHeaders(headers: Headers): void;\n};\n\n/** The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request. */\nexport type ShopifyRequestContext<TI18n extends ShopifyI18n | I18nConfig = ShopifyI18n> =\n ShopifyRequestContextBase & {\n /** The locale resolved for this request, with the path prefix it is served under. */\n locale: RequestLocale<TI18n>;\n /**\n * The locale resolved for this request.\n * @deprecated Use `locale` instead. Removed in the next major release.\n */\n i18n: RequestLocale<TI18n>;\n };\n\n/** A request context that includes the customer's IP address. Private Storefront API clients require this context. */\nexport type ShopifyRequestContextWithBuyerIp<TI18n extends ShopifyI18n | I18nConfig = ShopifyI18n> =\n ShopifyRequestContext<TI18n> & { readonly buyerIp: string };\n\n/** The values that the request context reads from the incoming request. */\ntype Context<TI18n extends ShopifyI18n | I18nConfig = ShopifyI18n> = {\n /** The incoming request's `Cookie` header. */\n cookie?: string;\n /** The incoming request's `Sec-GPC` header value, which carries the customer's Global Privacy Control signal. */\n globalPrivacyControl?: string;\n /** The customer's trusted IP address. */\n buyerIp?: string;\n /** The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one. */\n requestGroupId: string;\n /** The incoming request's abort signal. */\n signal?: AbortSignal;\n /** The incoming request's URL. */\n url?: string;\n /** The origin of the incoming request's URL. */\n storefrontOrigin?: string;\n /** The locale resolved for this request. */\n locale: RequestLocale<TI18n>;\n /** The same locale, under its deprecated name. */\n i18n: RequestLocale<TI18n>;\n /** Whether the incoming request asks for an HTML document. */\n documentRequest?: boolean;\n};\n\n/**\n * @deprecated Pass a definition from `defineShopifyI18n` as `i18n` instead of a fixed `{language, country, pathPrefix}`. Removed in the next major release.\n */\nexport function createShopifyRequestContext<const TConfig extends I18nConfig>(\n input: LegacyShopifyRequestContextInput<TConfig> & { buyerIp: string },\n): ShopifyRequestContextWithBuyerIp<TConfig>;\n/**\n * @deprecated Pass a definition from `defineShopifyI18n` as `i18n` instead of a fixed `{language, country, pathPrefix}`. Removed in the next major release.\n */\nexport function createShopifyRequestContext<const TConfig extends I18nConfig>(\n input: LegacyShopifyRequestContextInput<TConfig> & { buyerIp?: never },\n): ShopifyRequestContext<TConfig>;\n/**\n * Creates the context for one incoming request. Pass the same context to the Storefront API\n * client, the Customer Account API client, and `handleShopifyRoutes`. The context resolves the\n * request's locale from your i18n definition, forwards the customer's cookies, locale, and privacy\n * signal to Shopify, and adds Shopify's cookies and cache headers to your response.\n *\n * Call `applyResponseHeaders()` on each response that your app builds. Pass `buyerIp` with the customer's trusted IP address when you use a private Storefront API client. The function throws when `i18n` doesn't come from `defineShopifyI18n`, when `locale` isn't one of the definition's supported locales, and when `buyerIp` is an empty string.\n *\n * @publicDocs\n */\nexport function createShopifyRequestContext<const TI18n extends ShopifyI18n>(\n input: ShopifyRequestContextWithBuyerIpInput<TI18n>,\n): ShopifyRequestContextWithBuyerIp<TI18n>;\nexport function createShopifyRequestContext<const TI18n extends ShopifyI18n>(\n input: ShopifyRequestContextInput<TI18n>,\n): ShopifyRequestContext<TI18n>;\n/**\n * @param input The incoming request, the storefront's i18n definition, and the customer's IP address for private Storefront API clients.\n * @returns The context to pass to Hydrogen's API clients and route handlers for this request.\n */\nexport function createShopifyRequestContext<const TI18n extends ShopifyI18n>(\n input: (ShopifyRequestContextInputBase<TI18n> | LegacyShopifyRequestContextInput<I18nConfig>) & {\n buyerIp?: string;\n },\n): ShopifyRequestContext<TI18n> {\n const { request } = input;\n\n if (input.buyerIp !== undefined && !input.buyerIp) {\n throw new Error(\"buyerIp must be non-empty when provided\");\n }\n\n const requestMethod = request.method?.toUpperCase();\n const cookieHeader = request.headers.get(\"cookie\") || undefined;\n const inboundCookies = parseCookieHeader(cookieHeader);\n const hasEssentialCookie = inboundCookies.has(SHOPIFY_ESSENTIAL_COOKIE);\n const isConsentManagementRequest = request.headers.get(CONSENT_MANAGEMENT_HEADER) === \"1\";\n const url = request.url ?? request.headers.get(STOREFRONT_URL_HEADER) ?? undefined;\n const storefrontOrigin = getUrlOrigin(url);\n const locale = resolveRequestLocale(input, url);\n const context = {\n ...(cookieHeader && { cookie: cookieHeader }),\n globalPrivacyControl: request.headers.get(SEC_GPC_HEADER) ?? undefined,\n locale,\n i18n: locale,\n ...(url && { url }),\n ...(storefrontOrigin && { storefrontOrigin }),\n ...(input.buyerIp && { buyerIp: input.buyerIp }),\n requestGroupId:\n request.headers.get(REQUEST_GROUP_ID_HEADER) ??\n request.headers.get(\"x-request-id\") ??\n request.headers.get(\"request-id\") ??\n crypto.randomUUID(),\n ...(isDocumentRequest(request) && { documentRequest: true }),\n ...(request.signal && { signal: request.signal }),\n } as Context<ShopifyI18n | I18nConfig>;\n\n let capturedCookies: string[] | undefined;\n let personalizedResponseReason: string | undefined;\n let sessionEstablishingReason: string | undefined;\n\n const captureSubrequestHeaders = (headers: Headers): void => {\n // Capture the first fresh response cookies to increase the\n // chance of returning them from the main server response. The main response\n // needs headers set at send time, while the body can stream later, so this\n // may not be used if subrequests finish after the main response is sent.\n const cookies = headers.getSetCookie();\n if (cookies.length > 0) capturedCookies ??= cookies;\n };\n\n return {\n ...context,\n getForwardedRequestHeaders() {\n const headers = new Headers(request.headers);\n applyStorefrontRequestHeaders(context, headers);\n if (context.url) headers.set(STOREFRONT_URL_HEADER, context.url);\n return headers;\n },\n applyStorefrontRequestHeaders(headers) {\n applyStorefrontRequestHeaders(context, headers);\n },\n captureSubrequestHeaders,\n consumeStorefrontResponseHeaders(headers) {\n captureSubrequestHeaders(headers);\n headers.delete(\"set-cookie\");\n },\n markResponseAsPersonalized(reason) {\n personalizedResponseReason ??= reason;\n },\n markResponseAsSessionEstablishing(reason) {\n sessionEstablishingReason ??= reason;\n },\n applyResponseHeaders(headers) {\n headers.set(\"powered-by\", \"Shopify, Hydrogen\");\n\n // Documents may be shared or streamed, so they must not carry buyer-specific state.\n const isDocumentResponse =\n context.documentRequest || (headers.get(\"content-type\")?.startsWith(\"text/html\") ?? false);\n\n // Keep GET and HEAD responses cacheable, and fail closed when the request method is unknown.\n // Cold sessions may only be established by the explicitly marked consent request.\n const mayReturnShopifyState =\n requestMethod !== undefined &&\n requestMethod !== \"GET\" &&\n requestMethod !== \"HEAD\" &&\n !isDocumentResponse &&\n (hasEssentialCookie ||\n isConsentManagementRequest ||\n sessionEstablishingReason !== undefined);\n\n // Replay cookies captured from fresh SFAPI and proxy responses when allowed.\n if (capturedCookies && mayReturnShopifyState) {\n const existingSetCookies = new Set(headers.getSetCookie());\n for (const value of capturedCookies) {\n if (existingSetCookies.has(value)) continue;\n headers.append(\"set-cookie\", value);\n existingSetCookies.add(value);\n }\n }\n\n // Consent/session responses can contain private state in the body without setting cookies.\n if (\n personalizedResponseReason ||\n isConsentManagementRequest ||\n sessionEstablishingReason !== undefined ||\n headers.has(\"set-cookie\")\n ) {\n applyPrivateResponseCacheHeaders(headers);\n }\n },\n } as ShopifyRequestContext<TI18n>;\n}\n\nfunction resolveRequestLocale(\n input: RequestContextInput,\n url: string | undefined,\n): RequestLocale<ShopifyI18n | I18nConfig> {\n const { i18n } = input;\n if (\n i18n &&\n \"defaultLocale\" in i18n &&\n i18n.defaultLocale?.country &&\n i18n.defaultLocale.language\n ) {\n return input.locale ? resolveSupportedLocale(input.locale, i18n) : matchLocale(url, i18n);\n }\n // Legacy `I18nConfig` input pins one locale, exactly as before definitions existed.\n if (i18n && \"country\" in i18n && i18n.country && i18n.language) {\n return { ...i18n, pathPrefix: normalizePathPrefix(i18n.pathPrefix) };\n }\n throw new Error(\n \"i18n from defineShopifyI18n (with a defaultLocale) is required for Shopify request contexts.\",\n );\n}\n\nfunction applyStorefrontRequestHeaders(context: Context, headers: Headers): void {\n headers.set(SDK_VARIANT_HEADER, \"hydrogen\");\n headers.set(SDK_VARIANT_SOURCE_HEADER, \"kit\");\n headers.set(SDK_VERSION_HEADER, STOREFRONT_API_VERSION);\n headers.set(HYDROGEN_VERSION_HEADER, __HYDROGEN_VERSION__);\n headers.set(REQUEST_GROUP_ID_HEADER, context.requestGroupId);\n\n if (context.cookie) headers.set(\"cookie\", context.cookie);\n else headers.delete(\"cookie\");\n if (context.globalPrivacyControl !== undefined) {\n headers.set(SEC_GPC_HEADER, context.globalPrivacyControl);\n } else headers.delete(SEC_GPC_HEADER);\n if (context.storefrontOrigin) {\n headers.set(SHOPIFY_STOREFRONT_ORIGIN_HEADER, context.storefrontOrigin);\n } else headers.delete(SHOPIFY_STOREFRONT_ORIGIN_HEADER);\n}\n\nfunction getUrlOrigin(url: string | undefined): string | undefined {\n if (!url) return undefined;\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction isDocumentRequest(request: StorefrontRequest): boolean {\n if (request.method && request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n\n const destination = request.headers.get(\"sec-fetch-dest\");\n if (destination === \"document\") return true;\n\n return request.headers.get(\"accept\")?.includes(\"text/html\") ?? false;\n}\n\nfunction parseCookieHeader(cookieHeader: string | undefined): Map<string, string> {\n const cookies = new Map<string, string>();\n if (!cookieHeader) return cookies;\n\n for (const cookie of cookieHeader.split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator < 0) continue;\n\n const name = cookie.slice(0, separator).trim();\n if (!cookies.has(name)) cookies.set(name, cookie.slice(separator + 1));\n }\n\n return cookies;\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-shopify-routes.mjs","names":[],"sources":["../../../../src/core/request-routing/handle-shopify-routes.ts"],"sourcesContent":["import { handleProductVariantId } from \"../product/accept-variant-id\";\nimport { handleAjaxApi } from \"./interceptors/ajax-api\";\nimport { handleShopifyApiProxy } from \"./interceptors/api-proxy\";\nimport { handleBuyPermalinkRedirect, handleCheckoutRedirect } from \"./interceptors/checkout\";\nimport { handleMcpProxy } from \"./interceptors/mcp-proxy\";\nimport { handleSfapiProxy } from \"./interceptors/sfapi-proxy\";\nimport { handleUcpMcpProxy } from \"./interceptors/ucp-mcp-proxy\";\nimport { handleUcpProfileProxy } from \"./interceptors/ucp-profile-proxy\";\nimport { handleWellKnownProxy } from \"./interceptors/well-known\";\nimport { handleShopifyRouteHandlers } from \"./registered-routes\";\nimport type {\n HydrogenRouteHandler,\n HydrogenRouteInterceptor,\n HydrogenRoutesOptions,\n} from \"./route-types\";\nimport { safeApplyResponseHeaders } from \"./safe-apply-response-headers\";\n\nconst SHOPIFY_ROUTE_INTERCEPTORS = [\n handleShopifyApiProxy,\n handleSfapiProxy,\n handleProductVariantId,\n handleShopifyRouteHandlers,\n handleBuyPermalinkRedirect,\n handleCheckoutRedirect,\n handleUcpProfileProxy,\n handleWellKnownProxy,\n handleUcpMcpProxy,\n handleMcpProxy,\n handleAjaxApi,\n] satisfies readonly HydrogenRouteInterceptor[];\n\n/**\n * Serves Shopify's storefront endpoints and your custom route handlers.\n * Returns a promise for the matched response, or `null` when no route matches.\n * The matched response already carries the request context's headers.\n *\n * @publicDocs\n */\nexport const handleShopifyRoutes: HydrogenRouteHandler = (options) => {\n if (options.requestContext !== options.storefrontClient.requestContext) {\n throw new Error(\n \"handleShopifyRoutes must receive the same requestContext used by storefrontClient.\",\n );\n }\n\n const url = new URL(options.request.url);\n\n for (const interceptor of SHOPIFY_ROUTE_INTERCEPTORS) {\n const responsePromise = interceptor(url, options);\n if (!responsePromise) continue;\n\n return responsePromise.then((response) =>\n safeApplyResponseHeaders(response, options.requestContext),\n );\n }\n\n return null;\n};\n\n/**\n * Serves Shopify's storefront endpoints and your custom route handlers from your app. Call the function at the start of request handling, before your framework's router.\n *\n * When a route matches, the function returns a promise for the response. Return that response as is, because the response already carries the request context's headers. When no route matches, the function returns `null` synchronously, and your framework's router handles the request. The function throws when `requestContext` differs from the Storefront API client's request context. When a route handler throws, the returned promise rejects. Inside a `try` block, use `return await` on the result.\n *\n * The function checks these routes in order and returns the first match: the Shopify API proxy at `/__shopify`, the Storefront API proxy at `/api/{version}/graphql.json`, Liquid-style `?variant=` product URLs, registered handler groups, UCP buy permalinks at `/buy/...`, checkout and cart permalinks, allowlisted `.well-known` resources, the UCP MCP proxy at `/api/ucp/mcp`, the MCP proxy at `/api/mcp`, and AJAX cart URLs.\n *\n * Some routes answer unsupported methods with a `405` response. A registered handler path returns `405` for any method that no handler on that path registers. Checkout and cart permalinks accept only `GET` and `HEAD`. Buy permalinks accept only `GET`, and the UCP MCP proxy accepts only `POST`.\n *\n * When your bundler resolves the package's `development` export condition, the function also serves the GraphiQL explorer at `/graphiql` for GET requests that match no other route, and accepts a `graphiql` option. Set `graphiql.customerAccount` to an object with `apiUrl`, `accessToken`, and `schemaUrl` to add a Customer Account API tab. The explorer skips the tab when it can't fetch the schema.\n *\n * @publicDocs\n */\nexport type HandleShopifyRoutesForDocs =\n /**\n * @param options - The request, its context
|
|
1
|
+
{"version":3,"file":"handle-shopify-routes.mjs","names":[],"sources":["../../../../src/core/request-routing/handle-shopify-routes.ts"],"sourcesContent":["import { handleProductVariantId } from \"../product/accept-variant-id\";\nimport { handleAjaxApi } from \"./interceptors/ajax-api\";\nimport { handleShopifyApiProxy } from \"./interceptors/api-proxy\";\nimport { handleBuyPermalinkRedirect, handleCheckoutRedirect } from \"./interceptors/checkout\";\nimport { handleMcpProxy } from \"./interceptors/mcp-proxy\";\nimport { handleSfapiProxy } from \"./interceptors/sfapi-proxy\";\nimport { handleUcpMcpProxy } from \"./interceptors/ucp-mcp-proxy\";\nimport { handleUcpProfileProxy } from \"./interceptors/ucp-profile-proxy\";\nimport { handleWellKnownProxy } from \"./interceptors/well-known\";\nimport { handleShopifyRouteHandlers } from \"./registered-routes\";\nimport type {\n HydrogenRouteHandler,\n HydrogenRouteInterceptor,\n HydrogenRoutesOptions,\n} from \"./route-types\";\nimport { safeApplyResponseHeaders } from \"./safe-apply-response-headers\";\n\nconst SHOPIFY_ROUTE_INTERCEPTORS = [\n handleShopifyApiProxy,\n handleSfapiProxy,\n handleProductVariantId,\n handleShopifyRouteHandlers,\n handleBuyPermalinkRedirect,\n handleCheckoutRedirect,\n handleUcpProfileProxy,\n handleWellKnownProxy,\n handleUcpMcpProxy,\n handleMcpProxy,\n handleAjaxApi,\n] satisfies readonly HydrogenRouteInterceptor[];\n\n/**\n * Serves Shopify's storefront endpoints and your custom route handlers.\n * Returns a promise for the matched response, or `null` when no route matches.\n * The matched response already carries the request context's headers.\n *\n * @publicDocs\n */\nexport const handleShopifyRoutes: HydrogenRouteHandler = (options) => {\n if (options.requestContext !== options.storefrontClient.requestContext) {\n throw new Error(\n \"handleShopifyRoutes must receive the same requestContext used by storefrontClient.\",\n );\n }\n\n const url = new URL(options.request.url);\n\n for (const interceptor of SHOPIFY_ROUTE_INTERCEPTORS) {\n const responsePromise = interceptor(url, options);\n if (!responsePromise) continue;\n\n return responsePromise.then((response) =>\n safeApplyResponseHeaders(response, options.requestContext),\n );\n }\n\n return null;\n};\n\n/**\n * Serves Shopify's storefront endpoints and your custom route handlers from your app. Call the function at the start of request handling, before your framework's router.\n *\n * When a route matches, the function returns a promise for the response. Return that response as is, because the response already carries the request context's headers. When no route matches, the function returns `null` synchronously, and your framework's router handles the request. The function throws when `requestContext` differs from the Storefront API client's request context. When a route handler throws, the returned promise rejects. Inside a `try` block, use `return await` on the result.\n *\n * The function checks these routes in order and returns the first match: the Shopify API proxy at `/__shopify`, the Storefront API proxy at `/api/{version}/graphql.json`, Liquid-style `?variant=` product URLs, registered handler groups, UCP buy permalinks at `/buy/...`, checkout and cart permalinks, the UCP business profile at `/.well-known/ucp`, allowlisted `.well-known` resources, the UCP MCP proxy at `/api/ucp/mcp`, the MCP proxy at `/api/mcp`, and AJAX cart URLs.\n *\n * Some routes answer unsupported methods with a `405` response. A registered handler path returns `405` for any method that no handler on that path registers. Checkout and cart permalinks accept only `GET` and `HEAD`. Buy permalinks accept only `GET`, and the UCP MCP proxy accepts only `POST`.\n *\n * When your bundler resolves the package's `development` export condition, the function also serves the GraphiQL explorer at `/graphiql` for GET requests that match no other route, and accepts a `graphiql` option. Set `graphiql.customerAccount` to an object with `apiUrl`, `accessToken`, and `schemaUrl` to add a Customer Account API tab. The explorer skips the tab when it can't fetch the schema.\n *\n * @publicDocs\n */\nexport type HandleShopifyRoutesForDocs =\n /**\n * @param options - The request, its context, the Storefront API client, your route templates, your handler groups, and the session manager when a registered handler needs one.\n * @returns A promise for the matched route's response, or `null` when no route matches.\n */\n (options: HydrogenRoutesOptions) => null | Promise<Response>;\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,uBAA6C,YAAY;AACpE,KAAI,QAAQ,mBAAmB,QAAQ,iBAAiB,eACtD,OAAM,IAAI,MACR,qFACD;CAGH,MAAM,MAAM,IAAI,IAAI,QAAQ,QAAQ,IAAI;AAExC,MAAK,MAAM,eAAe,4BAA4B;EACpD,MAAM,kBAAkB,YAAY,KAAK,QAAQ;AACjD,MAAI,CAAC,gBAAiB;AAEtB,SAAO,gBAAgB,MAAM,aAC3B,yBAAyB,UAAU,QAAQ,eAAe,CAC3D;;AAGH,QAAO"}
|
|
@@ -4,7 +4,8 @@ import { createProxyInterceptor } from "./proxy.mjs";
|
|
|
4
4
|
import { rewriteShopifyJsPathname } from "./ajax-api.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/core/request-routing/interceptors/api-proxy.ts
|
|
7
|
-
const
|
|
7
|
+
const SHOPIFY_API_PROXY_ROOT_RE = /^\/__shopify\/*$/;
|
|
8
|
+
const proxyShopifyApiRequest = createProxyInterceptor({
|
|
8
9
|
match: SHOPIFY_API_PROXY_RE,
|
|
9
10
|
requestHeaders: { deny: PROXY_REQUEST_HEADER_DENYLIST },
|
|
10
11
|
rewritePathname: (pathname) => {
|
|
@@ -14,6 +15,13 @@ const handleShopifyApiProxy = createProxyInterceptor({
|
|
|
14
15
|
},
|
|
15
16
|
scope: "shopify-api-proxy"
|
|
16
17
|
});
|
|
18
|
+
const handleShopifyApiProxy = (url, options) => {
|
|
19
|
+
if (SHOPIFY_API_PROXY_ROOT_RE.test(url.pathname)) return Promise.resolve(new Response(options.request.method === "HEAD" ? null : JSON.stringify({ error: "Not Found" }), {
|
|
20
|
+
status: 404,
|
|
21
|
+
headers: { "content-type": "application/json" }
|
|
22
|
+
}));
|
|
23
|
+
return proxyShopifyApiRequest(url, options);
|
|
24
|
+
};
|
|
17
25
|
|
|
18
26
|
//#endregion
|
|
19
27
|
export { handleShopifyApiProxy };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-proxy.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/api-proxy.ts"],"sourcesContent":["import { PROXY_REQUEST_HEADER_DENYLIST } from \"../../headers\";\nimport { SHOPIFY_API_PROXY_PREFIX, SHOPIFY_API_PROXY_RE } from \"../../url\";\nimport { rewriteShopifyJsPathname } from \"./ajax-api\";\nimport { createProxyInterceptor } from \"./proxy\";\n\
|
|
1
|
+
{"version":3,"file":"api-proxy.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/api-proxy.ts"],"sourcesContent":["import { PROXY_REQUEST_HEADER_DENYLIST } from \"../../headers\";\nimport { SHOPIFY_API_PROXY_PREFIX, SHOPIFY_API_PROXY_RE } from \"../../url\";\nimport type { HydrogenRouteInterceptor } from \"../route-types\";\nimport { rewriteShopifyJsPathname } from \"./ajax-api\";\nimport { createProxyInterceptor } from \"./proxy\";\n\nconst SHOPIFY_API_PROXY_ROOT_RE = /^\\/__shopify\\/*$/;\n\nconst proxyShopifyApiRequest = createProxyInterceptor({\n match: SHOPIFY_API_PROXY_RE,\n requestHeaders: { deny: PROXY_REQUEST_HEADER_DENYLIST },\n rewritePathname: (pathname) => {\n const upstreamPathname =\n \"/\" + pathname.slice(SHOPIFY_API_PROXY_PREFIX.length).replace(/^\\/+/, \"\");\n\n if (upstreamPathname.startsWith(\"/cdn/\")) {\n throw new Error(\"CDN proxy is not supported.\");\n }\n\n return rewriteShopifyJsPathname(upstreamPathname);\n },\n scope: \"shopify-api-proxy\",\n});\n\nexport const handleShopifyApiProxy: HydrogenRouteInterceptor = (url, options) => {\n // The bare prefix would proxy the Online Store home page, which redirects off the storefront.\n if (SHOPIFY_API_PROXY_ROOT_RE.test(url.pathname)) {\n return Promise.resolve(\n new Response(\n options.request.method === \"HEAD\" ? null : JSON.stringify({ error: \"Not Found\" }),\n { status: 404, headers: { \"content-type\": \"application/json\" } },\n ),\n );\n }\n\n return proxyShopifyApiRequest(url, options);\n};\n"],"mappings":";;;;;;AAMA,MAAM,4BAA4B;AAElC,MAAM,yBAAyB,uBAAuB;CACpD,OAAO;CACP,gBAAgB,EAAE,MAAM,+BAA+B;CACvD,kBAAkB,aAAa;EAC7B,MAAM,mBACJ,MAAM,SAAS,MAAM,yBAAyB,OAAO,CAAC,QAAQ,QAAQ,GAAG;AAE3E,MAAI,iBAAiB,WAAW,QAAQ,CACtC,OAAM,IAAI,MAAM,8BAA8B;AAGhD,SAAO,yBAAyB,iBAAiB;;CAEnD,OAAO;CACR,CAAC;AAEF,MAAa,yBAAmD,KAAK,YAAY;AAE/E,KAAI,0BAA0B,KAAK,IAAI,SAAS,CAC9C,QAAO,QAAQ,QACb,IAAI,SACF,QAAQ,QAAQ,WAAW,SAAS,OAAO,KAAK,UAAU,EAAE,OAAO,aAAa,CAAC,EACjF;EAAE,QAAQ;EAAK,SAAS,EAAE,gBAAgB,oBAAoB;EAAE,CACjE,CACF;AAGH,QAAO,uBAAuB,KAAK,QAAQ"}
|
|
@@ -1,28 +1,34 @@
|
|
|
1
1
|
import { getLogger } from "../../logging/logging.mjs";
|
|
2
|
-
import { BUY_PERMALINK_RE,
|
|
2
|
+
import { BUY_PERMALINK_RE, CART_PERMALINK_RE, CHECKOUT_RE } from "../../url.mjs";
|
|
3
|
+
import { applyPrivateResponseCacheHeaders } from "../../headers.mjs";
|
|
3
4
|
import { getCart, getCartId } from "../../cart/get-cart.mjs";
|
|
4
5
|
|
|
5
6
|
//#region src/core/request-routing/interceptors/checkout.ts
|
|
6
7
|
const log = getLogger("checkout");
|
|
7
8
|
const MOCK_SHOP_PERMALINK_ORIGIN = "https://demostore.mock.shop";
|
|
8
9
|
const handleCheckoutRedirect = (url, { request, storefrontClient }) => {
|
|
9
|
-
|
|
10
|
+
const isCheckout = CHECKOUT_RE.test(url.pathname);
|
|
11
|
+
if (!isCheckout && !CART_PERMALINK_RE.test(url.pathname)) return null;
|
|
10
12
|
if (request.method !== "GET" && request.method !== "HEAD") return Promise.resolve(new Response("Method Not Allowed", { status: 405 }));
|
|
11
|
-
return (
|
|
13
|
+
return (isCheckout ? getCheckoutRedirectUrl(request, storefrontClient) : getCartRedirectUrl(request, storefrontClient)).then((redirectUrl) => {
|
|
12
14
|
if (redirectUrl.pathname !== "/") {
|
|
13
15
|
mergeSearchParams(redirectUrl, url.searchParams);
|
|
14
16
|
redirectUrl.searchParams.set("payment", url.searchParams.get("payment") ?? "shop_pay");
|
|
15
17
|
}
|
|
18
|
+
const headers = new Headers({ location: redirectUrl.toString() });
|
|
19
|
+
applyPrivateResponseCacheHeaders(headers);
|
|
16
20
|
return new Response(null, {
|
|
17
21
|
status: 302,
|
|
18
|
-
headers
|
|
22
|
+
headers
|
|
19
23
|
});
|
|
20
24
|
}).catch((error) => {
|
|
21
25
|
log.error("checkout redirect request failed", { error });
|
|
22
26
|
const message = error instanceof Error ? error.message : "Internal redirect error";
|
|
27
|
+
const headers = new Headers({ "content-type": "application/json" });
|
|
28
|
+
applyPrivateResponseCacheHeaders(headers);
|
|
23
29
|
return new Response(JSON.stringify({ error: message }), {
|
|
24
30
|
status: 502,
|
|
25
|
-
headers
|
|
31
|
+
headers
|
|
26
32
|
});
|
|
27
33
|
});
|
|
28
34
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/checkout.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../../client\";\nimport { getCart, getCartId } from \"../../cart/get-cart\";\nimport { getLogger } from \"../../logging\";\nimport { BUY_PERMALINK_RE,
|
|
1
|
+
{"version":3,"file":"checkout.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/checkout.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../../client\";\nimport { getCart, getCartId } from \"../../cart/get-cart\";\nimport { applyPrivateResponseCacheHeaders } from \"../../headers\";\nimport { getLogger } from \"../../logging\";\nimport { BUY_PERMALINK_RE, CART_PERMALINK_RE, CHECKOUT_RE } from \"../../url\";\nimport type { HydrogenRouteInterceptor } from \"../route-types\";\n\nconst log = getLogger(\"checkout\");\nconst MOCK_SHOP_PERMALINK_ORIGIN = \"https://demostore.mock.shop\";\n\nexport const handleCheckoutRedirect: HydrogenRouteInterceptor = (\n url,\n { request, storefrontClient },\n) => {\n // Match only checkout and cart permalinks. Customer account handoff paths belong to the app\n // router or registered customer account handlers, which run earlier in the interceptor list.\n const isCheckout = CHECKOUT_RE.test(url.pathname);\n if (!isCheckout && !CART_PERMALINK_RE.test(url.pathname)) {\n return null;\n }\n\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n return Promise.resolve(new Response(\"Method Not Allowed\", { status: 405 }));\n }\n\n const redirectUrlPromise = isCheckout\n ? getCheckoutRedirectUrl(request, storefrontClient)\n : getCartRedirectUrl(request, storefrontClient);\n\n return redirectUrlPromise\n .then((redirectUrl) => {\n if (redirectUrl.pathname !== \"/\") {\n mergeSearchParams(redirectUrl, url.searchParams);\n redirectUrl.searchParams.set(\"payment\", url.searchParams.get(\"payment\") ?? \"shop_pay\");\n }\n\n // The location can carry a buyer-specific checkout URL, so shared caches must never store it.\n const headers = new Headers({ location: redirectUrl.toString() });\n applyPrivateResponseCacheHeaders(headers);\n return new Response(null, { status: 302, headers });\n })\n .catch((error) => {\n log.error(\"checkout redirect request failed\", { error });\n const message = error instanceof Error ? error.message : \"Internal redirect error\";\n\n // The error message can name cart IDs or SFAPI details, so keep it out of shared caches too.\n const headers = new Headers({ \"content-type\": \"application/json\" });\n applyPrivateResponseCacheHeaders(headers);\n return new Response(JSON.stringify({ error: message }), { status: 502, headers });\n });\n};\n\nexport const handleBuyPermalinkRedirect: HydrogenRouteInterceptor = (\n url,\n { request, storefrontClient },\n) => {\n if (!BUY_PERMALINK_RE.test(url.pathname)) {\n return null;\n }\n\n if (request.method !== \"GET\") {\n return Promise.resolve(new Response(\"Method Not Allowed\", { status: 405 }));\n }\n\n // UCP permalink response shape (303, no-store, no-referrer), forwarded verbatim since re-encoding would alter `continue_to`.\n // https://ucp.dev/2026-08-25/specification/permalink/#redirect-resolution\n const location = `${getPermalinkOrigin(storefrontClient.storeUrl)}${url.pathname}${url.search}`;\n return Promise.resolve(\n new Response(null, {\n status: 303,\n headers: { location, \"cache-control\": \"no-store\", \"referrer-policy\": \"no-referrer\" },\n }),\n );\n};\n\nasync function getCheckoutRedirectUrl(\n request: Request,\n storefrontClient: StorefrontClient,\n): Promise<URL> {\n const cartId = getCartId(request);\n if (!cartId) return new URL(\"/\", request.url);\n\n const result = await getCart(cartId, storefrontClient);\n return result.cart?.checkoutUrl ? new URL(result.cart.checkoutUrl) : new URL(\"/\", request.url);\n}\n\nasync function getCartRedirectUrl(\n request: Request,\n storefrontClient: StorefrontClient,\n): Promise<URL> {\n const sourceUrl = new URL(request.url);\n const redirectUrl = new URL(sourceUrl.pathname, getPermalinkOrigin(storefrontClient.storeUrl));\n\n const cartId = getCartId(request);\n if (!cartId) return redirectUrl;\n\n try {\n const result = await getCart(cartId, storefrontClient);\n if (result.cart?.checkoutUrl) {\n mergeSearchParams(redirectUrl, new URL(result.cart.checkoutUrl).searchParams);\n }\n } catch (error) {\n log.warn(\"checkout redirect could not load cart permalink tracking params\", { error });\n }\n\n return redirectUrl;\n}\n\nfunction getPermalinkOrigin(storeUrl: string): string {\n const url = new URL(storeUrl);\n return isMockShopHost(url.hostname) ? MOCK_SHOP_PERMALINK_ORIGIN : url.origin;\n}\n\n// mock.shop serves many stores, each on its own host (pets.mock.shop, ...), and\n// none of them renders cart or buy permalinks, so every mock host hands off to the demo store.\nfunction isMockShopHost(hostname: string): boolean {\n return hostname === \"mock.shop\" || hostname.endsWith(\".mock.shop\");\n}\n\nfunction mergeSearchParams(target: URL, source: URLSearchParams): void {\n for (const [key, value] of source) {\n if (!target.searchParams.has(key)) target.searchParams.append(key, value);\n }\n}\n"],"mappings":"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"}
|
|
@@ -6,7 +6,7 @@ function handleStandardRouteRedirects({ request, storefrontClient, routeTemplate
|
|
|
6
6
|
const url = new URL(request.url);
|
|
7
7
|
const target = getStandardRouteTarget({
|
|
8
8
|
pathname: url.pathname,
|
|
9
|
-
pathPrefix: storefrontClient.requestContext.
|
|
9
|
+
pathPrefix: storefrontClient.requestContext.locale.pathPrefix,
|
|
10
10
|
routeTemplates
|
|
11
11
|
});
|
|
12
12
|
if (!target) return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard-routes.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/standard-routes.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../../client\";\nimport {\n getStandardRouteTarget,\n isStandardRouteSelfRedirect,\n type ShopifyRouteTemplates,\n} from \"../../standard-routes/index\";\nimport { createRedirectLocation, createRedirectResponse } from \"./url-redirects\";\n\nexport function handleStandardRouteRedirects({\n request,\n storefrontClient,\n routeTemplates,\n}: {\n request: Request;\n storefrontClient: StorefrontClient;\n routeTemplates: ShopifyRouteTemplates;\n}): Response | null {\n const url = new URL(request.url);\n const target = getStandardRouteTarget({\n pathname: url.pathname,\n pathPrefix: storefrontClient.requestContext.
|
|
1
|
+
{"version":3,"file":"standard-routes.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/standard-routes.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../../client\";\nimport {\n getStandardRouteTarget,\n isStandardRouteSelfRedirect,\n type ShopifyRouteTemplates,\n} from \"../../standard-routes/index\";\nimport { createRedirectLocation, createRedirectResponse } from \"./url-redirects\";\n\nexport function handleStandardRouteRedirects({\n request,\n storefrontClient,\n routeTemplates,\n}: {\n request: Request;\n storefrontClient: StorefrontClient;\n routeTemplates: ShopifyRouteTemplates;\n}): Response | null {\n const url = new URL(request.url);\n const target = getStandardRouteTarget({\n pathname: url.pathname,\n pathPrefix: storefrontClient.requestContext.locale.pathPrefix,\n routeTemplates,\n });\n\n if (!target) return null;\n\n const location = createRedirectLocation(target, url.searchParams);\n\n return isStandardRouteSelfRedirect(request.url, location)\n ? null\n : createRedirectResponse(location);\n}\n"],"mappings":";;;;AAQA,SAAgB,6BAA6B,EAC3C,SACA,kBACA,kBAKkB;CAClB,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;CAChC,MAAM,SAAS,uBAAuB;EACpC,UAAU,IAAI;EACd,YAAY,iBAAiB,eAAe,OAAO;EACnD;EACD,CAAC;AAEF,KAAI,CAAC,OAAQ,QAAO;CAEpB,MAAM,WAAW,uBAAuB,QAAQ,IAAI,aAAa;AAEjE,QAAO,4BAA4B,QAAQ,KAAK,SAAS,GACrD,OACA,uBAAuB,SAAS"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trimTrailingSlashes } from "../../standard-routes/path.mjs";
|
|
1
2
|
import { gql } from "../../../graphql/graphql.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/core/request-routing/interceptors/url-redirects.ts
|
|
@@ -5,7 +6,7 @@ const REDIRECT_QUERY = gql(`query redirects($query:String){urlRedirects(first:1
|
|
|
5
6
|
const PLACEHOLDER_BASE = "https://0.0.0.0";
|
|
6
7
|
async function handleUrlRedirects({ request, storefrontClient }) {
|
|
7
8
|
const { pathname, searchParams } = new URL(request.url);
|
|
8
|
-
const queryPath = pathname.toLowerCase()
|
|
9
|
+
const queryPath = trimTrailingSlashes(pathname.toLowerCase());
|
|
9
10
|
const result = await storefrontClient.graphql(REDIRECT_QUERY, { variables: { query: `path:${queryPath}` } });
|
|
10
11
|
if (result.errors) {
|
|
11
12
|
const messages = result.errors.map(({ message }) => message).join(", ");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-redirects.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/url-redirects.ts"],"sourcesContent":["import { gql } from \"../../../graphql\";\nimport type { RedirectOptions } from \"../handle-shopify-redirects\";\n\ntype UrlRedirectOptions = Pick<RedirectOptions, \"request\" | \"storefrontClient\">;\n\nconst REDIRECT_QUERY = gql(`\n query redirects($query: String) {\n urlRedirects(first: 1, query: $query) {\n edges {\n node {\n target\n }\n }\n }\n }\n`);\n\n// Used as a base for `new URL()` when constructing relative redirect URLs.\n// Stripped from the output — only needed because `new URL` requires a base for relative paths.\nconst PLACEHOLDER_BASE = \"https://0.0.0.0\";\n\nexport async function handleUrlRedirects({\n request,\n storefrontClient,\n}: UrlRedirectOptions): Promise<Response | null> {\n const url = new URL(request.url);\n const { pathname, searchParams } = url;\n\n const queryPath = pathname.toLowerCase()
|
|
1
|
+
{"version":3,"file":"url-redirects.mjs","names":[],"sources":["../../../../../src/core/request-routing/interceptors/url-redirects.ts"],"sourcesContent":["import { gql } from \"../../../graphql\";\nimport { trimTrailingSlashes } from \"../../standard-routes/path\";\nimport type { RedirectOptions } from \"../handle-shopify-redirects\";\n\ntype UrlRedirectOptions = Pick<RedirectOptions, \"request\" | \"storefrontClient\">;\n\nconst REDIRECT_QUERY = gql(`\n query redirects($query: String) {\n urlRedirects(first: 1, query: $query) {\n edges {\n node {\n target\n }\n }\n }\n }\n`);\n\n// Used as a base for `new URL()` when constructing relative redirect URLs.\n// Stripped from the output — only needed because `new URL` requires a base for relative paths.\nconst PLACEHOLDER_BASE = \"https://0.0.0.0\";\n\nexport async function handleUrlRedirects({\n request,\n storefrontClient,\n}: UrlRedirectOptions): Promise<Response | null> {\n const url = new URL(request.url);\n const { pathname, searchParams } = url;\n\n const queryPath = trimTrailingSlashes(pathname.toLowerCase());\n const result = await storefrontClient.graphql(REDIRECT_QUERY, {\n variables: { query: `path:${queryPath}` },\n });\n\n if (result.errors) {\n const messages = result.errors.map(({ message }) => message).join(\", \");\n throw new Error(`Storefront API errors: ${messages}`, { cause: result.errors });\n }\n\n const target = result.data?.urlRedirects?.edges[0]?.node.target;\n if (!target) return null;\n\n return createRedirectResponse(createRedirectLocation(target, searchParams));\n}\n\nexport function createRedirectLocation(location: string, searchParams: URLSearchParams): string {\n const url = new URL(location, PLACEHOLDER_BASE);\n\n for (const [key, value] of searchParams) {\n url.searchParams.append(key, value);\n }\n\n return url.toString().replace(PLACEHOLDER_BASE, \"\");\n}\n\nexport function createRedirectResponse(location: string, status: number = 301): Response {\n return new Response(null, {\n status,\n headers: { location },\n });\n}\n"],"mappings":";;;;AAMA,MAAA,iBAAA,IAAA,0FAUA;AAIA,MAAA,mBAAA;AAEA,eAAA,mBAAA,EACA,SACA,oBACA;CAEA,MAAA,EAAA,UAAA,iBAAA,IADA,IAAA,QAAA,IACA;CAEA,MAAA,YAAA,oBAAA,SAAA,aAAA,CAAA;CACA,MAAA,SAAA,MAAA,iBAAA,QAAA,gBAAA,EACA,WAAA,EAAA,OAAA,QAAA,aAAA,EACA,CAAA;AAEA,KAAA,OAAA,QAAA;EACA,MAAA,WAAA,OAAA,OAAA,KAAA,EAAA,cAAA,QAAA,CAAA,KAAA,KAAA;AACA,QAAA,IAAA,MAAA,0BAAA,YAAA,EAAA,OAAA,OAAA,QAAA,CAAA;;CAGA,MAAA,SAAA,OAAA,MAAA,cAAA,MAAA,IAAA,KAAA;AACA,KAAA,CAAA,OAAA,QAAA;AAEA,QAAA,uBAAA,uBAAA,QAAA,aAAA,CAAA;;AAGA,SAAA,uBAAA,UAAA,cAAA;CACA,MAAA,MAAA,IAAA,IAAA,UAAA,iBAAA;AAEA,MAAA,MAAA,CAAA,KAAA,UAAA,aACA,KAAA,aAAA,OAAA,KAAA,MAAA;AAGA,QAAA,IAAA,UAAA,CAAA,QAAA,kBAAA,GAAA;;AAGA,SAAA,uBAAA,UAAA,SAAA,KAAA;AACA,QAAA,IAAA,SAAA,MAAA;EACA;EACA,SAAA,EAAA,UAAA;EACA,CAAA"}
|
|
@@ -9,15 +9,22 @@ import { CallableRouteHandler, ShopifyRedirectStatus, ShopifyRouteError, Shopify
|
|
|
9
9
|
*
|
|
10
10
|
* Annotate the handler's context parameter with only the fields the handler reads, for example
|
|
11
11
|
* `Omit<ShopifyRouteHandlerContext, "sessionManager">`, so apps without a session manager can
|
|
12
|
-
* register it.
|
|
12
|
+
* register it. Hydrogen infers the context only from an annotated parameter. A handler with no
|
|
13
|
+
* parameter, or with an unannotated destructured parameter, gets the full context, so
|
|
14
|
+
* `handleShopifyRoutes` still requires `sessionManager` for it.
|
|
15
|
+
*
|
|
16
|
+
* Marking `sessionManager` optional in the annotation doesn't make it optional at runtime. It
|
|
17
|
+
* still makes `sessionManager` required, and when an untyped caller omits it, Hydrogen passes a
|
|
18
|
+
* stand-in that throws when the handler uses it. A check such as `if (sessionManager)` is always
|
|
19
|
+
* true, so don't use it as a fallback.
|
|
13
20
|
*
|
|
14
21
|
* @param pathname The exact URL pathname that the handler matches. Hydrogen doesn't match path parameters or prefixes.
|
|
15
22
|
* @param method The HTTP method that the handler matches, in uppercase, such as `POST`.
|
|
16
|
-
* @param handler The function that receives the request, its context, the session, and the Storefront API client, and returns a JSON, redirect, or error result.
|
|
23
|
+
* @param handler The function that receives the request, its context, the session manager, and the Storefront API client, and returns a JSON, redirect, or error result.
|
|
17
24
|
* @returns The handler to add to a handler object.
|
|
18
25
|
* @publicDocs
|
|
19
26
|
*/
|
|
20
|
-
declare function createShopifyRouteHandler<const TPathname extends string, const TMethod extends string, TContext extends Partial<ShopifyRouteHandlerContext> = ShopifyRouteHandlerContext>(pathname: TPathname, method: TMethod, handler: (context: TContext) => Promise<ShopifyRouteHandlerResult>):
|
|
27
|
+
declare function createShopifyRouteHandler<const TPathname extends string, const TMethod extends string, TContext extends Partial<ShopifyRouteHandlerContext> = ShopifyRouteHandlerContext>(pathname: TPathname, method: TMethod, handler: (context: TContext) => Promise<ShopifyRouteHandlerResult>): ShopifyRouteHandler<TPathname, TMethod, TContext>;
|
|
21
28
|
//#endregion
|
|
22
29
|
export { createShopifyRouteHandler };
|
|
23
30
|
//# sourceMappingURL=registered-routes.d.mts.map
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { stripI18nPathPrefix } from "../standard-routes/path.mjs";
|
|
2
|
+
|
|
1
3
|
//#region src/core/request-routing/registered-routes.ts
|
|
2
4
|
const HTTP_OK_STATUS = 200;
|
|
3
5
|
const HTTP_SEE_OTHER_STATUS = 303;
|
|
@@ -18,11 +20,18 @@ const VALID_REDIRECT_STATUSES = [
|
|
|
18
20
|
*
|
|
19
21
|
* Annotate the handler's context parameter with only the fields the handler reads, for example
|
|
20
22
|
* `Omit<ShopifyRouteHandlerContext, "sessionManager">`, so apps without a session manager can
|
|
21
|
-
* register it.
|
|
23
|
+
* register it. Hydrogen infers the context only from an annotated parameter. A handler with no
|
|
24
|
+
* parameter, or with an unannotated destructured parameter, gets the full context, so
|
|
25
|
+
* `handleShopifyRoutes` still requires `sessionManager` for it.
|
|
26
|
+
*
|
|
27
|
+
* Marking `sessionManager` optional in the annotation doesn't make it optional at runtime. It
|
|
28
|
+
* still makes `sessionManager` required, and when an untyped caller omits it, Hydrogen passes a
|
|
29
|
+
* stand-in that throws when the handler uses it. A check such as `if (sessionManager)` is always
|
|
30
|
+
* true, so don't use it as a fallback.
|
|
22
31
|
*
|
|
23
32
|
* @param pathname The exact URL pathname that the handler matches. Hydrogen doesn't match path parameters or prefixes.
|
|
24
33
|
* @param method The HTTP method that the handler matches, in uppercase, such as `POST`.
|
|
25
|
-
* @param handler The function that receives the request, its context, the session, and the Storefront API client, and returns a JSON, redirect, or error result.
|
|
34
|
+
* @param handler The function that receives the request, its context, the session manager, and the Storefront API client, and returns a JSON, redirect, or error result.
|
|
26
35
|
* @returns The handler to add to a handler object.
|
|
27
36
|
* @publicDocs
|
|
28
37
|
*/
|
|
@@ -38,7 +47,8 @@ function createCallableRouteHandler(pathname, method, handler) {
|
|
|
38
47
|
const handleShopifyRouteHandlers = (url, { request, sessionManager, storefrontClient, requestContext, handlers = [] }) => {
|
|
39
48
|
const routeHandlers = handlers.flatMap((group) => Object.values(group));
|
|
40
49
|
if (routeHandlers.length === 0) return null;
|
|
41
|
-
const
|
|
50
|
+
const pathname = stripI18nPathPrefix(url.pathname, requestContext.locale.pathPrefix);
|
|
51
|
+
const pathMatches = routeHandlers.filter((entry) => entry.pathname === pathname);
|
|
42
52
|
if (pathMatches.length === 0) return null;
|
|
43
53
|
const match = pathMatches.find((candidate) => candidate.method === request.method);
|
|
44
54
|
if (!match) return Promise.resolve(new Response("Method Not Allowed", { status: HTTP_METHOD_NOT_ALLOWED_STATUS }));
|