@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
package/dist/core/index.d.mts
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
import { Cache, CacheOptions, CachingStrategy } from "./cache/strategies.mjs";
|
|
2
2
|
import { CacheInstance, createRunWithCache } from "./cache/run-with-cache.mjs";
|
|
3
3
|
import { ProductCollectionSortKeys } from "../graphql/generated/storefront-api-types.mjs";
|
|
4
|
+
import { ShopifyCountryCode, ShopifyDomainLocale, ShopifyI18n, ShopifyI18nRouting, ShopifyLanguageCode, ShopifyLocale, ShopifyMatchedLocale, ShopifyPathnameLocale, ShopifySupportedLocale } from "./i18n/types.mjs";
|
|
4
5
|
import { I18nConfig, ShopifyRequestContext, ShopifyRequestContextWithBuyerIp, createShopifyRequestContext } from "./request-context.mjs";
|
|
5
6
|
import { InferResult, InferVariables } from "../graphql/type-resolver.mjs";
|
|
6
7
|
import { AnyStorefrontQueryString, StorefrontQueryString, gql } from "../graphql/graphql.mjs";
|
|
7
8
|
import { ClientType, CreateStorefrontClientArgs, GqlRestParam, GraphQLFormattedError, PrivateClientOptions, PrivateNoBuyerContextClientOptions, PrivateNoBuyerContextStorefrontClient, PrivateStorefrontClient, PublicClientOptions, PublicStorefrontClient, RequestScopedPrivateStorefrontClient, StorefrontApi, StorefrontClient, StorefrontClientOptions, StorefrontGraphql, StorefrontGraphqlOptions, StorefrontGraphqlResult } from "../client/types.mjs";
|
|
8
9
|
import { createStorefrontClient } from "../client/client.mjs";
|
|
9
10
|
import { ShopifyRouteTemplates } from "./standard-routes/types.mjs";
|
|
10
|
-
import { createShopifyRouteTemplates } from "./standard-routes/build.mjs";
|
|
11
|
+
import { createShopifyRouteTemplates, defineShopifyRouteTemplates } from "./standard-routes/build.mjs";
|
|
11
12
|
import { RedirectOptions, handleShopifyRedirects } from "./request-routing/handle-shopify-redirects.mjs";
|
|
13
|
+
import { defineShopifyI18n, getSupportedLocales } from "./i18n/define.mjs";
|
|
14
|
+
import { UnsupportedLocaleError } from "./i18n/errors.mjs";
|
|
15
|
+
import { GetLocalizedHrefOptions, getLocalizedHref } from "./i18n/href.mjs";
|
|
16
|
+
import { getLocalePathSegment, isSameLocale } from "./i18n/locale.mjs";
|
|
17
|
+
import { LocaleMatchSource, matchLocale, resolveSupportedLocale } from "./i18n/match.mjs";
|
|
12
18
|
import { CallableRouteHandler, ShopifyRedirectStatus, ShopifyRouteError, ShopifyRouteErrorResult, ShopifyRouteHandler, ShopifyRouteHandlerContext, ShopifyRouteHandlerGroup, ShopifyRouteHandlerResult, ShopifyRouteJsonResult, ShopifyRouteRedirectResult } from "./request-routing/route-types.mjs";
|
|
13
19
|
import { handleShopifyRoutes } from "./request-routing/handle-shopify-routes.mjs";
|
|
14
20
|
import { createShopifyRouteHandler } from "./request-routing/registered-routes.mjs";
|
|
21
|
+
import { ContentSecurityPolicy, ContentSecurityPolicyDirectives, ContentSecurityPolicyShop, CreateContentSecurityPolicyOptions } from "./csp/types.mjs";
|
|
22
|
+
import { createContentSecurityPolicy, getShopifyCspDirectives } from "./csp/index.mjs";
|
|
15
23
|
import { createFetchWithCache } from "./cache/fetch-with-cache.mjs";
|
|
16
24
|
import { StorefrontApiError, StorefrontTimeoutError } from "../client/errors.mjs";
|
|
17
25
|
import { ProductFilter } from "../vendor/standard-events.mjs";
|
|
@@ -22,7 +30,7 @@ import { AnalyticsEvent, AnalyticsEventName } from "./analytics/events.mjs";
|
|
|
22
30
|
import { ShopifyGlobal } from "../globals.mjs";
|
|
23
31
|
import { ShopifyRoutesOptions, ShopifyScriptTagDescriptor, ShopifyScriptTagDescriptors, ShopifyScriptTagsOptions, ShopifyScriptsAnalyticsConfig, ShopifyScriptsI18n, ShopifyScriptsOptions, ShopifyScriptsShop } from "./shopify-scripts/types.mjs";
|
|
24
32
|
import { AnalyticsCart, AnalyticsCartLine, AnalyticsEventMap, AnalyticsTrackingValues, CartLineUpdatePayload, CartUpdatePayload, CartViewPayload, CollectionViewPayload, ConsentConfig, ConsentPreferences, ConsentSetup, OtherData, PageViewPayload, PayloadFor, ProductPayload, ProductViewPayload, SearchViewPayload, ShopAnalytics, StorefrontAnalytics, StorefrontAnalyticsConfig, StorefrontAnalyticsDestination, StorefrontAnalyticsDestinationEventContext, StorefrontAnalyticsDestinationSetupContext } from "./analytics/types.mjs";
|
|
25
|
-
import { CartFormRegister, QuantityInputAttributes, SetButtonAttributes, createCartFormRegister } from "./cart/form.mjs";
|
|
33
|
+
import { CartFormRegister, QuantityInputAttributes, RemoveButtonAttributes, SetButtonAttributes, createCartFormRegister } from "./cart/form.mjs";
|
|
26
34
|
import { attachQuantityInput } from "./cart/attach-quantity-input.mjs";
|
|
27
35
|
import { CartAction, CartAttributeInput, CartLineAddInput, CartLineUpdateInput, parseCartRequest } from "./cart/actions.mjs";
|
|
28
36
|
import { cartQueries } from "./cart/queries.mjs";
|
|
@@ -30,6 +38,7 @@ import { createCartCookie } from "./cart/cookie.mjs";
|
|
|
30
38
|
import { CartDataFromQuery, CartResult, getCart, getCartId } from "./cart/get-cart.mjs";
|
|
31
39
|
import { CartDataFromHandlers, CartError, CartErrorCode, CartGetData, CartGetHandler, CartGetResult, CartPostHandler, CartPostResult, CartServerHandlers, CartServerHandlersWithCustomerSession, CreateCartServerHandlersOptions, createCartServerHandlers } from "./cart/server-handlers.mjs";
|
|
32
40
|
import { DEFAULT_MINIMUM_QUANTITY, NO_QUANTITY_LIMIT, sanitizeQuantity } from "./cart/quantity.mjs";
|
|
41
|
+
import { getShopifyScriptHashes } from "./shopify-scripts/hashes.mjs";
|
|
33
42
|
import { initializeShopifyScripts } from "./shopify-scripts/initialize.mjs";
|
|
34
43
|
import { getShopifyScriptTags, renderShopifyScriptTags } from "./shopify-scripts/index.mjs";
|
|
35
44
|
import { AvailableFilter, AvailableFilterValue, CollectionState, FilterPresentation, FilterType, createInitialCollectionState } from "./collection/state.mjs";
|
|
@@ -45,12 +54,12 @@ import { SHOP_PAY_BUTTON_TAG_NAME, ShopPayButtonOptions, createShopPayButton, de
|
|
|
45
54
|
import { PredictiveSearchFormAttributes, PredictiveSearchFormRegister, PredictiveSearchQueryInputAttributes, createPredictiveSearchFormRegister, getPredictiveSearchFormAttributes, readPredictiveSearchFormTerm } from "./predictive-search/form.mjs";
|
|
46
55
|
import { CreatePredictiveSearchQueriesOptions, PredictiveSearchFragments, makePredictiveSearchQueries } from "./predictive-search/queries.mjs";
|
|
47
56
|
import { PredictiveSearchData, QueryPredictiveSearchOptions, queryPredictiveSearch } from "./predictive-search/search.mjs";
|
|
48
|
-
import { CreatePredictiveSearchServerHandlersOptions, createPredictiveSearchServerHandlers } from "./predictive-search/server-handlers.mjs";
|
|
57
|
+
import { CreatePredictiveSearchServerHandlersOptions, PredictiveSearchDataFromHandlers, createPredictiveSearchServerHandlers } from "./predictive-search/server-handlers.mjs";
|
|
49
58
|
import { CreatePredictiveSearchStoreOptions, PredictiveSearchActions, PredictiveSearchState, PredictiveSearchStatus, PredictiveSearchStore, createPredictiveSearchStore } from "./predictive-search/store.mjs";
|
|
50
|
-
import { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, getPredictiveSearchItemUrl, getSearchResultUrl } from "./predictive-search/url.mjs";
|
|
59
|
+
import { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, SearchResultUrlOptions, getPredictiveSearchItemUrl, getSearchResultUrl } from "./predictive-search/url.mjs";
|
|
51
60
|
import { FormatMoneyOptions, FormattedMoney, FormattedMoneyRange, MoneyV2 } from "./money/types.mjs";
|
|
52
61
|
import { formatMoney } from "./money/format.mjs";
|
|
53
62
|
import { flattenConnection } from "./analytics/utils/flatten-connection.mjs";
|
|
54
63
|
import { HydrogenLogger, LogContext, LogLevel } from "./logging/types.mjs";
|
|
55
64
|
import { ConfigureLoggingOptions, configureLogging } from "./logging/logging.mjs";
|
|
56
|
-
export { type AnalyticsCart, type AnalyticsCartLine, AnalyticsEvent, type AnalyticsEventMap, type AnalyticsEventName, type AnalyticsTrackingValues, type AnyStorefrontQueryString, type Attribute, type AvailableFilter, type AvailableFilterValue, Cache, type CacheInstance, type CacheOptions, type CachingStrategy, type CallableRouteHandler, type CartAction, type CartActions, type CartAttributeInput, type CartCost, type CartData, type CartDataFromHandlers, type CartDataFromQuery, type CartError, type CartErrorCode, type CartErrorGroup, type CartErrorState, type CartFormRegister, type CartGetData, type CartGetHandler, type CartGetResult, type CartLine, type CartLineAddInput, type CartLineConnection, type CartLineCost, type CartLineMerchandise, type CartLineUpdateInput, type CartLineUpdatePayload, type CartNetworkEntry, CartNetworkError, type CartPending, type CartPostHandler, type CartPostResult, type CartResult, type CartServerHandlers, type CartServerHandlersWithCustomerSession, type CartState, type CartStore, type CartUpdatePayload, type CartUserError, type CartViewPayload, type CartWarning, type ClientType, type CollectionActions, type CollectionData, type CollectionParams, type CollectionReconciler, type CollectionState, type CollectionStore, type CollectionViewPayload, type ConfigureLoggingOptions, type ConsentConfig, type ConsentPreferences, type ConsentSetup, type CreateCartServerHandlersOptions, type CreateCartStoreOptions, type CreateCollectionStoreOptions, type CreatePredictiveSearchQueriesOptions, type CreatePredictiveSearchServerHandlersOptions, type CreatePredictiveSearchStoreOptions, type CreateProductFormStoreOptions, type CreateStorefrontClientArgs, DEFAULT_MINIMUM_QUANTITY, type DiscountCode, EMPTY_CART_DATA, EMPTY_CART_STATE, type FilterPresentation, type FilterType, type FormatMoneyOptions, type FormattedMoney, type FormattedMoneyRange, type GqlRestParam, type GraphQLFormattedError, type HydrogenLogger, type I18nConfig, type InferResult, type InferVariables, type LogContext, type LogLevel, type MoneyV2, NO_QUANTITY_LIMIT, type OtherData, type PageViewPayload, type PayloadFor, type PredictiveSearchActions, type PredictiveSearchArticleItem, type PredictiveSearchCollectionItem, type PredictiveSearchData, type PredictiveSearchFormAttributes, type PredictiveSearchFormRegister, type PredictiveSearchFragments, type PredictiveSearchItem, type PredictiveSearchItemUrlOptions, type PredictiveSearchPageItem, type PredictiveSearchProductItem, type PredictiveSearchQueryInputAttributes, type PredictiveSearchQueryItem, type PredictiveSearchQueryItemUrlOptions, type PredictiveSearchResourceItem, type PredictiveSearchState, type PredictiveSearchStatus, type PredictiveSearchStore, type PrivateClientOptions, type PrivateNoBuyerContextClientOptions, type PrivateNoBuyerContextStorefrontClient, type PrivateStorefrontClient, type ProductAddToCartProps, type ProductCollectionSortKeys, type ProductFilter, type ProductFormErrors, type ProductFormOptions, type ProductFormRegister, type ProductFormStore, type ProductFormStoreState, type ProductInput, type ProductMerchandiseIdProps, type ProductOptionInput, type ProductOptionValueInput, type ProductOptionValueProps, type ProductPayload, type ProductQuantityDefaultProps, type ProductQuantityProps, type ProductSelectionLinkStyle, type ProductVariantFrom, type ProductVariantInput, type ProductViewPayload, type PublicClientOptions, type PublicStorefrontClient, type QuantityInputAttributes, type QueryPredictiveSearchOptions, type ReconcilerCallbacks, type RedirectOptions, type RequestScopedPrivateStorefrontClient, SHOP_PAY_BUTTON_TAG_NAME, STANDARD_ACTION_TIMEOUT_IN_MS, type SearchViewPayload, type SelectedOption, type SetButtonAttributes, type ShopAnalytics, type ShopPayButtonOptions, type ShopifyGlobal, type ShopifyRedirectStatus, type ShopifyRequestContext, type ShopifyRequestContextWithBuyerIp, type ShopifyRouteError, type ShopifyRouteErrorResult, type ShopifyRouteHandler, type ShopifyRouteHandlerContext, type ShopifyRouteHandlerGroup, type ShopifyRouteHandlerResult, type ShopifyRouteJsonResult, type ShopifyRouteRedirectResult, type ShopifyRouteTemplates, type ShopifyRoutesOptions, type ShopifyScriptTagDescriptor, type ShopifyScriptTagDescriptors, type ShopifyScriptTagsOptions, type ShopifyScriptsAnalyticsConfig, type ShopifyScriptsI18n, type ShopifyScriptsOptions, type ShopifyScriptsShop, type StorefrontAnalytics, type StorefrontAnalyticsConfig, type StorefrontAnalyticsDestination, type StorefrontAnalyticsDestinationEventContext, type StorefrontAnalyticsDestinationSetupContext, type StorefrontApi, StorefrontApiError, type StorefrontClient, type StorefrontClientOptions, type StorefrontGraphql, type StorefrontGraphqlOptions, type StorefrontGraphqlResult, type StorefrontQueryString, StorefrontTimeoutError, type ValidProductSelectionResult, type VariantOptionState, type VariantOptionValueState, type VariantSelectionResult, attachQuantityInput, buildProductSelectionSearchParams, canAddToCart, cartQueries, configureCartEndpoint, configureLogging, createCartCookie, createCartFormRegister, createCartServerHandlers, createCartStore, createCollectionReconciler, createCollectionStore, createEmptyCartErrors, createEmptyErrorGroup, createFetchWithCache, createInitialCollectionState, createPredictiveSearchFormRegister, createPredictiveSearchServerHandlers, createPredictiveSearchStore, createProductFormRegister, createProductFormStore, createRunWithCache, createShopPayButton, createShopifyRequestContext, createShopifyRouteHandler, createShopifyRouteTemplates, createStorefrontClient, defineShopPayButton, filterEquals, findCartLineByMerchandiseId, flattenConnection, formatMoney, getCart, getCartId, getFilterRemovalUrl, getPredictiveSearchFormAttributes, getPredictiveSearchItemUrl, getSearchResultUrl, getSelectedProductOptions, getSelectedVariant, getShopPayButtonUrl, getShopifyScriptTags, getSortByValue, gql, handleShopifyRedirects, handleShopifyRoutes, initializeShopifyScripts, isFilterInputActive, makePredictiveSearchQueries, normalizeCollectionSearch, parseCartRequest, parseCollectionParams, parseSortByValue, queryPredictiveSearch, readPredictiveSearchFormTerm, renderShopPayButton, renderShopifyScriptTags, sanitizeQuantity, serializeCollectionParams, trackCartAnalytics };
|
|
65
|
+
export { type AnalyticsCart, type AnalyticsCartLine, AnalyticsEvent, type AnalyticsEventMap, type AnalyticsEventName, type AnalyticsTrackingValues, type AnyStorefrontQueryString, type Attribute, type AvailableFilter, type AvailableFilterValue, Cache, type CacheInstance, type CacheOptions, type CachingStrategy, type CallableRouteHandler, type CartAction, type CartActions, type CartAttributeInput, type CartCost, type CartData, type CartDataFromHandlers, type CartDataFromQuery, type CartError, type CartErrorCode, type CartErrorGroup, type CartErrorState, type CartFormRegister, type CartGetData, type CartGetHandler, type CartGetResult, type CartLine, type CartLineAddInput, type CartLineConnection, type CartLineCost, type CartLineMerchandise, type CartLineUpdateInput, type CartLineUpdatePayload, type CartNetworkEntry, CartNetworkError, type CartPending, type CartPostHandler, type CartPostResult, type CartResult, type CartServerHandlers, type CartServerHandlersWithCustomerSession, type CartState, type CartStore, type CartUpdatePayload, type CartUserError, type CartViewPayload, type CartWarning, type ClientType, type CollectionActions, type CollectionData, type CollectionParams, type CollectionReconciler, type CollectionState, type CollectionStore, type CollectionViewPayload, type ConfigureLoggingOptions, type ConsentConfig, type ConsentPreferences, type ConsentSetup, type ContentSecurityPolicy, type ContentSecurityPolicyDirectives, type ContentSecurityPolicyShop, type CreateCartServerHandlersOptions, type CreateCartStoreOptions, type CreateCollectionStoreOptions, type CreateContentSecurityPolicyOptions, type CreatePredictiveSearchQueriesOptions, type CreatePredictiveSearchServerHandlersOptions, type CreatePredictiveSearchStoreOptions, type CreateProductFormStoreOptions, type CreateStorefrontClientArgs, DEFAULT_MINIMUM_QUANTITY, type DiscountCode, EMPTY_CART_DATA, EMPTY_CART_STATE, type FilterPresentation, type FilterType, type FormatMoneyOptions, type FormattedMoney, type FormattedMoneyRange, type GetLocalizedHrefOptions, type GqlRestParam, type GraphQLFormattedError, type HydrogenLogger, type I18nConfig, type InferResult, type InferVariables, type LocaleMatchSource, type LogContext, type LogLevel, type MoneyV2, NO_QUANTITY_LIMIT, type OtherData, type PageViewPayload, type PayloadFor, type PredictiveSearchActions, type PredictiveSearchArticleItem, type PredictiveSearchCollectionItem, type PredictiveSearchData, type PredictiveSearchDataFromHandlers, type PredictiveSearchFormAttributes, type PredictiveSearchFormRegister, type PredictiveSearchFragments, type PredictiveSearchItem, type PredictiveSearchItemUrlOptions, type PredictiveSearchPageItem, type PredictiveSearchProductItem, type PredictiveSearchQueryInputAttributes, type PredictiveSearchQueryItem, type PredictiveSearchQueryItemUrlOptions, type PredictiveSearchResourceItem, type PredictiveSearchState, type PredictiveSearchStatus, type PredictiveSearchStore, type PrivateClientOptions, type PrivateNoBuyerContextClientOptions, type PrivateNoBuyerContextStorefrontClient, type PrivateStorefrontClient, type ProductAddToCartProps, type ProductCollectionSortKeys, type ProductFilter, type ProductFormErrors, type ProductFormOptions, type ProductFormRegister, type ProductFormStore, type ProductFormStoreState, type ProductInput, type ProductMerchandiseIdProps, type ProductOptionInput, type ProductOptionValueInput, type ProductOptionValueProps, type ProductPayload, type ProductQuantityDefaultProps, type ProductQuantityProps, type ProductSelectionLinkStyle, type ProductVariantFrom, type ProductVariantInput, type ProductViewPayload, type PublicClientOptions, type PublicStorefrontClient, type QuantityInputAttributes, type QueryPredictiveSearchOptions, type ReconcilerCallbacks, type RedirectOptions, type RemoveButtonAttributes, type RequestScopedPrivateStorefrontClient, SHOP_PAY_BUTTON_TAG_NAME, STANDARD_ACTION_TIMEOUT_IN_MS, type SearchResultUrlOptions, type SearchViewPayload, type SelectedOption, type SetButtonAttributes, type ShopAnalytics, type ShopPayButtonOptions, type ShopifyCountryCode, type ShopifyDomainLocale, type ShopifyGlobal, type ShopifyI18n, type ShopifyI18nRouting, type ShopifyLanguageCode, type ShopifyLocale, type ShopifyMatchedLocale, type ShopifyPathnameLocale, type ShopifyRedirectStatus, type ShopifyRequestContext, type ShopifyRequestContextWithBuyerIp, type ShopifyRouteError, type ShopifyRouteErrorResult, type ShopifyRouteHandler, type ShopifyRouteHandlerContext, type ShopifyRouteHandlerGroup, type ShopifyRouteHandlerResult, type ShopifyRouteJsonResult, type ShopifyRouteRedirectResult, type ShopifyRouteTemplates, type ShopifyRoutesOptions, type ShopifyScriptTagDescriptor, type ShopifyScriptTagDescriptors, type ShopifyScriptTagsOptions, type ShopifyScriptsAnalyticsConfig, type ShopifyScriptsI18n, type ShopifyScriptsOptions, type ShopifyScriptsShop, type ShopifySupportedLocale, type StorefrontAnalytics, type StorefrontAnalyticsConfig, type StorefrontAnalyticsDestination, type StorefrontAnalyticsDestinationEventContext, type StorefrontAnalyticsDestinationSetupContext, type StorefrontApi, StorefrontApiError, type StorefrontClient, type StorefrontClientOptions, type StorefrontGraphql, type StorefrontGraphqlOptions, type StorefrontGraphqlResult, type StorefrontQueryString, StorefrontTimeoutError, UnsupportedLocaleError, type ValidProductSelectionResult, type VariantOptionState, type VariantOptionValueState, type VariantSelectionResult, attachQuantityInput, buildProductSelectionSearchParams, canAddToCart, cartQueries, configureCartEndpoint, configureLogging, createCartCookie, createCartFormRegister, createCartServerHandlers, createCartStore, createCollectionReconciler, createCollectionStore, createContentSecurityPolicy, createEmptyCartErrors, createEmptyErrorGroup, createFetchWithCache, createInitialCollectionState, createPredictiveSearchFormRegister, createPredictiveSearchServerHandlers, createPredictiveSearchStore, createProductFormRegister, createProductFormStore, createRunWithCache, createShopPayButton, createShopifyRequestContext, createShopifyRouteHandler, createShopifyRouteTemplates, createStorefrontClient, defineShopPayButton, defineShopifyI18n, defineShopifyRouteTemplates, filterEquals, findCartLineByMerchandiseId, flattenConnection, formatMoney, getCart, getCartId, getFilterRemovalUrl, getLocalePathSegment, getLocalizedHref, getPredictiveSearchFormAttributes, getPredictiveSearchItemUrl, getSearchResultUrl, getSelectedProductOptions, getSelectedVariant, getShopPayButtonUrl, getShopifyCspDirectives, getShopifyScriptHashes, getShopifyScriptTags, getSortByValue, getSupportedLocales, gql, handleShopifyRedirects, handleShopifyRoutes, initializeShopifyScripts, isFilterInputActive, isSameLocale, makePredictiveSearchQueries, matchLocale, normalizeCollectionSearch, parseCartRequest, parseCollectionParams, parseSortByValue, queryPredictiveSearch, readPredictiveSearchFormTerm, renderShopPayButton, renderShopifyScriptTags, resolveSupportedLocale, sanitizeQuantity, serializeCollectionParams, trackCartAnalytics };
|
package/dist/core/index.mjs
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import { createShopifyRouteTemplates } from "./standard-routes/build.mjs";
|
|
1
|
+
import { createShopifyRouteTemplates, defineShopifyRouteTemplates } from "./standard-routes/build.mjs";
|
|
2
|
+
import { getLocalePathSegment, isSameLocale } from "./i18n/locale.mjs";
|
|
3
|
+
import { defineShopifyI18n, getSupportedLocales } from "./i18n/define.mjs";
|
|
4
|
+
import { UnsupportedLocaleError } from "./i18n/errors.mjs";
|
|
5
|
+
import { matchLocale, resolveSupportedLocale } from "./i18n/match.mjs";
|
|
6
|
+
import { getLocalizedHref } from "./i18n/href.mjs";
|
|
2
7
|
import { configureLogging } from "./logging/logging.mjs";
|
|
3
8
|
import { gql } from "../graphql/graphql.mjs";
|
|
4
9
|
import { handleShopifyRedirects } from "./request-routing/handle-shopify-redirects.mjs";
|
|
@@ -14,6 +19,8 @@ import { getCart, getCartId } from "./cart/get-cart.mjs";
|
|
|
14
19
|
import { createShopifyRouteHandler } from "./request-routing/registered-routes.mjs";
|
|
15
20
|
import { handleShopifyRoutes } from "./request-routing/handle-shopify-routes.mjs";
|
|
16
21
|
import { createShopifyRequestContext } from "./request-context.mjs";
|
|
22
|
+
import { getShopifyScriptHashes } from "./shopify-scripts/hashes.mjs";
|
|
23
|
+
import { createContentSecurityPolicy, getShopifyCspDirectives } from "./csp/index.mjs";
|
|
17
24
|
import { AnalyticsEvent } from "./analytics/events.mjs";
|
|
18
25
|
import { flattenConnection } from "./analytics/utils/flatten-connection.mjs";
|
|
19
26
|
import { trackCartAnalytics } from "./analytics/cart-tracker.mjs";
|
|
@@ -42,4 +49,4 @@ import { createPredictiveSearchStore } from "./predictive-search/store.mjs";
|
|
|
42
49
|
import { getPredictiveSearchItemUrl, getSearchResultUrl } from "./predictive-search/url.mjs";
|
|
43
50
|
import { formatMoney } from "./money/format.mjs";
|
|
44
51
|
|
|
45
|
-
export { AnalyticsEvent, Cache, CartNetworkError, DEFAULT_MINIMUM_QUANTITY, EMPTY_CART_DATA, EMPTY_CART_STATE, NO_QUANTITY_LIMIT, SHOP_PAY_BUTTON_TAG_NAME, STANDARD_ACTION_TIMEOUT_IN_MS, StorefrontApiError, StorefrontTimeoutError, attachQuantityInput, buildProductSelectionSearchParams, canAddToCart, cartQueries, configureCartEndpoint, configureLogging, createCartCookie, createCartFormRegister, createCartServerHandlers, createCartStore, createCollectionReconciler, createCollectionStore, createEmptyCartErrors, createEmptyErrorGroup, createFetchWithCache, createInitialCollectionState, createPredictiveSearchFormRegister, createPredictiveSearchServerHandlers, createPredictiveSearchStore, createProductFormRegister, createProductFormStore, createRunWithCache, createShopPayButton, createShopifyRequestContext, createShopifyRouteHandler, createShopifyRouteTemplates, createStorefrontClient, defineShopPayButton, filterEquals, findCartLineByMerchandiseId, flattenConnection, formatMoney, getCart, getCartId, getFilterRemovalUrl, getPredictiveSearchFormAttributes, getPredictiveSearchItemUrl, getSearchResultUrl, getSelectedProductOptions, getSelectedVariant, getShopPayButtonUrl, getShopifyScriptTags, getSortByValue, gql, handleShopifyRedirects, handleShopifyRoutes, initializeShopifyScripts, isFilterInputActive, makePredictiveSearchQueries, normalizeCollectionSearch, parseCartRequest, parseCollectionParams, parseSortByValue, queryPredictiveSearch, readPredictiveSearchFormTerm, renderShopPayButton, renderShopifyScriptTags, sanitizeQuantity, serializeCollectionParams, trackCartAnalytics };
|
|
52
|
+
export { AnalyticsEvent, Cache, CartNetworkError, DEFAULT_MINIMUM_QUANTITY, EMPTY_CART_DATA, EMPTY_CART_STATE, NO_QUANTITY_LIMIT, SHOP_PAY_BUTTON_TAG_NAME, STANDARD_ACTION_TIMEOUT_IN_MS, StorefrontApiError, StorefrontTimeoutError, UnsupportedLocaleError, attachQuantityInput, buildProductSelectionSearchParams, canAddToCart, cartQueries, configureCartEndpoint, configureLogging, createCartCookie, createCartFormRegister, createCartServerHandlers, createCartStore, createCollectionReconciler, createCollectionStore, createContentSecurityPolicy, createEmptyCartErrors, createEmptyErrorGroup, createFetchWithCache, createInitialCollectionState, createPredictiveSearchFormRegister, createPredictiveSearchServerHandlers, createPredictiveSearchStore, createProductFormRegister, createProductFormStore, createRunWithCache, createShopPayButton, createShopifyRequestContext, createShopifyRouteHandler, createShopifyRouteTemplates, createStorefrontClient, defineShopPayButton, defineShopifyI18n, defineShopifyRouteTemplates, filterEquals, findCartLineByMerchandiseId, flattenConnection, formatMoney, getCart, getCartId, getFilterRemovalUrl, getLocalePathSegment, getLocalizedHref, getPredictiveSearchFormAttributes, getPredictiveSearchItemUrl, getSearchResultUrl, getSelectedProductOptions, getSelectedVariant, getShopPayButtonUrl, getShopifyCspDirectives, getShopifyScriptHashes, getShopifyScriptTags, getSortByValue, getSupportedLocales, gql, handleShopifyRedirects, handleShopifyRoutes, initializeShopifyScripts, isFilterInputActive, isSameLocale, makePredictiveSearchQueries, matchLocale, normalizeCollectionSearch, parseCartRequest, parseCollectionParams, parseSortByValue, queryPredictiveSearch, readPredictiveSearchFormTerm, renderShopPayButton, renderShopifyScriptTags, resolveSupportedLocale, sanitizeQuantity, serializeCollectionParams, trackCartAnalytics };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PredictiveSearchFormAttributes, PredictiveSearchFormRegister, PredictiveSearchQueryInputAttributes, createPredictiveSearchFormRegister, getPredictiveSearchFormAttributes, readPredictiveSearchFormTerm } from "./form.mjs";
|
|
2
2
|
import { CreatePredictiveSearchQueriesOptions, PredictiveSearchFragments, makePredictiveSearchQueries, predictiveSearchQueries } from "./queries.mjs";
|
|
3
3
|
import { PredictiveSearchData, PredictiveSearchDataForOptions, QueryPredictiveSearchOptions, queryPredictiveSearch } from "./search.mjs";
|
|
4
|
-
import { CreatePredictiveSearchServerHandlersOptions, createPredictiveSearchServerHandlers } from "./server-handlers.mjs";
|
|
4
|
+
import { CreatePredictiveSearchServerHandlersOptions, PredictiveSearchDataFromHandlers, createPredictiveSearchServerHandlers } from "./server-handlers.mjs";
|
|
5
5
|
import { CreatePredictiveSearchStoreOptions, PredictiveSearchActions, PredictiveSearchState, PredictiveSearchStatus, PredictiveSearchStore, createPredictiveSearchStore } from "./store.mjs";
|
|
6
|
-
import { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, getPredictiveSearchItemUrl, getSearchResultUrl } from "./url.mjs";
|
|
6
|
+
import { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, SearchResultUrlOptions, getPredictiveSearchItemUrl, getSearchResultUrl } from "./url.mjs";
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { PredictiveSearchLimitScope, PredictiveSearchType, SearchUnavailableProductsType, SearchableField } from "../../graphql/generated/storefront-api-types.mjs";
|
|
2
2
|
import { CallableRouteHandler, ShopifyRouteError, ShopifyRouteErrorResult, ShopifyRouteJsonResult } from "../request-routing/route-types.mjs";
|
|
3
|
-
import { CreatePredictiveSearchQueriesOptions
|
|
4
|
-
import { PredictiveSearchDataForOptions, QueryPredictiveSearchOptions } from "./search.mjs";
|
|
3
|
+
import { CreatePredictiveSearchQueriesOptions } from "./queries.mjs";
|
|
4
|
+
import { PredictiveSearchData, PredictiveSearchDataForOptions, QueryPredictiveSearchOptions } from "./search.mjs";
|
|
5
5
|
import { PREDICTIVE_SEARCH_GET_METHOD } from "./constants.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/core/predictive-search/server-handlers.d.ts
|
|
8
|
-
declare const predictiveSearchServerHandlersQuery: unique symbol;
|
|
9
8
|
type PredictiveSearchHandlerContext = {
|
|
10
9
|
request: Request;
|
|
11
10
|
storefrontClient: QueryPredictiveSearchOptions["storefrontClient"];
|
|
@@ -20,9 +19,31 @@ type PredictiveSearchError = ShopifyRouteError & {
|
|
|
20
19
|
type PredictiveSearchGetHandler<TData = PredictiveSearchDataForOptions<{}>> = CallableRouteHandler<PredictiveSearchHandlerContext, PredictiveSearchGetResult<TData>, string, typeof PREDICTIVE_SEARCH_GET_METHOD>;
|
|
21
20
|
/** Predictive search route handlers to pass to `handleShopifyRoutes`. */
|
|
22
21
|
type PredictiveSearchServerHandlers<TOptions extends CreatePredictiveSearchServerHandlersOptions = {}, TData = PredictiveSearchDataForOptions<TOptions>> = {
|
|
23
|
-
/**
|
|
24
|
-
get: PredictiveSearchGetHandler<TData>;
|
|
22
|
+
/** Answers GET requests with predictive search results as JSON. */get: PredictiveSearchGetHandler<TData>;
|
|
25
23
|
};
|
|
24
|
+
type AsyncHandlerResult<THandler> = THandler extends ((...args: infer _Args) => Promise<infer TResult>) ? TResult : never;
|
|
25
|
+
type JsonResultData<TResult> = TResult extends {
|
|
26
|
+
type: "json";
|
|
27
|
+
data: {
|
|
28
|
+
items: infer TItems;
|
|
29
|
+
};
|
|
30
|
+
} ? PredictiveSearchData<TItems> : never;
|
|
31
|
+
/**
|
|
32
|
+
* Infers the {@link PredictiveSearchData} shape returned by handlers from {@link createPredictiveSearchServerHandlers}.
|
|
33
|
+
*
|
|
34
|
+
* Pass it as the type argument to `usePredictiveSearch` so client state includes the handlers' custom fragment fields.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* type SearchData = PredictiveSearchDataFromHandlers<typeof predictiveSearchHandlers>;
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
type PredictiveSearchDataFromHandlers<THandlers extends {
|
|
42
|
+
get: (context: never) => Promise<{
|
|
43
|
+
type: string;
|
|
44
|
+
data?: PredictiveSearchData<unknown>;
|
|
45
|
+
}>;
|
|
46
|
+
}> = JsonResultData<AsyncHandlerResult<THandlers["get"]>>;
|
|
26
47
|
/**
|
|
27
48
|
* Route path, custom fragments, and default search settings for the predictive search route.
|
|
28
49
|
*
|
|
@@ -57,5 +78,5 @@ interface CreatePredictiveSearchServerHandlersOptions extends CreatePredictiveSe
|
|
|
57
78
|
declare function createPredictiveSearchServerHandlers(): PredictiveSearchServerHandlers;
|
|
58
79
|
declare function createPredictiveSearchServerHandlers<const TOptions extends CreatePredictiveSearchServerHandlersOptions>(options: TOptions): PredictiveSearchServerHandlers<TOptions>;
|
|
59
80
|
//#endregion
|
|
60
|
-
export { CreatePredictiveSearchServerHandlersOptions, createPredictiveSearchServerHandlers };
|
|
81
|
+
export { CreatePredictiveSearchServerHandlersOptions, PredictiveSearchDataFromHandlers, createPredictiveSearchServerHandlers };
|
|
61
82
|
//# sourceMappingURL=server-handlers.d.mts.map
|
|
@@ -5,7 +5,6 @@ import { makePredictiveSearchQueries, predictiveSearchQueries } from "./queries.
|
|
|
5
5
|
import { DEFAULT_PREDICTIVE_SEARCH_LIMIT_SCOPE, DEFAULT_PREDICTIVE_SEARCH_UNAVAILABLE_PRODUCTS, fetchPredictiveSearch } from "./search.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/core/predictive-search/server-handlers.ts
|
|
8
|
-
const predictiveSearchServerHandlersQuery = Symbol("hydrogen.predictiveSearchQuery");
|
|
9
8
|
const VALID_LIMIT_SCOPES = ["ALL", "EACH"];
|
|
10
9
|
const VALID_PREDICTIVE_SEARCH_TYPES = [
|
|
11
10
|
"ARTICLE",
|
|
@@ -36,9 +35,7 @@ const VALID_UNAVAILABLE_PRODUCTS = [
|
|
|
36
35
|
*/
|
|
37
36
|
function createPredictiveSearchServerHandlers(options = {}) {
|
|
38
37
|
const queries = options.fragments ? makePredictiveSearchQueries(options) : predictiveSearchQueries;
|
|
39
|
-
|
|
40
|
-
Object.defineProperty(handlers, predictiveSearchServerHandlersQuery, { value: queries.predictiveSearch });
|
|
41
|
-
return handlers;
|
|
38
|
+
return { get: createCallableRouteHandler(options.path ?? "/api/predictive-search", "GET", (context) => handleGet(context, options, queries)) };
|
|
42
39
|
}
|
|
43
40
|
async function handleGet({ request, storefrontClient }, options, queries) {
|
|
44
41
|
let searchOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-handlers.mjs","names":[],"sources":["../../../src/core/predictive-search/server-handlers.ts"],"sourcesContent":["import type {\n PredictiveSearchLimitScope,\n PredictiveSearchType,\n SearchUnavailableProductsType,\n SearchableField,\n} from \"../../graphql/generated/storefront-api-types\";\nimport { createProxyResponseHeaders } from \"../request-routing/interceptors/proxy\";\nimport type {\n CallableRouteHandler,\n ShopifyRouteError,\n ShopifyRouteErrorResult,\n ShopifyRouteJsonResult,\n} from \"../request-routing/registered-routes\";\nimport { createCallableRouteHandler } from \"../request-routing/registered-routes\";\nimport { PREDICTIVE_SEARCH_API_PATH, PREDICTIVE_SEARCH_GET_METHOD } from \"./constants\";\nimport {\n makePredictiveSearchQueries,\n predictiveSearchQueries,\n type CreatePredictiveSearchQueriesOptions,\n type PredictiveSearchQueriesForOptions,\n} from \"./queries\";\nimport {\n DEFAULT_PREDICTIVE_SEARCH_LIMIT,\n DEFAULT_PREDICTIVE_SEARCH_LIMIT_SCOPE,\n DEFAULT_PREDICTIVE_SEARCH_UNAVAILABLE_PRODUCTS,\n fetchPredictiveSearch,\n type PredictiveSearchDataForOptions,\n type QueryPredictiveSearchOptions,\n} from \"./search\";\n\nconst predictiveSearchServerHandlersQuery: unique symbol = Symbol(\"hydrogen.predictiveSearchQuery\");\n\nconst VALID_LIMIT_SCOPES: readonly PredictiveSearchLimitScope[] = [\"ALL\", \"EACH\"];\nconst VALID_PREDICTIVE_SEARCH_TYPES: readonly PredictiveSearchType[] = [\n \"ARTICLE\",\n \"COLLECTION\",\n \"PAGE\",\n \"PRODUCT\",\n \"QUERY\",\n];\nconst VALID_SEARCHABLE_FIELDS: readonly SearchableField[] = [\n \"AUTHOR\",\n \"BODY\",\n \"PRODUCT_TYPE\",\n \"TAG\",\n \"TITLE\",\n \"VARIANTS_BARCODE\",\n \"VARIANTS_SKU\",\n \"VARIANTS_TITLE\",\n \"VENDOR\",\n];\nconst VALID_UNAVAILABLE_PRODUCTS: readonly SearchUnavailableProductsType[] = [\n \"HIDE\",\n \"LAST\",\n \"SHOW\",\n];\n\ntype PredictiveSearchHandlerContext = {\n request: Request;\n storefrontClient: QueryPredictiveSearchOptions[\"storefrontClient\"];\n};\n\ntype PredictiveSearchGetData<TData = PredictiveSearchDataForOptions<{}>> = TData;\ntype PredictiveSearchGetResult<TData = PredictiveSearchDataForOptions<{}>> =\n | ShopifyRouteJsonResult<PredictiveSearchGetData<TData>>\n | ShopifyRouteErrorResult<PredictiveSearchError>;\n\ntype PredictiveSearchErrorCode = \"invalid_predictive_search_request\";\ntype PredictiveSearchError = ShopifyRouteError & {\n code: PredictiveSearchErrorCode;\n};\n\n/** GET route handler that returns predictive search results or an error. */\ntype PredictiveSearchGetHandler<TData = PredictiveSearchDataForOptions<{}>> = CallableRouteHandler<\n PredictiveSearchHandlerContext,\n PredictiveSearchGetResult<TData>,\n string,\n typeof PREDICTIVE_SEARCH_GET_METHOD\n>;\n\n/** Predictive search route handlers to pass to `handleShopifyRoutes`. */\ntype PredictiveSearchServerHandlers<\n TOptions extends CreatePredictiveSearchServerHandlersOptions = {},\n TData = PredictiveSearchDataForOptions<TOptions>,\n> = {\n /** Query that the handlers run, with any custom fragments. */\n readonly [predictiveSearchServerHandlersQuery]: PredictiveSearchQueriesForOptions<TOptions>[\"predictiveSearch\"];\n /** Answers GET requests with predictive search results as JSON. */\n get: PredictiveSearchGetHandler<TData>;\n};\n\n/**\n * Route path, custom fragments, and default search settings for the predictive search route.\n *\n * A request overrides a default search setting with a URL parameter of the same name.\n */\nexport interface CreatePredictiveSearchServerHandlersOptions extends CreatePredictiveSearchQueriesOptions {\n /** Route path that the GET handler serves. Defaults to `/api/predictive-search`. */\n path?: string;\n /** Default maximum number of results, from 1 to 10. Applies when a request has no numeric `limit` parameter. Predictive search clamps other values to that range. Defaults to `5`. */\n limit?: number;\n /** Default limit scope. Defaults to `EACH`. */\n limitScope?: PredictiveSearchLimitScope;\n /** Default result types. A request can set `types` to a comma-separated list. */\n types?: PredictiveSearchType[];\n /** Default fields to search. A request can set `searchableFields` to a comma-separated list. */\n searchableFields?: SearchableField[];\n /** Default handling of unavailable products. Defaults to `HIDE`. */\n unavailableProducts?: SearchUnavailableProductsType;\n}\n\n/**\n * Creates the route that answers predictive search requests from the browser.\n * Register the handlers with `handleShopifyRoutes`. The default route path matches\n * the default endpoint of `createPredictiveSearchStore` and `PredictiveSearchProvider`.\n *\n * The route reads the search term from the `q` URL parameter. A URL parameter with the same name as a search setting overrides the setting's default.\n *\n * An invalid setting value or a failed Storefront API query returns HTTP status `400` with a JSON body of `{error: {code, message}}`. The `code` value is `invalid_predictive_search_request`.\n * A successful response forwards the Storefront API response headers except the content encoding, content length, and server timing headers.\n *\n * @publicDocs\n */\nexport function createPredictiveSearchServerHandlers(): PredictiveSearchServerHandlers;\nexport function createPredictiveSearchServerHandlers<\n const TOptions extends CreatePredictiveSearchServerHandlersOptions,\n>(options: TOptions): PredictiveSearchServerHandlers<TOptions>;\n/**\n * @param options Route path, custom fragments, and default search settings for the route.\n * @returns Route handlers to pass to `handleShopifyRoutes`.\n */\nexport function createPredictiveSearchServerHandlers(\n options: CreatePredictiveSearchServerHandlersOptions = {},\n): PredictiveSearchServerHandlers<CreatePredictiveSearchServerHandlersOptions> {\n const queries = options.fragments\n ? makePredictiveSearchQueries(options)\n : predictiveSearchQueries;\n const handler = createCallableRouteHandler(\n options.path ?? PREDICTIVE_SEARCH_API_PATH,\n PREDICTIVE_SEARCH_GET_METHOD,\n (context: PredictiveSearchHandlerContext) => handleGet(context, options, queries),\n );\n const handlers = {\n get: handler,\n } as PredictiveSearchServerHandlers<CreatePredictiveSearchServerHandlersOptions>;\n\n Object.defineProperty(handlers, predictiveSearchServerHandlersQuery, {\n value: queries.predictiveSearch,\n });\n return handlers;\n}\n\nasync function handleGet(\n { request, storefrontClient }: PredictiveSearchHandlerContext,\n options: CreatePredictiveSearchServerHandlersOptions,\n queries: PredictiveSearchQueriesForOptions<CreatePredictiveSearchServerHandlersOptions>,\n): Promise<PredictiveSearchGetResult> {\n let searchOptions: ParsedPredictiveSearchRequest;\n try {\n searchOptions = parsePredictiveSearchRequest(request, options);\n } catch (error) {\n return errorResult(getErrorMessage(error, \"Invalid predictive search request\"));\n }\n\n try {\n const result = await fetchPredictiveSearch({\n storefrontClient,\n query: queries.predictiveSearch,\n ...searchOptions,\n });\n return {\n type: \"json\",\n data: result.data,\n headers: createProxyResponseHeaders(result.headers),\n };\n } catch (error) {\n return errorResult(getErrorMessage(error, \"Predictive search request failed\"));\n }\n}\n\ntype ParsedPredictiveSearchRequest = Omit<\n QueryPredictiveSearchOptions,\n \"storefrontClient\" | \"query\" | \"signal\"\n>;\n\nfunction parsePredictiveSearchRequest(\n request: Request,\n options: CreatePredictiveSearchServerHandlersOptions,\n): ParsedPredictiveSearchRequest {\n const searchParams = new URL(request.url).searchParams;\n return {\n term: searchParams.get(\"q\") ?? \"\",\n limit: parseLimit(searchParams, options),\n limitScope:\n parseOne(searchParams, \"limitScope\", VALID_LIMIT_SCOPES) ??\n options.limitScope ??\n DEFAULT_PREDICTIVE_SEARCH_LIMIT_SCOPE,\n types: parseMany(searchParams, \"types\", VALID_PREDICTIVE_SEARCH_TYPES) ?? options.types,\n searchableFields:\n parseMany(searchParams, \"searchableFields\", VALID_SEARCHABLE_FIELDS) ??\n options.searchableFields,\n unavailableProducts:\n parseOne(searchParams, \"unavailableProducts\", VALID_UNAVAILABLE_PRODUCTS) ??\n options.unavailableProducts ??\n DEFAULT_PREDICTIVE_SEARCH_UNAVAILABLE_PRODUCTS,\n };\n}\n\n// Invalid enum params return a typed error, but an unparseable limit falls back to the configured default.\nfunction parseLimit(\n searchParams: URLSearchParams,\n options: CreatePredictiveSearchServerHandlersOptions,\n): number {\n const defaultLimit = options.limit ?? DEFAULT_PREDICTIVE_SEARCH_LIMIT;\n const rawLimit = searchParams.get(\"limit\")?.trim() ?? \"\";\n if (rawLimit === \"\") return defaultLimit;\n\n const limit = Number(rawLimit);\n return Number.isFinite(limit) ? limit : defaultLimit;\n}\n\nfunction parseOne<TValue extends string>(\n searchParams: URLSearchParams,\n name: string,\n allowedValues: readonly TValue[],\n): TValue | undefined {\n const value = searchParams.get(name);\n if (value === null || value === \"\") return undefined;\n if (isAllowedValue(value, allowedValues)) return value;\n throw new Error(`Invalid ${name} value \"${value}\".`);\n}\n\nfunction parseMany<TValue extends string>(\n searchParams: URLSearchParams,\n name: string,\n allowedValues: readonly TValue[],\n): TValue[] | undefined {\n const values = splitParamValues(searchParams, name);\n if (values.length === 0) return undefined;\n return values.map((value) => parseAllowedValue(name, value, allowedValues));\n}\n\nfunction splitParamValues(searchParams: URLSearchParams, name: string): string[] {\n return searchParams\n .getAll(name)\n .flatMap((value) => value.split(\",\"))\n .map((value) => value.trim())\n .filter(Boolean);\n}\n\nfunction parseAllowedValue<TValue extends string>(\n name: string,\n value: string,\n allowedValues: readonly TValue[],\n): TValue {\n if (isAllowedValue(value, allowedValues)) return value;\n throw new Error(`Invalid ${name} value \"${value}\".`);\n}\n\nfunction isAllowedValue<TValue extends string>(\n value: string,\n allowedValues: readonly TValue[],\n): value is TValue {\n return allowedValues.some((allowedValue) => allowedValue === value);\n}\n\nfunction errorResult(message: string): ShopifyRouteErrorResult<PredictiveSearchError> {\n return {\n type: \"error\",\n error: {\n code: \"invalid_predictive_search_request\",\n message,\n },\n };\n}\n\nfunction getErrorMessage(error: unknown, fallback: string): string {\n return error instanceof Error ? error.message : fallback;\n}\n"],"mappings":";;;;;;;AA8BA,MAAM,sCAAqD,OAAO,iCAAiC;AAEnG,MAAM,qBAA4D,CAAC,OAAO,OAAO;AACjF,MAAM,gCAAiE;CACrE;CACA;CACA;CACA;CACA;CACD;AACD,MAAM,0BAAsD;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AACD,MAAM,6BAAuE;CAC3E;CACA;CACA;CACD;;;;;AA4ED,SAAgB,qCACd,UAAuD,EAAE,EACoB;CAC7E,MAAM,UAAU,QAAQ,YACpB,4BAA4B,QAAQ,GACpC;CAMJ,MAAM,WAAW,EACf,KANc,2BACd,QAAQ,0CAEP,YAA4C,UAAU,SAAS,SAAS,QAAQ,CAGrE,EACb;AAED,QAAO,eAAe,UAAU,qCAAqC,EACnE,OAAO,QAAQ,kBAChB,CAAC;AACF,QAAO;;AAGT,eAAe,UACb,EAAE,SAAS,oBACX,SACA,SACoC;CACpC,IAAI;AACJ,KAAI;AACF,kBAAgB,6BAA6B,SAAS,QAAQ;UACvD,OAAO;AACd,SAAO,YAAY,gBAAgB,OAAO,oCAAoC,CAAC;;AAGjF,KAAI;EACF,MAAM,SAAS,MAAM,sBAAsB;GACzC;GACA,OAAO,QAAQ;GACf,GAAG;GACJ,CAAC;AACF,SAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,SAAS,2BAA2B,OAAO,QAAQ;GACpD;UACM,OAAO;AACd,SAAO,YAAY,gBAAgB,OAAO,mCAAmC,CAAC;;;AASlF,SAAS,6BACP,SACA,SAC+B;CAC/B,MAAM,eAAe,IAAI,IAAI,QAAQ,IAAI,CAAC;AAC1C,QAAO;EACL,MAAM,aAAa,IAAI,IAAI,IAAI;EAC/B,OAAO,WAAW,cAAc,QAAQ;EACxC,YACE,SAAS,cAAc,cAAc,mBAAmB,IACxD,QAAQ;EAEV,OAAO,UAAU,cAAc,SAAS,8BAA8B,IAAI,QAAQ;EAClF,kBACE,UAAU,cAAc,oBAAoB,wBAAwB,IACpE,QAAQ;EACV,qBACE,SAAS,cAAc,uBAAuB,2BAA2B,IACzE,QAAQ;EAEX;;AAIH,SAAS,WACP,cACA,SACQ;CACR,MAAM,eAAe,QAAQ;CAC7B,MAAM,WAAW,aAAa,IAAI,QAAQ,EAAE,MAAM,IAAI;AACtD,KAAI,aAAa,GAAI,QAAO;CAE5B,MAAM,QAAQ,OAAO,SAAS;AAC9B,QAAO,OAAO,SAAS,MAAM,GAAG,QAAQ;;AAG1C,SAAS,SACP,cACA,MACA,eACoB;CACpB,MAAM,QAAQ,aAAa,IAAI,KAAK;AACpC,KAAI,UAAU,QAAQ,UAAU,GAAI,QAAO;AAC3C,KAAI,eAAe,OAAO,cAAc,CAAE,QAAO;AACjD,OAAM,IAAI,MAAM,WAAW,KAAK,UAAU,MAAM,IAAI;;AAGtD,SAAS,UACP,cACA,MACA,eACsB;CACtB,MAAM,SAAS,iBAAiB,cAAc,KAAK;AACnD,KAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAO,OAAO,KAAK,UAAU,kBAAkB,MAAM,OAAO,cAAc,CAAC;;AAG7E,SAAS,iBAAiB,cAA+B,MAAwB;AAC/E,QAAO,aACJ,OAAO,KAAK,CACZ,SAAS,UAAU,MAAM,MAAM,IAAI,CAAC,CACpC,KAAK,UAAU,MAAM,MAAM,CAAC,CAC5B,OAAO,QAAQ;;AAGpB,SAAS,kBACP,MACA,OACA,eACQ;AACR,KAAI,eAAe,OAAO,cAAc,CAAE,QAAO;AACjD,OAAM,IAAI,MAAM,WAAW,KAAK,UAAU,MAAM,IAAI;;AAGtD,SAAS,eACP,OACA,eACiB;AACjB,QAAO,cAAc,MAAM,iBAAiB,iBAAiB,MAAM;;AAGrE,SAAS,YAAY,SAAiE;AACpF,QAAO;EACL,MAAM;EACN,OAAO;GACL,MAAM;GACN;GACD;EACF;;AAGH,SAAS,gBAAgB,OAAgB,UAA0B;AACjE,QAAO,iBAAiB,QAAQ,MAAM,UAAU"}
|
|
1
|
+
{"version":3,"file":"server-handlers.mjs","names":[],"sources":["../../../src/core/predictive-search/server-handlers.ts"],"sourcesContent":["import type {\n PredictiveSearchLimitScope,\n PredictiveSearchType,\n SearchUnavailableProductsType,\n SearchableField,\n} from \"../../graphql/generated/storefront-api-types\";\nimport { createProxyResponseHeaders } from \"../request-routing/interceptors/proxy\";\nimport type {\n CallableRouteHandler,\n ShopifyRouteError,\n ShopifyRouteErrorResult,\n ShopifyRouteJsonResult,\n} from \"../request-routing/registered-routes\";\nimport { createCallableRouteHandler } from \"../request-routing/registered-routes\";\nimport { PREDICTIVE_SEARCH_API_PATH, PREDICTIVE_SEARCH_GET_METHOD } from \"./constants\";\nimport {\n makePredictiveSearchQueries,\n predictiveSearchQueries,\n type CreatePredictiveSearchQueriesOptions,\n type PredictiveSearchQueriesForOptions,\n} from \"./queries\";\nimport {\n DEFAULT_PREDICTIVE_SEARCH_LIMIT,\n DEFAULT_PREDICTIVE_SEARCH_LIMIT_SCOPE,\n DEFAULT_PREDICTIVE_SEARCH_UNAVAILABLE_PRODUCTS,\n fetchPredictiveSearch,\n type PredictiveSearchData,\n type PredictiveSearchDataForOptions,\n type QueryPredictiveSearchOptions,\n} from \"./search\";\n\nconst VALID_LIMIT_SCOPES: readonly PredictiveSearchLimitScope[] = [\"ALL\", \"EACH\"];\nconst VALID_PREDICTIVE_SEARCH_TYPES: readonly PredictiveSearchType[] = [\n \"ARTICLE\",\n \"COLLECTION\",\n \"PAGE\",\n \"PRODUCT\",\n \"QUERY\",\n];\nconst VALID_SEARCHABLE_FIELDS: readonly SearchableField[] = [\n \"AUTHOR\",\n \"BODY\",\n \"PRODUCT_TYPE\",\n \"TAG\",\n \"TITLE\",\n \"VARIANTS_BARCODE\",\n \"VARIANTS_SKU\",\n \"VARIANTS_TITLE\",\n \"VENDOR\",\n];\nconst VALID_UNAVAILABLE_PRODUCTS: readonly SearchUnavailableProductsType[] = [\n \"HIDE\",\n \"LAST\",\n \"SHOW\",\n];\n\ntype PredictiveSearchHandlerContext = {\n request: Request;\n storefrontClient: QueryPredictiveSearchOptions[\"storefrontClient\"];\n};\n\ntype PredictiveSearchGetData<TData = PredictiveSearchDataForOptions<{}>> = TData;\ntype PredictiveSearchGetResult<TData = PredictiveSearchDataForOptions<{}>> =\n | ShopifyRouteJsonResult<PredictiveSearchGetData<TData>>\n | ShopifyRouteErrorResult<PredictiveSearchError>;\n\ntype PredictiveSearchErrorCode = \"invalid_predictive_search_request\";\ntype PredictiveSearchError = ShopifyRouteError & {\n code: PredictiveSearchErrorCode;\n};\n\n/** GET route handler that returns predictive search results or an error. */\ntype PredictiveSearchGetHandler<TData = PredictiveSearchDataForOptions<{}>> = CallableRouteHandler<\n PredictiveSearchHandlerContext,\n PredictiveSearchGetResult<TData>,\n string,\n typeof PREDICTIVE_SEARCH_GET_METHOD\n>;\n\n/** Predictive search route handlers to pass to `handleShopifyRoutes`. */\ntype PredictiveSearchServerHandlers<\n TOptions extends CreatePredictiveSearchServerHandlersOptions = {},\n TData = PredictiveSearchDataForOptions<TOptions>,\n> = {\n /** Answers GET requests with predictive search results as JSON. */\n get: PredictiveSearchGetHandler<TData>;\n};\n\ntype AsyncHandlerResult<THandler> = THandler extends (\n ...args: infer _Args\n) => Promise<infer TResult>\n ? TResult\n : never;\n\n// Rebuilt on PredictiveSearchData: TypeScript compares PredictiveSearchDataForOptions instantiations\n// through their type arguments and can't tell fragment options apart, so handler data would be interchangeable.\ntype JsonResultData<TResult> = TResult extends { type: \"json\"; data: { items: infer TItems } }\n ? PredictiveSearchData<TItems>\n : never;\n\n/**\n * Infers the {@link PredictiveSearchData} shape returned by handlers from {@link createPredictiveSearchServerHandlers}.\n *\n * Pass it as the type argument to `usePredictiveSearch` so client state includes the handlers' custom fragment fields.\n *\n * @example\n * ```ts\n * type SearchData = PredictiveSearchDataFromHandlers<typeof predictiveSearchHandlers>;\n * ```\n */\nexport type PredictiveSearchDataFromHandlers<\n THandlers extends {\n get: (context: never) => Promise<{ type: string; data?: PredictiveSearchData<unknown> }>;\n },\n> = JsonResultData<AsyncHandlerResult<THandlers[\"get\"]>>;\n\n/**\n * Route path, custom fragments, and default search settings for the predictive search route.\n *\n * A request overrides a default search setting with a URL parameter of the same name.\n */\nexport interface CreatePredictiveSearchServerHandlersOptions extends CreatePredictiveSearchQueriesOptions {\n /** Route path that the GET handler serves. Defaults to `/api/predictive-search`. */\n path?: string;\n /** Default maximum number of results, from 1 to 10. Applies when a request has no numeric `limit` parameter. Predictive search clamps other values to that range. Defaults to `5`. */\n limit?: number;\n /** Default limit scope. Defaults to `EACH`. */\n limitScope?: PredictiveSearchLimitScope;\n /** Default result types. A request can set `types` to a comma-separated list. */\n types?: PredictiveSearchType[];\n /** Default fields to search. A request can set `searchableFields` to a comma-separated list. */\n searchableFields?: SearchableField[];\n /** Default handling of unavailable products. Defaults to `HIDE`. */\n unavailableProducts?: SearchUnavailableProductsType;\n}\n\n/**\n * Creates the route that answers predictive search requests from the browser.\n * Register the handlers with `handleShopifyRoutes`. The default route path matches\n * the default endpoint of `createPredictiveSearchStore` and `PredictiveSearchProvider`.\n *\n * The route reads the search term from the `q` URL parameter. A URL parameter with the same name as a search setting overrides the setting's default.\n *\n * An invalid setting value or a failed Storefront API query returns HTTP status `400` with a JSON body of `{error: {code, message}}`. The `code` value is `invalid_predictive_search_request`.\n * A successful response forwards the Storefront API response headers except the content encoding, content length, and server timing headers.\n *\n * @publicDocs\n */\nexport function createPredictiveSearchServerHandlers(): PredictiveSearchServerHandlers;\nexport function createPredictiveSearchServerHandlers<\n const TOptions extends CreatePredictiveSearchServerHandlersOptions,\n>(options: TOptions): PredictiveSearchServerHandlers<TOptions>;\n/**\n * @param options Route path, custom fragments, and default search settings for the route.\n * @returns Route handlers to pass to `handleShopifyRoutes`.\n */\nexport function createPredictiveSearchServerHandlers(\n options: CreatePredictiveSearchServerHandlersOptions = {},\n): PredictiveSearchServerHandlers<CreatePredictiveSearchServerHandlersOptions> {\n const queries = options.fragments\n ? makePredictiveSearchQueries(options)\n : predictiveSearchQueries;\n const handler = createCallableRouteHandler(\n options.path ?? PREDICTIVE_SEARCH_API_PATH,\n PREDICTIVE_SEARCH_GET_METHOD,\n (context: PredictiveSearchHandlerContext) => handleGet(context, options, queries),\n );\n return { get: handler };\n}\n\nasync function handleGet(\n { request, storefrontClient }: PredictiveSearchHandlerContext,\n options: CreatePredictiveSearchServerHandlersOptions,\n queries: PredictiveSearchQueriesForOptions<CreatePredictiveSearchServerHandlersOptions>,\n): Promise<PredictiveSearchGetResult> {\n let searchOptions: ParsedPredictiveSearchRequest;\n try {\n searchOptions = parsePredictiveSearchRequest(request, options);\n } catch (error) {\n return errorResult(getErrorMessage(error, \"Invalid predictive search request\"));\n }\n\n try {\n const result = await fetchPredictiveSearch({\n storefrontClient,\n query: queries.predictiveSearch,\n ...searchOptions,\n });\n return {\n type: \"json\",\n data: result.data,\n headers: createProxyResponseHeaders(result.headers),\n };\n } catch (error) {\n return errorResult(getErrorMessage(error, \"Predictive search request failed\"));\n }\n}\n\ntype ParsedPredictiveSearchRequest = Omit<\n QueryPredictiveSearchOptions,\n \"storefrontClient\" | \"query\" | \"signal\"\n>;\n\nfunction parsePredictiveSearchRequest(\n request: Request,\n options: CreatePredictiveSearchServerHandlersOptions,\n): ParsedPredictiveSearchRequest {\n const searchParams = new URL(request.url).searchParams;\n return {\n term: searchParams.get(\"q\") ?? \"\",\n limit: parseLimit(searchParams, options),\n limitScope:\n parseOne(searchParams, \"limitScope\", VALID_LIMIT_SCOPES) ??\n options.limitScope ??\n DEFAULT_PREDICTIVE_SEARCH_LIMIT_SCOPE,\n types: parseMany(searchParams, \"types\", VALID_PREDICTIVE_SEARCH_TYPES) ?? options.types,\n searchableFields:\n parseMany(searchParams, \"searchableFields\", VALID_SEARCHABLE_FIELDS) ??\n options.searchableFields,\n unavailableProducts:\n parseOne(searchParams, \"unavailableProducts\", VALID_UNAVAILABLE_PRODUCTS) ??\n options.unavailableProducts ??\n DEFAULT_PREDICTIVE_SEARCH_UNAVAILABLE_PRODUCTS,\n };\n}\n\n// Invalid enum params return a typed error, but an unparseable limit falls back to the configured default.\nfunction parseLimit(\n searchParams: URLSearchParams,\n options: CreatePredictiveSearchServerHandlersOptions,\n): number {\n const defaultLimit = options.limit ?? DEFAULT_PREDICTIVE_SEARCH_LIMIT;\n const rawLimit = searchParams.get(\"limit\")?.trim() ?? \"\";\n if (rawLimit === \"\") return defaultLimit;\n\n const limit = Number(rawLimit);\n return Number.isFinite(limit) ? limit : defaultLimit;\n}\n\nfunction parseOne<TValue extends string>(\n searchParams: URLSearchParams,\n name: string,\n allowedValues: readonly TValue[],\n): TValue | undefined {\n const value = searchParams.get(name);\n if (value === null || value === \"\") return undefined;\n if (isAllowedValue(value, allowedValues)) return value;\n throw new Error(`Invalid ${name} value \"${value}\".`);\n}\n\nfunction parseMany<TValue extends string>(\n searchParams: URLSearchParams,\n name: string,\n allowedValues: readonly TValue[],\n): TValue[] | undefined {\n const values = splitParamValues(searchParams, name);\n if (values.length === 0) return undefined;\n return values.map((value) => parseAllowedValue(name, value, allowedValues));\n}\n\nfunction splitParamValues(searchParams: URLSearchParams, name: string): string[] {\n return searchParams\n .getAll(name)\n .flatMap((value) => value.split(\",\"))\n .map((value) => value.trim())\n .filter(Boolean);\n}\n\nfunction parseAllowedValue<TValue extends string>(\n name: string,\n value: string,\n allowedValues: readonly TValue[],\n): TValue {\n if (isAllowedValue(value, allowedValues)) return value;\n throw new Error(`Invalid ${name} value \"${value}\".`);\n}\n\nfunction isAllowedValue<TValue extends string>(\n value: string,\n allowedValues: readonly TValue[],\n): value is TValue {\n return allowedValues.some((allowedValue) => allowedValue === value);\n}\n\nfunction errorResult(message: string): ShopifyRouteErrorResult<PredictiveSearchError> {\n return {\n type: \"error\",\n error: {\n code: \"invalid_predictive_search_request\",\n message,\n },\n };\n}\n\nfunction getErrorMessage(error: unknown, fallback: string): string {\n return error instanceof Error ? error.message : fallback;\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,qBAA4D,CAAC,OAAO,OAAO;AACjF,MAAM,gCAAiE;CACrE;CACA;CACA;CACA;CACA;CACD;AACD,MAAM,0BAAsD;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AACD,MAAM,6BAAuE;CAC3E;CACA;CACA;CACD;;;;;AAsGD,SAAgB,qCACd,UAAuD,EAAE,EACoB;CAC7E,MAAM,UAAU,QAAQ,YACpB,4BAA4B,QAAQ,GACpC;AAMJ,QAAO,EAAE,KALO,2BACd,QAAQ,0CAEP,YAA4C,UAAU,SAAS,SAAS,QAAQ,CAE9D,EAAE;;AAGzB,eAAe,UACb,EAAE,SAAS,oBACX,SACA,SACoC;CACpC,IAAI;AACJ,KAAI;AACF,kBAAgB,6BAA6B,SAAS,QAAQ;UACvD,OAAO;AACd,SAAO,YAAY,gBAAgB,OAAO,oCAAoC,CAAC;;AAGjF,KAAI;EACF,MAAM,SAAS,MAAM,sBAAsB;GACzC;GACA,OAAO,QAAQ;GACf,GAAG;GACJ,CAAC;AACF,SAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,SAAS,2BAA2B,OAAO,QAAQ;GACpD;UACM,OAAO;AACd,SAAO,YAAY,gBAAgB,OAAO,mCAAmC,CAAC;;;AASlF,SAAS,6BACP,SACA,SAC+B;CAC/B,MAAM,eAAe,IAAI,IAAI,QAAQ,IAAI,CAAC;AAC1C,QAAO;EACL,MAAM,aAAa,IAAI,IAAI,IAAI;EAC/B,OAAO,WAAW,cAAc,QAAQ;EACxC,YACE,SAAS,cAAc,cAAc,mBAAmB,IACxD,QAAQ;EAEV,OAAO,UAAU,cAAc,SAAS,8BAA8B,IAAI,QAAQ;EAClF,kBACE,UAAU,cAAc,oBAAoB,wBAAwB,IACpE,QAAQ;EACV,qBACE,SAAS,cAAc,uBAAuB,2BAA2B,IACzE,QAAQ;EAEX;;AAIH,SAAS,WACP,cACA,SACQ;CACR,MAAM,eAAe,QAAQ;CAC7B,MAAM,WAAW,aAAa,IAAI,QAAQ,EAAE,MAAM,IAAI;AACtD,KAAI,aAAa,GAAI,QAAO;CAE5B,MAAM,QAAQ,OAAO,SAAS;AAC9B,QAAO,OAAO,SAAS,MAAM,GAAG,QAAQ;;AAG1C,SAAS,SACP,cACA,MACA,eACoB;CACpB,MAAM,QAAQ,aAAa,IAAI,KAAK;AACpC,KAAI,UAAU,QAAQ,UAAU,GAAI,QAAO;AAC3C,KAAI,eAAe,OAAO,cAAc,CAAE,QAAO;AACjD,OAAM,IAAI,MAAM,WAAW,KAAK,UAAU,MAAM,IAAI;;AAGtD,SAAS,UACP,cACA,MACA,eACsB;CACtB,MAAM,SAAS,iBAAiB,cAAc,KAAK;AACnD,KAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAO,OAAO,KAAK,UAAU,kBAAkB,MAAM,OAAO,cAAc,CAAC;;AAG7E,SAAS,iBAAiB,cAA+B,MAAwB;AAC/E,QAAO,aACJ,OAAO,KAAK,CACZ,SAAS,UAAU,MAAM,MAAM,IAAI,CAAC,CACpC,KAAK,UAAU,MAAM,MAAM,CAAC,CAC5B,OAAO,QAAQ;;AAGpB,SAAS,kBACP,MACA,OACA,eACQ;AACR,KAAI,eAAe,OAAO,cAAc,CAAE,QAAO;AACjD,OAAM,IAAI,MAAM,WAAW,KAAK,UAAU,MAAM,IAAI;;AAGtD,SAAS,eACP,OACA,eACiB;AACjB,QAAO,cAAc,MAAM,iBAAiB,iBAAiB,MAAM;;AAGrE,SAAS,YAAY,SAAiE;AACpF,QAAO;EACL,MAAM;EACN,OAAO;GACL,MAAM;GACN;GACD;EACF;;AAGH,SAAS,gBAAgB,OAAgB,UAA0B;AACjE,QAAO,iBAAiB,QAAQ,MAAM,UAAU"}
|
|
@@ -23,7 +23,7 @@ type PredictiveSearchItem = PredictiveSearchResourceItem | PredictiveSearchQuery
|
|
|
23
23
|
* Pass the route templates and the customer's search term.
|
|
24
24
|
*/
|
|
25
25
|
type PredictiveSearchItemUrlOptions = {
|
|
26
|
-
/** Prefix to add before the route path, such as a locale prefix. */pathPrefix?: string; /** Route templates for product, collection, page, and article paths, from `
|
|
26
|
+
/** Prefix to add before the route path, such as a locale prefix. */pathPrefix?: string; /** Route templates for product, collection, page, and article paths, from `defineShopifyRouteTemplates`. */
|
|
27
27
|
routes: ShopifyRouteTemplates; /** Search term that the customer typed. The link carries the term in the `q` URL parameter. */
|
|
28
28
|
term: string;
|
|
29
29
|
};
|
|
@@ -78,5 +78,5 @@ declare function getSearchResultUrl({
|
|
|
78
78
|
searchParamName
|
|
79
79
|
}: SearchResultUrlOptions): string;
|
|
80
80
|
//#endregion
|
|
81
|
-
export { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, getPredictiveSearchItemUrl, getSearchResultUrl };
|
|
81
|
+
export { PredictiveSearchArticleItem, PredictiveSearchCollectionItem, PredictiveSearchItem, PredictiveSearchItemUrlOptions, PredictiveSearchPageItem, PredictiveSearchProductItem, PredictiveSearchQueryItem, PredictiveSearchQueryItemUrlOptions, PredictiveSearchResourceItem, SearchResultUrlOptions, getPredictiveSearchItemUrl, getSearchResultUrl };
|
|
82
82
|
//# sourceMappingURL=url.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url.mjs","names":[],"sources":["../../../src/core/predictive-search/url.ts"],"sourcesContent":["import { getStandardRoute, type ShopifyRouteTemplates } from \"../standard-routes/index\";\nimport type { PredictiveSearchData } from \"./search\";\n\nconst RELATIVE_URL_BASE = \"https://hydrogen.local\";\n\ntype PredictiveSearchItems = PredictiveSearchData[\"items\"];\n\n/** A product result from predictive search. */\nexport type PredictiveSearchProductItem = PredictiveSearchItems[\"products\"][number];\n/** A collection result from predictive search. */\nexport type PredictiveSearchCollectionItem = PredictiveSearchItems[\"collections\"][number];\n/** A page result from predictive search. */\nexport type PredictiveSearchPageItem = PredictiveSearchItems[\"pages\"][number];\n/** An article result from predictive search. */\nexport type PredictiveSearchArticleItem = PredictiveSearchItems[\"articles\"][number];\n/** A suggested search term from predictive search. */\nexport type PredictiveSearchQueryItem = PredictiveSearchItems[\"queries\"][number];\n\n/** A product, collection, page, or article result. Excludes query suggestions. */\nexport type PredictiveSearchResourceItem =\n | PredictiveSearchProductItem\n | PredictiveSearchCollectionItem\n | PredictiveSearchPageItem\n | PredictiveSearchArticleItem;\n\n/** Any predictive search result, including query suggestions. */\nexport type PredictiveSearchItem = PredictiveSearchResourceItem | PredictiveSearchQueryItem;\n\n/**\n * Options for the link of a product, collection, page, or article result.\n *\n * Pass the route templates and the customer's search term.\n */\nexport type PredictiveSearchItemUrlOptions = {\n /** Prefix to add before the route path, such as a locale prefix. */\n pathPrefix?: string;\n /** Route templates for product, collection, page, and article paths, from `createShopifyRouteTemplates`. */\n routes: ShopifyRouteTemplates;\n /** Search term that the customer typed. The link carries the term in the `q` URL parameter. */\n term: string;\n};\n\n/**\n * Options for the link of a query suggestion.\n *\n * By default, a suggestion links to the standard search route and searches for the suggestion's text.\n */\nexport type PredictiveSearchQueryItemUrlOptions = {\n /** Prefix to add before the search route, such as a locale prefix. Has no effect when you set a search path. */\n pathPrefix?: string;\n /** Route templates that set the search page path. Defaults to Hydrogen's standard search route. */\n routes?: ShopifyRouteTemplates;\n /** Search page path or URL to use as is, without the route templates or the path prefix. */\n searchPath?: string;\n};\n\n/** URL options for any predictive search result, either resource options or query suggestion options. */\ntype AnyPredictiveSearchItemUrlOptions =\n | PredictiveSearchItemUrlOptions\n | PredictiveSearchQueryItemUrlOptions;\n\n/** Options for a search result URL. */\ntype SearchResultUrlOptions = {\n /** Search page path or absolute URL. */\n baseUrl: string;\n /** Search term to add to the URL. */\n term: string;\n /** Tracking parameters from a Storefront API search result. Pass the result's `trackingParameters` value unchanged. */\n trackingParameters?: string | null;\n /** Extra URL parameters, such as a result type filter. The search term replaces an extra parameter with the same name. */\n params?: Record<string, string>;\n /** URL parameter that carries the search term. Defaults to `q`. */\n searchParamName?: string;\n};\n\n/**\n * Builds the link for a predictive search result. A product, collection, page, or\n * article result links to the resource's page with the search term. A query suggestion links to\n * the search page and searches for the suggestion's text. Every link keeps the\n * result's tracking parameters.\n *\n * For a product, collection, page, or article, pass the route templates and the search term. The function throws an error without them.\n *\n * @throws {Error} When you pass a resource item without `routes` and `term` in the options.\n * @publicDocs\n */\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchQueryItem,\n options?: PredictiveSearchQueryItemUrlOptions,\n): string;\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchResourceItem,\n options: PredictiveSearchItemUrlOptions,\n): string;\n/**\n * @param item The predictive search result to link to.\n * @param options Route templates, search term, and path settings for the link.\n * @returns The link URL. The URL is relative unless you pass an absolute search path.\n */\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchItem,\n options?: AnyPredictiveSearchItemUrlOptions,\n): string {\n return getSearchResultUrl({\n baseUrl: getPredictiveSearchItemBaseUrl(item, options),\n term: getPredictiveSearchItemSearchTerm(item, options),\n trackingParameters: item.trackingParameters,\n });\n}\n\n/**\n * Builds a search page URL from a path, a search term, and optional extra\n * parameters. Use the function for search page links, such as a link to every\n * result for the current term.\n *\n * The search term and the extra parameters replace values with the same names in the base URL.\n *\n * @param options - The base URL, the search term, the extra and tracking parameters, and the search parameter name.\n * @returns A relative URL, or an absolute URL when the base URL is absolute.\n *\n * @publicDocs\n */\nexport function getSearchResultUrl({\n baseUrl,\n term,\n trackingParameters,\n params,\n searchParamName = \"q\",\n}: SearchResultUrlOptions): string {\n const url = new URL(baseUrl, RELATIVE_URL_BASE);\n\n for (const [name, value] of Object.entries(params ?? {})) {\n url.searchParams.set(name, value);\n }\n\n url.searchParams.set(searchParamName, term);\n appendTrackingParameters(url.searchParams, trackingParameters);\n\n if (isAbsoluteUrl(baseUrl)) return url.href;\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction getPredictiveSearchItemBaseUrl(\n item: PredictiveSearchItem,\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): string {\n if (item.__typename === \"SearchQuerySuggestion\") return getQueryBaseUrl(options);\n\n const { pathPrefix, routes } = requirePredictiveSearchItemUrlOptions(options);\n return getResourceBaseUrl(item, routes, pathPrefix);\n}\n\nfunction getQueryBaseUrl(options: AnyPredictiveSearchItemUrlOptions | undefined): string {\n if (options && \"searchPath\" in options && options.searchPath) return options.searchPath;\n\n return getStandardRoute(\n options?.routes ?? {},\n \"search\",\n {},\n {\n pathPrefix: options?.pathPrefix,\n },\n );\n}\n\nfunction getResourceBaseUrl(\n item: PredictiveSearchResourceItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n switch (item.__typename) {\n case \"Product\":\n return getProductBaseUrl(item, routes, pathPrefix);\n case \"Collection\":\n return getCollectionBaseUrl(item, routes, pathPrefix);\n case \"Page\":\n return getPageBaseUrl(item, routes, pathPrefix);\n case \"Article\":\n return getArticleBaseUrl(item, routes, pathPrefix);\n }\n}\n\nfunction getProductBaseUrl(\n product: PredictiveSearchProductItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(routes, \"product\", { productHandle: product.handle }, { pathPrefix });\n}\n\nfunction getCollectionBaseUrl(\n collection: PredictiveSearchCollectionItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(\n routes,\n \"collection\",\n { collectionHandle: collection.handle },\n { pathPrefix },\n );\n}\n\nfunction getPageBaseUrl(\n page: PredictiveSearchPageItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(routes, \"page\", { pageHandle: page.handle }, { pathPrefix });\n}\n\nfunction getArticleBaseUrl(\n article: PredictiveSearchArticleItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(\n routes,\n \"article\",\n { articleHandle: article.handle, blogHandle: article.blog.handle },\n { pathPrefix },\n );\n}\n\nfunction getPredictiveSearchItemSearchTerm(\n item: PredictiveSearchItem,\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): string {\n if (item.__typename === \"SearchQuerySuggestion\") return item.text;\n return requirePredictiveSearchItemUrlOptions(options).term;\n}\n\nfunction requirePredictiveSearchItemUrlOptions(\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): PredictiveSearchItemUrlOptions {\n if (options && \"term\" in options && \"routes\" in options) return options;\n\n throw new Error(\n \"Predictive search resource URLs require route templates and the typed search term.\",\n );\n}\n\nfunction appendTrackingParameters(params: URLSearchParams, trackingParameters?: string | null) {\n if (!trackingParameters) return;\n\n const tracking = new URLSearchParams(trackingParameters);\n for (const [name, value] of tracking) {\n params.append(name, value);\n }\n}\n\nfunction isAbsoluteUrl(url: string): boolean {\n return URL.canParse(url);\n}\n"],"mappings":";;;AAGA,MAAM,oBAAoB;;;;;;AAgG1B,SAAgB,2BACd,MACA,SACQ;AACR,QAAO,mBAAmB;EACxB,SAAS,+BAA+B,MAAM,QAAQ;EACtD,MAAM,kCAAkC,MAAM,QAAQ;EACtD,oBAAoB,KAAK;EAC1B,CAAC;;;;;;;;;;;;;;AAeJ,SAAgB,mBAAmB,EACjC,SACA,MACA,oBACA,QACA,kBAAkB,OACe;CACjC,MAAM,MAAM,IAAI,IAAI,SAAS,kBAAkB;AAE/C,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,EAAE,CAAC,CACtD,KAAI,aAAa,IAAI,MAAM,MAAM;AAGnC,KAAI,aAAa,IAAI,iBAAiB,KAAK;AAC3C,0BAAyB,IAAI,cAAc,mBAAmB;AAE9D,KAAI,cAAc,QAAQ,CAAE,QAAO,IAAI;AACvC,QAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;;AAG5C,SAAS,+BACP,MACA,SACQ;AACR,KAAI,KAAK,eAAe,wBAAyB,QAAO,gBAAgB,QAAQ;CAEhF,MAAM,EAAE,YAAY,WAAW,sCAAsC,QAAQ;AAC7E,QAAO,mBAAmB,MAAM,QAAQ,WAAW;;AAGrD,SAAS,gBAAgB,SAAgE;AACvF,KAAI,WAAW,gBAAgB,WAAW,QAAQ,WAAY,QAAO,QAAQ;AAE7E,QAAO,iBACL,SAAS,UAAU,EAAE,EACrB,UACA,EAAE,EACF,EACE,YAAY,SAAS,YACtB,CACF;;AAGH,SAAS,mBACP,MACA,QACA,YACQ;AACR,SAAQ,KAAK,YAAb;EACE,KAAK,UACH,QAAO,kBAAkB,MAAM,QAAQ,WAAW;EACpD,KAAK,aACH,QAAO,qBAAqB,MAAM,QAAQ,WAAW;EACvD,KAAK,OACH,QAAO,eAAe,MAAM,QAAQ,WAAW;EACjD,KAAK,UACH,QAAO,kBAAkB,MAAM,QAAQ,WAAW;;;AAIxD,SAAS,kBACP,SACA,QACA,YACQ;AACR,QAAO,iBAAiB,QAAQ,WAAW,EAAE,eAAe,QAAQ,QAAQ,EAAE,EAAE,YAAY,CAAC;;AAG/F,SAAS,qBACP,YACA,QACA,YACQ;AACR,QAAO,iBACL,QACA,cACA,EAAE,kBAAkB,WAAW,QAAQ,EACvC,EAAE,YAAY,CACf;;AAGH,SAAS,eACP,MACA,QACA,YACQ;AACR,QAAO,iBAAiB,QAAQ,QAAQ,EAAE,YAAY,KAAK,QAAQ,EAAE,EAAE,YAAY,CAAC;;AAGtF,SAAS,kBACP,SACA,QACA,YACQ;AACR,QAAO,iBACL,QACA,WACA;EAAE,eAAe,QAAQ;EAAQ,YAAY,QAAQ,KAAK;EAAQ,EAClE,EAAE,YAAY,CACf;;AAGH,SAAS,kCACP,MACA,SACQ;AACR,KAAI,KAAK,eAAe,wBAAyB,QAAO,KAAK;AAC7D,QAAO,sCAAsC,QAAQ,CAAC;;AAGxD,SAAS,sCACP,SACgC;AAChC,KAAI,WAAW,UAAU,WAAW,YAAY,QAAS,QAAO;AAEhE,OAAM,IAAI,MACR,qFACD;;AAGH,SAAS,yBAAyB,QAAyB,oBAAoC;AAC7F,KAAI,CAAC,mBAAoB;CAEzB,MAAM,WAAW,IAAI,gBAAgB,mBAAmB;AACxD,MAAK,MAAM,CAAC,MAAM,UAAU,SAC1B,QAAO,OAAO,MAAM,MAAM;;AAI9B,SAAS,cAAc,KAAsB;AAC3C,QAAO,IAAI,SAAS,IAAI"}
|
|
1
|
+
{"version":3,"file":"url.mjs","names":[],"sources":["../../../src/core/predictive-search/url.ts"],"sourcesContent":["import { getStandardRoute, type ShopifyRouteTemplates } from \"../standard-routes/index\";\nimport type { PredictiveSearchData } from \"./search\";\n\nconst RELATIVE_URL_BASE = \"https://hydrogen.local\";\n\ntype PredictiveSearchItems = PredictiveSearchData[\"items\"];\n\n/** A product result from predictive search. */\nexport type PredictiveSearchProductItem = PredictiveSearchItems[\"products\"][number];\n/** A collection result from predictive search. */\nexport type PredictiveSearchCollectionItem = PredictiveSearchItems[\"collections\"][number];\n/** A page result from predictive search. */\nexport type PredictiveSearchPageItem = PredictiveSearchItems[\"pages\"][number];\n/** An article result from predictive search. */\nexport type PredictiveSearchArticleItem = PredictiveSearchItems[\"articles\"][number];\n/** A suggested search term from predictive search. */\nexport type PredictiveSearchQueryItem = PredictiveSearchItems[\"queries\"][number];\n\n/** A product, collection, page, or article result. Excludes query suggestions. */\nexport type PredictiveSearchResourceItem =\n | PredictiveSearchProductItem\n | PredictiveSearchCollectionItem\n | PredictiveSearchPageItem\n | PredictiveSearchArticleItem;\n\n/** Any predictive search result, including query suggestions. */\nexport type PredictiveSearchItem = PredictiveSearchResourceItem | PredictiveSearchQueryItem;\n\n/**\n * Options for the link of a product, collection, page, or article result.\n *\n * Pass the route templates and the customer's search term.\n */\nexport type PredictiveSearchItemUrlOptions = {\n /** Prefix to add before the route path, such as a locale prefix. */\n pathPrefix?: string;\n /** Route templates for product, collection, page, and article paths, from `defineShopifyRouteTemplates`. */\n routes: ShopifyRouteTemplates;\n /** Search term that the customer typed. The link carries the term in the `q` URL parameter. */\n term: string;\n};\n\n/**\n * Options for the link of a query suggestion.\n *\n * By default, a suggestion links to the standard search route and searches for the suggestion's text.\n */\nexport type PredictiveSearchQueryItemUrlOptions = {\n /** Prefix to add before the search route, such as a locale prefix. Has no effect when you set a search path. */\n pathPrefix?: string;\n /** Route templates that set the search page path. Defaults to Hydrogen's standard search route. */\n routes?: ShopifyRouteTemplates;\n /** Search page path or URL to use as is, without the route templates or the path prefix. */\n searchPath?: string;\n};\n\n/** URL options for any predictive search result, either resource options or query suggestion options. */\ntype AnyPredictiveSearchItemUrlOptions =\n | PredictiveSearchItemUrlOptions\n | PredictiveSearchQueryItemUrlOptions;\n\n/** Options for a search result URL. */\nexport type SearchResultUrlOptions = {\n /** Search page path or absolute URL. */\n baseUrl: string;\n /** Search term to add to the URL. */\n term: string;\n /** Tracking parameters from a Storefront API search result. Pass the result's `trackingParameters` value unchanged. */\n trackingParameters?: string | null;\n /** Extra URL parameters, such as a result type filter. The search term replaces an extra parameter with the same name. */\n params?: Record<string, string>;\n /** URL parameter that carries the search term. Defaults to `q`. */\n searchParamName?: string;\n};\n\n/**\n * Builds the link for a predictive search result. A product, collection, page, or\n * article result links to the resource's page with the search term. A query suggestion links to\n * the search page and searches for the suggestion's text. Every link keeps the\n * result's tracking parameters.\n *\n * For a product, collection, page, or article, pass the route templates and the search term. The function throws an error without them.\n *\n * @throws {Error} When you pass a resource item without `routes` and `term` in the options.\n * @publicDocs\n */\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchQueryItem,\n options?: PredictiveSearchQueryItemUrlOptions,\n): string;\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchResourceItem,\n options: PredictiveSearchItemUrlOptions,\n): string;\n/**\n * @param item The predictive search result to link to.\n * @param options Route templates, search term, and path settings for the link.\n * @returns The link URL. The URL is relative unless you pass an absolute search path.\n */\nexport function getPredictiveSearchItemUrl(\n item: PredictiveSearchItem,\n options?: AnyPredictiveSearchItemUrlOptions,\n): string {\n return getSearchResultUrl({\n baseUrl: getPredictiveSearchItemBaseUrl(item, options),\n term: getPredictiveSearchItemSearchTerm(item, options),\n trackingParameters: item.trackingParameters,\n });\n}\n\n/**\n * Builds a search page URL from a path, a search term, and optional extra\n * parameters. Use the function for search page links, such as a link to every\n * result for the current term.\n *\n * The search term and the extra parameters replace values with the same names in the base URL.\n *\n * @param options - The base URL, the search term, the extra and tracking parameters, and the search parameter name.\n * @returns A relative URL, or an absolute URL when the base URL is absolute.\n *\n * @publicDocs\n */\nexport function getSearchResultUrl({\n baseUrl,\n term,\n trackingParameters,\n params,\n searchParamName = \"q\",\n}: SearchResultUrlOptions): string {\n const url = new URL(baseUrl, RELATIVE_URL_BASE);\n\n for (const [name, value] of Object.entries(params ?? {})) {\n url.searchParams.set(name, value);\n }\n\n url.searchParams.set(searchParamName, term);\n appendTrackingParameters(url.searchParams, trackingParameters);\n\n if (isAbsoluteUrl(baseUrl)) return url.href;\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction getPredictiveSearchItemBaseUrl(\n item: PredictiveSearchItem,\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): string {\n if (item.__typename === \"SearchQuerySuggestion\") return getQueryBaseUrl(options);\n\n const { pathPrefix, routes } = requirePredictiveSearchItemUrlOptions(options);\n return getResourceBaseUrl(item, routes, pathPrefix);\n}\n\nfunction getQueryBaseUrl(options: AnyPredictiveSearchItemUrlOptions | undefined): string {\n if (options && \"searchPath\" in options && options.searchPath) return options.searchPath;\n\n return getStandardRoute(\n options?.routes ?? {},\n \"search\",\n {},\n {\n pathPrefix: options?.pathPrefix,\n },\n );\n}\n\nfunction getResourceBaseUrl(\n item: PredictiveSearchResourceItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n switch (item.__typename) {\n case \"Product\":\n return getProductBaseUrl(item, routes, pathPrefix);\n case \"Collection\":\n return getCollectionBaseUrl(item, routes, pathPrefix);\n case \"Page\":\n return getPageBaseUrl(item, routes, pathPrefix);\n case \"Article\":\n return getArticleBaseUrl(item, routes, pathPrefix);\n }\n}\n\nfunction getProductBaseUrl(\n product: PredictiveSearchProductItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(routes, \"product\", { productHandle: product.handle }, { pathPrefix });\n}\n\nfunction getCollectionBaseUrl(\n collection: PredictiveSearchCollectionItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(\n routes,\n \"collection\",\n { collectionHandle: collection.handle },\n { pathPrefix },\n );\n}\n\nfunction getPageBaseUrl(\n page: PredictiveSearchPageItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(routes, \"page\", { pageHandle: page.handle }, { pathPrefix });\n}\n\nfunction getArticleBaseUrl(\n article: PredictiveSearchArticleItem,\n routes: ShopifyRouteTemplates,\n pathPrefix: string | undefined,\n): string {\n return getStandardRoute(\n routes,\n \"article\",\n { articleHandle: article.handle, blogHandle: article.blog.handle },\n { pathPrefix },\n );\n}\n\nfunction getPredictiveSearchItemSearchTerm(\n item: PredictiveSearchItem,\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): string {\n if (item.__typename === \"SearchQuerySuggestion\") return item.text;\n return requirePredictiveSearchItemUrlOptions(options).term;\n}\n\nfunction requirePredictiveSearchItemUrlOptions(\n options: AnyPredictiveSearchItemUrlOptions | undefined,\n): PredictiveSearchItemUrlOptions {\n if (options && \"term\" in options && \"routes\" in options) return options;\n\n throw new Error(\n \"Predictive search resource URLs require route templates and the typed search term.\",\n );\n}\n\nfunction appendTrackingParameters(params: URLSearchParams, trackingParameters?: string | null) {\n if (!trackingParameters) return;\n\n const tracking = new URLSearchParams(trackingParameters);\n for (const [name, value] of tracking) {\n params.append(name, value);\n }\n}\n\nfunction isAbsoluteUrl(url: string): boolean {\n return URL.canParse(url);\n}\n"],"mappings":";;;AAGA,MAAM,oBAAoB;;;;;;AAgG1B,SAAgB,2BACd,MACA,SACQ;AACR,QAAO,mBAAmB;EACxB,SAAS,+BAA+B,MAAM,QAAQ;EACtD,MAAM,kCAAkC,MAAM,QAAQ;EACtD,oBAAoB,KAAK;EAC1B,CAAC;;;;;;;;;;;;;;AAeJ,SAAgB,mBAAmB,EACjC,SACA,MACA,oBACA,QACA,kBAAkB,OACe;CACjC,MAAM,MAAM,IAAI,IAAI,SAAS,kBAAkB;AAE/C,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,UAAU,EAAE,CAAC,CACtD,KAAI,aAAa,IAAI,MAAM,MAAM;AAGnC,KAAI,aAAa,IAAI,iBAAiB,KAAK;AAC3C,0BAAyB,IAAI,cAAc,mBAAmB;AAE9D,KAAI,cAAc,QAAQ,CAAE,QAAO,IAAI;AACvC,QAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;;AAG5C,SAAS,+BACP,MACA,SACQ;AACR,KAAI,KAAK,eAAe,wBAAyB,QAAO,gBAAgB,QAAQ;CAEhF,MAAM,EAAE,YAAY,WAAW,sCAAsC,QAAQ;AAC7E,QAAO,mBAAmB,MAAM,QAAQ,WAAW;;AAGrD,SAAS,gBAAgB,SAAgE;AACvF,KAAI,WAAW,gBAAgB,WAAW,QAAQ,WAAY,QAAO,QAAQ;AAE7E,QAAO,iBACL,SAAS,UAAU,EAAE,EACrB,UACA,EAAE,EACF,EACE,YAAY,SAAS,YACtB,CACF;;AAGH,SAAS,mBACP,MACA,QACA,YACQ;AACR,SAAQ,KAAK,YAAb;EACE,KAAK,UACH,QAAO,kBAAkB,MAAM,QAAQ,WAAW;EACpD,KAAK,aACH,QAAO,qBAAqB,MAAM,QAAQ,WAAW;EACvD,KAAK,OACH,QAAO,eAAe,MAAM,QAAQ,WAAW;EACjD,KAAK,UACH,QAAO,kBAAkB,MAAM,QAAQ,WAAW;;;AAIxD,SAAS,kBACP,SACA,QACA,YACQ;AACR,QAAO,iBAAiB,QAAQ,WAAW,EAAE,eAAe,QAAQ,QAAQ,EAAE,EAAE,YAAY,CAAC;;AAG/F,SAAS,qBACP,YACA,QACA,YACQ;AACR,QAAO,iBACL,QACA,cACA,EAAE,kBAAkB,WAAW,QAAQ,EACvC,EAAE,YAAY,CACf;;AAGH,SAAS,eACP,MACA,QACA,YACQ;AACR,QAAO,iBAAiB,QAAQ,QAAQ,EAAE,YAAY,KAAK,QAAQ,EAAE,EAAE,YAAY,CAAC;;AAGtF,SAAS,kBACP,SACA,QACA,YACQ;AACR,QAAO,iBACL,QACA,WACA;EAAE,eAAe,QAAQ;EAAQ,YAAY,QAAQ,KAAK;EAAQ,EAClE,EAAE,YAAY,CACf;;AAGH,SAAS,kCACP,MACA,SACQ;AACR,KAAI,KAAK,eAAe,wBAAyB,QAAO,KAAK;AAC7D,QAAO,sCAAsC,QAAQ,CAAC;;AAGxD,SAAS,sCACP,SACgC;AAChC,KAAI,WAAW,UAAU,WAAW,YAAY,QAAS,QAAO;AAEhE,OAAM,IAAI,MACR,qFACD;;AAGH,SAAS,yBAAyB,QAAyB,oBAAoC;AAC7F,KAAI,CAAC,mBAAoB;CAEzB,MAAM,WAAW,IAAI,gBAAgB,mBAAmB;AACxD,MAAK,MAAM,CAAC,MAAM,UAAU,SAC1B,QAAO,OAAO,MAAM,MAAM;;AAI9B,SAAS,cAAc,KAAsB;AAC3C,QAAO,IAAI,SAAS,IAAI"}
|
|
@@ -33,7 +33,7 @@ const handleProductVariantId = (url, { request, requestContext, storefrontClient
|
|
|
33
33
|
if (request.method !== "GET" && request.method !== "HEAD") return null;
|
|
34
34
|
const variantId = parseVariantSearchParam(url.searchParams.get(VARIANT_SEARCH_PARAM));
|
|
35
35
|
if (!variantId) return null;
|
|
36
|
-
const pathPrefix = requestContext.
|
|
36
|
+
const pathPrefix = requestContext.locale.pathPrefix;
|
|
37
37
|
const match = matchStandardRouteUrl({
|
|
38
38
|
routeTemplates,
|
|
39
39
|
pathPrefix,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accept-variant-id.mjs","names":[],"sources":["../../../src/core/product/accept-variant-id.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../client\";\nimport { withStorefrontClientCache } from \"../../client/client\";\nimport { StorefrontApiError } from \"../../client/errors\";\nimport { gql } from \"../../graphql\";\nimport { Cache } from \"../cache\";\nimport { getLogger } from \"../logging\";\nimport type { HydrogenRouteInterceptor } from \"../request-routing/route-types\";\nimport { getStandardRoute } from \"../standard-routes/build\";\nimport { matchStandardRouteUrl } from \"../standard-routes/match\";\nimport type { ShopifyRouteTemplates } from \"../standard-routes/types\";\nimport {\n buildProductSelectionSearchParams,\n parseVariantSearchParam,\n VARIANT_SEARCH_PARAM,\n} from \"./url\";\n\nconst log = getLogger(\"product\");\n\nconst HTTP_FOUND_STATUS = 302;\n\nconst VARIANT_SELECTED_OPTIONS_QUERY = gql(`\n query VariantSelectedOptions($id: ID!, $country: CountryCode, $language: LanguageCode)\n @inContext(country: $country, language: $language) {\n node(id: $id) {\n ... on ProductVariant {\n selectedOptions {\n name\n value\n }\n product {\n handle\n }\n }\n }\n }\n`);\n\ntype SelectedOptionsVariant = {\n selectedOptions: { name: string; value: string }[];\n product: { handle: string };\n};\n\n/**\n * Accepts Liquid-style `?variant=<numeric id>` links on product pages by redirecting them\n * to the canonical option-params URL, e.g. `/products/snowboard?variant=123` →\n * `302 /products/snowboard?Color=Red&Size=M`.\n *\n * `handleShopifyRoutes` runs this before app routing. It claims only GET/HEAD requests\n * whose URL matches a product route template and carries a numeric `variant` param;\n * everything else falls through to the framework. When both `variant` and option params\n * are present, the variant wins and the option params are replaced.\n * Unknown/deleted variant ids redirect to the same URL with the `variant` param stripped,\n * preserving any remaining params for the product loader. Params unrelated to the\n * selection (`?ref=campaign`) are preserved. On cross-product (combined listing) redirects,\n * params matching the *source* product's option names are not stripped — the handler only\n * knows the target variant's options; loaders filtering with `allowedOptionNames` ignore\n * the leftovers.\n *\n * Configure the app's URL shape once with `handleShopifyRoutes({ routeTemplates })`.\n */\nexport const handleProductVariantId: HydrogenRouteInterceptor = (\n url,\n { request, requestContext, storefrontClient, routeTemplates = {} },\n) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n\n const variantId = parseVariantSearchParam(url.searchParams.get(VARIANT_SEARCH_PARAM));\n if (!variantId) return null;\n\n const pathPrefix = requestContext.
|
|
1
|
+
{"version":3,"file":"accept-variant-id.mjs","names":[],"sources":["../../../src/core/product/accept-variant-id.ts"],"sourcesContent":["import type { StorefrontClient } from \"../../client\";\nimport { withStorefrontClientCache } from \"../../client/client\";\nimport { StorefrontApiError } from \"../../client/errors\";\nimport { gql } from \"../../graphql\";\nimport { Cache } from \"../cache\";\nimport { getLogger } from \"../logging\";\nimport type { HydrogenRouteInterceptor } from \"../request-routing/route-types\";\nimport { getStandardRoute } from \"../standard-routes/build\";\nimport { matchStandardRouteUrl } from \"../standard-routes/match\";\nimport type { ShopifyRouteTemplates } from \"../standard-routes/types\";\nimport {\n buildProductSelectionSearchParams,\n parseVariantSearchParam,\n VARIANT_SEARCH_PARAM,\n} from \"./url\";\n\nconst log = getLogger(\"product\");\n\nconst HTTP_FOUND_STATUS = 302;\n\nconst VARIANT_SELECTED_OPTIONS_QUERY = gql(`\n query VariantSelectedOptions($id: ID!, $country: CountryCode, $language: LanguageCode)\n @inContext(country: $country, language: $language) {\n node(id: $id) {\n ... on ProductVariant {\n selectedOptions {\n name\n value\n }\n product {\n handle\n }\n }\n }\n }\n`);\n\ntype SelectedOptionsVariant = {\n selectedOptions: { name: string; value: string }[];\n product: { handle: string };\n};\n\n/**\n * Accepts Liquid-style `?variant=<numeric id>` links on product pages by redirecting them\n * to the canonical option-params URL, e.g. `/products/snowboard?variant=123` →\n * `302 /products/snowboard?Color=Red&Size=M`.\n *\n * `handleShopifyRoutes` runs this before app routing. It claims only GET/HEAD requests\n * whose URL matches a product route template and carries a numeric `variant` param;\n * everything else falls through to the framework. When both `variant` and option params\n * are present, the variant wins and the option params are replaced.\n * Unknown/deleted variant ids redirect to the same URL with the `variant` param stripped,\n * preserving any remaining params for the product loader. Params unrelated to the\n * selection (`?ref=campaign`) are preserved. On cross-product (combined listing) redirects,\n * params matching the *source* product's option names are not stripped — the handler only\n * knows the target variant's options; loaders filtering with `allowedOptionNames` ignore\n * the leftovers.\n *\n * Configure the app's URL shape once with `handleShopifyRoutes({ routeTemplates })`.\n */\nexport const handleProductVariantId: HydrogenRouteInterceptor = (\n url,\n { request, requestContext, storefrontClient, routeTemplates = {} },\n) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n\n const variantId = parseVariantSearchParam(url.searchParams.get(VARIANT_SEARCH_PARAM));\n if (!variantId) return null;\n\n const pathPrefix = requestContext.locale.pathPrefix;\n const match = matchStandardRouteUrl({ routeTemplates, pathPrefix, url: url.href });\n if (match?.pageTemplateName !== \"product\") return null;\n\n return resolveVariantRedirect({\n pathPrefix,\n requestedHandle: match.params.productHandle,\n routeTemplates,\n storefrontClient,\n url,\n variantId,\n });\n};\n\nasync function resolveVariantRedirect({\n pathPrefix,\n requestedHandle,\n routeTemplates,\n storefrontClient,\n url,\n variantId,\n}: {\n pathPrefix: string | undefined;\n requestedHandle: string | undefined;\n routeTemplates: ShopifyRouteTemplates;\n storefrontClient: StorefrontClient;\n url: URL;\n variantId: string;\n}): Promise<Response> {\n const variant = await queryVariantSelectedOptions(storefrontClient, variantId);\n\n const searchParams = buildProductSelectionSearchParams({\n selectedOptions: variant?.selectedOptions ?? [],\n optionNames: [],\n base: url.searchParams,\n });\n\n const pathname =\n variant && !isSameHandle(variant.product.handle, requestedHandle)\n ? getStandardRoute(\n routeTemplates,\n \"product\",\n { productHandle: variant.product.handle },\n { pathPrefix },\n )\n : url.pathname;\n\n const search = searchParams.toString();\n const location = search ? `${pathname}?${search}` : pathname;\n return new Response(null, {\n status: HTTP_FOUND_STATUS,\n headers: { location: new URL(location, url.origin).toString() },\n });\n}\n\nasync function queryVariantSelectedOptions(\n storefrontClient: StorefrontClient,\n variantId: string,\n): Promise<SelectedOptionsVariant | null> {\n try {\n const result = await storefrontClient.graphql(\n VARIANT_SELECTED_OPTIONS_QUERY,\n withStorefrontClientCache(\n storefrontClient,\n { variables: { id: variantId } },\n Cache.long(),\n hasResolvedVariant,\n ),\n );\n\n if (result.errors) {\n log.error(\"variant id redirect lookup failed\", { errors: result.errors, variantId });\n return null;\n }\n\n const node = result.data?.node;\n if (node && \"selectedOptions\" in node) return node;\n } catch (error) {\n if (!(error instanceof StorefrontApiError)) throw error;\n\n // Losing the requested selection beats failing the page: strip the param and render\n // the default variant instead of surfacing a 5xx for a lookup the buyer cannot retry.\n log.error(\"variant id redirect lookup failed\", { error, variantId });\n }\n\n return null;\n}\n\nfunction hasResolvedVariant(body: object): boolean {\n if (!(\"data\" in body) || typeof body.data !== \"object\" || body.data == null) return false;\n return \"node\" in body.data && body.data.node != null;\n}\n\nfunction isSameHandle(variantProductHandle: string, requestedHandle: string | undefined): boolean {\n return requestedHandle !== undefined\n ? variantProductHandle.toLowerCase() === requestedHandle.toLowerCase()\n : true;\n}\n"],"mappings":";;;;;;;;;;AAgBA,MAAA,MAAA,UAAA,UAAA;AAEA,MAAA,oBAAA;AAEA,MAAA,iCAAA,IAAA,iNAeA;;;;;;;;;;;;;;;;;;;AAyBA,MAAA,0BACA,KACA,EAAA,SAAA,gBAAA,kBAAA,iBAAA,EAAA,OACA;AACA,KAAA,QAAA,WAAA,SAAA,QAAA,WAAA,OAAA,QAAA;CAEA,MAAA,YAAA,wBAAA,IAAA,aAAA,IAAA,qBAAA,CAAA;AACA,KAAA,CAAA,UAAA,QAAA;CAEA,MAAA,aAAA,eAAA,OAAA;CACA,MAAA,QAAA,sBAAA;EAAA;EAAA;EAAA,KAAA,IAAA;EAAA,CAAA;AACA,KAAA,OAAA,qBAAA,UAAA,QAAA;AAEA,QAAA,uBAAA;EACA;EACA,iBAAA,MAAA,OAAA;EACA;EACA;EACA;EACA;EACA,CAAA;;AAGA,eAAA,uBAAA,EACA,YACA,iBACA,gBACA,kBACA,KACA,aAQA;CACA,MAAA,UAAA,MAAA,4BAAA,kBAAA,UAAA;CAEA,MAAA,eAAA,kCAAA;EACA,iBAAA,SAAA,mBAAA,EAAA;EACA,aAAA,EAAA;EACA,MAAA,IAAA;EACA,CAAA;CAEA,MAAA,WACA,WAAA,CAAA,aAAA,QAAA,QAAA,QAAA,gBAAA,GACA,iBACA,gBACA,WACA,EAAA,eAAA,QAAA,QAAA,QAAA,EACA,EAAA,YAAA,CACA,GACA,IAAA;CAEA,MAAA,SAAA,aAAA,UAAA;CACA,MAAA,WAAA,SAAA,GAAA,SAAA,GAAA,WAAA;AACA,QAAA,IAAA,SAAA,MAAA;EACA,QAAA;EACA,SAAA,EAAA,UAAA,IAAA,IAAA,UAAA,IAAA,OAAA,CAAA,UAAA,EAAA;EACA,CAAA;;AAGA,eAAA,4BACA,kBACA,WACA;AACA,KAAA;EACA,MAAA,SAAA,MAAA,iBAAA,QACA,gCACA,0BACA,kBACA,EAAA,WAAA,EAAA,IAAA,WAAA,EAAA,EACA,MAAA,MAAA,EACA,mBACA,CACA;AAEA,MAAA,OAAA,QAAA;AACA,OAAA,MAAA,qCAAA;IAAA,QAAA,OAAA;IAAA;IAAA,CAAA;AACA,UAAA;;EAGA,MAAA,OAAA,OAAA,MAAA;AACA,MAAA,QAAA,qBAAA,KAAA,QAAA;UACA,OAAA;AACA,MAAA,EAAA,iBAAA,oBAAA,OAAA;AAIA,MAAA,MAAA,qCAAA;GAAA;GAAA;GAAA,CAAA;;AAGA,QAAA;;AAGA,SAAA,mBAAA,MAAA;AACA,KAAA,EAAA,UAAA,SAAA,OAAA,KAAA,SAAA,YAAA,KAAA,QAAA,KAAA,QAAA;AACA,QAAA,UAAA,KAAA,QAAA,KAAA,KAAA,QAAA;;AAGA,SAAA,aAAA,sBAAA,iBAAA;AACA,QAAA,oBAAA,SACA,qBAAA,aAAA,KAAA,gBAAA,aAAA,GACA"}
|
|
@@ -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
|