@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.
Files changed (245) hide show
  1. package/README.md +3 -5
  2. package/dist/cli/index.mjs +2 -2
  3. package/dist/client/client.mjs +44 -9
  4. package/dist/client/client.mjs.map +1 -1
  5. package/dist/client/i18n-variables.d.mts +1 -1
  6. package/dist/client/i18n-variables.mjs +14 -6
  7. package/dist/client/i18n-variables.mjs.map +1 -1
  8. package/dist/client/types.d.mts +12 -6
  9. package/dist/core/cache/fetch-with-cache.mjs +8 -1
  10. package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
  11. package/dist/core/cart/cart.mjs +1 -1
  12. package/dist/core/cart/cookie.mjs +6 -1
  13. package/dist/core/cart/cookie.mjs.map +1 -1
  14. package/dist/core/cart/form.d.mts +17 -5
  15. package/dist/core/cart/form.mjs +5 -0
  16. package/dist/core/cart/form.mjs.map +1 -1
  17. package/dist/core/cart/index.d.mts +1 -1
  18. package/dist/core/collection/url.mjs +8 -1
  19. package/dist/core/collection/url.mjs.map +1 -1
  20. package/dist/core/constants.mjs +2 -1
  21. package/dist/core/constants.mjs.map +1 -1
  22. package/dist/core/csp/index.d.mts +56 -0
  23. package/dist/core/csp/index.mjs +117 -0
  24. package/dist/core/csp/index.mjs.map +1 -0
  25. package/dist/core/csp/types.d.mts +52 -0
  26. package/dist/core/headers.mjs +2 -2
  27. package/dist/core/headers.mjs.map +1 -1
  28. package/dist/core/i18n/define.d.mts +54 -0
  29. package/dist/core/i18n/define.mjs +135 -0
  30. package/dist/core/i18n/define.mjs.map +1 -0
  31. package/dist/core/i18n/errors.d.mts +18 -0
  32. package/dist/core/i18n/errors.mjs +24 -0
  33. package/dist/core/i18n/errors.mjs.map +1 -0
  34. package/dist/core/i18n/href.d.mts +28 -0
  35. package/dist/core/i18n/href.mjs +45 -0
  36. package/dist/core/i18n/href.mjs.map +1 -0
  37. package/dist/core/i18n/locale.d.mts +21 -0
  38. package/dist/core/i18n/locale.mjs +36 -0
  39. package/dist/core/i18n/locale.mjs.map +1 -0
  40. package/dist/core/i18n/match.d.mts +37 -0
  41. package/dist/core/i18n/match.mjs +82 -0
  42. package/dist/core/i18n/match.mjs.map +1 -0
  43. package/dist/core/i18n/types.d.mts +80 -0
  44. package/dist/core/index.d.mts +14 -5
  45. package/dist/core/index.mjs +9 -2
  46. package/dist/core/predictive-search/index.d.mts +2 -2
  47. package/dist/core/predictive-search/server-handlers.d.mts +27 -6
  48. package/dist/core/predictive-search/server-handlers.mjs +1 -4
  49. package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
  50. package/dist/core/predictive-search/url.d.mts +2 -2
  51. package/dist/core/predictive-search/url.mjs.map +1 -1
  52. package/dist/core/product/accept-variant-id.mjs +1 -1
  53. package/dist/core/product/accept-variant-id.mjs.map +1 -1
  54. package/dist/core/request-context.d.mts +61 -35
  55. package/dist/core/request-context.mjs +11 -7
  56. package/dist/core/request-context.mjs.map +1 -1
  57. package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  58. package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
  59. package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  60. package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
  61. package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
  62. package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
  63. package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  64. package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
  65. package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  66. package/dist/core/request-routing/registered-routes.d.mts +10 -3
  67. package/dist/core/request-routing/registered-routes.mjs +13 -3
  68. package/dist/core/request-routing/registered-routes.mjs.map +1 -1
  69. package/dist/core/request-routing/route-types.d.mts +2 -2
  70. package/dist/core/shop-pay/shop-pay.mjs +5 -4
  71. package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
  72. package/dist/core/shopify-scripts/analytics.mjs +3 -5
  73. package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
  74. package/dist/core/shopify-scripts/constants.mjs +3 -1
  75. package/dist/core/shopify-scripts/constants.mjs.map +1 -1
  76. package/dist/core/shopify-scripts/global.mjs +13 -11
  77. package/dist/core/shopify-scripts/global.mjs.map +1 -1
  78. package/dist/core/shopify-scripts/hashes.d.mts +17 -0
  79. package/dist/core/shopify-scripts/hashes.mjs +12 -0
  80. package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
  81. package/dist/core/shopify-scripts/index.d.mts +1 -0
  82. package/dist/core/shopify-scripts/index.mjs +12 -9
  83. package/dist/core/shopify-scripts/index.mjs.map +1 -1
  84. package/dist/core/shopify-scripts/page-view.mjs +4 -1
  85. package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
  86. package/dist/core/shopify-scripts/types.d.mts +4 -2
  87. package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
  88. package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  89. package/dist/core/standard-routes/build.d.mts +7 -2
  90. package/dist/core/standard-routes/build.mjs +10 -3
  91. package/dist/core/standard-routes/build.mjs.map +1 -1
  92. package/dist/core/standard-routes/match.mjs +11 -1
  93. package/dist/core/standard-routes/match.mjs.map +1 -1
  94. package/dist/core/standard-routes/path.mjs +14 -3
  95. package/dist/core/standard-routes/path.mjs.map +1 -1
  96. package/dist/core/standard-routes/types.d.mts +6 -1
  97. package/dist/core/url.mjs +5 -3
  98. package/dist/core/url.mjs.map +1 -1
  99. package/dist/customer-account/client.d.mts +14 -10
  100. package/dist/customer-account/client.mjs +4 -5
  101. package/dist/customer-account/client.mjs.map +1 -1
  102. package/dist/customer-account/graphql.d.mts +7 -1
  103. package/dist/customer-account/graphql.mjs +6 -7
  104. package/dist/customer-account/graphql.mjs.map +1 -1
  105. package/dist/customer-account/session.mjs +3 -4
  106. package/dist/customer-account/session.mjs.map +1 -1
  107. package/dist/development/client/client.mjs +44 -9
  108. package/dist/development/client/client.mjs.map +1 -1
  109. package/dist/development/client/i18n-variables.d.mts +1 -1
  110. package/dist/development/client/i18n-variables.mjs +13 -5
  111. package/dist/development/client/i18n-variables.mjs.map +1 -1
  112. package/dist/development/client/types.d.mts +12 -6
  113. package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
  114. package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
  115. package/dist/development/core/cart/cart.mjs +1 -1
  116. package/dist/development/core/cart/cookie.mjs +6 -1
  117. package/dist/development/core/cart/cookie.mjs.map +1 -1
  118. package/dist/development/core/cart/form.d.mts +17 -5
  119. package/dist/development/core/cart/form.mjs +5 -0
  120. package/dist/development/core/cart/form.mjs.map +1 -1
  121. package/dist/development/core/cart/index.d.mts +1 -1
  122. package/dist/development/core/cart/queries.d.mts +57 -57
  123. package/dist/development/core/collection/url.mjs +8 -1
  124. package/dist/development/core/collection/url.mjs.map +1 -1
  125. package/dist/development/core/constants.mjs +2 -1
  126. package/dist/development/core/constants.mjs.map +1 -1
  127. package/dist/development/core/csp/index.d.mts +56 -0
  128. package/dist/development/core/csp/index.mjs +128 -0
  129. package/dist/development/core/csp/index.mjs.map +1 -0
  130. package/dist/development/core/csp/types.d.mts +52 -0
  131. package/dist/development/core/development.d.mts +14 -5
  132. package/dist/development/core/development.mjs +9 -2
  133. package/dist/development/core/headers.mjs +2 -2
  134. package/dist/development/core/headers.mjs.map +1 -1
  135. package/dist/development/core/i18n/define.d.mts +54 -0
  136. package/dist/development/core/i18n/define.mjs +135 -0
  137. package/dist/development/core/i18n/define.mjs.map +1 -0
  138. package/dist/development/core/i18n/errors.d.mts +18 -0
  139. package/dist/development/core/i18n/errors.mjs +24 -0
  140. package/dist/development/core/i18n/errors.mjs.map +1 -0
  141. package/dist/development/core/i18n/href.d.mts +28 -0
  142. package/dist/development/core/i18n/href.mjs +45 -0
  143. package/dist/development/core/i18n/href.mjs.map +1 -0
  144. package/dist/development/core/i18n/locale.d.mts +21 -0
  145. package/dist/development/core/i18n/locale.mjs +36 -0
  146. package/dist/development/core/i18n/locale.mjs.map +1 -0
  147. package/dist/development/core/i18n/match.d.mts +37 -0
  148. package/dist/development/core/i18n/match.mjs +82 -0
  149. package/dist/development/core/i18n/match.mjs.map +1 -0
  150. package/dist/development/core/i18n/types.d.mts +80 -0
  151. package/dist/development/core/index.d.mts +13 -4
  152. package/dist/development/core/predictive-search/index.d.mts +2 -2
  153. package/dist/development/core/predictive-search/queries.d.mts +2 -2
  154. package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
  155. package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
  156. package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
  157. package/dist/development/core/predictive-search/url.d.mts +2 -2
  158. package/dist/development/core/predictive-search/url.mjs.map +1 -1
  159. package/dist/development/core/product/accept-variant-id.mjs +1 -1
  160. package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
  161. package/dist/development/core/request-context.d.mts +61 -35
  162. package/dist/development/core/request-context.mjs +11 -7
  163. package/dist/development/core/request-context.mjs.map +1 -1
  164. package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  165. package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
  166. package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  167. package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
  168. package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
  169. package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
  170. package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  171. package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
  172. package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  173. package/dist/development/core/request-routing/registered-routes.d.mts +10 -3
  174. package/dist/development/core/request-routing/registered-routes.mjs +13 -3
  175. package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
  176. package/dist/development/core/request-routing/route-types.d.mts +2 -2
  177. package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
  178. package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
  179. package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
  180. package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
  181. package/dist/development/core/shopify-scripts/constants.mjs +3 -1
  182. package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
  183. package/dist/development/core/shopify-scripts/global.mjs +13 -11
  184. package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
  185. package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
  186. package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
  187. package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
  188. package/dist/development/core/shopify-scripts/index.d.mts +1 -0
  189. package/dist/development/core/shopify-scripts/index.mjs +12 -9
  190. package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
  191. package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
  192. package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
  193. package/dist/development/core/shopify-scripts/types.d.mts +4 -2
  194. package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
  195. package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  196. package/dist/development/core/standard-routes/build.d.mts +7 -2
  197. package/dist/development/core/standard-routes/build.mjs +10 -3
  198. package/dist/development/core/standard-routes/build.mjs.map +1 -1
  199. package/dist/development/core/standard-routes/match.mjs +11 -1
  200. package/dist/development/core/standard-routes/match.mjs.map +1 -1
  201. package/dist/development/core/standard-routes/path.mjs +14 -3
  202. package/dist/development/core/standard-routes/path.mjs.map +1 -1
  203. package/dist/development/core/standard-routes/types.d.mts +6 -1
  204. package/dist/development/core/url.mjs +5 -3
  205. package/dist/development/core/url.mjs.map +1 -1
  206. package/dist/development/customer-account/session.mjs.map +1 -1
  207. package/dist/development/globals.d.mts +8 -4
  208. package/dist/development/graphql/type-resolver.d.mts +13 -1
  209. package/dist/development/react/index.d.mts +2 -2
  210. package/dist/globals.d.mts +8 -4
  211. package/dist/graphql/type-resolver.d.mts +13 -1
  212. package/dist/react/index.d.mts +2 -2
  213. package/dist/vite/index.mjs +1 -1
  214. package/dist/vue/shopify-scripts.d.mts +1 -1
  215. package/package.json +13 -3
  216. package/skills/hydrogen-analytics/SKILL.md +2 -2
  217. package/skills/hydrogen-analytics/references/react.md +2 -2
  218. package/skills/hydrogen-markets/SKILL.md +127 -93
  219. package/skills/hydrogen-markets/references/nextjs.md +77 -87
  220. package/skills/hydrogen-oxygen/references/react-router.md +1 -2
  221. package/skills/hydrogen-predictive-search/SKILL.md +18 -1
  222. package/skills/hydrogen-request-handlers/SKILL.md +23 -5
  223. package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
  224. package/skills/hydrogen-request-handlers/references/frameworks.md +8 -6
  225. package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
  226. package/skills/hydrogen-request-handlers/references/nuxt.md +7 -5
  227. package/skills/hydrogen-robots-txt/SKILL.md +87 -0
  228. package/skills/hydrogen-routing/SKILL.md +36 -14
  229. package/skills/hydrogen-setup/SKILL.md +2 -2
  230. package/skills/hydrogen-setup/references/analytics.md +5 -5
  231. package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
  232. package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
  233. package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
  234. package/skills/hydrogen-smoke-test/SKILL.md +9 -2
  235. package/skills/hydrogen-storefront-client/SKILL.md +27 -9
  236. package/skills/hydrogen-storefront-client/references/astro.md +8 -3
  237. package/skills/hydrogen-storefront-client/references/caching.md +2 -0
  238. package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
  239. package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
  240. package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
  241. package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
  242. package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
  243. package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
  244. package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
  245. package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
@@ -1,6 +1,6 @@
1
1
  import { getLogger } from "../core/logging/logging.mjs";
2
2
  import { CUSTOMER_ACCOUNT_PATHS, getSameOriginPath } from "../core/url.mjs";
3
- import { DEFAULT_TIMEOUT_IN_MS } from "../core/constants.mjs";
3
+ import { DEFAULT_TIMEOUT_IN_MS, HYDROGEN_USER_AGENT } from "../core/constants.mjs";
4
4
  import { createCallableRouteHandler } from "../core/request-routing/registered-routes.mjs";
5
5
  import { getCartBuyerIdentitySync } from "../core/cart/buyer-identity-sync.mjs";
6
6
  import { CustomerAccountApiError, CustomerAccountOAuthError } from "./errors.mjs";
@@ -44,7 +44,6 @@ const AUTHORIZATION_CODE_GRANT_TYPE = "authorization_code";
44
44
  const REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
45
45
  const CUSTOMER_ACCOUNT_SCOPE = "openid email customer-account-api:full";
46
46
  const CODE_CHALLENGE_METHOD = "S256";
47
- const USER_AGENT = `Hydrogen 2026.10.2`;
48
47
  const EXPIRY_BUFFER_IN_SECONDS = 120;
49
48
  const PENDING_LOGIN_TTL_IN_MINUTES = 10;
50
49
  const SECONDS_PER_MINUTE = 60;
@@ -266,7 +265,7 @@ async function handleLoginRoute(customerSession, sessionManager, requestContext,
266
265
  return redirectResult(await customerSession.prepareLoginUrl(sessionManager, requestContext, {
267
266
  origin,
268
267
  returnTo,
269
- countryCode: requestContext.i18n.country,
268
+ countryCode: requestContext.locale.country,
270
269
  locale: getOptionalSearchParam(requestUrl, "locale"),
271
270
  acrValues: getOptionalSearchParam(requestUrl, "acr_values"),
272
271
  loginHint: getOptionalSearchParam(requestUrl, "login_hint"),
@@ -518,7 +517,7 @@ async function postTokenRequest({ url, origin, body, fetch, signal }) {
518
517
  method: "POST",
519
518
  headers: new Headers({
520
519
  "Content-Type": "application/x-www-form-urlencoded",
521
- "User-Agent": USER_AGENT,
520
+ "User-Agent": HYDROGEN_USER_AGENT,
522
521
  Origin: origin
523
522
  }),
524
523
  body,
@@ -1 +1 @@
1
- {"version":3,"file":"session.mjs","names":[],"sources":["../../src/customer-account/session.ts"],"sourcesContent":["import type { StorefrontClient } from \"../client\";\nimport {\n getCartBuyerIdentitySync,\n type CartBuyerIdentitySync,\n type CartBuyerIdentitySyncSource,\n} from \"../core/cart/buyer-identity-sync\";\nimport { DEFAULT_TIMEOUT_IN_MS } from \"../core/constants\";\nimport { getLogger } from \"../core/logging\";\nimport type { ShopifyRequestContext } from \"../core/request-context\";\nimport {\n createCallableRouteHandler,\n type CallableRouteHandler,\n type ShopifyRouteErrorResult,\n type ShopifyRouteHandlerContext,\n type ShopifyRouteRedirectResult,\n type ShopifyRouteSessionManager,\n} from \"../core/request-routing/registered-routes\";\nimport { CUSTOMER_ACCOUNT_PATHS, getSameOriginPath } from \"../core/url\";\nimport { CustomerAccountApiError, CustomerAccountOAuthError } from \"./errors\";\n\nconst log = getLogger(\"customer-account\");\n\n/**\n * OAuth callback route path: `\"/account/authorize\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_AUTHORIZE_PATH = CUSTOMER_ACCOUNT_PATHS.authorize;\n/**\n * Login route path: `\"/account/login\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_LOGIN_PATH = CUSTOMER_ACCOUNT_PATHS.login;\n/**\n * Logout route path: `\"/account/logout\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_LOGOUT_PATH = CUSTOMER_ACCOUNT_PATHS.logout;\n/**\n * Token refresh route path: `\"/account/refresh\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_REFRESH_PATH = CUSTOMER_ACCOUNT_PATHS.refresh;\n\nconst CUSTOMER_ACCOUNT_SESSION_KEY = \"customerAccount\";\nconst DEFAULT_LOGIN_RETURN_TO_PATH = \"/account\";\nconst DEFAULT_POST_LOGIN_REDIRECT_PATHNAME = \"/\";\nconst DEFAULT_POST_LOGOUT_REDIRECT_URI = \"/\";\nconst FAILED_LOGIN_PATH = \"/account?login=failed\";\nconst FORBIDDEN_STATUS = 403;\nconst FORBIDDEN_ERROR_CODE = \"forbidden\";\nconst FORBIDDEN_ERROR_MESSAGE = \"Forbidden\";\nconst NO_STORE_CACHE_CONTROL = \"no-store\";\nconst AUTHORIZATION_CODE_GRANT_TYPE = \"authorization_code\";\nconst REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\";\nconst CUSTOMER_ACCOUNT_SCOPE = \"openid email customer-account-api:full\";\nconst CODE_CHALLENGE_METHOD = \"S256\";\nconst USER_AGENT = `Hydrogen ${__HYDROGEN_VERSION__}`;\nconst EXPIRY_BUFFER_IN_SECONDS = 120;\nconst PENDING_LOGIN_TTL_IN_MINUTES = 10;\nconst SECONDS_PER_MINUTE = 60;\nconst MILLISECONDS_PER_SECOND = 1_000;\nconst PENDING_LOGIN_TTL_IN_MS =\n PENDING_LOGIN_TTL_IN_MINUTES * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND;\nconst RANDOM_BYTES_LENGTH = 32;\nconst MAX_RETURN_TO_LENGTH_IN_BYTES = 2_048;\nconst MAX_SET_TIMEOUT_IN_MS = 2_147_483_647;\nconst SHOP_ID_RE = /^\\d+$/;\nconst CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON = \"customer-session-access-token\";\nconst CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON = \"customer-session-mutation\";\nconst CUSTOMER_SESSION_INTERNAL_BRAND: unique symbol = Symbol(\"hydrogen.customerSessionInternal\");\n\n/**\n * A value or a promise for that value. Session manager methods can return either.\n */\nexport type Awaitable<T> = T | Promise<T>;\n\n/** The session storage that `isLoggedIn()` and `getAccessToken()` read. */\nexport type ReadonlyCustomerSessionManager = {\n /** Returns the session value for a key. The customer session keeps its data under the `customerAccount` key. */\n getSessionItem(key: string): Awaitable<unknown>;\n};\n\n/** The session storage that sign-in, the OAuth callback, token refresh, and logout write to. Commit the session to the response after you call `prepareLoginUrl()`, `handleOAuthCallback()`, `getOrRefreshAccessToken()`, or `logout()`. */\nexport type WritableCustomerSessionManager = ShopifyRouteSessionManager;\n\ntype CustomerAccountSessionData = {\n tokens?: {\n accessToken?: string;\n refreshToken?: string;\n idToken?: string;\n expiresAt?: number;\n };\n pendingLogin?: {\n state?: string;\n nonce?: string;\n codeVerifier?: string;\n returnTo?: string;\n origin?: string;\n createdAt?: number;\n };\n};\n\n/** Options for creating a customer session. */\nexport type CreateCustomerSessionOptions = {\n /** Numeric Shopify shop ID as a string of digits, such as `12345`. */\n shopId: string;\n /** The Customer Account API OAuth client ID. Must contain at least one non-whitespace character. */\n customerAccountApiClientId: string;\n /**\n * The base URL for Shopify's OAuth authorize, token, and logout endpoints. Defaults to `https://shopify.com/authentication/{shopId}`.\n *\n * The URL must use HTTPS, or creating the session throws. Sign-in fails with the `issuer_mismatch` code when the ID token's issuer differs from this URL.\n */\n customerAccountApiUrl?: string;\n /** A custom fetch implementation. Defaults to the global fetch. */\n fetch?: typeof globalThis.fetch;\n /** The timeout for OAuth token requests in milliseconds. Must be a positive integer no greater than 2,147,483,647. Defaults to `30000`. */\n defaultTimeoutInMs?: number;\n};\n\n/** Options for building a Shopify OAuth login URL. */\nexport type PrepareLoginUrlOptions = {\n /**\n * Your storefront's origin for the OAuth redirect URL. Defaults to the origin that the session manager returns.\n *\n * The origin must use HTTPS, including on localhost. Use a public HTTPS tunnel for local sign-in.\n */\n origin?: string;\n /**\n * The same-origin path or URL to send the customer to after sign-in, such as `/account/orders`. Defaults to `/account`. Cross-origin values and paths over 2,048 bytes fall back to the default.\n */\n returnTo?: string;\n /** The language for Shopify's login page, sent as the `locale` search param. */\n locale?: string;\n /** The customer's country, sent as the `region_country` search param. */\n countryCode?: string;\n /** A value that prefills Shopify's login page, such as the customer's email address, sent as the `login_hint` search param. */\n loginHint?: string;\n /** How Shopify's login page uses the login hint, such as `submit`, sent as the `login_hint_mode` search param. Hydrogen sends the value only with `loginHint`. */\n loginHintMode?: string;\n /** The authentication context class to request, sent as the `acr_values` search param. */\n acrValues?: string;\n};\n\n/**\n * The storefront origin for a token refresh or logout.\n */\nexport type RequestOriginOptions = {\n /** Your storefront's HTTPS origin. Defaults to the origin that the session manager returns. A non-HTTPS origin throws. */\n origin?: string;\n};\n\n/** Options for logging the customer out. */\nexport interface LogoutOptions extends RequestOriginOptions {\n /**\n * The URL to send the customer to after logout. A relative URL resolves against the origin. Defaults to the origin, and a cross-origin URL falls back to the origin.\n */\n postLogoutRedirectUri?: string;\n}\n\n/**\n * Signs customers in and out with Shopify customer accounts, and gives your server their Customer Account API access tokens. Use the session on the server only.\n *\n * Pass your session storage and the request context to each method. Each method makes the final response private and uncacheable.\n *\n * @publicDocs\n */\nexport type CustomerSession = {\n /**\n * Returns `true` when the customer has a usable access token or a refresh token. The method never refreshes tokens.\n *\n * Use the result for UI state, such as an account link. Gate Customer Account API data on an access token from `getOrRefreshAccessToken()`.\n */\n isLoggedIn(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ): Promise<boolean>;\n /**\n * Returns the customer's stored access token, or `undefined` when the token is missing or expired. The method never refreshes the token or writes to the session. Call `getOrRefreshAccessToken()` to refresh an expired token.\n */\n getAccessToken(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ): Promise<string | undefined>;\n /**\n * Returns a usable access token for the customer. When the stored token is missing or expired, the session gets new tokens from Shopify and writes them to your session storage. Call the method only where you commit the session to the response.\n *\n * Returns `undefined` when the customer has no refresh token, or when a temporary refresh failure keeps the session for a retry. When Shopify rejects the refresh token with a `400` or `401` status, the session clears the stored tokens and returns `undefined`. Refresh failures never throw.\n */\n getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: RequestOriginOptions,\n ): Promise<string | undefined>;\n /**\n * Starts customer sign-in and returns the URL of Shopify's login page. Commit the session to the response, then redirect the customer to the URL.\n *\n * The customer has 10 minutes to finish signing in. After that, the OAuth callback fails with the `missing_pending_login` code.\n */\n prepareLoginUrl(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: PrepareLoginUrlOptions,\n ): Promise<string>;\n /**\n * Completes sign-in from Shopify's OAuth callback request, saves the customer's tokens to your session storage, and returns the path to send the customer to. Commit the session to the response after the call.\n *\n * The method throws `CustomerAccountOAuthError` when sign-in fails a check, and `CustomerAccountApiError` when the token request times out. After a failure, the customer needs to start sign-in again.\n *\n * @throws {CustomerAccountOAuthError} When the callback parameters, pending login, token exchange, token response, or ID token claims fail validation.\n * @throws {CustomerAccountApiError} When the token request times out.\n */\n handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<string>;\n /**\n * Clears the customer's session data and returns the URL to send the customer to. Commit the session to the response after the call.\n *\n * When the session has an ID token, the URL points to Shopify's logout endpoint with the post-logout URL attached. Without an ID token, the method returns the post-logout URL.\n */\n logout(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: LogoutOptions,\n ): Promise<string>;\n};\n\n/**\n * The login, authorize, refresh, and logout routes for customer accounts. Add the object to the `handlers` option of `handleShopifyRoutes`.\n */\nexport type CustomerAccountServerHandlers<\n TContext extends CustomerAccountRouteHandlerContext = CustomerAccountRouteHandlerContext,\n> = {\n /** Completes sign-in at `/account/authorize`, the OAuth callback, and redirects the customer to the return path. Accepts `GET`. */\n authorize: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_AUTHORIZE_PATH,\n \"GET\"\n >;\n /** Starts sign-in at `/account/login` and redirects the customer to Shopify's login page. Accepts `GET`. Pass `return_to`, `locale`, `acr_values`, `login_hint`, and `login_hint_mode` as search params. The route sends the request context's country to Shopify. */\n login: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_LOGIN_PATH,\n \"GET\"\n >;\n /**\n * Logs the customer out at `/account/logout`. Accepts `POST`. For CSRF protection, the route returns a `403` response unless the `Origin` or `Referer` header matches your storefront's origin.\n *\n * Through `handleShopifyRoutes`, a GET request to the logout path returns a `405` response. Log out with a `<form method=\"post\" action=\"/account/logout\">` and a submit button, which works without JavaScript.\n */\n logout: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_LOGOUT_PATH,\n \"POST\"\n >;\n /** Refreshes the access token at `/account/refresh` and redirects the customer to the same-origin `return_to` path, which defaults to `/account`. Accepts `GET`. */\n refresh: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_REFRESH_PATH,\n \"GET\"\n >;\n};\n\n/**\n * Customer account routes that also keep the cart's buyer identity in step with the signed-in customer. These routes need `storefrontClient` in the handler context.\n */\nexport type CustomerAccountServerHandlersWithCartSync =\n CustomerAccountServerHandlers<ShopifyRouteHandlerContext>;\n\n/** A customer session that `createCustomerSession` returns. Cart buyer identity sync requires this session. */\ntype CustomerSessionWithInternals = CustomerSession & {\n readonly [CUSTOMER_SESSION_INTERNAL_BRAND]: true;\n};\n\n/** Options for the customer account routes. */\ntype CreateCustomerAccountServerHandlersBaseOptions = {\n /** The path to send the customer to after sign-in when the login request has no same-origin `return_to` search param. Defaults to `/`. */\n defaultPostLoginRedirectPathname?: string;\n /** The same-origin path to send the customer to when sign-in fails with `CustomerAccountOAuthError`. Defaults to `/account?login=failed`. A cross-origin value falls back to `/account`. The authorize route rethrows other errors. */\n loginFailedRedirectPath?: string;\n /** Your storefront's HTTPS origin, or a function that returns the origin for a request. Defaults to the origin that the session manager returns. */\n origin?: string | ((request: Request) => string);\n /** The URL to send the customer to after logout. Defaults to `/`. A same-origin `return_to` search param on the logout request overrides this value. */\n postLogoutRedirectUri?: string;\n};\n\n/** Options for the customer account routes without cart buyer identity sync. */\ninterface CustomerAccountServerHandlersOptionsWithoutCart extends CreateCustomerAccountServerHandlersBaseOptions {\n /** The customer session from `createCustomerSession`. */\n customerSession: CustomerSession;\n /**\n * The cart server handlers that `createCartServerHandlers` returns with its `customerSession` option. Pass the cart handlers to keep the cart's buyer identity in step with the signed-in customer.\n *\n * The authorize and refresh routes attach the customer to the cart. The logout route, and a refresh that ends the session, detach the customer from the cart. When a sync fails, the route logs the error and still redirects. When a detach fails, the route also expires the `cart` cookie. The sync needs `storefrontClient` in the handler context.\n *\n * Creating the handlers throws when the cart handlers lack the `customerSession` option, or when the customer session doesn't come from `createCustomerSession`.\n */\n cartServerHandlers?: undefined;\n}\n\n/** Options for the customer account routes that keep the cart's buyer identity in step with the signed-in customer. */\ninterface CustomerAccountServerHandlersOptionsWithCart extends CreateCustomerAccountServerHandlersBaseOptions {\n /** The customer session from `createCustomerSession`. */\n customerSession: CustomerSessionWithInternals;\n /**\n * The cart server handlers that `createCartServerHandlers` returns with its `customerSession` option. Pass the cart handlers to keep the cart's buyer identity in step with the signed-in customer.\n *\n * The authorize and refresh routes attach the customer to the cart. The logout route, and a refresh that ends the session, detach the customer from the cart. When a sync fails, the route logs the error and still redirects. When a detach fails, the route also expires the `cart` cookie. The sync needs `storefrontClient` in the handler context.\n *\n * Creating the handlers throws when the cart handlers lack the `customerSession` option, or when the customer session doesn't come from `createCustomerSession`.\n */\n cartServerHandlers: CartBuyerIdentitySyncSource;\n}\n\n/** Options for the customer account routes, with optional cart buyer identity sync. */\nexport type CreateCustomerAccountServerHandlersOptions =\n | CustomerAccountServerHandlersOptionsWithoutCart\n | CustomerAccountServerHandlersOptionsWithCart;\n\ntype CustomerAccountTokens = NonNullable<CustomerAccountSessionData[\"tokens\"]>;\ntype PendingLogin = NonNullable<CustomerAccountSessionData[\"pendingLogin\"]>;\ntype TokenEndpointResponse = {\n access_token?: unknown;\n refresh_token?: unknown;\n id_token?: unknown;\n expires_in?: unknown;\n};\ntype ParsedTokenEndpointResponse = {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n expires_in: number;\n};\ntype RefreshResult =\n | { type: \"success\"; tokens: CustomerAccountTokens }\n | { type: \"invalid\" }\n | { type: \"transient\" };\ntype TokenRefreshResult =\n | {\n /** A usable access token is available. */\n status: \"authenticated\";\n accessToken: string;\n }\n | {\n /** Refresh failed transiently, but the refreshable session remains. */\n status: \"transient\";\n accessToken: undefined;\n }\n | {\n /** No usable or refreshable customer session remains. */\n status: \"unauthenticated\";\n accessToken: undefined;\n };\ntype OAuthCallbackResult = {\n location: string;\n accessToken: string;\n};\ntype CustomerSessionInternals = {\n getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: RequestOriginOptions,\n ): Promise<TokenRefreshResult>;\n handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<OAuthCallbackResult>;\n};\nconst customerSessionInternals = new WeakMap<CustomerSession, CustomerSessionInternals>();\n/** A redirect, or a `403` error when a logout request comes from another origin. */\ntype CustomerAccountRouteResult = ShopifyRouteRedirectResult | ShopifyRouteErrorResult;\ntype CustomerAccountRouteHandlerContext = {\n request: Request;\n sessionManager: WritableCustomerSessionManager;\n requestContext: ShopifyRequestContext;\n};\ntype CustomerAccountRuntimeRouteHandlerContext = CustomerAccountRouteHandlerContext & {\n storefrontClient?: StorefrontClient;\n};\ntype CustomerAccountServerHandlersForOptions<TOptions> = TOptions extends {\n cartServerHandlers: CartBuyerIdentitySyncSource;\n}\n ? CustomerAccountServerHandlersWithCartSync\n : CustomerAccountServerHandlers;\ntype TokenRequestParams = {\n url: string;\n origin: string;\n body: URLSearchParams;\n fetch: typeof globalThis.fetch;\n signal: AbortSignal;\n};\n\n/**\n * Creates a customer session that signs customers in and out with Shopify customer accounts and manages their access tokens. Use the session on the server only.\n *\n * The function throws when the shop ID, client ID, API URL, or timeout is invalid, when no fetch implementation is available, and when the function runs in a browser.\n *\n * @example\n * ```ts\n * import { createCustomerSession } from '@shopify/hydrogen/customer-account';\n *\n * const customerSession = createCustomerSession({\n * shopId: env.SHOP_ID,\n * customerAccountApiClientId: env.CUSTOMER_ACCOUNT_API_CLIENT_ID,\n * });\n * ```\n *\n * @param options - The shop ID, the OAuth client ID, the authentication base URL, a custom fetch, and the token request timeout.\n * @returns A customer session with methods for sign-in, the OAuth callback, access tokens, and logout.\n * @throws {Error} When called in a browser, when an option fails validation, or when no fetch is available.\n * @publicDocs\n */\nexport function createCustomerSession({\n shopId,\n customerAccountApiClientId,\n customerAccountApiUrl,\n fetch: customFetch,\n defaultTimeoutInMs = DEFAULT_TIMEOUT_IN_MS,\n}: CreateCustomerSessionOptions): CustomerSessionWithInternals {\n if (typeof document !== \"undefined\") {\n throw new Error(\n \"Customer Account OAuth sessions cannot be used in a browser context. Use this helper from server or edge routes only.\",\n );\n }\n\n validateShopId(shopId);\n validateCustomerAccountApiClientId(customerAccountApiClientId);\n validateTimeout(defaultTimeoutInMs);\n\n const fetch = customFetch ?? globalThis.fetch;\n if (typeof fetch !== \"function\") {\n throw new Error(\n \"No fetch function available. Pass a fetch option or ensure globalThis.fetch exists.\",\n );\n }\n\n const endpoints = createCustomerAccountEndpoints(shopId, customerAccountApiUrl);\n const refreshFlights = new Map<string, Promise<RefreshResult>>();\n\n async function getAccessToken(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON);\n const accessToken = getUsableAccessToken(await readSessionData(sessionManager));\n return accessToken;\n }\n\n async function getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n ) {\n const result = await getOrRefreshAccessTokenResult(sessionManager, requestContext, options);\n return result.accessToken;\n }\n\n async function getOrRefreshAccessTokenResult(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n ): Promise<TokenRefreshResult> {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON);\n const sessionData = await readSessionData(sessionManager);\n const accessToken = getUsableAccessToken(sessionData);\n if (accessToken) return { status: \"authenticated\", accessToken };\n\n const refreshToken = getRefreshToken(sessionData);\n if (!refreshToken) return { status: \"unauthenticated\", accessToken: undefined };\n\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const idToken = sessionData.tokens?.idToken;\n const refreshResult = await getRefreshResult({\n refreshFlights,\n refreshToken,\n idToken,\n origin,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs: defaultTimeoutInMs,\n });\n\n if (refreshResult.type === \"success\") {\n const refreshedAccessToken = refreshResult.tokens.accessToken;\n if (!refreshedAccessToken) {\n return { status: \"transient\", accessToken: undefined };\n }\n await writeTokens(sessionManager, refreshResult.tokens);\n return {\n status: \"authenticated\",\n accessToken: refreshedAccessToken,\n };\n }\n\n if (refreshResult.type === \"invalid\") {\n await clearTokens(sessionManager);\n return { status: \"unauthenticated\", accessToken: undefined };\n }\n\n return { status: \"transient\", accessToken: undefined };\n }\n\n async function prepareLoginUrl(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: PrepareLoginUrlOptions,\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const state = generateRandomBase64Url();\n const nonce = generateRandomBase64Url();\n const codeVerifier = generateRandomBase64Url();\n const codeChallenge = await createCodeChallenge(codeVerifier);\n const returnTo = sanitizeReturnTo(options.returnTo, origin);\n const createdAt = Date.now();\n\n const sessionData = await readSessionData(sessionManager);\n await writeSessionData(sessionManager, {\n ...sessionData,\n pendingLogin: { state, nonce, codeVerifier, returnTo, origin, createdAt },\n });\n\n const loginUrl = new URL(endpoints.authorizeUrl);\n loginUrl.searchParams.set(\"client_id\", customerAccountApiClientId);\n loginUrl.searchParams.set(\"scope\", CUSTOMER_ACCOUNT_SCOPE);\n loginUrl.searchParams.set(\"response_type\", \"code\");\n loginUrl.searchParams.set(\"redirect_uri\", `${origin}${CUSTOMER_ACCOUNT_AUTHORIZE_PATH}`);\n loginUrl.searchParams.set(\"state\", state);\n loginUrl.searchParams.set(\"nonce\", nonce);\n loginUrl.searchParams.set(\"code_challenge\", codeChallenge);\n loginUrl.searchParams.set(\"code_challenge_method\", CODE_CHALLENGE_METHOD);\n setOptionalLoginParams(loginUrl, options);\n\n return loginUrl.toString();\n }\n\n async function handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ) {\n return (await handleOAuthCallbackResult(sessionManager, requestContext, request)).location;\n }\n\n async function handleOAuthCallbackResult(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<OAuthCallbackResult> {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n try {\n return await completeOAuthCallback({\n sessionManager,\n request,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs: defaultTimeoutInMs,\n });\n } catch (error) {\n await clearPendingLogin(sessionManager);\n throw error;\n }\n }\n\n async function logout(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: LogoutOptions = {},\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const sessionData = await readSessionData(sessionManager);\n const idToken = sessionData.tokens?.idToken;\n const postLogoutRedirectUri = absoluteSameOriginUrl(\n options.postLogoutRedirectUri ?? origin,\n origin,\n );\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n\n if (!idToken) return postLogoutRedirectUri;\n\n const logoutUrl = new URL(endpoints.logoutUrl);\n logoutUrl.searchParams.set(\"id_token_hint\", idToken);\n logoutUrl.searchParams.set(\"post_logout_redirect_uri\", postLogoutRedirectUri);\n return logoutUrl.toString();\n }\n\n const customerSession: CustomerSessionWithInternals = {\n [CUSTOMER_SESSION_INTERNAL_BRAND]: true,\n isLoggedIn: async (sessionManager, requestContext) => {\n requestContext.markResponseAsPersonalized(\n CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON,\n );\n return hasCustomerSession(await readSessionData(sessionManager));\n },\n getAccessToken,\n getOrRefreshAccessToken,\n prepareLoginUrl,\n handleOAuthCallback,\n logout,\n };\n customerSessionInternals.set(customerSession, {\n getOrRefreshAccessToken: getOrRefreshAccessTokenResult,\n handleOAuthCallback: handleOAuthCallbackResult,\n });\n return customerSession;\n}\n\nexport async function getCustomerSessionRefreshResult(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n): Promise<TokenRefreshResult | undefined> {\n return customerSessionInternals\n .get(customerSession)\n ?.getOrRefreshAccessToken(sessionManager, requestContext, options);\n}\n\n/**\n * Creates the customer account routes under `/account` for sign-in, the OAuth callback, token refresh, and logout. Add the returned object to the `handlers` option of `handleShopifyRoutes`.\n *\n * The login route redirects to Shopify's login page. The authorize and refresh routes redirect back to a same-origin path in your app. The logout route redirects to Shopify's logout endpoint when the session has an ID token, and to the post-logout URL otherwise. Each redirect commits the session and sends `cache-control: no-store`.\n *\n * Link to these paths with full-page navigation, such as a plain `<a>` link or a `<form>`. Client-side navigation components can't follow these redirects.\n *\n * @returns The login, authorize, refresh, and logout routes.\n * @publicDocs\n */\nexport function createCustomerAccountServerHandlers<\n const TOptions extends CreateCustomerAccountServerHandlersOptions,\n>(options: TOptions): CustomerAccountServerHandlersForOptions<TOptions>;\n/**\n * @param options The customer session, the redirect paths, and optional cart handlers for the account routes.\n * @returns The login, authorize, refresh, and logout routes.\n */\nexport function createCustomerAccountServerHandlers(\n options: CreateCustomerAccountServerHandlersOptions,\n): CustomerAccountServerHandlers | CustomerAccountServerHandlersWithCartSync {\n const {\n customerSession,\n defaultPostLoginRedirectPathname = DEFAULT_POST_LOGIN_REDIRECT_PATHNAME,\n loginFailedRedirectPath = FAILED_LOGIN_PATH,\n postLogoutRedirectUri = DEFAULT_POST_LOGOUT_REDIRECT_URI,\n } = options;\n const { origin: originOption } = options;\n const cartSync = resolveCartBuyerIdentitySync(options);\n\n return {\n authorize: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_AUTHORIZE_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleAuthorizeRoute(\n customerSession,\n context,\n loginFailedRedirectPath,\n originOption,\n cartSync,\n );\n },\n ),\n login: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_LOGIN_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n const { request, sessionManager, requestContext } = context;\n return handleLoginRoute(\n customerSession,\n sessionManager,\n requestContext,\n request,\n defaultPostLoginRedirectPathname,\n originOption,\n );\n },\n ),\n logout: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_LOGOUT_PATH,\n \"POST\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleLogoutRoute(\n customerSession,\n context,\n postLogoutRedirectUri,\n originOption,\n cartSync,\n );\n },\n ),\n refresh: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_REFRESH_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleRefreshRoute(customerSession, context, originOption, cartSync);\n },\n ),\n };\n}\n\nfunction resolveCartBuyerIdentitySync(\n options: CreateCustomerAccountServerHandlersOptions,\n): CartBuyerIdentitySync | undefined {\n if (!options.cartServerHandlers) return undefined;\n\n const cartSync = getCartBuyerIdentitySync(options.cartServerHandlers);\n if (!cartSync) {\n throw new Error(\n \"cartServerHandlers must be created by createCartServerHandlers with the customerSession option.\",\n );\n }\n if (!customerSessionInternals.has(options.customerSession)) {\n throw new Error(\n \"Cart buyer identity sync requires the customerSession returned by createCustomerSession.\",\n );\n }\n return cartSync;\n}\n\nasync function handleLoginRoute(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n defaultPostLoginRedirectPathname: string,\n originOption: string | ((request: Request) => string) | undefined,\n): Promise<CustomerAccountRouteResult> {\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n const requestUrl = new URL(request.url);\n const defaultReturnTo = sanitizeReturnTo(\n defaultPostLoginRedirectPathname,\n origin,\n DEFAULT_POST_LOGIN_REDIRECT_PATHNAME,\n );\n const requestedReturnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n const returnTo = sanitizeReturnTo(requestedReturnTo, origin, defaultReturnTo);\n const loginUrl = await customerSession.prepareLoginUrl(sessionManager, requestContext, {\n origin,\n returnTo,\n countryCode: requestContext.i18n.country,\n locale: getOptionalSearchParam(requestUrl, \"locale\"),\n acrValues: getOptionalSearchParam(requestUrl, \"acr_values\"),\n loginHint: getOptionalSearchParam(requestUrl, \"login_hint\"),\n loginHintMode: getOptionalSearchParam(requestUrl, \"login_hint_mode\"),\n });\n return redirectResult(loginUrl, await commitSession(sessionManager));\n}\n\nasync function handleLogoutRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n postLogoutRedirectUri: string,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n if (!isSameOriginPost(request, origin)) return forbiddenResult();\n\n const requestUrl = new URL(request.url);\n const requestedReturnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n const logoutUrl = await customerSession.logout(sessionManager, requestContext, {\n origin,\n postLogoutRedirectUri: sanitizeReturnTo(requestedReturnTo, origin, postLogoutRedirectUri),\n });\n\n // The redirect must complete even when detach fails: skipping it would leave\n // the Shopify IdP session alive after the app session is already destroyed.\n // Expiring the cart cookie is the fail-safe when the cart keeps the identity.\n let detachFailed = false;\n if (cartSync) {\n detachFailed = !(await syncCartBuyerIdentity(cartSync, context, null, \"logout\"));\n }\n const headers = new Headers(await commitSession(sessionManager));\n if (cartSync && detachFailed) headers.append(\"set-cookie\", cartSync.expiredCartCookie);\n return redirectResult(logoutUrl, headers);\n}\n\nasync function handleAuthorizeRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n loginFailedRedirectPath: string,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n try {\n if (!cartSync) {\n const location = await customerSession.handleOAuthCallback(\n sessionManager,\n requestContext,\n request,\n );\n return redirectResult(location, await commitSession(sessionManager));\n }\n\n const { location, accessToken } = await handleOAuthCallbackWithAccessToken(\n customerSession,\n sessionManager,\n requestContext,\n request,\n );\n // Best-effort: the customer is authenticated at this point, so a failed\n // cart sync must not turn a successful login into an error response. The\n // next refresh retries the attach.\n await syncCartBuyerIdentity(cartSync, context, accessToken, \"authorize\");\n return redirectResult(location, await commitSession(sessionManager));\n } catch (error) {\n if (!(error instanceof CustomerAccountOAuthError)) throw error;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n return redirectResult(\n sanitizeReturnTo(loginFailedRedirectPath, origin),\n await commitSession(sessionManager),\n );\n }\n}\n\nasync function handleRefreshRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n if (!cartSync) {\n await customerSession.getOrRefreshAccessToken(sessionManager, requestContext, { origin });\n return refreshRedirectResult(request, origin, await commitSession(sessionManager));\n }\n\n const refreshResult = await getOrRefreshAccessTokenWithStatus(\n customerSession,\n sessionManager,\n requestContext,\n { origin },\n );\n // Transient refresh failures keep the refreshable session, so the cart's\n // identity is left untouched; a definitive outcome attaches or detaches it.\n let detachFailed = false;\n if (refreshResult.status !== \"transient\") {\n const customerAccessToken = refreshResult.accessToken ?? null;\n const syncSucceeded = await syncCartBuyerIdentity(\n cartSync,\n context,\n customerAccessToken,\n \"refresh\",\n );\n detachFailed = customerAccessToken === null && !syncSucceeded;\n }\n\n const headers = new Headers(await commitSession(sessionManager));\n if (detachFailed) headers.append(\"set-cookie\", cartSync.expiredCartCookie);\n return refreshRedirectResult(request, origin, headers);\n}\n\nfunction refreshRedirectResult(\n request: Request,\n origin: string,\n headers?: HeadersInit,\n): ShopifyRouteRedirectResult {\n const requestUrl = new URL(request.url);\n const returnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n return redirectResult(sanitizeReturnTo(returnTo, origin), headers);\n}\n\nasync function handleOAuthCallbackWithAccessToken(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n): Promise<OAuthCallbackResult> {\n const internal = customerSessionInternals.get(customerSession);\n if (!internal) {\n throw new Error(\"Customer session was not created by createCustomerSession\");\n }\n return internal.handleOAuthCallback(sessionManager, requestContext, request);\n}\n\nasync function getOrRefreshAccessTokenWithStatus(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions,\n): Promise<TokenRefreshResult> {\n const internal = customerSessionInternals.get(customerSession);\n if (!internal) {\n throw new Error(\"Customer session was not created by createCustomerSession\");\n }\n return internal.getOrRefreshAccessToken(sessionManager, requestContext, options);\n}\n\nasync function syncCartBuyerIdentity(\n cartSync: CartBuyerIdentitySync,\n context: CustomerAccountRuntimeRouteHandlerContext,\n customerAccessToken: string | null,\n route: \"authorize\" | \"refresh\" | \"logout\",\n): Promise<boolean> {\n try {\n if (!context.storefrontClient) {\n throw new Error(\n \"Customer Account handlers configured with cartServerHandlers require storefrontClient.\",\n );\n }\n await cartSync.updateBuyerIdentity(\n { request: context.request, storefrontClient: context.storefrontClient },\n customerAccessToken,\n );\n return true;\n } catch (error) {\n log.error(\"cart buyer identity sync failed\", { route, error });\n return false;\n }\n}\n\nasync function resolveRouteOrigin(\n sessionManager: WritableCustomerSessionManager,\n request: Request,\n originOption: string | ((request: Request) => string) | undefined,\n) {\n if (typeof originOption === \"function\") return normalizeOrigin(originOption(request));\n return getResolvedOrigin(sessionManager, originOption);\n}\n\nasync function getResolvedOrigin(\n sessionManager: WritableCustomerSessionManager,\n originOverride: string | undefined,\n) {\n return normalizeOrigin(originOverride ?? (await sessionManager.getSessionOrigin()));\n}\n\nfunction getOptionalSearchParam(url: URL, name: string): string | undefined {\n return url.searchParams.get(name) ?? undefined;\n}\n\nfunction redirectResult(location: string, headers?: HeadersInit): ShopifyRouteRedirectResult {\n const redirectHeaders = new Headers(headers);\n redirectHeaders.set(\"cache-control\", NO_STORE_CACHE_CONTROL);\n return { type: \"redirect\", location, headers: redirectHeaders };\n}\n\nfunction forbiddenResult(): ShopifyRouteErrorResult {\n return {\n type: \"error\",\n status: FORBIDDEN_STATUS,\n error: { code: FORBIDDEN_ERROR_CODE, message: FORBIDDEN_ERROR_MESSAGE },\n headers: { \"cache-control\": NO_STORE_CACHE_CONTROL },\n };\n}\n\nasync function commitSession(\n sessionManager: WritableCustomerSessionManager,\n): Promise<HeadersInit | undefined> {\n return (await sessionManager.commit?.()) ?? undefined;\n}\n\nasync function completeOAuthCallback({\n sessionManager,\n request,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs,\n}: {\n sessionManager: WritableCustomerSessionManager;\n request: Request;\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<OAuthCallbackResult> {\n const requestUrl = new URL(request.url);\n const code = requestUrl.searchParams.get(\"code\");\n const state = requestUrl.searchParams.get(\"state\");\n const sessionData = await readSessionData(sessionManager);\n const pendingLogin = getPendingLogin(sessionData);\n\n assertOAuthCallbackParams(code, state, pendingLogin);\n\n const origin = pendingLogin.origin ?? getOriginFromRequest(request);\n const tokenResponse = await exchangeAuthorizationCode({\n endpoints,\n customerAccountApiClientId,\n origin,\n code,\n codeVerifier: pendingLogin.codeVerifier,\n fetch,\n timeoutInMs,\n });\n validateIdTokenClaims(tokenResponse.id_token, {\n audience: customerAccountApiClientId,\n issuer: endpoints.issuer,\n nonce: pendingLogin.nonce,\n });\n\n await writeSessionData(sessionManager, {\n tokens: createTokensFromResponse(tokenResponse),\n });\n\n return {\n location: pendingLogin.returnTo ?? DEFAULT_LOGIN_RETURN_TO_PATH,\n accessToken: tokenResponse.access_token,\n };\n}\n\nfunction isSameOriginPost(request: Request, trustedOrigin: string): boolean {\n const origin = request.headers.get(\"origin\");\n if (origin) {\n try {\n return normalizeOrigin(origin) === trustedOrigin;\n } catch {\n return false;\n }\n }\n\n const referer = request.headers.get(\"referer\");\n if (!referer) return false;\n\n try {\n return normalizeOrigin(new URL(referer).origin) === trustedOrigin;\n } catch {\n return false;\n }\n}\n\nfunction assertOAuthCallbackParams(\n code: string | null,\n state: string | null,\n pendingLogin: Required<PendingLogin>,\n): asserts code is string {\n if (!code || !state) {\n throw new CustomerAccountOAuthError(\n \"missing_callback_params\",\n \"OAuth callback is missing code or state\",\n );\n }\n\n if (pendingLogin.state !== state) {\n throw new CustomerAccountOAuthError(\n \"state_mismatch\",\n \"OAuth callback state does not match session state\",\n );\n }\n}\n\nasync function exchangeAuthorizationCode({\n endpoints,\n customerAccountApiClientId,\n origin,\n code,\n codeVerifier,\n fetch,\n timeoutInMs,\n}: {\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n origin: string;\n code: string;\n codeVerifier: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<Required<ParsedTokenEndpointResponse>> {\n const body = new URLSearchParams({\n grant_type: AUTHORIZATION_CODE_GRANT_TYPE,\n client_id: customerAccountApiClientId,\n redirect_uri: `${origin}${CUSTOMER_ACCOUNT_AUTHORIZE_PATH}`,\n code,\n code_verifier: codeVerifier,\n });\n return withTokenRequestTimeout(timeoutInMs, async (signal) => {\n const response = await postTokenRequest({\n url: endpoints.tokenUrl,\n origin,\n body,\n fetch,\n signal,\n });\n\n if (!response.ok) {\n cancelResponseBody(response);\n const errorCode =\n response.status === 400 || response.status === 401\n ? \"token_exchange_rejected\"\n : \"token_exchange_failed\";\n throw new CustomerAccountOAuthError(\n errorCode,\n `Customer Account OAuth token exchange failed with ${response.status}`,\n );\n }\n\n return parseRequiredTokenResponse(await readTokenResponseJson(response, signal));\n });\n}\n\nasync function getRefreshResult({\n refreshFlights,\n refreshToken,\n idToken,\n origin,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs,\n}: {\n refreshFlights: Map<string, Promise<RefreshResult>>;\n refreshToken: string;\n idToken: string | undefined;\n origin: string;\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}) {\n const flightKey = `${origin}\\n${refreshToken}`;\n const existingFlight = refreshFlights.get(flightKey);\n if (existingFlight) return existingFlight;\n\n const flight = refreshAccessToken({\n endpoints,\n customerAccountApiClientId,\n refreshToken,\n idToken,\n origin,\n fetch,\n timeoutInMs,\n });\n refreshFlights.set(flightKey, flight);\n\n try {\n return await flight;\n } finally {\n refreshFlights.delete(flightKey);\n }\n}\n\nasync function refreshAccessToken({\n endpoints,\n customerAccountApiClientId,\n refreshToken,\n idToken,\n origin,\n fetch,\n timeoutInMs,\n}: {\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n refreshToken: string;\n idToken: string | undefined;\n origin: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<RefreshResult> {\n const body = new URLSearchParams({\n grant_type: REFRESH_TOKEN_GRANT_TYPE,\n client_id: customerAccountApiClientId,\n refresh_token: refreshToken,\n });\n\n try {\n return await withTokenRequestTimeout(timeoutInMs, async (signal) => {\n const response = await postTokenRequest({\n url: endpoints.tokenUrl,\n origin,\n body,\n fetch,\n signal,\n });\n return readRefreshResult(response, refreshToken, idToken, signal);\n });\n } catch {\n return { type: \"transient\" };\n }\n}\n\nasync function readRefreshResult(\n response: Response,\n currentRefreshToken: string,\n currentIdToken: string | undefined,\n signal: AbortSignal,\n): Promise<RefreshResult> {\n if (response.status === 400 || response.status === 401) {\n cancelResponseBody(response);\n return { type: \"invalid\" };\n }\n\n if (!response.ok) {\n cancelResponseBody(response);\n return { type: \"transient\" };\n }\n\n try {\n const tokenResponse = await readTokenResponseJson(response, signal);\n const parsedTokenResponse = parseRefreshTokenResponse(tokenResponse);\n return {\n type: \"success\",\n tokens: createTokensFromResponse({\n ...parsedTokenResponse,\n refresh_token: parsedTokenResponse.refresh_token ?? currentRefreshToken,\n id_token: parsedTokenResponse.id_token ?? currentIdToken,\n }),\n };\n } catch {\n return { type: \"transient\" };\n }\n}\n\nasync function postTokenRequest({\n url,\n origin,\n body,\n fetch,\n signal,\n}: TokenRequestParams): Promise<Response> {\n return await withAbort(\n fetch(url, {\n method: \"POST\",\n headers: new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": USER_AGENT,\n Origin: origin,\n }),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n signal,\n }),\n signal,\n );\n}\n\nasync function withTokenRequestTimeout<T>(\n timeoutInMs: number,\n operation: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort(\n new CustomerAccountApiError(\n `Customer Account OAuth request timed out after ${timeoutInMs}ms`,\n ),\n );\n }, timeoutInMs);\n\n try {\n return await operation(controller.signal);\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\nfunction withAbort<T>(promise: T | Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(getAbortReason(signal));\n\n return new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener(\"abort\", abort);\n reject(getAbortReason(signal));\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n Promise.resolve(promise).then(\n (value) => {\n signal.removeEventListener(\"abort\", abort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n },\n );\n });\n}\n\nfunction getAbortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"signal is aborted without reason\", \"AbortError\");\n}\n\nasync function readTokenResponseJson(\n response: Response,\n signal: AbortSignal,\n): Promise<TokenEndpointResponse> {\n const json = await withAbort(response.json(), signal);\n if (!isObjectRecord(json)) {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response must be an object\",\n );\n }\n return {\n access_token: json.access_token,\n refresh_token: json.refresh_token,\n id_token: json.id_token,\n expires_in: json.expires_in,\n };\n}\n\nfunction parseRequiredTokenResponse(\n response: TokenEndpointResponse,\n): Required<ParsedTokenEndpointResponse> {\n const parsed = parseRefreshTokenResponse(response);\n if (typeof response.refresh_token !== \"string\" || response.refresh_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing refresh_token\",\n );\n }\n\n if (typeof response.id_token !== \"string\" || response.id_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing id_token\",\n );\n }\n return { ...parsed, refresh_token: response.refresh_token, id_token: response.id_token };\n}\n\nfunction parseRefreshTokenResponse(response: TokenEndpointResponse): ParsedTokenEndpointResponse {\n if (typeof response.access_token !== \"string\" || response.access_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing access_token\",\n );\n }\n\n if (\n typeof response.expires_in !== \"number\" ||\n !Number.isFinite(response.expires_in) ||\n response.expires_in <= 0\n ) {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing expires_in\",\n );\n }\n\n return {\n access_token: response.access_token,\n refresh_token:\n typeof response.refresh_token === \"string\" && response.refresh_token !== \"\"\n ? response.refresh_token\n : undefined,\n id_token:\n typeof response.id_token === \"string\" && response.id_token !== \"\"\n ? response.id_token\n : undefined,\n expires_in: response.expires_in,\n };\n}\n\nfunction createTokensFromResponse(response: ParsedTokenEndpointResponse): CustomerAccountTokens {\n return {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n idToken: response.id_token,\n expiresAt:\n Date.now() + (response.expires_in - EXPIRY_BUFFER_IN_SECONDS) * MILLISECONDS_PER_SECOND,\n };\n}\n\nfunction validateIdTokenClaims(\n idToken: string,\n expected: { audience: string; issuer: string; nonce: string },\n): void {\n const claims = parseJwtPayload(idToken);\n if (claims.nonce !== expected.nonce) {\n throw new CustomerAccountOAuthError(\n \"nonce_mismatch\",\n \"OAuth id_token nonce does not match session nonce\",\n );\n }\n\n if (claims.iss !== expected.issuer) {\n throw new CustomerAccountOAuthError(\n \"issuer_mismatch\",\n \"OAuth id_token issuer does not match Customer Account issuer\",\n );\n }\n\n if (!hasAudienceClaim(claims.aud, expected.audience)) {\n throw new CustomerAccountOAuthError(\n \"audience_mismatch\",\n \"OAuth id_token audience does not match Customer Account client ID\",\n );\n }\n\n if (\n typeof claims.exp !== \"number\" ||\n claims.exp <= Math.floor(Date.now() / MILLISECONDS_PER_SECOND)\n ) {\n throw new CustomerAccountOAuthError(\"expired_id_token\", \"OAuth id_token is expired\");\n }\n}\n\nfunction parseJwtPayload(idToken: string): Record<string, unknown> {\n try {\n const [, payload] = idToken.split(\".\");\n if (!payload) throw new Error(\"Missing JWT payload\");\n\n const decodedPayload = JSON.parse(base64UrlDecode(payload));\n if (!isObjectRecord(decodedPayload)) throw new Error(\"JWT payload must be an object\");\n\n return decodedPayload;\n } catch (cause) {\n throw new CustomerAccountOAuthError(\n \"invalid_id_token\",\n \"Customer Account OAuth id_token is invalid\",\n { cause },\n );\n }\n}\n\nfunction hasAudienceClaim(audience: unknown, expectedAudience: string): boolean {\n if (audience === expectedAudience) return true;\n if (!Array.isArray(audience)) return false;\n return audience.includes(expectedAudience);\n}\n\nasync function readSessionData(\n sessionManager: ReadonlyCustomerSessionManager,\n): Promise<CustomerAccountSessionData> {\n const value = await sessionManager.getSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n return isCustomerAccountSessionData(value) ? value : {};\n}\n\nasync function writeSessionData(\n sessionManager: WritableCustomerSessionManager,\n sessionData: CustomerAccountSessionData,\n): Promise<void> {\n await sessionManager.setSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY, sessionData);\n}\n\nasync function writeTokens(\n sessionManager: WritableCustomerSessionManager,\n tokens: CustomerAccountTokens,\n): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n await writeSessionData(sessionManager, { ...sessionData, tokens });\n}\n\nasync function clearTokens(sessionManager: WritableCustomerSessionManager): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n const { pendingLogin } = sessionData;\n if (pendingLogin) {\n await writeSessionData(sessionManager, { pendingLogin });\n return;\n }\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n}\n\nasync function clearPendingLogin(sessionManager: WritableCustomerSessionManager): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n const { tokens } = sessionData;\n if (tokens) {\n await writeSessionData(sessionManager, { tokens });\n return;\n }\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n}\n\nfunction getUsableAccessToken(sessionData: CustomerAccountSessionData): string | undefined {\n const tokens = sessionData.tokens;\n if (!isTokenUsable(tokens)) return undefined;\n return tokens.accessToken;\n}\n\nfunction hasCustomerSession(sessionData: CustomerAccountSessionData): boolean {\n return (\n getUsableAccessToken(sessionData) !== undefined || getRefreshToken(sessionData) !== undefined\n );\n}\n\nfunction getRefreshToken(sessionData: CustomerAccountSessionData): string | undefined {\n const refreshToken = sessionData.tokens?.refreshToken;\n return typeof refreshToken === \"string\" && refreshToken !== \"\" ? refreshToken : undefined;\n}\n\nfunction getPendingLogin(sessionData: CustomerAccountSessionData): Required<PendingLogin> {\n const pendingLogin = sessionData.pendingLogin;\n if (isPendingLoginReady(pendingLogin)) return pendingLogin;\n throw new CustomerAccountOAuthError(\n \"missing_pending_login\",\n \"OAuth callback has no pending login state\",\n );\n}\n\nfunction isTokenUsable(\n tokens: CustomerAccountSessionData[\"tokens\"],\n): tokens is Required<CustomerAccountTokens> {\n if (!tokens || typeof tokens.accessToken !== \"string\" || tokens.accessToken === \"\") return false;\n if (typeof tokens.expiresAt !== \"number\") return false;\n return tokens.expiresAt > Date.now();\n}\n\nfunction isPendingLoginReady(\n pendingLogin: PendingLogin | undefined,\n): pendingLogin is Required<PendingLogin> {\n if (!pendingLogin) return false;\n if (!isNonEmptyString(pendingLogin.state)) return false;\n if (!isNonEmptyString(pendingLogin.nonce)) return false;\n if (!isNonEmptyString(pendingLogin.codeVerifier)) return false;\n if (!isNonEmptyString(pendingLogin.returnTo)) return false;\n if (!isNonEmptyString(pendingLogin.origin)) return false;\n if (typeof pendingLogin.createdAt !== \"number\") return false;\n return Date.now() - pendingLogin.createdAt <= PENDING_LOGIN_TTL_IN_MS;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\nfunction isCustomerAccountSessionData(value: unknown): value is CustomerAccountSessionData {\n if (!isObjectRecord(value) || Array.isArray(value)) return false;\n const tokens = value.tokens;\n const pendingLogin = value.pendingLogin;\n if (tokens !== undefined && (!isObjectRecord(tokens) || Array.isArray(tokens))) return false;\n return (\n pendingLogin === undefined || (isObjectRecord(pendingLogin) && !Array.isArray(pendingLogin))\n );\n}\n\nfunction setOptionalLoginParams(loginUrl: URL, options: PrepareLoginUrlOptions): void {\n if (options.locale) loginUrl.searchParams.set(\"locale\", options.locale);\n if (options.countryCode) loginUrl.searchParams.set(\"region_country\", options.countryCode);\n if (options.acrValues) loginUrl.searchParams.set(\"acr_values\", options.acrValues);\n if (!options.loginHint) return;\n\n loginUrl.searchParams.set(\"login_hint\", options.loginHint);\n if (options.loginHintMode) loginUrl.searchParams.set(\"login_hint_mode\", options.loginHintMode);\n}\n\nfunction sanitizeReturnTo(\n returnTo: string | null | undefined,\n origin: string,\n fallbackReturnTo = DEFAULT_LOGIN_RETURN_TO_PATH,\n): string {\n const path = getSameOriginPath(returnTo, origin);\n if (!path || new TextEncoder().encode(path).byteLength > MAX_RETURN_TO_LENGTH_IN_BYTES) {\n return fallbackReturnTo;\n }\n return path;\n}\n\nfunction absoluteSameOriginUrl(url: string, origin: string): string {\n const parsedUrl = new URL(url, origin);\n if (parsedUrl.origin !== origin) return origin;\n return parsedUrl.toString();\n}\n\nasync function createCodeChallenge(codeVerifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(codeVerifier));\n return base64UrlEncode(String.fromCharCode(...new Uint8Array(digest)));\n}\n\nfunction generateRandomBase64Url(): string {\n const bytes = new Uint8Array(RANDOM_BYTES_LENGTH);\n crypto.getRandomValues(bytes);\n return base64UrlEncode(String.fromCharCode(...bytes));\n}\n\nfunction base64UrlEncode(value: string): string {\n return btoa(value).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n\nfunction base64UrlDecode(value: string): string {\n const base64 = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const paddingLength = (4 - (base64.length % 4)) % 4;\n return atob(base64.padEnd(base64.length + paddingLength, \"=\"));\n}\n\ntype CustomerAccountEndpoints = {\n authorizeUrl: string;\n tokenUrl: string;\n logoutUrl: string;\n issuer: string;\n};\n\nfunction createCustomerAccountEndpoints(\n shopId: string,\n customerAccountApiUrl: string | undefined,\n): CustomerAccountEndpoints {\n const authBaseUrl = normalizeAuthBaseUrl(\n customerAccountApiUrl ?? `https://shopify.com/authentication/${shopId}`,\n );\n return {\n authorizeUrl: `${authBaseUrl}/oauth/authorize`,\n tokenUrl: `${authBaseUrl}/oauth/token`,\n logoutUrl: `${authBaseUrl}/logout`,\n issuer: authBaseUrl,\n };\n}\n\nfunction normalizeAuthBaseUrl(customerAccountApiUrl: string): string {\n const url = new URL(customerAccountApiUrl);\n if (url.protocol !== \"https:\") {\n throw new Error(\"customerAccountApiUrl must use HTTPS\");\n }\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction getOriginFromRequest(request: Request): string {\n return normalizeOrigin(new URL(request.url).origin);\n}\n\nfunction normalizeOrigin(origin: string): string {\n const url = new URL(origin);\n if (url.protocol === \"https:\") return url.origin;\n throw new Error(\n \"Customer Account OAuth origin must use HTTPS. Use a public HTTPS tunnel for local Customer Account login.\",\n );\n}\n\nfunction cancelResponseBody(response: Response): void {\n try {\n void response.body?.cancel().catch(() => undefined);\n } catch {}\n}\n\nfunction validateShopId(shopId: string): void {\n if (!SHOP_ID_RE.test(shopId)) {\n throw new Error(\"shopId must be a numeric Shopify shop ID string\");\n }\n}\n\nfunction validateCustomerAccountApiClientId(customerAccountApiClientId: string): void {\n if (typeof customerAccountApiClientId !== \"string\" || customerAccountApiClientId.trim() === \"\") {\n throw new Error(\"customerAccountApiClientId is required\");\n }\n}\n\nfunction validateTimeout(timeoutInMs: number): void {\n if (\n !Number.isSafeInteger(timeoutInMs) ||\n timeoutInMs <= 0 ||\n timeoutInMs > MAX_SET_TIMEOUT_IN_MS\n ) {\n throw new Error(\n `defaultTimeoutInMs must be a positive safe integer no greater than ${MAX_SET_TIMEOUT_IN_MS}`,\n );\n }\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"],"mappings":";;;;;;;;AAoBA,MAAM,MAAM,UAAU,mBAAmB;;;;;;AAOzC,MAA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I,UAAU,CAAC,QAAQ,OAAO,GAAG;;AAG1C,SAAS,qBAAqB,SAA0B;AACtD,QAAO,gBAAgB,IAAI,IAAI,QAAQ,IAAI,CAAC,OAAO;;AAGrD,SAAS,gBAAgB,QAAwB;CAC/C,MAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,KAAI,IAAI,aAAa,SAAU,QAAO,IAAI;AAC1C,OAAM,IAAI,MACR,4GACD;;AAGH,SAAS,mBAAmB,UAA0B;AACpD,KAAI;AACF,EAAK,SAAS,MAAM,QAAQ,CAAC,YAAY,OAAU;SAC7C;;AAGV,SAAS,eAAe,QAAsB;AAC5C,KAAI,CAAC,WAAW,KAAK,OAAO,CAC1B,OAAM,IAAI,MAAM,kDAAkD;;AAItE,SAAS,mCAAmC,4BAA0C;AACpF,KAAI,OAAO,+BAA+B,YAAY,2BAA2B,MAAM,KAAK,GAC1F,OAAM,IAAI,MAAM,yCAAyC;;AAI7D,SAAS,gBAAgB,aAA2B;AAClD,KACE,CAAC,OAAO,cAAc,YAAY,IAClC,eAAe,KACf,cAAc,sBAEd,OAAM,IAAI,MACR,sEAAsE,wBACvE;;AAIL,SAAS,eAAe,OAAkD;AACxE,QAAO,OAAO,UAAU,YAAY,UAAU"}
1
+ {"version":3,"file":"session.mjs","names":[],"sources":["../../src/customer-account/session.ts"],"sourcesContent":["import type { StorefrontClient } from \"../client\";\nimport {\n getCartBuyerIdentitySync,\n type CartBuyerIdentitySync,\n type CartBuyerIdentitySyncSource,\n} from \"../core/cart/buyer-identity-sync\";\nimport { DEFAULT_TIMEOUT_IN_MS, HYDROGEN_USER_AGENT } from \"../core/constants\";\nimport { getLogger } from \"../core/logging\";\nimport type { ShopifyRequestContext } from \"../core/request-context\";\nimport {\n createCallableRouteHandler,\n type CallableRouteHandler,\n type ShopifyRouteErrorResult,\n type ShopifyRouteHandlerContext,\n type ShopifyRouteRedirectResult,\n type ShopifyRouteSessionManager,\n} from \"../core/request-routing/registered-routes\";\nimport { CUSTOMER_ACCOUNT_PATHS, getSameOriginPath } from \"../core/url\";\nimport { CustomerAccountApiError, CustomerAccountOAuthError } from \"./errors\";\n\nconst log = getLogger(\"customer-account\");\n\n/**\n * OAuth callback route path: `\"/account/authorize\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_AUTHORIZE_PATH = CUSTOMER_ACCOUNT_PATHS.authorize;\n/**\n * Login route path: `\"/account/login\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_LOGIN_PATH = CUSTOMER_ACCOUNT_PATHS.login;\n/**\n * Logout route path: `\"/account/logout\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_LOGOUT_PATH = CUSTOMER_ACCOUNT_PATHS.logout;\n/**\n * Token refresh route path: `\"/account/refresh\"`.\n *\n * @publicDocs\n */\nexport const CUSTOMER_ACCOUNT_REFRESH_PATH = CUSTOMER_ACCOUNT_PATHS.refresh;\n\nconst CUSTOMER_ACCOUNT_SESSION_KEY = \"customerAccount\";\nconst DEFAULT_LOGIN_RETURN_TO_PATH = \"/account\";\nconst DEFAULT_POST_LOGIN_REDIRECT_PATHNAME = \"/\";\nconst DEFAULT_POST_LOGOUT_REDIRECT_URI = \"/\";\nconst FAILED_LOGIN_PATH = \"/account?login=failed\";\nconst FORBIDDEN_STATUS = 403;\nconst FORBIDDEN_ERROR_CODE = \"forbidden\";\nconst FORBIDDEN_ERROR_MESSAGE = \"Forbidden\";\nconst NO_STORE_CACHE_CONTROL = \"no-store\";\nconst AUTHORIZATION_CODE_GRANT_TYPE = \"authorization_code\";\nconst REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\";\nconst CUSTOMER_ACCOUNT_SCOPE = \"openid email customer-account-api:full\";\nconst CODE_CHALLENGE_METHOD = \"S256\";\nconst EXPIRY_BUFFER_IN_SECONDS = 120;\nconst PENDING_LOGIN_TTL_IN_MINUTES = 10;\nconst SECONDS_PER_MINUTE = 60;\nconst MILLISECONDS_PER_SECOND = 1_000;\nconst PENDING_LOGIN_TTL_IN_MS =\n PENDING_LOGIN_TTL_IN_MINUTES * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND;\nconst RANDOM_BYTES_LENGTH = 32;\nconst MAX_RETURN_TO_LENGTH_IN_BYTES = 2_048;\nconst MAX_SET_TIMEOUT_IN_MS = 2_147_483_647;\nconst SHOP_ID_RE = /^\\d+$/;\nconst CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON = \"customer-session-access-token\";\nconst CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON = \"customer-session-mutation\";\nconst CUSTOMER_SESSION_INTERNAL_BRAND: unique symbol = Symbol(\"hydrogen.customerSessionInternal\");\n\n/**\n * A value or a promise for that value. Session manager methods can return either.\n */\nexport type Awaitable<T> = T | Promise<T>;\n\n/** The session storage that `isLoggedIn()` and `getAccessToken()` read. */\nexport type ReadonlyCustomerSessionManager = {\n /** Returns the session value for a key. The customer session keeps its data under the `customerAccount` key. */\n getSessionItem(key: string): Awaitable<unknown>;\n};\n\n/** The session storage that sign-in, the OAuth callback, token refresh, and logout write to. Commit the session to the response after you call `prepareLoginUrl()`, `handleOAuthCallback()`, `getOrRefreshAccessToken()`, or `logout()`. */\nexport type WritableCustomerSessionManager = ShopifyRouteSessionManager;\n\ntype CustomerAccountSessionData = {\n tokens?: {\n accessToken?: string;\n refreshToken?: string;\n idToken?: string;\n expiresAt?: number;\n };\n pendingLogin?: {\n state?: string;\n nonce?: string;\n codeVerifier?: string;\n returnTo?: string;\n origin?: string;\n createdAt?: number;\n };\n};\n\n/** Options for creating a customer session. */\nexport type CreateCustomerSessionOptions = {\n /** Numeric Shopify shop ID as a string of digits, such as `12345`. */\n shopId: string;\n /** The Customer Account API OAuth client ID. Must contain at least one non-whitespace character. */\n customerAccountApiClientId: string;\n /**\n * The base URL for Shopify's OAuth authorize, token, and logout endpoints. Defaults to `https://shopify.com/authentication/{shopId}`.\n *\n * The URL must use HTTPS, or creating the session throws. Sign-in fails with the `issuer_mismatch` code when the ID token's issuer differs from this URL.\n */\n customerAccountApiUrl?: string;\n /** A custom fetch implementation. Defaults to the global fetch. */\n fetch?: typeof globalThis.fetch;\n /** The timeout for OAuth token requests in milliseconds. Must be a positive integer no greater than 2,147,483,647. Defaults to `30000`. */\n defaultTimeoutInMs?: number;\n};\n\n/** Options for building a Shopify OAuth login URL. */\nexport type PrepareLoginUrlOptions = {\n /**\n * Your storefront's origin for the OAuth redirect URL. Defaults to the origin that the session manager returns.\n *\n * The origin must use HTTPS, including on localhost. Use a public HTTPS tunnel for local sign-in.\n */\n origin?: string;\n /**\n * The same-origin path or URL to send the customer to after sign-in, such as `/account/orders`. Defaults to `/account`. Cross-origin values and paths over 2,048 bytes fall back to the default.\n */\n returnTo?: string;\n /** The language for Shopify's login page, sent as the `locale` search param. */\n locale?: string;\n /** The customer's country, sent as the `region_country` search param. */\n countryCode?: string;\n /** A value that prefills Shopify's login page, such as the customer's email address, sent as the `login_hint` search param. */\n loginHint?: string;\n /** How Shopify's login page uses the login hint, such as `submit`, sent as the `login_hint_mode` search param. Hydrogen sends the value only with `loginHint`. */\n loginHintMode?: string;\n /** The authentication context class to request, sent as the `acr_values` search param. */\n acrValues?: string;\n};\n\n/**\n * The storefront origin for a token refresh or logout.\n */\nexport type RequestOriginOptions = {\n /** Your storefront's HTTPS origin. Defaults to the origin that the session manager returns. A non-HTTPS origin throws. */\n origin?: string;\n};\n\n/** Options for logging the customer out. */\nexport interface LogoutOptions extends RequestOriginOptions {\n /**\n * The URL to send the customer to after logout. A relative URL resolves against the origin. Defaults to the origin, and a cross-origin URL falls back to the origin.\n */\n postLogoutRedirectUri?: string;\n}\n\n/**\n * Signs customers in and out with Shopify customer accounts, and gives your server their Customer Account API access tokens. Use the session on the server only.\n *\n * Pass your session storage and the request context to each method. Each method makes the final response private and uncacheable.\n *\n * @publicDocs\n */\nexport type CustomerSession = {\n /**\n * Returns `true` when the customer has a usable access token or a refresh token. The method never refreshes tokens.\n *\n * Use the result for UI state, such as an account link. Gate Customer Account API data on an access token from `getOrRefreshAccessToken()`.\n */\n isLoggedIn(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ): Promise<boolean>;\n /**\n * Returns the customer's stored access token, or `undefined` when the token is missing or expired. The method never refreshes the token or writes to the session. Call `getOrRefreshAccessToken()` to refresh an expired token.\n */\n getAccessToken(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ): Promise<string | undefined>;\n /**\n * Returns a usable access token for the customer. When the stored token is missing or expired, the session gets new tokens from Shopify and writes them to your session storage. Call the method only where you commit the session to the response.\n *\n * Returns `undefined` when the customer has no refresh token, or when a temporary refresh failure keeps the session for a retry. When Shopify rejects the refresh token with a `400` or `401` status, the session clears the stored tokens and returns `undefined`. Refresh failures never throw.\n */\n getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: RequestOriginOptions,\n ): Promise<string | undefined>;\n /**\n * Starts customer sign-in and returns the URL of Shopify's login page. Commit the session to the response, then redirect the customer to the URL.\n *\n * The customer has 10 minutes to finish signing in. After that, the OAuth callback fails with the `missing_pending_login` code.\n */\n prepareLoginUrl(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: PrepareLoginUrlOptions,\n ): Promise<string>;\n /**\n * Completes sign-in from Shopify's OAuth callback request, saves the customer's tokens to your session storage, and returns the path to send the customer to. Commit the session to the response after the call.\n *\n * The method throws `CustomerAccountOAuthError` when sign-in fails a check, and `CustomerAccountApiError` when the token request times out. After a failure, the customer needs to start sign-in again.\n *\n * @throws {CustomerAccountOAuthError} When the callback parameters, pending login, token exchange, token response, or ID token claims fail validation.\n * @throws {CustomerAccountApiError} When the token request times out.\n */\n handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<string>;\n /**\n * Clears the customer's session data and returns the URL to send the customer to. Commit the session to the response after the call.\n *\n * When the session has an ID token, the URL points to Shopify's logout endpoint with the post-logout URL attached. Without an ID token, the method returns the post-logout URL.\n */\n logout(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: LogoutOptions,\n ): Promise<string>;\n};\n\n/**\n * The login, authorize, refresh, and logout routes for customer accounts. Add the object to the `handlers` option of `handleShopifyRoutes`.\n */\nexport type CustomerAccountServerHandlers<\n TContext extends CustomerAccountRouteHandlerContext = CustomerAccountRouteHandlerContext,\n> = {\n /** Completes sign-in at `/account/authorize`, the OAuth callback, and redirects the customer to the return path. Accepts `GET`. */\n authorize: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_AUTHORIZE_PATH,\n \"GET\"\n >;\n /** Starts sign-in at `/account/login` and redirects the customer to Shopify's login page. Accepts `GET`. Pass `return_to`, `locale`, `acr_values`, `login_hint`, and `login_hint_mode` as search params. The route sends the request context's country to Shopify. */\n login: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_LOGIN_PATH,\n \"GET\"\n >;\n /**\n * Logs the customer out at `/account/logout`. Accepts `POST`. For CSRF protection, the route returns a `403` response unless the `Origin` or `Referer` header matches your storefront's origin.\n *\n * Through `handleShopifyRoutes`, a GET request to the logout path returns a `405` response. Log out with a `<form method=\"post\" action=\"/account/logout\">` and a submit button, which works without JavaScript.\n */\n logout: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_LOGOUT_PATH,\n \"POST\"\n >;\n /** Refreshes the access token at `/account/refresh` and redirects the customer to the same-origin `return_to` path, which defaults to `/account`. Accepts `GET`. */\n refresh: CallableRouteHandler<\n TContext,\n CustomerAccountRouteResult,\n typeof CUSTOMER_ACCOUNT_REFRESH_PATH,\n \"GET\"\n >;\n};\n\n/**\n * Customer account routes that also keep the cart's buyer identity in step with the signed-in customer. These routes need `storefrontClient` in the handler context.\n */\nexport type CustomerAccountServerHandlersWithCartSync =\n CustomerAccountServerHandlers<ShopifyRouteHandlerContext>;\n\n/** A customer session that `createCustomerSession` returns. Cart buyer identity sync requires this session. */\ntype CustomerSessionWithInternals = CustomerSession & {\n readonly [CUSTOMER_SESSION_INTERNAL_BRAND]: true;\n};\n\n/** Options for the customer account routes. */\ntype CreateCustomerAccountServerHandlersBaseOptions = {\n /** The path to send the customer to after sign-in when the login request has no same-origin `return_to` search param. Defaults to `/`. */\n defaultPostLoginRedirectPathname?: string;\n /** The same-origin path to send the customer to when sign-in fails with `CustomerAccountOAuthError`. Defaults to `/account?login=failed`. A cross-origin value falls back to `/account`. The authorize route rethrows other errors. */\n loginFailedRedirectPath?: string;\n /** Your storefront's HTTPS origin, or a function that returns the origin for a request. Defaults to the origin that the session manager returns. */\n origin?: string | ((request: Request) => string);\n /** The URL to send the customer to after logout. Defaults to `/`. A same-origin `return_to` search param on the logout request overrides this value. */\n postLogoutRedirectUri?: string;\n};\n\n/** Options for the customer account routes without cart buyer identity sync. */\ninterface CustomerAccountServerHandlersOptionsWithoutCart extends CreateCustomerAccountServerHandlersBaseOptions {\n /** The customer session from `createCustomerSession`. */\n customerSession: CustomerSession;\n /**\n * The cart server handlers that `createCartServerHandlers` returns with its `customerSession` option. Pass the cart handlers to keep the cart's buyer identity in step with the signed-in customer.\n *\n * The authorize and refresh routes attach the customer to the cart. The logout route, and a refresh that ends the session, detach the customer from the cart. When a sync fails, the route logs the error and still redirects. When a detach fails, the route also expires the `cart` cookie. The sync needs `storefrontClient` in the handler context.\n *\n * Creating the handlers throws when the cart handlers lack the `customerSession` option, or when the customer session doesn't come from `createCustomerSession`.\n */\n cartServerHandlers?: undefined;\n}\n\n/** Options for the customer account routes that keep the cart's buyer identity in step with the signed-in customer. */\ninterface CustomerAccountServerHandlersOptionsWithCart extends CreateCustomerAccountServerHandlersBaseOptions {\n /** The customer session from `createCustomerSession`. */\n customerSession: CustomerSessionWithInternals;\n /**\n * The cart server handlers that `createCartServerHandlers` returns with its `customerSession` option. Pass the cart handlers to keep the cart's buyer identity in step with the signed-in customer.\n *\n * The authorize and refresh routes attach the customer to the cart. The logout route, and a refresh that ends the session, detach the customer from the cart. When a sync fails, the route logs the error and still redirects. When a detach fails, the route also expires the `cart` cookie. The sync needs `storefrontClient` in the handler context.\n *\n * Creating the handlers throws when the cart handlers lack the `customerSession` option, or when the customer session doesn't come from `createCustomerSession`.\n */\n cartServerHandlers: CartBuyerIdentitySyncSource;\n}\n\n/** Options for the customer account routes, with optional cart buyer identity sync. */\nexport type CreateCustomerAccountServerHandlersOptions =\n | CustomerAccountServerHandlersOptionsWithoutCart\n | CustomerAccountServerHandlersOptionsWithCart;\n\ntype CustomerAccountTokens = NonNullable<CustomerAccountSessionData[\"tokens\"]>;\ntype PendingLogin = NonNullable<CustomerAccountSessionData[\"pendingLogin\"]>;\ntype TokenEndpointResponse = {\n access_token?: unknown;\n refresh_token?: unknown;\n id_token?: unknown;\n expires_in?: unknown;\n};\ntype ParsedTokenEndpointResponse = {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n expires_in: number;\n};\ntype RefreshResult =\n | { type: \"success\"; tokens: CustomerAccountTokens }\n | { type: \"invalid\" }\n | { type: \"transient\" };\ntype TokenRefreshResult =\n | {\n /** A usable access token is available. */\n status: \"authenticated\";\n accessToken: string;\n }\n | {\n /** Refresh failed transiently, but the refreshable session remains. */\n status: \"transient\";\n accessToken: undefined;\n }\n | {\n /** No usable or refreshable customer session remains. */\n status: \"unauthenticated\";\n accessToken: undefined;\n };\ntype OAuthCallbackResult = {\n location: string;\n accessToken: string;\n};\ntype CustomerSessionInternals = {\n getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options?: RequestOriginOptions,\n ): Promise<TokenRefreshResult>;\n handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<OAuthCallbackResult>;\n};\nconst customerSessionInternals = new WeakMap<CustomerSession, CustomerSessionInternals>();\n/** A redirect, or a `403` error when a logout request comes from another origin. */\ntype CustomerAccountRouteResult = ShopifyRouteRedirectResult | ShopifyRouteErrorResult;\ntype CustomerAccountRouteHandlerContext = {\n request: Request;\n sessionManager: WritableCustomerSessionManager;\n requestContext: ShopifyRequestContext;\n};\ntype CustomerAccountRuntimeRouteHandlerContext = CustomerAccountRouteHandlerContext & {\n storefrontClient?: StorefrontClient;\n};\ntype CustomerAccountServerHandlersForOptions<TOptions> = TOptions extends {\n cartServerHandlers: CartBuyerIdentitySyncSource;\n}\n ? CustomerAccountServerHandlersWithCartSync\n : CustomerAccountServerHandlers;\ntype TokenRequestParams = {\n url: string;\n origin: string;\n body: URLSearchParams;\n fetch: typeof globalThis.fetch;\n signal: AbortSignal;\n};\n\n/**\n * Creates a customer session that signs customers in and out with Shopify customer accounts and manages their access tokens. Use the session on the server only.\n *\n * The function throws when the shop ID, client ID, API URL, or timeout is invalid, when no fetch implementation is available, and when the function runs in a browser.\n *\n * @example\n * ```ts\n * import { createCustomerSession } from '@shopify/hydrogen/customer-account';\n *\n * const customerSession = createCustomerSession({\n * shopId: env.SHOP_ID,\n * customerAccountApiClientId: env.CUSTOMER_ACCOUNT_API_CLIENT_ID,\n * });\n * ```\n *\n * @param options - The shop ID, the OAuth client ID, the authentication base URL, a custom fetch, and the token request timeout.\n * @returns A customer session with methods for sign-in, the OAuth callback, access tokens, and logout.\n * @throws {Error} When called in a browser, when an option fails validation, or when no fetch is available.\n * @publicDocs\n */\nexport function createCustomerSession({\n shopId,\n customerAccountApiClientId,\n customerAccountApiUrl,\n fetch: customFetch,\n defaultTimeoutInMs = DEFAULT_TIMEOUT_IN_MS,\n}: CreateCustomerSessionOptions): CustomerSessionWithInternals {\n if (typeof document !== \"undefined\") {\n throw new Error(\n \"Customer Account OAuth sessions cannot be used in a browser context. Use this helper from server or edge routes only.\",\n );\n }\n\n validateShopId(shopId);\n validateCustomerAccountApiClientId(customerAccountApiClientId);\n validateTimeout(defaultTimeoutInMs);\n\n const fetch = customFetch ?? globalThis.fetch;\n if (typeof fetch !== \"function\") {\n throw new Error(\n \"No fetch function available. Pass a fetch option or ensure globalThis.fetch exists.\",\n );\n }\n\n const endpoints = createCustomerAccountEndpoints(shopId, customerAccountApiUrl);\n const refreshFlights = new Map<string, Promise<RefreshResult>>();\n\n async function getAccessToken(\n sessionManager: ReadonlyCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON);\n const accessToken = getUsableAccessToken(await readSessionData(sessionManager));\n return accessToken;\n }\n\n async function getOrRefreshAccessToken(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n ) {\n const result = await getOrRefreshAccessTokenResult(sessionManager, requestContext, options);\n return result.accessToken;\n }\n\n async function getOrRefreshAccessTokenResult(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n ): Promise<TokenRefreshResult> {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON);\n const sessionData = await readSessionData(sessionManager);\n const accessToken = getUsableAccessToken(sessionData);\n if (accessToken) return { status: \"authenticated\", accessToken };\n\n const refreshToken = getRefreshToken(sessionData);\n if (!refreshToken) return { status: \"unauthenticated\", accessToken: undefined };\n\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const idToken = sessionData.tokens?.idToken;\n const refreshResult = await getRefreshResult({\n refreshFlights,\n refreshToken,\n idToken,\n origin,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs: defaultTimeoutInMs,\n });\n\n if (refreshResult.type === \"success\") {\n const refreshedAccessToken = refreshResult.tokens.accessToken;\n if (!refreshedAccessToken) {\n return { status: \"transient\", accessToken: undefined };\n }\n await writeTokens(sessionManager, refreshResult.tokens);\n return {\n status: \"authenticated\",\n accessToken: refreshedAccessToken,\n };\n }\n\n if (refreshResult.type === \"invalid\") {\n await clearTokens(sessionManager);\n return { status: \"unauthenticated\", accessToken: undefined };\n }\n\n return { status: \"transient\", accessToken: undefined };\n }\n\n async function prepareLoginUrl(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: PrepareLoginUrlOptions,\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const state = generateRandomBase64Url();\n const nonce = generateRandomBase64Url();\n const codeVerifier = generateRandomBase64Url();\n const codeChallenge = await createCodeChallenge(codeVerifier);\n const returnTo = sanitizeReturnTo(options.returnTo, origin);\n const createdAt = Date.now();\n\n const sessionData = await readSessionData(sessionManager);\n await writeSessionData(sessionManager, {\n ...sessionData,\n pendingLogin: { state, nonce, codeVerifier, returnTo, origin, createdAt },\n });\n\n const loginUrl = new URL(endpoints.authorizeUrl);\n loginUrl.searchParams.set(\"client_id\", customerAccountApiClientId);\n loginUrl.searchParams.set(\"scope\", CUSTOMER_ACCOUNT_SCOPE);\n loginUrl.searchParams.set(\"response_type\", \"code\");\n loginUrl.searchParams.set(\"redirect_uri\", `${origin}${CUSTOMER_ACCOUNT_AUTHORIZE_PATH}`);\n loginUrl.searchParams.set(\"state\", state);\n loginUrl.searchParams.set(\"nonce\", nonce);\n loginUrl.searchParams.set(\"code_challenge\", codeChallenge);\n loginUrl.searchParams.set(\"code_challenge_method\", CODE_CHALLENGE_METHOD);\n setOptionalLoginParams(loginUrl, options);\n\n return loginUrl.toString();\n }\n\n async function handleOAuthCallback(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ) {\n return (await handleOAuthCallbackResult(sessionManager, requestContext, request)).location;\n }\n\n async function handleOAuthCallbackResult(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n ): Promise<OAuthCallbackResult> {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n try {\n return await completeOAuthCallback({\n sessionManager,\n request,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs: defaultTimeoutInMs,\n });\n } catch (error) {\n await clearPendingLogin(sessionManager);\n throw error;\n }\n }\n\n async function logout(\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: LogoutOptions = {},\n ) {\n requestContext.markResponseAsPersonalized(CUSTOMER_SESSION_MUTATION_PERSONALIZATION_REASON);\n const origin = await getResolvedOrigin(sessionManager, options.origin);\n const sessionData = await readSessionData(sessionManager);\n const idToken = sessionData.tokens?.idToken;\n const postLogoutRedirectUri = absoluteSameOriginUrl(\n options.postLogoutRedirectUri ?? origin,\n origin,\n );\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n\n if (!idToken) return postLogoutRedirectUri;\n\n const logoutUrl = new URL(endpoints.logoutUrl);\n logoutUrl.searchParams.set(\"id_token_hint\", idToken);\n logoutUrl.searchParams.set(\"post_logout_redirect_uri\", postLogoutRedirectUri);\n return logoutUrl.toString();\n }\n\n const customerSession: CustomerSessionWithInternals = {\n [CUSTOMER_SESSION_INTERNAL_BRAND]: true,\n isLoggedIn: async (sessionManager, requestContext) => {\n requestContext.markResponseAsPersonalized(\n CUSTOMER_SESSION_ACCESS_TOKEN_PERSONALIZATION_REASON,\n );\n return hasCustomerSession(await readSessionData(sessionManager));\n },\n getAccessToken,\n getOrRefreshAccessToken,\n prepareLoginUrl,\n handleOAuthCallback,\n logout,\n };\n customerSessionInternals.set(customerSession, {\n getOrRefreshAccessToken: getOrRefreshAccessTokenResult,\n handleOAuthCallback: handleOAuthCallbackResult,\n });\n return customerSession;\n}\n\nexport async function getCustomerSessionRefreshResult(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions = {},\n): Promise<TokenRefreshResult | undefined> {\n return customerSessionInternals\n .get(customerSession)\n ?.getOrRefreshAccessToken(sessionManager, requestContext, options);\n}\n\n/**\n * Creates the customer account routes under `/account` for sign-in, the OAuth callback, token refresh, and logout. Add the returned object to the `handlers` option of `handleShopifyRoutes`.\n *\n * The login route redirects to Shopify's login page. The authorize and refresh routes redirect back to a same-origin path in your app. The logout route redirects to Shopify's logout endpoint when the session has an ID token, and to the post-logout URL otherwise. Each redirect commits the session and sends `cache-control: no-store`.\n *\n * Link to these paths with full-page navigation, such as a plain `<a>` link or a `<form>`. Client-side navigation components can't follow these redirects.\n *\n * @returns The login, authorize, refresh, and logout routes.\n * @publicDocs\n */\nexport function createCustomerAccountServerHandlers<\n const TOptions extends CreateCustomerAccountServerHandlersOptions,\n>(options: TOptions): CustomerAccountServerHandlersForOptions<TOptions>;\n/**\n * @param options The customer session, the redirect paths, and optional cart handlers for the account routes.\n * @returns The login, authorize, refresh, and logout routes.\n */\nexport function createCustomerAccountServerHandlers(\n options: CreateCustomerAccountServerHandlersOptions,\n): CustomerAccountServerHandlers | CustomerAccountServerHandlersWithCartSync {\n const {\n customerSession,\n defaultPostLoginRedirectPathname = DEFAULT_POST_LOGIN_REDIRECT_PATHNAME,\n loginFailedRedirectPath = FAILED_LOGIN_PATH,\n postLogoutRedirectUri = DEFAULT_POST_LOGOUT_REDIRECT_URI,\n } = options;\n const { origin: originOption } = options;\n const cartSync = resolveCartBuyerIdentitySync(options);\n\n return {\n authorize: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_AUTHORIZE_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleAuthorizeRoute(\n customerSession,\n context,\n loginFailedRedirectPath,\n originOption,\n cartSync,\n );\n },\n ),\n login: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_LOGIN_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n const { request, sessionManager, requestContext } = context;\n return handleLoginRoute(\n customerSession,\n sessionManager,\n requestContext,\n request,\n defaultPostLoginRedirectPathname,\n originOption,\n );\n },\n ),\n logout: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_LOGOUT_PATH,\n \"POST\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleLogoutRoute(\n customerSession,\n context,\n postLogoutRedirectUri,\n originOption,\n cartSync,\n );\n },\n ),\n refresh: createCallableRouteHandler(\n CUSTOMER_ACCOUNT_REFRESH_PATH,\n \"GET\",\n async (context: CustomerAccountRuntimeRouteHandlerContext) => {\n return handleRefreshRoute(customerSession, context, originOption, cartSync);\n },\n ),\n };\n}\n\nfunction resolveCartBuyerIdentitySync(\n options: CreateCustomerAccountServerHandlersOptions,\n): CartBuyerIdentitySync | undefined {\n if (!options.cartServerHandlers) return undefined;\n\n const cartSync = getCartBuyerIdentitySync(options.cartServerHandlers);\n if (!cartSync) {\n throw new Error(\n \"cartServerHandlers must be created by createCartServerHandlers with the customerSession option.\",\n );\n }\n if (!customerSessionInternals.has(options.customerSession)) {\n throw new Error(\n \"Cart buyer identity sync requires the customerSession returned by createCustomerSession.\",\n );\n }\n return cartSync;\n}\n\nasync function handleLoginRoute(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n defaultPostLoginRedirectPathname: string,\n originOption: string | ((request: Request) => string) | undefined,\n): Promise<CustomerAccountRouteResult> {\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n const requestUrl = new URL(request.url);\n const defaultReturnTo = sanitizeReturnTo(\n defaultPostLoginRedirectPathname,\n origin,\n DEFAULT_POST_LOGIN_REDIRECT_PATHNAME,\n );\n const requestedReturnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n const returnTo = sanitizeReturnTo(requestedReturnTo, origin, defaultReturnTo);\n const loginUrl = await customerSession.prepareLoginUrl(sessionManager, requestContext, {\n origin,\n returnTo,\n countryCode: requestContext.locale.country,\n locale: getOptionalSearchParam(requestUrl, \"locale\"),\n acrValues: getOptionalSearchParam(requestUrl, \"acr_values\"),\n loginHint: getOptionalSearchParam(requestUrl, \"login_hint\"),\n loginHintMode: getOptionalSearchParam(requestUrl, \"login_hint_mode\"),\n });\n return redirectResult(loginUrl, await commitSession(sessionManager));\n}\n\nasync function handleLogoutRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n postLogoutRedirectUri: string,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n if (!isSameOriginPost(request, origin)) return forbiddenResult();\n\n const requestUrl = new URL(request.url);\n const requestedReturnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n const logoutUrl = await customerSession.logout(sessionManager, requestContext, {\n origin,\n postLogoutRedirectUri: sanitizeReturnTo(requestedReturnTo, origin, postLogoutRedirectUri),\n });\n\n // The redirect must complete even when detach fails: skipping it would leave\n // the Shopify IdP session alive after the app session is already destroyed.\n // Expiring the cart cookie is the fail-safe when the cart keeps the identity.\n let detachFailed = false;\n if (cartSync) {\n detachFailed = !(await syncCartBuyerIdentity(cartSync, context, null, \"logout\"));\n }\n const headers = new Headers(await commitSession(sessionManager));\n if (cartSync && detachFailed) headers.append(\"set-cookie\", cartSync.expiredCartCookie);\n return redirectResult(logoutUrl, headers);\n}\n\nasync function handleAuthorizeRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n loginFailedRedirectPath: string,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n try {\n if (!cartSync) {\n const location = await customerSession.handleOAuthCallback(\n sessionManager,\n requestContext,\n request,\n );\n return redirectResult(location, await commitSession(sessionManager));\n }\n\n const { location, accessToken } = await handleOAuthCallbackWithAccessToken(\n customerSession,\n sessionManager,\n requestContext,\n request,\n );\n // Best-effort: the customer is authenticated at this point, so a failed\n // cart sync must not turn a successful login into an error response. The\n // next refresh retries the attach.\n await syncCartBuyerIdentity(cartSync, context, accessToken, \"authorize\");\n return redirectResult(location, await commitSession(sessionManager));\n } catch (error) {\n if (!(error instanceof CustomerAccountOAuthError)) throw error;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n return redirectResult(\n sanitizeReturnTo(loginFailedRedirectPath, origin),\n await commitSession(sessionManager),\n );\n }\n}\n\nasync function handleRefreshRoute(\n customerSession: CustomerSession,\n context: CustomerAccountRuntimeRouteHandlerContext,\n originOption: string | ((request: Request) => string) | undefined,\n cartSync: CartBuyerIdentitySync | undefined,\n): Promise<CustomerAccountRouteResult> {\n const { request, sessionManager, requestContext } = context;\n const origin = await resolveRouteOrigin(sessionManager, request, originOption);\n if (!cartSync) {\n await customerSession.getOrRefreshAccessToken(sessionManager, requestContext, { origin });\n return refreshRedirectResult(request, origin, await commitSession(sessionManager));\n }\n\n const refreshResult = await getOrRefreshAccessTokenWithStatus(\n customerSession,\n sessionManager,\n requestContext,\n { origin },\n );\n // Transient refresh failures keep the refreshable session, so the cart's\n // identity is left untouched; a definitive outcome attaches or detaches it.\n let detachFailed = false;\n if (refreshResult.status !== \"transient\") {\n const customerAccessToken = refreshResult.accessToken ?? null;\n const syncSucceeded = await syncCartBuyerIdentity(\n cartSync,\n context,\n customerAccessToken,\n \"refresh\",\n );\n detachFailed = customerAccessToken === null && !syncSucceeded;\n }\n\n const headers = new Headers(await commitSession(sessionManager));\n if (detachFailed) headers.append(\"set-cookie\", cartSync.expiredCartCookie);\n return refreshRedirectResult(request, origin, headers);\n}\n\nfunction refreshRedirectResult(\n request: Request,\n origin: string,\n headers?: HeadersInit,\n): ShopifyRouteRedirectResult {\n const requestUrl = new URL(request.url);\n const returnTo =\n requestUrl.searchParams.get(\"return_to\") ?? requestUrl.searchParams.get(\"returnTo\");\n return redirectResult(sanitizeReturnTo(returnTo, origin), headers);\n}\n\nasync function handleOAuthCallbackWithAccessToken(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n request: Request,\n): Promise<OAuthCallbackResult> {\n const internal = customerSessionInternals.get(customerSession);\n if (!internal) {\n throw new Error(\"Customer session was not created by createCustomerSession\");\n }\n return internal.handleOAuthCallback(sessionManager, requestContext, request);\n}\n\nasync function getOrRefreshAccessTokenWithStatus(\n customerSession: CustomerSession,\n sessionManager: WritableCustomerSessionManager,\n requestContext: ShopifyRequestContext,\n options: RequestOriginOptions,\n): Promise<TokenRefreshResult> {\n const internal = customerSessionInternals.get(customerSession);\n if (!internal) {\n throw new Error(\"Customer session was not created by createCustomerSession\");\n }\n return internal.getOrRefreshAccessToken(sessionManager, requestContext, options);\n}\n\nasync function syncCartBuyerIdentity(\n cartSync: CartBuyerIdentitySync,\n context: CustomerAccountRuntimeRouteHandlerContext,\n customerAccessToken: string | null,\n route: \"authorize\" | \"refresh\" | \"logout\",\n): Promise<boolean> {\n try {\n if (!context.storefrontClient) {\n throw new Error(\n \"Customer Account handlers configured with cartServerHandlers require storefrontClient.\",\n );\n }\n await cartSync.updateBuyerIdentity(\n { request: context.request, storefrontClient: context.storefrontClient },\n customerAccessToken,\n );\n return true;\n } catch (error) {\n log.error(\"cart buyer identity sync failed\", { route, error });\n return false;\n }\n}\n\nasync function resolveRouteOrigin(\n sessionManager: WritableCustomerSessionManager,\n request: Request,\n originOption: string | ((request: Request) => string) | undefined,\n) {\n if (typeof originOption === \"function\") return normalizeOrigin(originOption(request));\n return getResolvedOrigin(sessionManager, originOption);\n}\n\nasync function getResolvedOrigin(\n sessionManager: WritableCustomerSessionManager,\n originOverride: string | undefined,\n) {\n return normalizeOrigin(originOverride ?? (await sessionManager.getSessionOrigin()));\n}\n\nfunction getOptionalSearchParam(url: URL, name: string): string | undefined {\n return url.searchParams.get(name) ?? undefined;\n}\n\nfunction redirectResult(location: string, headers?: HeadersInit): ShopifyRouteRedirectResult {\n const redirectHeaders = new Headers(headers);\n redirectHeaders.set(\"cache-control\", NO_STORE_CACHE_CONTROL);\n return { type: \"redirect\", location, headers: redirectHeaders };\n}\n\nfunction forbiddenResult(): ShopifyRouteErrorResult {\n return {\n type: \"error\",\n status: FORBIDDEN_STATUS,\n error: { code: FORBIDDEN_ERROR_CODE, message: FORBIDDEN_ERROR_MESSAGE },\n headers: { \"cache-control\": NO_STORE_CACHE_CONTROL },\n };\n}\n\nasync function commitSession(\n sessionManager: WritableCustomerSessionManager,\n): Promise<HeadersInit | undefined> {\n return (await sessionManager.commit?.()) ?? undefined;\n}\n\nasync function completeOAuthCallback({\n sessionManager,\n request,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs,\n}: {\n sessionManager: WritableCustomerSessionManager;\n request: Request;\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<OAuthCallbackResult> {\n const requestUrl = new URL(request.url);\n const code = requestUrl.searchParams.get(\"code\");\n const state = requestUrl.searchParams.get(\"state\");\n const sessionData = await readSessionData(sessionManager);\n const pendingLogin = getPendingLogin(sessionData);\n\n assertOAuthCallbackParams(code, state, pendingLogin);\n\n const origin = pendingLogin.origin ?? getOriginFromRequest(request);\n const tokenResponse = await exchangeAuthorizationCode({\n endpoints,\n customerAccountApiClientId,\n origin,\n code,\n codeVerifier: pendingLogin.codeVerifier,\n fetch,\n timeoutInMs,\n });\n validateIdTokenClaims(tokenResponse.id_token, {\n audience: customerAccountApiClientId,\n issuer: endpoints.issuer,\n nonce: pendingLogin.nonce,\n });\n\n await writeSessionData(sessionManager, {\n tokens: createTokensFromResponse(tokenResponse),\n });\n\n return {\n location: pendingLogin.returnTo ?? DEFAULT_LOGIN_RETURN_TO_PATH,\n accessToken: tokenResponse.access_token,\n };\n}\n\nfunction isSameOriginPost(request: Request, trustedOrigin: string): boolean {\n const origin = request.headers.get(\"origin\");\n if (origin) {\n try {\n return normalizeOrigin(origin) === trustedOrigin;\n } catch {\n return false;\n }\n }\n\n const referer = request.headers.get(\"referer\");\n if (!referer) return false;\n\n try {\n return normalizeOrigin(new URL(referer).origin) === trustedOrigin;\n } catch {\n return false;\n }\n}\n\nfunction assertOAuthCallbackParams(\n code: string | null,\n state: string | null,\n pendingLogin: Required<PendingLogin>,\n): asserts code is string {\n if (!code || !state) {\n throw new CustomerAccountOAuthError(\n \"missing_callback_params\",\n \"OAuth callback is missing code or state\",\n );\n }\n\n if (pendingLogin.state !== state) {\n throw new CustomerAccountOAuthError(\n \"state_mismatch\",\n \"OAuth callback state does not match session state\",\n );\n }\n}\n\nasync function exchangeAuthorizationCode({\n endpoints,\n customerAccountApiClientId,\n origin,\n code,\n codeVerifier,\n fetch,\n timeoutInMs,\n}: {\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n origin: string;\n code: string;\n codeVerifier: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<Required<ParsedTokenEndpointResponse>> {\n const body = new URLSearchParams({\n grant_type: AUTHORIZATION_CODE_GRANT_TYPE,\n client_id: customerAccountApiClientId,\n redirect_uri: `${origin}${CUSTOMER_ACCOUNT_AUTHORIZE_PATH}`,\n code,\n code_verifier: codeVerifier,\n });\n return withTokenRequestTimeout(timeoutInMs, async (signal) => {\n const response = await postTokenRequest({\n url: endpoints.tokenUrl,\n origin,\n body,\n fetch,\n signal,\n });\n\n if (!response.ok) {\n cancelResponseBody(response);\n const errorCode =\n response.status === 400 || response.status === 401\n ? \"token_exchange_rejected\"\n : \"token_exchange_failed\";\n throw new CustomerAccountOAuthError(\n errorCode,\n `Customer Account OAuth token exchange failed with ${response.status}`,\n );\n }\n\n return parseRequiredTokenResponse(await readTokenResponseJson(response, signal));\n });\n}\n\nasync function getRefreshResult({\n refreshFlights,\n refreshToken,\n idToken,\n origin,\n endpoints,\n customerAccountApiClientId,\n fetch,\n timeoutInMs,\n}: {\n refreshFlights: Map<string, Promise<RefreshResult>>;\n refreshToken: string;\n idToken: string | undefined;\n origin: string;\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}) {\n const flightKey = `${origin}\\n${refreshToken}`;\n const existingFlight = refreshFlights.get(flightKey);\n if (existingFlight) return existingFlight;\n\n const flight = refreshAccessToken({\n endpoints,\n customerAccountApiClientId,\n refreshToken,\n idToken,\n origin,\n fetch,\n timeoutInMs,\n });\n refreshFlights.set(flightKey, flight);\n\n try {\n return await flight;\n } finally {\n refreshFlights.delete(flightKey);\n }\n}\n\nasync function refreshAccessToken({\n endpoints,\n customerAccountApiClientId,\n refreshToken,\n idToken,\n origin,\n fetch,\n timeoutInMs,\n}: {\n endpoints: CustomerAccountEndpoints;\n customerAccountApiClientId: string;\n refreshToken: string;\n idToken: string | undefined;\n origin: string;\n fetch: typeof globalThis.fetch;\n timeoutInMs: number;\n}): Promise<RefreshResult> {\n const body = new URLSearchParams({\n grant_type: REFRESH_TOKEN_GRANT_TYPE,\n client_id: customerAccountApiClientId,\n refresh_token: refreshToken,\n });\n\n try {\n return await withTokenRequestTimeout(timeoutInMs, async (signal) => {\n const response = await postTokenRequest({\n url: endpoints.tokenUrl,\n origin,\n body,\n fetch,\n signal,\n });\n return readRefreshResult(response, refreshToken, idToken, signal);\n });\n } catch {\n return { type: \"transient\" };\n }\n}\n\nasync function readRefreshResult(\n response: Response,\n currentRefreshToken: string,\n currentIdToken: string | undefined,\n signal: AbortSignal,\n): Promise<RefreshResult> {\n if (response.status === 400 || response.status === 401) {\n cancelResponseBody(response);\n return { type: \"invalid\" };\n }\n\n if (!response.ok) {\n cancelResponseBody(response);\n return { type: \"transient\" };\n }\n\n try {\n const tokenResponse = await readTokenResponseJson(response, signal);\n const parsedTokenResponse = parseRefreshTokenResponse(tokenResponse);\n return {\n type: \"success\",\n tokens: createTokensFromResponse({\n ...parsedTokenResponse,\n refresh_token: parsedTokenResponse.refresh_token ?? currentRefreshToken,\n id_token: parsedTokenResponse.id_token ?? currentIdToken,\n }),\n };\n } catch {\n return { type: \"transient\" };\n }\n}\n\nasync function postTokenRequest({\n url,\n origin,\n body,\n fetch,\n signal,\n}: TokenRequestParams): Promise<Response> {\n return await withAbort(\n fetch(url, {\n method: \"POST\",\n headers: new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": HYDROGEN_USER_AGENT,\n Origin: origin,\n }),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n signal,\n }),\n signal,\n );\n}\n\nasync function withTokenRequestTimeout<T>(\n timeoutInMs: number,\n operation: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort(\n new CustomerAccountApiError(\n `Customer Account OAuth request timed out after ${timeoutInMs}ms`,\n ),\n );\n }, timeoutInMs);\n\n try {\n return await operation(controller.signal);\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\nfunction withAbort<T>(promise: T | Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(getAbortReason(signal));\n\n return new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener(\"abort\", abort);\n reject(getAbortReason(signal));\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n Promise.resolve(promise).then(\n (value) => {\n signal.removeEventListener(\"abort\", abort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n },\n );\n });\n}\n\nfunction getAbortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"signal is aborted without reason\", \"AbortError\");\n}\n\nasync function readTokenResponseJson(\n response: Response,\n signal: AbortSignal,\n): Promise<TokenEndpointResponse> {\n const json = await withAbort(response.json(), signal);\n if (!isObjectRecord(json)) {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response must be an object\",\n );\n }\n return {\n access_token: json.access_token,\n refresh_token: json.refresh_token,\n id_token: json.id_token,\n expires_in: json.expires_in,\n };\n}\n\nfunction parseRequiredTokenResponse(\n response: TokenEndpointResponse,\n): Required<ParsedTokenEndpointResponse> {\n const parsed = parseRefreshTokenResponse(response);\n if (typeof response.refresh_token !== \"string\" || response.refresh_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing refresh_token\",\n );\n }\n\n if (typeof response.id_token !== \"string\" || response.id_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing id_token\",\n );\n }\n return { ...parsed, refresh_token: response.refresh_token, id_token: response.id_token };\n}\n\nfunction parseRefreshTokenResponse(response: TokenEndpointResponse): ParsedTokenEndpointResponse {\n if (typeof response.access_token !== \"string\" || response.access_token === \"\") {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing access_token\",\n );\n }\n\n if (\n typeof response.expires_in !== \"number\" ||\n !Number.isFinite(response.expires_in) ||\n response.expires_in <= 0\n ) {\n throw new CustomerAccountOAuthError(\n \"invalid_token_response\",\n \"Customer Account OAuth response is missing expires_in\",\n );\n }\n\n return {\n access_token: response.access_token,\n refresh_token:\n typeof response.refresh_token === \"string\" && response.refresh_token !== \"\"\n ? response.refresh_token\n : undefined,\n id_token:\n typeof response.id_token === \"string\" && response.id_token !== \"\"\n ? response.id_token\n : undefined,\n expires_in: response.expires_in,\n };\n}\n\nfunction createTokensFromResponse(response: ParsedTokenEndpointResponse): CustomerAccountTokens {\n return {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n idToken: response.id_token,\n expiresAt:\n Date.now() + (response.expires_in - EXPIRY_BUFFER_IN_SECONDS) * MILLISECONDS_PER_SECOND,\n };\n}\n\nfunction validateIdTokenClaims(\n idToken: string,\n expected: { audience: string; issuer: string; nonce: string },\n): void {\n const claims = parseJwtPayload(idToken);\n if (claims.nonce !== expected.nonce) {\n throw new CustomerAccountOAuthError(\n \"nonce_mismatch\",\n \"OAuth id_token nonce does not match session nonce\",\n );\n }\n\n if (claims.iss !== expected.issuer) {\n throw new CustomerAccountOAuthError(\n \"issuer_mismatch\",\n \"OAuth id_token issuer does not match Customer Account issuer\",\n );\n }\n\n if (!hasAudienceClaim(claims.aud, expected.audience)) {\n throw new CustomerAccountOAuthError(\n \"audience_mismatch\",\n \"OAuth id_token audience does not match Customer Account client ID\",\n );\n }\n\n if (\n typeof claims.exp !== \"number\" ||\n claims.exp <= Math.floor(Date.now() / MILLISECONDS_PER_SECOND)\n ) {\n throw new CustomerAccountOAuthError(\"expired_id_token\", \"OAuth id_token is expired\");\n }\n}\n\nfunction parseJwtPayload(idToken: string): Record<string, unknown> {\n try {\n const [, payload] = idToken.split(\".\");\n if (!payload) throw new Error(\"Missing JWT payload\");\n\n const decodedPayload = JSON.parse(base64UrlDecode(payload));\n if (!isObjectRecord(decodedPayload)) throw new Error(\"JWT payload must be an object\");\n\n return decodedPayload;\n } catch (cause) {\n throw new CustomerAccountOAuthError(\n \"invalid_id_token\",\n \"Customer Account OAuth id_token is invalid\",\n { cause },\n );\n }\n}\n\nfunction hasAudienceClaim(audience: unknown, expectedAudience: string): boolean {\n if (audience === expectedAudience) return true;\n if (!Array.isArray(audience)) return false;\n return audience.includes(expectedAudience);\n}\n\nasync function readSessionData(\n sessionManager: ReadonlyCustomerSessionManager,\n): Promise<CustomerAccountSessionData> {\n const value = await sessionManager.getSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n return isCustomerAccountSessionData(value) ? value : {};\n}\n\nasync function writeSessionData(\n sessionManager: WritableCustomerSessionManager,\n sessionData: CustomerAccountSessionData,\n): Promise<void> {\n await sessionManager.setSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY, sessionData);\n}\n\nasync function writeTokens(\n sessionManager: WritableCustomerSessionManager,\n tokens: CustomerAccountTokens,\n): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n await writeSessionData(sessionManager, { ...sessionData, tokens });\n}\n\nasync function clearTokens(sessionManager: WritableCustomerSessionManager): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n const { pendingLogin } = sessionData;\n if (pendingLogin) {\n await writeSessionData(sessionManager, { pendingLogin });\n return;\n }\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n}\n\nasync function clearPendingLogin(sessionManager: WritableCustomerSessionManager): Promise<void> {\n const sessionData = await readSessionData(sessionManager);\n const { tokens } = sessionData;\n if (tokens) {\n await writeSessionData(sessionManager, { tokens });\n return;\n }\n\n await sessionManager.removeSessionItem(CUSTOMER_ACCOUNT_SESSION_KEY);\n}\n\nfunction getUsableAccessToken(sessionData: CustomerAccountSessionData): string | undefined {\n const tokens = sessionData.tokens;\n if (!isTokenUsable(tokens)) return undefined;\n return tokens.accessToken;\n}\n\nfunction hasCustomerSession(sessionData: CustomerAccountSessionData): boolean {\n return (\n getUsableAccessToken(sessionData) !== undefined || getRefreshToken(sessionData) !== undefined\n );\n}\n\nfunction getRefreshToken(sessionData: CustomerAccountSessionData): string | undefined {\n const refreshToken = sessionData.tokens?.refreshToken;\n return typeof refreshToken === \"string\" && refreshToken !== \"\" ? refreshToken : undefined;\n}\n\nfunction getPendingLogin(sessionData: CustomerAccountSessionData): Required<PendingLogin> {\n const pendingLogin = sessionData.pendingLogin;\n if (isPendingLoginReady(pendingLogin)) return pendingLogin;\n throw new CustomerAccountOAuthError(\n \"missing_pending_login\",\n \"OAuth callback has no pending login state\",\n );\n}\n\nfunction isTokenUsable(\n tokens: CustomerAccountSessionData[\"tokens\"],\n): tokens is Required<CustomerAccountTokens> {\n if (!tokens || typeof tokens.accessToken !== \"string\" || tokens.accessToken === \"\") return false;\n if (typeof tokens.expiresAt !== \"number\") return false;\n return tokens.expiresAt > Date.now();\n}\n\nfunction isPendingLoginReady(\n pendingLogin: PendingLogin | undefined,\n): pendingLogin is Required<PendingLogin> {\n if (!pendingLogin) return false;\n if (!isNonEmptyString(pendingLogin.state)) return false;\n if (!isNonEmptyString(pendingLogin.nonce)) return false;\n if (!isNonEmptyString(pendingLogin.codeVerifier)) return false;\n if (!isNonEmptyString(pendingLogin.returnTo)) return false;\n if (!isNonEmptyString(pendingLogin.origin)) return false;\n if (typeof pendingLogin.createdAt !== \"number\") return false;\n return Date.now() - pendingLogin.createdAt <= PENDING_LOGIN_TTL_IN_MS;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\nfunction isCustomerAccountSessionData(value: unknown): value is CustomerAccountSessionData {\n if (!isObjectRecord(value) || Array.isArray(value)) return false;\n const tokens = value.tokens;\n const pendingLogin = value.pendingLogin;\n if (tokens !== undefined && (!isObjectRecord(tokens) || Array.isArray(tokens))) return false;\n return (\n pendingLogin === undefined || (isObjectRecord(pendingLogin) && !Array.isArray(pendingLogin))\n );\n}\n\nfunction setOptionalLoginParams(loginUrl: URL, options: PrepareLoginUrlOptions): void {\n if (options.locale) loginUrl.searchParams.set(\"locale\", options.locale);\n if (options.countryCode) loginUrl.searchParams.set(\"region_country\", options.countryCode);\n if (options.acrValues) loginUrl.searchParams.set(\"acr_values\", options.acrValues);\n if (!options.loginHint) return;\n\n loginUrl.searchParams.set(\"login_hint\", options.loginHint);\n if (options.loginHintMode) loginUrl.searchParams.set(\"login_hint_mode\", options.loginHintMode);\n}\n\nfunction sanitizeReturnTo(\n returnTo: string | null | undefined,\n origin: string,\n fallbackReturnTo = DEFAULT_LOGIN_RETURN_TO_PATH,\n): string {\n const path = getSameOriginPath(returnTo, origin);\n if (!path || new TextEncoder().encode(path).byteLength > MAX_RETURN_TO_LENGTH_IN_BYTES) {\n return fallbackReturnTo;\n }\n return path;\n}\n\nfunction absoluteSameOriginUrl(url: string, origin: string): string {\n const parsedUrl = new URL(url, origin);\n if (parsedUrl.origin !== origin) return origin;\n return parsedUrl.toString();\n}\n\nasync function createCodeChallenge(codeVerifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(codeVerifier));\n return base64UrlEncode(String.fromCharCode(...new Uint8Array(digest)));\n}\n\nfunction generateRandomBase64Url(): string {\n const bytes = new Uint8Array(RANDOM_BYTES_LENGTH);\n crypto.getRandomValues(bytes);\n return base64UrlEncode(String.fromCharCode(...bytes));\n}\n\nfunction base64UrlEncode(value: string): string {\n return btoa(value).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n\nfunction base64UrlDecode(value: string): string {\n const base64 = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const paddingLength = (4 - (base64.length % 4)) % 4;\n return atob(base64.padEnd(base64.length + paddingLength, \"=\"));\n}\n\ntype CustomerAccountEndpoints = {\n authorizeUrl: string;\n tokenUrl: string;\n logoutUrl: string;\n issuer: string;\n};\n\nfunction createCustomerAccountEndpoints(\n shopId: string,\n customerAccountApiUrl: string | undefined,\n): CustomerAccountEndpoints {\n const authBaseUrl = normalizeAuthBaseUrl(\n customerAccountApiUrl ?? `https://shopify.com/authentication/${shopId}`,\n );\n return {\n authorizeUrl: `${authBaseUrl}/oauth/authorize`,\n tokenUrl: `${authBaseUrl}/oauth/token`,\n logoutUrl: `${authBaseUrl}/logout`,\n issuer: authBaseUrl,\n };\n}\n\nfunction normalizeAuthBaseUrl(customerAccountApiUrl: string): string {\n const url = new URL(customerAccountApiUrl);\n if (url.protocol !== \"https:\") {\n throw new Error(\"customerAccountApiUrl must use HTTPS\");\n }\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction getOriginFromRequest(request: Request): string {\n return normalizeOrigin(new URL(request.url).origin);\n}\n\nfunction normalizeOrigin(origin: string): string {\n const url = new URL(origin);\n if (url.protocol === \"https:\") return url.origin;\n throw new Error(\n \"Customer Account OAuth origin must use HTTPS. Use a public HTTPS tunnel for local Customer Account login.\",\n );\n}\n\nfunction cancelResponseBody(response: Response): void {\n try {\n void response.body?.cancel().catch(() => undefined);\n } catch {}\n}\n\nfunction validateShopId(shopId: string): void {\n if (!SHOP_ID_RE.test(shopId)) {\n throw new Error(\"shopId must be a numeric Shopify shop ID string\");\n }\n}\n\nfunction validateCustomerAccountApiClientId(customerAccountApiClientId: string): void {\n if (typeof customerAccountApiClientId !== \"string\" || customerAccountApiClientId.trim() === \"\") {\n throw new Error(\"customerAccountApiClientId is required\");\n }\n}\n\nfunction validateTimeout(timeoutInMs: number): void {\n if (\n !Number.isSafeInteger(timeoutInMs) ||\n timeoutInMs <= 0 ||\n timeoutInMs > MAX_SET_TIMEOUT_IN_MS\n ) {\n throw new Error(\n `defaultTimeoutInMs must be a positive safe integer no greater than ${MAX_SET_TIMEOUT_IN_MS}`,\n );\n }\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"],"mappings":";;;;;;;;AAoBA,MAAM,MAAM,UAAU,mBAAmB;;;;;;AAOzC,MAAa,kCAAkC,uBAAuB;;;;;;AAMtE,MAAa,8BAA8B,uBAAuB;;;;;;AAMlE,MAAa,+BAA+B,uBAAuB;;;;;;AAMnE,MAAa,gCAAgC,uBAAuB;AAEpE,MAAM,+BAA+B;AACrC,MAAM,+BAA+B;AACrC,MAAM,uCAAuC;AAC7C,MAAM,mCAAmC;AACzC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,yBAAyB;AAC/B,MAAM,gCAAgC;AACtC,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,wBAAwB;AAC9B,MAAM,2BAA2B;AACjC,MAAM,+BAA+B;AACrC,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAChC,MAAM,0BACJ,+BAA+B,qBAAqB;AACtD,MAAM,sBAAsB;AAC5B,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAC9B,MAAM,aAAa;AACnB,MAAM,uDAAuD;AAC7D,MAAM,mDAAmD;AACzD,MAA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,IAAI,MACR,sEAAsE,wBACvE;;AAIL,SAAS,eAAe,OAAkD;AACxE,QAAO,OAAO,UAAU,YAAY,UAAU"}
@@ -1,7 +1,7 @@
1
1
  import { normalizeStoreDomain } from "../core/url.mjs";
2
2
  import { getHydrogenCacheStatus } from "../core/cache/cache-status.mjs";
3
3
  import { createFetchWithCache } from "../core/cache/fetch-with-cache.mjs";
4
- import { DEFAULT_TIMEOUT_IN_MS, STOREFRONT_API_VERSION } from "../core/constants.mjs";
4
+ import { DEFAULT_TIMEOUT_IN_MS, HYDROGEN_USER_AGENT, STOREFRONT_API_VERSION } from "../core/constants.mjs";
5
5
  import { HYDROGEN_VERSION_HEADER, REQUEST_GROUP_ID_HEADER, SDK_VARIANT_HEADER, SDK_VARIANT_SOURCE_HEADER, SDK_VERSION_HEADER, SHOPIFY_STOREFRONT_S_HEADER, SHOPIFY_STOREFRONT_Y_HEADER, SHOPIFY_UNIQUE_TOKEN_HEADER, SHOPIFY_VISIT_TOKEN_HEADER, STOREFRONT_ACCESS_TOKEN_HEADER, STOREFRONT_BUYER_IP_HEADER, STOREFRONT_ID_HEADER, STOREFRONT_PRIVATE_TOKEN_HEADER } from "../core/headers.mjs";
6
6
  import { StorefrontApiError, StorefrontTimeoutError } from "./errors.mjs";
7
7
  import { getI18nVariableNames } from "./i18n-variables.mjs";
@@ -26,8 +26,17 @@ const REQUEST_IDENTITY_HEADERS = new Set([
26
26
  SHOPIFY_STOREFRONT_Y_HEADER.toLowerCase(),
27
27
  SHOPIFY_STOREFRONT_S_HEADER.toLowerCase()
28
28
  ]);
29
+ const REDIRECT_STATUSES = new Set([
30
+ 301,
31
+ 302,
32
+ 303,
33
+ 307,
34
+ 308
35
+ ]);
29
36
  const CACHE_ENABLED_GRAPHQL_CLIENTS = /* @__PURE__ */ new WeakSet();
30
37
  const SHOULD_CACHE_RESULT = Symbol();
38
+ const PRIVATE_RESPONSE_DIRECTIVES = new Set(["private", "no-store"]);
39
+ const STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON = "storefront-api-private-response";
31
40
  var StorefrontCacheConfigError = class extends Error {};
32
41
  function withStorefrontClientCache(client, options, strategy, shouldCacheResult) {
33
42
  if (!CACHE_ENABLED_GRAPHQL_CLIENTS.has(client.graphql)) return options;
@@ -56,6 +65,7 @@ function createStorefrontClient(args) {
56
65
  const timeoutInMs = config.defaultTimeoutInMs ?? 3e4;
57
66
  if (timeoutInMs < 0 || Number.isNaN(timeoutInMs)) throw new Error("defaultTimeoutInMs must be a non-negative number");
58
67
  const staticHeaders = { "content-type": "application/json" };
68
+ if (typeof document === "undefined") staticHeaders["user-agent"] = HYDROGEN_USER_AGENT;
59
69
  if (config.storefrontId) staticHeaders[STOREFRONT_ID_HEADER] = config.storefrontId;
60
70
  switch (clientType) {
61
71
  case "private":
@@ -70,7 +80,7 @@ function createStorefrontClient(args) {
70
80
  break;
71
81
  default: throw new Error(`Unsupported client type: ${clientType}`);
72
82
  }
73
- const i18n = requestContext.i18n;
83
+ const locale = requestContext.locale;
74
84
  const requestHeaders = new Headers(staticHeaders);
75
85
  requestContext.applyStorefrontRequestHeaders(requestHeaders);
76
86
  if (clientType === "private") {
@@ -84,7 +94,7 @@ function createStorefrontClient(args) {
84
94
  if (typeof queryText !== "string") throw new StorefrontApiError("Expected gql() to return a string at runtime. Check gql.tada version compatibility.");
85
95
  if (opts.cache && !config.cache) throw new StorefrontCacheConfigError("Storefront API cache options require a cache configured in createStorefrontClient().");
86
96
  if (opts.cache?.mode === "private") throw new StorefrontCacheConfigError("Storefront API cache mode 'private' is not supported yet. Use Cache() without private mode, or cache buyer-specific work with createRunWithCache() and an explicit private key.");
87
- const variables = buildVariables(queryText, opts.variables, i18n);
97
+ const variables = buildVariables(queryText, opts.variables, locale);
88
98
  const externalSignals = [requestContext.signal, opts.signal].filter((signal) => Boolean(signal));
89
99
  const earlyAbortSignal = externalSignals.find((signal) => signal.aborted);
90
100
  if (earlyAbortSignal) throw earlyAbortSignal.reason ?? new DOMException("signal is aborted without reason", "AbortError");
@@ -105,13 +115,26 @@ function createStorefrontClient(args) {
105
115
  query: queryText,
106
116
  variables
107
117
  }),
118
+ redirect: "manual",
108
119
  signal: externalSignals.length > 0 ? AbortSignal.any(externalSignals) : void 0
109
120
  };
110
121
  const response = await resolvedFetch(apiUrl, init, createStorefrontCacheOptions(apiUrl, init, queryText, opts.cache, opts[SHOULD_CACHE_RESULT], timeoutInMs > 0 ? timeoutInMs : DEFAULT_TIMEOUT_IN_MS));
111
122
  responseHeaders = response.headers;
112
- if (getHydrogenCacheStatus(responseHeaders) !== "hit") requestContext.captureSubrequestHeaders(responseHeaders);
113
123
  requestId = responseHeaders.get("x-request-id") ?? void 0;
114
124
  status = response.status;
125
+ const isOpaqueRedirect = response.type === "opaqueredirect";
126
+ if (isOpaqueRedirect || REDIRECT_STATUSES.has(status)) {
127
+ response.body?.cancel().catch(() => {});
128
+ const locationOrigin = getLocationOrigin(responseHeaders.get("location"), apiUrl);
129
+ throw new StorefrontApiError(isOpaqueRedirect ? "SFAPI responded with a redirect; redirects are not followed" : `SFAPI responded with a redirect (${status}${locationOrigin ? ` to ${locationOrigin}` : ""}); redirects are not followed`, {
130
+ status: isOpaqueRedirect ? void 0 : status,
131
+ requestId,
132
+ queryText,
133
+ variables
134
+ });
135
+ }
136
+ if (getHydrogenCacheStatus(responseHeaders) !== "hit") requestContext.captureSubrequestHeaders(responseHeaders);
137
+ if (isPrivateResponse(responseHeaders)) requestContext.markResponseAsPersonalized(STOREFRONT_PRIVATE_RESPONSE_PERSONALIZATION_REASON);
115
138
  if (!response.ok) {
116
139
  const bodyHint = await response.text().catch(() => "");
117
140
  throw new StorefrontApiError(`SFAPI responded with ${status}${bodyHint ? `: ${bodyHint.slice(0, 200)}` : ""}`, {
@@ -161,7 +184,8 @@ function createStorefrontClient(args) {
161
184
  }
162
185
  const client = {
163
186
  type: clientType,
164
- i18n,
187
+ i18n: locale,
188
+ locale,
165
189
  graphql,
166
190
  apiUrl,
167
191
  storeUrl,
@@ -171,9 +195,17 @@ function createStorefrontClient(args) {
171
195
  if (config.cache) CACHE_ENABLED_GRAPHQL_CLIENTS.add(client.graphql);
172
196
  return client;
173
197
  }
174
- function buildVariables(queryText, userVariables, resolvedI18n) {
198
+ function getLocationOrigin(location, baseUrl) {
199
+ if (!location) return void 0;
200
+ try {
201
+ return new URL(location, baseUrl).origin;
202
+ } catch {
203
+ return;
204
+ }
205
+ }
206
+ function buildVariables(queryText, userVariables, locale) {
175
207
  const variables = { ...userVariables };
176
- for (const name of getI18nVariableNames(queryText)) variables[name] = resolvedI18n[name];
208
+ for (const name of getI18nVariableNames(queryText)) variables[name] = locale[name];
177
209
  return variables;
178
210
  }
179
211
  function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldCacheResult, backgroundTimeoutInMs) {
@@ -182,8 +214,8 @@ function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldC
182
214
  return {
183
215
  key: createStorefrontCacheKey(apiUrl, init),
184
216
  strategy,
185
- shouldCacheResponse: async ({ json }) => {
186
- if (!json) return false;
217
+ shouldCacheResponse: async ({ headers, json }) => {
218
+ if (!json || isPrivateResponse(headers)) return false;
187
219
  const body = await json().catch(() => void 0);
188
220
  if (typeof body !== "object" || body == null || Array.isArray(body) || "errors" in body) return false;
189
221
  return shouldCacheResult?.(body) ?? true;
@@ -191,6 +223,9 @@ function createStorefrontCacheOptions(apiUrl, init, queryText, strategy, shouldC
191
223
  backgroundSignal: () => AbortSignal.timeout(backgroundTimeoutInMs)
192
224
  };
193
225
  }
226
+ function isPrivateResponse(headers) {
227
+ return headers.get("cache-control")?.split(",").some((directive) => PRIVATE_RESPONSE_DIRECTIVES.has(directive.split("=")[0]?.trim().toLowerCase() ?? "")) ?? false;
228
+ }
194
229
  function createStorefrontCacheKey(apiUrl, init) {
195
230
  return [
196
231
  "storefront-api",