hydrogen-sfdgspsdmq-test1 0.0.1-security → 2024.1.12

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of hydrogen-sfdgspsdmq-test1 might be problematic. Click here for more details.

@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/seo/log-seo-tags.ts","../../src/storefront.ts","../../src/utils/hash.ts","../../src/cache/strategies.ts","../../src/utils/parse-json.ts","../../src/cache/api.ts","../../src/cache/sub-request.ts","../../src/cache/fetch.ts","../../src/constants.ts","../../src/utils/uuid.ts","../../src/utils/warning.ts","../../src/version.ts","../../src/utils/graphql.ts","../../src/utils/callsites.ts","../../src/utils/request.ts","../../src/with-cache.ts","../../src/cache/in-memory.ts","../../src/utils/get-redirect-url.ts","../../src/routing/redirect.ts","../../src/routing/graphiql.ts","../../src/seo/seo.ts","../../src/seo/escape.ts","../../src/seo/generate-seo-tags.ts","../../src/pagination/Pagination.ts","../../src/customer/constants.ts","../../src/customer/BadRequest.ts","../../src/customer/auth.helpers.ts","../../src/csp/nonce.ts","../../src/customer/customer.ts","../../src/changelogHandler.ts","../../src/cart/CartForm.tsx","../../src/cart/queries/cart-fragments.ts","../../src/cart/queries/cartCreateDefault.ts","../../src/cart/queries/cartGetDefault.ts","../../src/cart/queries/cartLinesAddDefault.ts","../../src/cart/queries/cartLinesUpdateDefault.ts","../../src/cart/queries/cartLinesRemoveDefault.ts","../../src/cart/queries/cartDiscountCodesUpdateDefault.ts","../../src/cart/queries/cartBuyerIdentityUpdateDefault.ts","../../src/cart/queries/cartNoteUpdateDefault.ts","../../src/cart/queries/cartSelectedDeliveryOptionsUpdateDefault.ts","../../src/cart/queries/cartAttributesUpdateDefault.ts","../../src/cart/queries/cartMetafieldsSetDefault.ts","../../src/cart/queries/cartMetafieldDeleteDefault.ts","../../../../node_modules/worktop/cookie/index.mjs","../../src/cart/cartGetIdDefault.ts","../../src/cart/cartSetIdDefault.ts","../../src/cart/createCartHandler.ts","../../src/product/VariantSelector.ts","../../src/csp/csp.ts","../../src/csp/Script.tsx","../../src/optimistic-ui/optimistic-ui.tsx","../../src/shop/ShopPayButton.tsx","../../src/index.ts"],"names":["isStale","logSubRequestEvent","result","errors","options","graphiqlLoader","schema","html","loggerMarkup","createElement","useMemo","useLocation","NextLink","params","refreshToken","flattenConnection","Fragment","option","variant","forwardRef","jsx","jsxs","getShopifyCookies"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEe,SAAR,OAAwB,EAAC,SAAQ,GAAsC;AAC5E,aAAW,QAAQ;AAEnB,SAAO;AACT;AAMO,SAAS,WAAW,UAAiC;AAC1D,UAAQ,IAAI,GAAG;AACf,UAAQ,IAAI,mBAAmB,GAAG,UAAU,EAAE;AAC9C,UAAQ,IAAI,GAAG;AAEf,WAAS,QAAQ,CAAC,QAAQ;AACxB,QAAI,IAAI,QAAQ,UAAU;AACxB,cAAQ,IAAI,qBAAgB,YAAY;AAExC,UAAI,IAAI,UAAU;AAChB,YAAI;AACF,kBAAQ,MAAM,KAAK,MAAM,IAAI,QAAQ,GAAG,CAAC,QAAQ,SAAS,CAAC;AAAA,QAC7D,QAAQ;AACN,kBAAQ,IAAI,IAAI,QAAQ;AAAA,QAC1B;AAAA,MACF;AAAA,IACF,OAAO;AACL,cAAQ,IAAI,YAAO,IAAI,GAAG,KAAK,YAAY;AAE3C,UAAI,IAAI,UAAU;AAChB,YAAI,OAAO,IAAI,aAAa,UAAU;AACpC,kBAAQ,IAAI,UAAK,IAAI,QAAQ,EAAE;AAAA,QACjC,OAAO;AACL,cAAI;AACF,mBAAO,QAAQ,KAAK,MAAM,IAAI,QAAQ,CAAC,EAAE;AAAA,cAAI,CAAC,CAAC,KAAK,GAAG,MACrD,QAAQ,IAAI,UAAK,GAAG,EAAE;AAAA,YACxB;AAAA,UACF,QAAQ;AACN,oBAAQ,IAAI,IAAI,QAAQ;AAAA,UAC1B;AAAA,QACF;AAAA,MACF;AAEA,UAAI,IAAI,MAAM,aAAa,gBAAgB;AACzC,cAAM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AA;AAAA,QACC,MAAK;AAAA,QACL,MAAK;AAAA,QACL,OAAO,KAAK,UAAU,IAAI;AAAA;AAAA,IAC5B;AAAA,KACF;AAEJ;;;AC/CA,SAAQ,iBAAiB,yBAAwB;AAIxC,gBAAAA,YAAA;AADF,SAAS,cAAc,OAAiD;AAC7E,SAAO,gBAAAA,KAAC,qBAAkB,SAAQ,YAAY,GAAG,OAAO;AAC1D;;;ACyEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAL;AAAA,EACA;AAAA,EACA,qBAAAO;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK","sourcesContent":["import type {CustomHeadTagObject} from './generate-seo-tags';\n\nexport default function Logger({headTags}: {headTags: CustomHeadTagObject[]}) {\n logSeoTags(headTags);\n\n return null;\n}\n\nconst headingStyle = 'text-transform: uppercase;';\nconst titleStyle =\n 'text-transform: uppercase; font-weight: bold; text-transform: uppercase;font-weight: bold';\n\nexport function logSeoTags(headTags: CustomHeadTagObject[]) {\n console.log(' ');\n console.log('%cSEO Meta Tags', `${titleStyle}`);\n console.log(' ');\n\n headTags.forEach((tag) => {\n if (tag.tag === 'script') {\n console.log(`%c• JSON LD `, headingStyle);\n\n if (tag.children) {\n try {\n console.table(JSON.parse(tag.children), ['name', 'content']);\n } catch {\n console.log(tag.children);\n }\n }\n } else {\n console.log(`%c• ${tag.tag} `, headingStyle);\n\n if (tag.children) {\n if (typeof tag.children === 'string') {\n console.log(`↳ ${tag.children}`);\n } else {\n try {\n Object.entries(JSON.parse(tag.children)).map(([key, val]) =>\n console.log(`↳ ${val}`),\n );\n } catch {\n console.log(tag.children);\n }\n }\n }\n\n if (tag.props.property === 'og:image:url') {\n const urlKey = tag.props.content as string;\n\n fetchImage(urlKey)\n .then((image) => {\n const imageStyle = `font-size: 400px; padding: 10px; background: white url(${image}) no-repeat center; background-size: contain;`;\n\n console.log(`%c• Share image preview`, headingStyle);\n console.log('%c ', imageStyle);\n console.log(`↳ ${urlKey}`);\n })\n .catch((err) => {\n console.error(err);\n });\n }\n\n Object.entries(tag.props).map(([key, val]) => {\n console.log(`↳ ${key} → ${val}`);\n });\n }\n console.log(' ');\n });\n}\n\nasync function fetchImage(url: string) {\n const result = await fetch(url);\n const data = await result.blob();\n const buff = await data.arrayBuffer();\n const base64String = arrayBufferToBase64(buff);\n\n return `data:image/png;base64,${base64String}`;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n\n for (let index = 0; index < len; index++) {\n binary += String.fromCharCode(bytes[index]);\n }\n\n return btoa(binary);\n}\n","import {\n createStorefrontClient as createStorefrontUtilities,\n getShopifyCookies,\n SHOPIFY_S,\n SHOPIFY_Y,\n SHOPIFY_STOREFRONT_ID_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n type StorefrontClientProps,\n} from '@shopify/hydrogen-react';\nimport type {WritableDeep} from 'type-fest';\nimport {fetchWithServerCache, checkGraphQLErrors} from './cache/fetch';\nimport {\n SDK_VARIANT_HEADER,\n SDK_VARIANT_SOURCE_HEADER,\n SDK_VERSION_HEADER,\n STOREFRONT_ACCESS_TOKEN_HEADER,\n STOREFRONT_REQUEST_GROUP_ID_HEADER,\n} from './constants';\nimport {\n CacheNone,\n CacheLong,\n CacheShort,\n CacheDefault,\n CacheCustom,\n generateCacheControlHeader,\n type CachingStrategy,\n} from './cache/strategies';\nimport {generateUUID} from './utils/uuid';\nimport {parseJSON} from './utils/parse-json';\nimport {\n CountryCode,\n LanguageCode,\n} from '@shopify/hydrogen-react/storefront-api-types';\nimport type {\n ClientReturn,\n ClientVariablesInRestParams,\n GenericVariables,\n} from '@shopify/hydrogen-codegen';\nimport {warnOnce} from './utils/warning';\nimport {LIB_VERSION} from './version';\nimport {\n minifyQuery,\n assertQuery,\n assertMutation,\n throwErrorWithGqlLink,\n GraphQLError,\n type GraphQLApiResponse,\n type GraphQLErrorOptions,\n} from './utils/graphql';\nimport {\n getCallerStackLine,\n withSyncStack,\n type StackInfo,\n} from './utils/callsites';\n\nexport type I18nBase = {\n language: LanguageCode;\n country: CountryCode;\n};\n\n// When passing GraphQLError through Remix' `json` or `defer`,\n// the class instance is lost and it becomes a plain JSON object.\n// Therefore, we need make TS think this is a plain object instead of\n// a class to make it work in server and client.\n// Also, Remix' `Jsonify` type is broken and can't infer types of classes properly.\ntype JsonGraphQLError = ReturnType<GraphQLError['toJSON']>; // Equivalent to `Jsonify<GraphQLError>[]`\nexport type StorefrontApiErrors = JsonGraphQLError[] | undefined;\n\ntype StorefrontError = {\n errors?: StorefrontApiErrors;\n};\n\n/**\n * Wraps all the returned utilities from `createStorefrontClient`.\n */\nexport type StorefrontClient<TI18n extends I18nBase> = {\n storefront: Storefront<TI18n>;\n};\n\n/**\n * Maps all the queries found in the project to variables and return types.\n */\nexport interface StorefrontQueries {\n // Example of how a generated query type looks like:\n // '#graphql query q1 {...}': {return: Q1Query; variables: Q1QueryVariables};\n}\n\n/**\n * Maps all the mutations found in the project to variables and return types.\n */\nexport interface StorefrontMutations {\n // Example of how a generated mutation type looks like:\n // '#graphql mutation m1 {...}': {return: M1Mutation; variables: M1MutationVariables};\n}\n\n// These are the variables that are automatically added to the storefront API.\n// We use this type to make parameters optional in storefront client\n// when these are the only variables that can be passed.\ntype AutoAddedVariableNames = 'country' | 'language';\n\ntype StorefrontCommonExtraParams = {\n headers?: HeadersInit;\n storefrontApiVersion?: string;\n displayName?: string;\n};\n\n/**\n * Interface to interact with the Storefront API.\n */\nexport type Storefront<TI18n extends I18nBase = I18nBase> = {\n query: <\n OverrideReturnType extends any = never,\n RawGqlString extends string = string,\n >(\n query: RawGqlString,\n ...options: ClientVariablesInRestParams<\n StorefrontQueries,\n RawGqlString,\n StorefrontCommonExtraParams & Pick<StorefrontQueryOptions, 'cache'>,\n AutoAddedVariableNames\n >\n ) => Promise<\n ClientReturn<StorefrontQueries, RawGqlString, OverrideReturnType> &\n StorefrontError\n >;\n mutate: <\n OverrideReturnType extends any = never,\n RawGqlString extends string = string,\n >(\n mutation: RawGqlString,\n ...options: ClientVariablesInRestParams<\n StorefrontMutations,\n RawGqlString,\n StorefrontCommonExtraParams,\n AutoAddedVariableNames\n >\n ) => Promise<\n ClientReturn<StorefrontMutations, RawGqlString, OverrideReturnType> &\n StorefrontError\n >;\n cache?: Cache;\n CacheNone: typeof CacheNone;\n CacheLong: typeof CacheLong;\n CacheShort: typeof CacheShort;\n CacheCustom: typeof CacheCustom;\n generateCacheControlHeader: typeof generateCacheControlHeader;\n getPublicTokenHeaders: ReturnType<\n typeof createStorefrontUtilities\n >['getPublicTokenHeaders'];\n getPrivateTokenHeaders: ReturnType<\n typeof createStorefrontUtilities\n >['getPrivateTokenHeaders'];\n getShopifyDomain: ReturnType<\n typeof createStorefrontUtilities\n >['getShopifyDomain'];\n getApiUrl: ReturnType<\n typeof createStorefrontUtilities\n >['getStorefrontApiUrl'];\n isApiError: (error: any) => boolean;\n i18n: TI18n;\n};\n\ntype HydrogenClientProps<TI18n> = {\n /** Storefront API headers. If on Oxygen, use `getStorefrontHeaders()` */\n storefrontHeaders?: StorefrontHeaders;\n /** An instance that implements the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) */\n cache?: Cache;\n /** The globally unique identifier for the Shop */\n storefrontId?: string;\n /** The `waitUntil` function is used to keep the current request/response lifecycle alive even after a response has been sent. It should be provided by your platform. */\n waitUntil?: ExecutionContext['waitUntil'];\n /** An object containing a country code and language code */\n i18n?: TI18n;\n /** Whether it should print GraphQL errors automatically. Defaults to true */\n logErrors?: boolean | ((error?: Error) => boolean);\n};\n\nexport type CreateStorefrontClientOptions<TI18n extends I18nBase> =\n HydrogenClientProps<TI18n> & StorefrontClientProps;\n\ntype StorefrontHeaders = {\n /** A unique ID that correlates all sub-requests together. */\n requestGroupId: string | null;\n /** The IP address of the client. */\n buyerIp: string | null;\n /** The cookie header from the client */\n cookie: string | null;\n /** The purpose header value for debugging */\n purpose: string | null;\n};\n\ntype StorefrontQueryOptions = StorefrontCommonExtraParams & {\n query: string;\n mutation?: never;\n cache?: CachingStrategy;\n};\n\ntype StorefrontMutationOptions = StorefrontCommonExtraParams & {\n query?: never;\n mutation: string;\n cache?: never;\n};\n\nconst defaultI18n: I18nBase = {language: 'EN', country: 'US'};\n\n/**\n * This function extends `createStorefrontClient` from [Hydrogen React](/docs/api/hydrogen-react/2024-01/utilities/createstorefrontclient). The additional arguments enable internationalization (i18n), caching, and other features particular to Remix and Oxygen.\n *\n * Learn more about [data fetching in Hydrogen](/docs/custom-storefronts/hydrogen/data-fetching/fetch-data).\n */\nexport function createStorefrontClient<TI18n extends I18nBase>(\n options: CreateStorefrontClientOptions<TI18n>,\n): StorefrontClient<TI18n> {\n const {\n storefrontHeaders,\n cache,\n waitUntil,\n i18n,\n storefrontId,\n logErrors = true,\n ...clientOptions\n } = options;\n const H2_PREFIX_WARN = '[h2:warn:createStorefrontClient] ';\n\n if (process.env.NODE_ENV === 'development' && !cache) {\n warnOnce(\n H2_PREFIX_WARN +\n 'Storefront API client created without a cache instance. This may slow down your sub-requests.',\n );\n }\n\n const {\n getPublicTokenHeaders,\n getPrivateTokenHeaders,\n getStorefrontApiUrl,\n getShopifyDomain,\n } = createStorefrontUtilities(clientOptions);\n\n const getHeaders = clientOptions.privateStorefrontToken\n ? getPrivateTokenHeaders\n : getPublicTokenHeaders;\n\n const defaultHeaders = getHeaders({\n contentType: 'json',\n buyerIp: storefrontHeaders?.buyerIp || '',\n });\n\n defaultHeaders[STOREFRONT_REQUEST_GROUP_ID_HEADER] =\n storefrontHeaders?.requestGroupId || generateUUID();\n\n if (storefrontId) defaultHeaders[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId;\n if (LIB_VERSION) defaultHeaders['user-agent'] = `Hydrogen ${LIB_VERSION}`;\n\n if (storefrontHeaders && storefrontHeaders.cookie) {\n const cookies = getShopifyCookies(storefrontHeaders.cookie ?? '');\n\n if (cookies[SHOPIFY_Y])\n defaultHeaders[SHOPIFY_STOREFRONT_Y_HEADER] = cookies[SHOPIFY_Y];\n if (cookies[SHOPIFY_S])\n defaultHeaders[SHOPIFY_STOREFRONT_S_HEADER] = cookies[SHOPIFY_S];\n }\n\n // Remove any headers that are identifiable to the user or request\n const cacheKeyHeader = JSON.stringify({\n 'content-type': defaultHeaders['content-type'],\n 'user-agent': defaultHeaders['user-agent'],\n [SDK_VARIANT_HEADER]: defaultHeaders[SDK_VARIANT_HEADER],\n [SDK_VARIANT_SOURCE_HEADER]: defaultHeaders[SDK_VARIANT_SOURCE_HEADER],\n [SDK_VERSION_HEADER]: defaultHeaders[SDK_VERSION_HEADER],\n [STOREFRONT_ACCESS_TOKEN_HEADER]:\n defaultHeaders[STOREFRONT_ACCESS_TOKEN_HEADER],\n });\n\n async function fetchStorefrontApi<T = any>({\n query,\n mutation,\n variables,\n cache: cacheOptions,\n headers = [],\n storefrontApiVersion,\n displayName,\n stackInfo,\n }: {variables?: GenericVariables; stackInfo?: StackInfo} & (\n | StorefrontQueryOptions\n | StorefrontMutationOptions\n )): Promise<T & StorefrontError> {\n const userHeaders =\n headers instanceof Headers\n ? Object.fromEntries(headers.entries())\n : Array.isArray(headers)\n ? Object.fromEntries(headers)\n : headers;\n\n query = query ?? mutation;\n\n const queryVariables = {...variables};\n\n if (i18n) {\n if (!variables?.country && /\\$country/.test(query)) {\n queryVariables.country = i18n.country;\n }\n\n if (!variables?.language && /\\$language/.test(query)) {\n queryVariables.language = i18n.language;\n }\n }\n\n const url = getStorefrontApiUrl({storefrontApiVersion});\n const graphqlData = JSON.stringify({query, variables: queryVariables});\n const requestInit = {\n method: 'POST',\n headers: {...defaultHeaders, ...userHeaders},\n body: graphqlData,\n } satisfies RequestInit;\n\n const cacheKey = [\n url,\n requestInit.method,\n cacheKeyHeader,\n requestInit.body,\n ];\n\n const [body, response] = await fetchWithServerCache(url, requestInit, {\n cacheInstance: mutation ? undefined : cache,\n cache: cacheOptions || CacheDefault(),\n cacheKey,\n shouldCacheResponse: checkGraphQLErrors,\n waitUntil,\n debugInfo: {\n url,\n graphql: graphqlData,\n requestId: requestInit.headers[STOREFRONT_REQUEST_GROUP_ID_HEADER],\n purpose: storefrontHeaders?.purpose,\n stackInfo,\n displayName,\n },\n });\n\n const errorOptions: GraphQLErrorOptions<T> = {\n url,\n response,\n type: mutation ? 'mutation' : 'query',\n query,\n queryVariables,\n errors: undefined,\n };\n\n if (!response.ok) {\n /**\n * The Storefront API might return a string error, or a JSON-formatted {error: string}.\n * We try both and conform them to a single {errors} format.\n */\n let errors;\n try {\n errors = parseJSON(body);\n } catch (_e) {\n errors = [{message: body}];\n }\n\n throwErrorWithGqlLink({...errorOptions, errors});\n }\n\n const {data, errors} = body as GraphQLApiResponse<T>;\n\n const gqlErrors = errors?.map(\n ({message, ...rest}) =>\n new GraphQLError(message, {\n ...(rest as WritableDeep<typeof rest>),\n clientOperation: `storefront.${errorOptions.type}`,\n requestId: response.headers.get('x-request-id'),\n queryVariables,\n query,\n }),\n );\n\n return formatAPIResult(data, gqlErrors);\n }\n\n return {\n storefront: {\n /**\n * Sends a GraphQL query to the Storefront API.\n *\n * Example:\n *\n * ```js\n * async function loader ({context: {storefront}}) {\n * const data = await storefront.query('query { ... }', {\n * variables: {},\n * cache: storefront.CacheLong()\n * });\n * }\n * ```\n */\n query(query, options?) {\n query = minifyQuery(query);\n assertQuery(query, 'storefront.query');\n\n const stackOffset = getStackOffset?.(query);\n\n return withSyncStack(\n fetchStorefrontApi({\n ...options,\n query,\n stackInfo: getCallerStackLine?.(stackOffset),\n }),\n {stackOffset, logErrors},\n );\n },\n /**\n * Sends a GraphQL mutation to the Storefront API.\n *\n * Example:\n *\n * ```js\n * async function loader ({context: {storefront}}) {\n * await storefront.mutate('mutation { ... }', {\n * variables: {},\n * });\n * }\n * ```\n */\n mutate(mutation, options?) {\n mutation = minifyQuery(mutation);\n assertMutation(mutation, 'storefront.mutate');\n\n const stackOffset = getStackOffset?.(mutation);\n\n return withSyncStack(\n fetchStorefrontApi({\n ...options,\n mutation,\n stackInfo: getCallerStackLine?.(stackOffset),\n }),\n {stackOffset, logErrors},\n );\n },\n cache,\n CacheNone,\n CacheLong,\n CacheShort,\n CacheCustom,\n generateCacheControlHeader,\n getPublicTokenHeaders,\n getPrivateTokenHeaders,\n getShopifyDomain,\n getApiUrl: getStorefrontApiUrl,\n /**\n * @deprecated\n * Wether it's a GraphQL error returned in the Storefront API response.\n *\n * Example:\n *\n * ```js\n * async function loader ({context: {storefront}}) {\n * try {\n * await storefront.query(...);\n * } catch(error) {\n * if (storefront.isApiError(error)) {\n * // ...\n * }\n *\n * throw error;\n * }\n * }\n * ```\n */\n isApiError: (error: any) => {\n if (process.env.NODE_ENV === 'development') {\n warnOnce(\n '`isApiError` is deprecated. An `errors` object would be returned from the API if there is an error.',\n );\n }\n return false;\n },\n i18n: (i18n ?? defaultI18n) as TI18n,\n },\n };\n}\n\nconst getStackOffset =\n process.env.NODE_ENV === 'development'\n ? (query: string) => {\n let stackOffset = 0;\n if (/fragment CartApi(Query|Mutation) on Cart/.test(query)) {\n // The cart handler is wrapping storefront.query/mutate,\n // so we need to go up one more stack frame to show\n // the caller in /subrequest-profiler\n stackOffset = 1;\n }\n\n return stackOffset;\n }\n : undefined;\n\nexport function formatAPIResult<T>(\n data: T,\n errors: StorefrontApiErrors,\n): T & StorefrontError {\n return {\n ...data,\n ...(errors && {errors}),\n };\n}\n\nexport type CreateStorefrontClientForDocs<TI18n extends I18nBase> = {\n storefront?: StorefrontForDoc<TI18n>;\n};\n\nexport type StorefrontForDoc<TI18n extends I18nBase = I18nBase> = {\n /** The function to run a query on Storefront API. */\n query?: <TData = any>(\n query: string,\n options: StorefrontQueryOptionsForDocs,\n ) => Promise<TData & StorefrontError>;\n /** The function to run a mutation on Storefront API. */\n mutate?: <TData = any>(\n mutation: string,\n options: StorefrontMutationOptionsForDocs,\n ) => Promise<TData & StorefrontError>;\n /** The cache instance passed in from the `createStorefrontClient` argument. */\n cache?: Cache;\n /** Re-export of [`CacheNone`](/docs/api/hydrogen/2024-01/utilities/cachenone). */\n CacheNone?: typeof CacheNone;\n /** Re-export of [`CacheLong`](/docs/api/hydrogen/2024-01/utilities/cachelong). */\n CacheLong?: typeof CacheLong;\n /** Re-export of [`CacheShort`](/docs/api/hydrogen/2024-01/utilities/cacheshort). */\n CacheShort?: typeof CacheShort;\n /** Re-export of [`CacheCustom`](/docs/api/hydrogen/2024-01/utilities/cachecustom). */\n CacheCustom?: typeof CacheCustom;\n /** Re-export of [`generateCacheControlHeader`](/docs/api/hydrogen/2024-01/utilities/generatecachecontrolheader). */\n generateCacheControlHeader?: typeof generateCacheControlHeader;\n /** Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. See [`getPublicTokenHeaders` in Hydrogen React](/docs/api/hydrogen-react/2024-01/utilities/createstorefrontclient#:~:text=%27graphql%27.-,getPublicTokenHeaders,-(props%3F%3A) for more details. */\n getPublicTokenHeaders?: ReturnType<\n typeof createStorefrontUtilities\n >['getPublicTokenHeaders'];\n /** Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint for API calls made from a server. See [`getPrivateTokenHeaders` in Hydrogen React](/docs/api/hydrogen-react/2024-01/utilities/createstorefrontclient#:~:text=storefrontApiVersion-,getPrivateTokenHeaders,-(props%3F%3A) for more details.*/\n getPrivateTokenHeaders?: ReturnType<\n typeof createStorefrontUtilities\n >['getPrivateTokenHeaders'];\n /** Creates the fully-qualified URL to your myshopify.com domain. See [`getShopifyDomain` in Hydrogen React](/docs/api/hydrogen-react/2024-01/utilities/createstorefrontclient#:~:text=StorefrontClientReturn-,getShopifyDomain,-(props%3F%3A) for more details. */\n getShopifyDomain?: ReturnType<\n typeof createStorefrontUtilities\n >['getShopifyDomain'];\n /** Creates the fully-qualified URL to your store's GraphQL endpoint. See [`getStorefrontApiUrl` in Hydrogen React](/docs/api/hydrogen-react/2024-01/utilities/createstorefrontclient#:~:text=storeDomain-,getStorefrontApiUrl,-(props%3F%3A) for more details.*/\n getApiUrl?: ReturnType<\n typeof createStorefrontUtilities\n >['getStorefrontApiUrl'];\n /**\n * @deprecated Use the `errors` object returned from the API if exists.\n * */\n isApiError?: (error: any) => boolean;\n /** The `i18n` object passed in from the `createStorefrontClient` argument. */\n i18n?: TI18n;\n};\n\nexport type StorefrontQueryOptionsForDocs = {\n /** The variables for the GraphQL query statement. */\n variables?: Record<string, unknown>;\n /** The cache strategy for this query. Default to max-age=1, stale-while-revalidate=86399. */\n cache?: CachingStrategy;\n /** Additional headers for this query. */\n headers?: HeadersInit;\n /** Override the Storefront API version for this query. */\n storefrontApiVersion?: string;\n /** The name of the query for debugging in the Subrequest Profiler. */\n displayName?: string;\n};\n\nexport type StorefrontMutationOptionsForDocs = {\n /** The variables for the GraphQL mutation statement. */\n variables?: Record<string, unknown>;\n /** Additional headers for this query. */\n headers?: HeadersInit;\n /** Override the Storefront API version for this query. */\n storefrontApiVersion?: string;\n /** The name of the query for debugging in the Subrequest Profiler. */\n displayName?: string;\n};\n","type QueryKey = string | readonly unknown[];\n\nexport function hashKey(queryKey: QueryKey): string {\n const rawKeys = Array.isArray(queryKey) ? queryKey : [queryKey];\n let hash = '';\n\n // Keys could be in the following shape:\n //\n // From `storefront.query`:\n // ['api-endpoint', 'method', 'headers', 'query']\n //\n // From `createWithCache`:\n // ['string', {}, 1, []]\n for (const key of rawKeys) {\n if (key != null) {\n if (typeof key === 'object') {\n hash += JSON.stringify(key);\n } else {\n hash += key.toString();\n }\n }\n }\n\n return encodeURIComponent(hash);\n}\n","/**\n * Override options for a cache strategy.\n */\nexport interface AllCacheOptions {\n /**\n * The caching mode, generally `public`, `private`, or `no-store`.\n */\n mode?: string;\n /**\n * The maximum amount of time in seconds that a resource will be considered fresh. See `max-age` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage).\n */\n maxAge?: number;\n /**\n * Indicate that the cache should serve the stale response in the background while revalidating the cache. See `stale-while-revalidate` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate).\n */\n staleWhileRevalidate?: number;\n /**\n * Similar to `maxAge` but specific to shared caches. See `s-maxage` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage).\n */\n sMaxAge?: number;\n /**\n * Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See `stale-if-error` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error).\n */\n staleIfError?: number;\n}\n\n/**\n * Use the `CachingStrategy` to define a custom caching mechanism for your data. Or use one of the pre-defined caching strategies: CacheNone, CacheShort, CacheLong.\n */\nexport type CachingStrategy = AllCacheOptions;\n\nexport type NoStoreStrategy = {\n mode: string;\n};\n\nconst PUBLIC = 'public';\nconst PRIVATE = 'private';\nexport const NO_STORE = 'no-store';\n\nconst optionMapping: {\n [key: string]: string;\n} = {\n maxAge: 'max-age',\n staleWhileRevalidate: 'stale-while-revalidate',\n sMaxAge: 's-maxage',\n staleIfError: 'stale-if-error',\n};\n\nexport function generateCacheControlHeader(\n cacheOptions: CachingStrategy,\n): string {\n const cacheControl: string[] = [];\n Object.keys(cacheOptions).forEach((key: string) => {\n if (key === 'mode') {\n cacheControl.push(cacheOptions[key] as string);\n } else if (optionMapping[key]) {\n cacheControl.push(\n `${optionMapping[key]}=${cacheOptions[key as keyof CachingStrategy]}`,\n );\n }\n });\n return cacheControl.join(', ');\n}\n\n/**\n *\n * @public\n */\nexport function CacheNone(): NoStoreStrategy {\n return {\n mode: NO_STORE,\n };\n}\n\nfunction guardExpirableModeType(overrideOptions?: CachingStrategy) {\n if (\n overrideOptions?.mode &&\n overrideOptions?.mode !== PUBLIC &&\n overrideOptions?.mode !== PRIVATE\n ) {\n throw Error(\"'mode' must be either 'public' or 'private'\");\n }\n}\n\n/**\n *\n * @public\n */\nexport function CacheShort(overrideOptions?: CachingStrategy): AllCacheOptions {\n guardExpirableModeType(overrideOptions);\n return {\n mode: PUBLIC,\n maxAge: 1,\n staleWhileRevalidate: 9,\n ...overrideOptions,\n };\n}\n\n/**\n *\n * @public\n */\nexport function CacheLong(overrideOptions?: CachingStrategy): AllCacheOptions {\n guardExpirableModeType(overrideOptions);\n return {\n mode: PUBLIC,\n maxAge: 3600, // 1 hour\n staleWhileRevalidate: 82800, // 23 Hours\n ...overrideOptions,\n };\n}\n\n/**\n *\n * @private\n */\nexport function CacheDefault(\n overrideOptions?: CachingStrategy,\n): AllCacheOptions {\n guardExpirableModeType(overrideOptions);\n return {\n mode: PUBLIC,\n maxAge: 1,\n staleWhileRevalidate: 86399, // 1 second less than 24 hours\n ...overrideOptions,\n };\n}\n\n/**\n *\n * @public\n */\nexport function CacheCustom(overrideOptions: CachingStrategy): AllCacheOptions {\n return overrideOptions as AllCacheOptions;\n}\n","export function parseJSON(json: any) {\n if (String(json).includes('__proto__')) return JSON.parse(json, noproto);\n return JSON.parse(json);\n}\nfunction noproto(k: string, v: string) {\n if (k !== '__proto__') return v;\n}\n","import type {CachingStrategy} from './strategies';\nimport {CacheDefault, generateCacheControlHeader} from './strategies';\n\nfunction logCacheApiStatus(\n status: string | null,\n request: Request,\n response?: Response,\n) {\n // const url = request.url;\n // if (!/Product\\(/.test(url)) return;\n // // eslint-disable-next-line no-console\n // console.log(status, 'cacheKey', url.substring(0, 50));\n // if (response) {\n // let headersJson: Record<string, string> = {};\n // response.headers.forEach((value, key) => {\n // headersJson[key] = value;\n // });\n // const responseDate = response.headers.get('cache-put-date');\n // if (responseDate) {\n // const [age] = calculateAge(response, responseDate);\n // headersJson['age'] = age.toString();\n // }\n // // eslint-disable-next-line no-console\n // console.log(`${status} response headers: `, headersJson);\n // }\n}\n\nfunction getCacheControlSetting(\n userCacheOptions?: CachingStrategy,\n options?: CachingStrategy,\n): CachingStrategy {\n if (userCacheOptions && options) {\n return {\n ...userCacheOptions,\n ...options,\n };\n } else {\n return userCacheOptions || CacheDefault();\n }\n}\n\nfunction generateDefaultCacheControlHeader(\n userCacheOptions?: CachingStrategy,\n): string {\n return generateCacheControlHeader(getCacheControlSetting(userCacheOptions));\n}\n\n/**\n * Get an item from the cache. If a match is found, returns a tuple\n * containing the `JSON.parse` version of the response as well\n * as the response itself so it can be checked for staleness.\n */\nasync function getItem(\n cache: Cache,\n request: Request,\n): Promise<Response | undefined> {\n if (!cache) return;\n\n const response = await cache.match(request);\n if (!response) {\n logCacheApiStatus('MISS', request);\n return;\n }\n\n logCacheApiStatus('HIT', request, response);\n\n return response;\n}\n\n/**\n * Put an item into the cache.\n */\nasync function setItem(\n cache: Cache,\n request: Request,\n response: Response,\n userCacheOptions: CachingStrategy,\n) {\n if (!cache) return;\n\n /**\n * We are manually managing staled request by adding this workaround.\n * Why? cache control header support is dependent on hosting platform\n *\n * For example:\n *\n * Cloudflare's Cache API does not support `stale-while-revalidate`.\n * Cloudflare cache control header has a very odd behaviour.\n * Say we have the following cache control header on a request:\n *\n * public, max-age=15, stale-while-revalidate=30\n *\n * When there is a cache.match HIT, the cache control header would become\n *\n * public, max-age=14400, stale-while-revalidate=30\n *\n * == `stale-while-revalidate` workaround ==\n * Update response max-age so that:\n *\n * max-age = max-age + stale-while-revalidate\n *\n * For example:\n *\n * public, max-age=1, stale-while-revalidate=9\n * |\n * V\n * public, max-age=10, stale-while-revalidate=9\n *\n * Store the following information in the response header:\n *\n * cache-put-date - UTC time string of when this request is PUT into cache\n *\n * Note on `cache-put-date`: The `response.headers.get('date')` isn't static. I am\n * not positive what date this is returning but it is never over 500 ms\n * after subtracting from the current timestamp.\n *\n * `isStale` function will use the above information to test for stale-ness of a cached response\n */\n\n const cacheControl = getCacheControlSetting(userCacheOptions);\n\n // The padded cache-control to mimic stale-while-revalidate\n const paddedCacheControlString = generateDefaultCacheControlHeader(\n getCacheControlSetting(cacheControl, {\n maxAge:\n (cacheControl.maxAge || 0) + (cacheControl.staleWhileRevalidate || 0),\n }),\n );\n // The cache-control we want to set on response\n const cacheControlString = generateDefaultCacheControlHeader(\n getCacheControlSetting(cacheControl),\n );\n\n // CF will override cache-control, so we need to keep a non-modified real-cache-control\n // cache-control is still necessary for mini-oxygen\n response.headers.set('cache-control', paddedCacheControlString);\n response.headers.set('real-cache-control', cacheControlString);\n response.headers.set('cache-put-date', new Date().toUTCString());\n\n logCacheApiStatus('PUT', request, response);\n await cache.put(request, response);\n}\n\nasync function deleteItem(cache: Cache, request: Request) {\n if (!cache) return;\n\n logCacheApiStatus('DELETE', request);\n await cache.delete(request);\n}\n\nfunction calculateAge(response: Response, responseDate: string) {\n const cacheControl = response.headers.get('real-cache-control');\n let responseMaxAge = 0;\n\n if (cacheControl) {\n const maxAgeMatch = cacheControl.match(/max-age=(\\d*)/);\n if (maxAgeMatch && maxAgeMatch.length > 1) {\n responseMaxAge = parseFloat(maxAgeMatch[1]);\n }\n }\n\n const ageInMs =\n new Date().valueOf() - new Date(responseDate as string).valueOf();\n return [ageInMs / 1000, responseMaxAge];\n}\n\n/**\n * Manually check the response to see if it's stale.\n */\nfunction isStale(request: Request, response: Response) {\n const responseDate = response.headers.get('cache-put-date');\n\n if (!responseDate) {\n return false;\n }\n\n const [age, responseMaxAge] = calculateAge(response, responseDate);\n const result = age > responseMaxAge;\n\n if (result) {\n logCacheApiStatus('STALE', request, response);\n }\n\n return result;\n}\n\n/**\n *\n * @private\n */\nexport const CacheAPI = {\n get: getItem,\n set: setItem,\n delete: deleteItem,\n generateDefaultCacheControlHeader,\n isStale,\n};\n","import {parseJSON} from '../utils/parse-json';\nimport {CacheAPI} from './api';\nimport {\n CacheDefault,\n type CachingStrategy,\n type AllCacheOptions,\n} from './strategies.js';\n\n/**\n * Wrapper Cache functions for sub queries\n */\n\n/**\n * Cache API is weird. We just need a full URL, so we make one up.\n */\nexport function getKeyUrl(key: string) {\n return `https://shopify.dev/?${key}`;\n}\n\nfunction getCacheOption(userCacheOptions?: CachingStrategy): AllCacheOptions {\n return userCacheOptions || CacheDefault();\n}\n\nexport function generateSubRequestCacheControlHeader(\n userCacheOptions?: CachingStrategy,\n): string {\n return CacheAPI.generateDefaultCacheControlHeader(\n getCacheOption(userCacheOptions),\n );\n}\n\n/**\n * Get an item from the cache. If a match is found, returns a tuple\n * containing the `JSON.parse` version of the response as well\n * as the response itself so it can be checked for staleness.\n * @private\n */\nexport async function getItemFromCache(\n cache: Cache,\n key: string,\n): Promise<undefined | [any, Response]> {\n if (!cache) return;\n const url = getKeyUrl(key);\n const request = new Request(url);\n\n const response = await CacheAPI.get(cache, request);\n\n if (!response) {\n return;\n }\n\n const text = await response.text();\n try {\n return [parseJSON(text), response];\n } catch {\n return [text, response];\n }\n}\n\n/**\n * Put an item into the cache.\n * @private\n */\nexport async function setItemInCache(\n cache: Cache,\n key: string,\n value: any,\n userCacheOptions?: CachingStrategy,\n) {\n if (!cache) return;\n\n const url = getKeyUrl(key);\n const request = new Request(url);\n const response = new Response(JSON.stringify(value));\n\n await CacheAPI.set(\n cache,\n request,\n response,\n getCacheOption(userCacheOptions),\n );\n}\n\n/**\n *\n * @private\n */\nexport async function deleteItemFromCache(cache: Cache, key: string) {\n if (!cache) return;\n\n const url = getKeyUrl(key);\n const request = new Request(url);\n\n await CacheAPI.delete(cache, request);\n}\n\n/**\n * Manually check the response to see if it's stale.\n * @private\n */\nexport function isStale(key: string, response: Response) {\n return CacheAPI.isStale(new Request(getKeyUrl(key)), response);\n}\n","/// <reference types=\"@shopify/remix-oxygen\" />\n\nimport {hashKey} from '../utils/hash.js';\nimport {\n CacheShort,\n CachingStrategy,\n NO_STORE,\n generateCacheControlHeader,\n} from './strategies';\nimport type {StackInfo} from '../utils/callsites.js';\nimport {\n getItemFromCache,\n setItemInCache,\n isStale,\n getKeyUrl,\n} from './sub-request';\n\n/**\n * The cache key is used to uniquely identify a value in the cache.\n */\nexport type CacheKey = string | readonly unknown[];\n\nexport type FetchDebugInfo = {\n url?: string;\n requestId?: string | null;\n graphql?: string | null;\n purpose?: string | null;\n stackInfo?: StackInfo;\n displayName?: string;\n};\n\nexport type DebugInfo = {\n displayName?: string;\n url?: string;\n responseInit?: {\n status: number;\n statusText: string;\n headers?: [string, string][];\n };\n};\n\ntype AddDebugDataParam = {\n displayName?: string;\n response?: Response;\n};\n\nexport type CacheActionFunctionParam = {\n addDebugData: (info: AddDebugDataParam) => void;\n};\n\nexport type WithCacheOptions<T = unknown> = {\n strategy?: CachingStrategy | null;\n cacheInstance?: Cache;\n shouldCacheResult?: (value: T) => boolean;\n waitUntil?: ExecutionContext['waitUntil'];\n debugInfo?: FetchDebugInfo;\n};\n\nexport type FetchCacheOptions = {\n cache?: CachingStrategy;\n cacheInstance?: Cache;\n cacheKey?: CacheKey;\n shouldCacheResponse?: (body: any, response: Response) => boolean;\n waitUntil?: ExecutionContext['waitUntil'];\n returnType?: 'json' | 'text' | 'arrayBuffer' | 'blob';\n debugInfo?: FetchDebugInfo;\n};\n\nfunction toSerializableResponse(body: any, response: Response) {\n return [\n body,\n {\n status: response.status,\n statusText: response.statusText,\n headers: Array.from(response.headers.entries()),\n },\n ] satisfies [any, ResponseInit];\n}\n\nfunction fromSerializableResponse([body, init]: [any, ResponseInit]) {\n return [body, new Response(body, init)] as const;\n}\n\n// Check if the response body has GraphQL errors\n// https://spec.graphql.org/June2018/#sec-Response-Format\nexport const checkGraphQLErrors = (body: any, response: Response) =>\n !body?.errors && response.status < 400;\n\n// Lock to prevent revalidating the same sub-request\n// in the same isolate. Note that different isolates\n// in the same colo could duplicate the revalidation\n// since this is only an in-memory lock.\n// https://github.com/Shopify/oxygen-platform/issues/625\nconst swrLock = new Set<string>();\n\nexport async function runWithCache<T = unknown>(\n cacheKey: CacheKey,\n actionFn: ({addDebugData}: CacheActionFunctionParam) => T | Promise<T>,\n {\n strategy = CacheShort(),\n cacheInstance,\n shouldCacheResult = () => true,\n waitUntil,\n debugInfo,\n }: WithCacheOptions<T>,\n): Promise<T> {\n const startTime = Date.now();\n const key = hashKey([\n // '__HYDROGEN_CACHE_ID__', // TODO purgeQueryCacheOnBuild\n ...(typeof cacheKey === 'string' ? [cacheKey] : cacheKey),\n ]);\n\n let debugData: DebugInfo;\n const addDebugData = (info: AddDebugDataParam) => {\n debugData = {\n displayName: info.displayName,\n url: info.response?.url,\n responseInit: {\n status: info.response?.status || 0,\n statusText: info.response?.statusText || '',\n headers: Array.from(info.response?.headers.entries() || []),\n },\n };\n };\n\n const logSubRequestEvent =\n process.env.NODE_ENV === 'development'\n ? ({\n result,\n cacheStatus,\n overrideStartTime,\n }: {\n result?: any;\n cacheStatus?: 'MISS' | 'HIT' | 'STALE' | 'PUT';\n overrideStartTime?: number;\n }) => {\n globalThis.__H2O_LOG_EVENT?.({\n eventType: 'subrequest',\n startTime: overrideStartTime || startTime,\n cacheStatus,\n responsePayload: (result && result[0]) || result,\n responseInit: (result && result[1]) || debugData?.responseInit,\n cache: {\n status: cacheStatus,\n strategy: generateCacheControlHeader(strategy || {}),\n key,\n },\n waitUntil,\n ...debugInfo,\n url: debugData?.url || debugInfo?.url || getKeyUrl(key),\n displayName: debugInfo?.displayName || debugData?.displayName,\n });\n }\n : undefined;\n\n if (!cacheInstance || !strategy || strategy.mode === NO_STORE) {\n const result = await actionFn({addDebugData});\n // Log non-cached requests\n logSubRequestEvent?.({result});\n return result;\n }\n\n const cachedItem = await getItemFromCache(cacheInstance, key);\n // console.log('--- Cache', cachedItem ? 'HIT' : 'MISS');\n\n if (cachedItem) {\n const [cachedResult, cacheInfo] = cachedItem;\n const cacheStatus = isStale(key, cacheInfo) ? 'STALE' : 'HIT';\n\n if (!swrLock.has(key) && cacheStatus === 'STALE') {\n swrLock.add(key);\n\n // Important: Run revalidation asynchronously.\n const revalidatingPromise = Promise.resolve().then(async () => {\n const revalidateStartTime = Date.now();\n try {\n const result = await actionFn({addDebugData});\n\n if (shouldCacheResult(result)) {\n await setItemInCache(cacheInstance, key, result, strategy);\n\n // Log PUT requests with the revalidate start time\n logSubRequestEvent?.({\n result,\n cacheStatus: 'PUT',\n overrideStartTime: revalidateStartTime,\n });\n }\n } catch (error: any) {\n if (error.message) {\n error.message = 'SWR in sub-request failed: ' + error.message;\n }\n\n console.error(error);\n } finally {\n swrLock.delete(key);\n }\n });\n\n // Asynchronously wait for it in workers\n waitUntil?.(revalidatingPromise);\n }\n\n // Log HIT/STALE requests\n logSubRequestEvent?.({\n result: cachedResult,\n cacheStatus,\n });\n\n return cachedResult;\n }\n\n const result = await actionFn({addDebugData});\n\n // Log MISS requests\n logSubRequestEvent?.({\n result,\n cacheStatus: 'MISS',\n });\n\n /**\n * Important: Do this async\n */\n if (shouldCacheResult(result)) {\n const setItemInCachePromise = Promise.resolve().then(async () => {\n const putStartTime = Date.now();\n await setItemInCache(cacheInstance, key, result, strategy);\n logSubRequestEvent?.({\n result,\n cacheStatus: 'PUT',\n overrideStartTime: putStartTime,\n });\n });\n\n waitUntil?.(setItemInCachePromise);\n }\n\n return result;\n}\n\n/**\n * `fetch` equivalent that stores responses in cache.\n * Useful for calling third-party APIs that need to be cached.\n * @private\n */\nexport async function fetchWithServerCache(\n url: string,\n requestInit: Request | RequestInit,\n {\n cacheInstance,\n cache: cacheOptions,\n cacheKey = [url, requestInit],\n shouldCacheResponse = () => true,\n waitUntil,\n returnType = 'json',\n debugInfo,\n }: FetchCacheOptions = {},\n): Promise<readonly [any, Response]> {\n if (!cacheOptions && (!requestInit.method || requestInit.method === 'GET')) {\n cacheOptions = CacheShort();\n }\n\n return runWithCache(\n cacheKey,\n async () => {\n const response = await fetch(url, requestInit);\n let data;\n\n try {\n data = await response[returnType]();\n } catch {\n try {\n data = await response.text();\n } catch {\n // Getting a response without a valid body\n return toSerializableResponse('', response);\n }\n }\n\n return toSerializableResponse(data, response);\n },\n {\n cacheInstance,\n waitUntil,\n strategy: cacheOptions ?? null,\n debugInfo,\n shouldCacheResult: (result) =>\n shouldCacheResponse(...fromSerializableResponse(result)),\n },\n ).then(fromSerializableResponse);\n}\n","export const STOREFRONT_REQUEST_GROUP_ID_HEADER =\n 'Custom-Storefront-Request-Group-ID';\nexport const STOREFRONT_ACCESS_TOKEN_HEADER =\n 'X-Shopify-Storefront-Access-Token';\nexport const SDK_VARIANT_HEADER = 'X-SDK-Variant';\nexport const SDK_VARIANT_SOURCE_HEADER = 'X-SDK-Variant-Source';\nexport const SDK_VERSION_HEADER = 'X-SDK-Version';\n","/*\n * Generate a UUID using crypto and fallback to Math.random if crypto is not available.\n */\nexport function generateUUID() {\n if (typeof crypto !== 'undefined' && !!crypto.randomUUID) {\n return crypto.randomUUID();\n } else {\n return `weak-${Math.random().toString(16).substring(2)}`;\n }\n}\n","const warnings = new Set<string>();\nexport const warnOnce = (string: string) => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n","export const LIB_VERSION = '2024.1.6';\n","import type {StorefrontApiResponseOk} from '@shopify/hydrogen-react';\nimport type {GenericVariables} from '@shopify/hydrogen-codegen';\n\nexport function extractQueryName(query: string) {\n return query.match(/(query|mutation)\\s+([^({]*)/)?.[0]?.trim();\n}\n\nexport function minifyQuery<T extends string>(string: T) {\n return string\n .replace(/\\s*#.*$/gm, '') // Remove GQL comments\n .replace(/\\s+/gm, ' ') // Minify spaces\n .trim() as T;\n}\n\nconst IS_QUERY_RE = /(^|}\\s)query[\\s({]/im;\nconst IS_MUTATION_RE = /(^|}\\s)mutation[\\s({]/im;\n\nexport function assertQuery(query: string, callerName: string) {\n if (!IS_QUERY_RE.test(query)) {\n throw new Error(`[h2:error:${callerName}] Can only execute queries`);\n }\n}\n\nexport function assertMutation(query: string, callerName: string) {\n if (!IS_MUTATION_RE.test(query)) {\n throw new Error(`[h2:error:${callerName}] Can only execute mutations`);\n }\n}\n\nexport type GraphQLApiResponse<T> = StorefrontApiResponseOk<T>;\n\nexport type GraphQLErrorOptions<T> = {\n url: string;\n response: Response;\n errors: GraphQLApiResponse<T>['errors'];\n type: 'query' | 'mutation';\n query: string;\n queryVariables: GenericVariables;\n ErrorConstructor?: ErrorConstructor;\n client?: string;\n};\n\n// Reference: https://github.com/graphql/graphql-js/blob/main/src/error/GraphQLError.ts#L218-L242\nexport class GraphQLError extends Error {\n /**\n * If an error can be associated to a particular point in the requested\n * GraphQL document, it should contain a list of locations.\n */\n locations?: Array<{line: number; column: number}>;\n /**\n * If an error can be associated to a particular field in the GraphQL result,\n * it _must_ contain an entry with the key `path` that details the path of\n * the response field which experienced the error. This allows clients to\n * identify whether a null result is intentional or caused by a runtime error.\n */\n path?: Array<string | number>;\n /**\n * Reserved for implementors to extend the protocol however they see fit,\n * and hence there are no additional restrictions on its contents.\n */\n extensions?: {[key: string]: unknown};\n\n constructor(\n message?: string,\n options: Pick<\n GraphQLError,\n 'locations' | 'path' | 'extensions' | 'stack' | 'cause'\n > & {\n query?: string;\n queryVariables?: GenericVariables;\n requestId?: string | null;\n clientOperation?: string;\n } = {},\n ) {\n const h2Prefix = options.clientOperation\n ? `[h2:error:${options.clientOperation}] `\n : '';\n\n const enhancedMessage =\n h2Prefix +\n message +\n (options.requestId ? ` - Request ID: ${options.requestId}` : '');\n\n super(enhancedMessage);\n this.name = 'GraphQLError';\n this.extensions = options.extensions;\n this.locations = options.locations;\n this.path = options.path;\n this.stack = options.stack || undefined;\n\n try {\n this.cause = JSON.stringify({\n ...(typeof options.cause === 'object' ? options.cause : {}),\n requestId: options.requestId,\n ...(process.env.NODE_ENV === 'development' && {\n path: options.path,\n extensions: options.extensions,\n graphql: h2Prefix &&\n options.query && {\n query: options.query,\n variables: JSON.stringify(options.queryVariables),\n },\n }),\n });\n } catch {\n if (options.cause) this.cause = options.cause;\n }\n }\n\n get [Symbol.toStringTag]() {\n return this.name;\n }\n\n /**\n * Note: `toString()` is internally used by `console.log(...)` / `console.error(...)`\n * when ingesting logs in Oxygen production. Therefore, we want to make sure that\n * the error message is as informative as possible instead of `[object Object]`.\n */\n override toString() {\n let result = `${this.name}: ${this.message}`;\n\n if (this.path) {\n try {\n result += ` | path: ${JSON.stringify(this.path)}`;\n } catch {}\n }\n\n if (this.extensions) {\n try {\n result += ` | extensions: ${JSON.stringify(this.extensions)}`;\n } catch {}\n }\n\n result += '\\n';\n\n if (this.stack) {\n // Remove the message line from the stack.\n result += `${this.stack.slice(this.stack.indexOf('\\n') + 1)}\\n`;\n }\n\n return result;\n }\n\n /**\n * Note: toJSON` is internally used by `JSON.stringify(...)`.\n * The most common scenario when this error instance is going to be stringified is\n * when it's passed to Remix' `json` and `defer` functions: e.g. `defer({promise: storefront.query(...)})`.\n * In this situation, we don't want to expose private error information to the browser so we only\n * do it in development.\n */\n toJSON() {\n const formatted: Pick<\n GraphQLError,\n 'name' | 'message' | 'path' | 'extensions' | 'locations' | 'stack'\n > = {name: 'Error', message: ''};\n\n if (process.env.NODE_ENV === 'development') {\n formatted.name = this.name;\n formatted.message = 'Development: ' + this.message;\n if (this.path) formatted.path = this.path;\n if (this.locations) formatted.locations = this.locations;\n if (this.extensions) formatted.extensions = this.extensions;\n // Skip stack on purpose because we don't want to expose it to the browser.\n }\n\n return formatted;\n }\n}\n\nexport function throwErrorWithGqlLink<T>({\n url,\n response,\n errors,\n type,\n query,\n queryVariables,\n ErrorConstructor = Error,\n client = 'storefront',\n}: GraphQLErrorOptions<T>): never {\n const errorMessage =\n (typeof errors === 'string'\n ? errors\n : errors?.map?.((error) => error.message).join('\\n')) ||\n `URL: ${url}\\nAPI response error: ${response.status}`;\n\n const gqlError = new GraphQLError(errorMessage, {\n query,\n queryVariables,\n cause: {errors},\n clientOperation: `${client}.${type}`,\n requestId: response.headers.get('x-request-id'),\n });\n\n throw new ErrorConstructor(gqlError.message, {cause: gqlError.cause});\n}\n","/**\n * Ensures that the error of an async rejected promise\n * contains the entire synchronous stack trace.\n */\nexport function withSyncStack<T>(\n promise: Promise<T>,\n options: {\n stackOffset?: number;\n logErrors?: boolean | ((error?: Error) => boolean);\n } = {},\n): Promise<T> {\n const syncError = new Error();\n const getSyncStack = (message: string, name = 'Error') => {\n // Remove error message, caller function and current function from the stack.\n const syncStack = (syncError.stack ?? '')\n .split('\\n')\n .slice(3 + (options.stackOffset ?? 0))\n .join('\\n')\n // Sometimes stack traces show loaders with a number suffix due to ESBuild.\n .replace(/ at loader(\\d+) \\(/, (all, m1) => all.replace(m1, ''));\n\n return `${name}: ${message}\\n` + syncStack;\n };\n\n return promise\n .then((result: any) => {\n if (result?.errors && Array.isArray(result.errors)) {\n const logErrors =\n typeof options.logErrors === 'function'\n ? options.logErrors\n : () => options.logErrors ?? false;\n\n result.errors.forEach((error: Error) => {\n if (error) {\n error.stack = getSyncStack(error.message, error.name);\n if (logErrors(error)) console.error(error);\n }\n });\n }\n\n return result;\n })\n .catch((error: Error) => {\n if (error) error.stack = getSyncStack(error.message, error.name);\n throw error;\n });\n}\n\nexport type StackInfo = {\n file?: string;\n func?: string;\n line?: number;\n column?: number;\n};\n\n/**\n * Finds the stack line of a caller function without using sourcemaps.\n * @param {number} stackOffset - The number of stack frames to skip.\n * @returns {StackInfo | undefined}\n */\nexport const getCallerStackLine =\n process.env.NODE_ENV === 'development'\n ? (stackOffset = 0) => {\n let stackInfo: StackInfo | undefined = undefined;\n const original = Error.prepareStackTrace;\n\n // Accessing sourcemaps slows down execution time significantly.\n // Overwrite the prepareStackTrace function to avoid accessing\n // sourcemaps and just store what we need.\n Error.prepareStackTrace = (_, callsites) => {\n // The first callsite is `getCallerStackLine` itself.\n // The second one is the immediate caller function (e.g. `withCache`).\n // Skip both and find the first ancestor.\n const cs = callsites[2 + stackOffset];\n\n stackInfo = cs && {\n file: cs.getFileName() ?? undefined,\n func: cs.getFunctionName() ?? undefined,\n line: cs.getLineNumber() ?? undefined,\n column: cs.getColumnNumber() ?? undefined,\n };\n\n return '';\n };\n\n // Create and access stack to run the previous function\n const err = {stack: ''};\n Error.captureStackTrace(err);\n err.stack;\n\n Error.prepareStackTrace = original;\n\n return stackInfo as StackInfo | undefined;\n }\n : undefined;\n","export type CrossRuntimeRequest = {\n url?: string;\n method?: string;\n headers: {\n get?: (key: string) => string | null | undefined;\n [key: string]: any;\n };\n};\n\nexport function getHeader(request: CrossRuntimeRequest, key: string) {\n const value = request.headers?.get?.(key) ?? request.headers?.[key];\n return typeof value === 'string' ? value : null;\n}\n\nexport function getDebugHeaders(request?: CrossRuntimeRequest) {\n return {\n requestId: request ? getHeader(request, 'request-id') : undefined,\n purpose: request ? getHeader(request, 'purpose') : undefined,\n };\n}\n","import {\n type CacheKey,\n runWithCache,\n type CacheActionFunctionParam,\n} from './cache/fetch';\nimport type {CachingStrategy} from './cache/strategies';\nimport {type CrossRuntimeRequest, getDebugHeaders} from './utils/request';\nimport {getCallerStackLine} from './utils/callsites';\n\ntype CreateWithCacheOptions = {\n /** An instance that implements the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) */\n cache: Cache;\n /** The `waitUntil` function is used to keep the current request/response lifecycle alive even after a response has been sent. It should be provided by your platform. */\n waitUntil: ExecutionContext['waitUntil'];\n /** The `request` object is used to access certain headers for debugging */\n request?: CrossRuntimeRequest;\n};\n\n/**\n * Creates a utility function that executes an asynchronous operation\n * like `fetch` and caches the result according to the strategy provided.\n * Use this to call any third-party APIs from loaders or actions.\n * By default, it uses the `CacheShort` strategy.\n *\n */\nexport function createWithCache<T = unknown>({\n cache,\n waitUntil,\n request,\n}: CreateWithCacheOptions): CreateWithCacheReturn<T> {\n return function withCache<T = unknown>(\n cacheKey: CacheKey,\n strategy: CachingStrategy,\n actionFn: ({addDebugData}: CacheActionFunctionParam) => T | Promise<T>,\n ) {\n return runWithCache<T>(cacheKey, actionFn, {\n strategy,\n cacheInstance: cache,\n waitUntil,\n debugInfo: {\n ...getDebugHeaders(request),\n stackInfo: getCallerStackLine?.(),\n },\n });\n };\n}\n\n/**\n * This is a caching async function. Whatever data is returned from the `actionFn` will be cached according to the strategy provided.\n *\n * Use the `CachingStrategy` to define a custom caching mechanism for your data. Or use one of the built-in caching strategies: `CacheNone`, `CacheShort`, `CacheLong`.\n */\ntype CreateWithCacheReturn<T> = <U = T>(\n cacheKey: CacheKey,\n strategy: CachingStrategy,\n actionFn: ({addDebugData}: CacheActionFunctionParam) => U | Promise<U>,\n) => Promise<U>;\n\nexport type WithCache = ReturnType<typeof createWithCache>;\n","type CacheMatch = {\n body: Uint8Array;\n timestamp: number;\n status: number;\n headers: [string, string][];\n};\n\n/**\n * This is a limited implementation of an in-memory cache.\n * It only supports the `cache-control` header.\n * It does NOT support `age` or `expires` headers.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Cache\n */\nexport class InMemoryCache implements Cache {\n #store: Map<string, CacheMatch>;\n\n constructor() {\n this.#store = new Map();\n }\n\n add(request: RequestInfo): Promise<void> {\n throw new Error('Method not implemented. Use `put` instead.');\n }\n\n addAll(requests: RequestInfo[]): Promise<void> {\n throw new Error('Method not implemented. Use `put` instead.');\n }\n\n matchAll(\n request?: RequestInfo,\n options?: CacheQueryOptions,\n ): Promise<readonly Response[]> {\n throw new Error('Method not implemented. Use `match` instead.');\n }\n\n async put(request: Request, response: Response) {\n if (request.method !== 'GET') {\n throw new TypeError('Cannot cache response to non-GET request.');\n }\n\n if (response.status === 206) {\n throw new TypeError(\n 'Cannot cache response to a range request (206 Partial Content).',\n );\n }\n\n if (response.headers.get('vary')?.includes('*')) {\n throw new TypeError(\"Cannot cache response with 'Vary: *' header.\");\n }\n\n this.#store.set(request.url, {\n body: new Uint8Array(await response.arrayBuffer()),\n status: response.status,\n headers: [...response.headers],\n timestamp: Date.now(),\n });\n }\n\n async match(request: Request) {\n if (request.method !== 'GET') return;\n\n const match = this.#store.get(request.url);\n\n if (!match) {\n return;\n }\n\n const {body, timestamp, ...metadata} = match;\n\n const headers = new Headers(metadata.headers);\n const cacheControl =\n headers.get('cache-control') || headers.get('real-cache-control') || '';\n const maxAge = parseInt(\n cacheControl.match(/max-age=(\\d+)/)?.[1] || '0',\n 10,\n );\n const swr = parseInt(\n cacheControl.match(/stale-while-revalidate=(\\d+)/)?.[1] || '0',\n 10,\n );\n const age = (Date.now() - timestamp) / 1000;\n\n const isMiss = age > maxAge + swr;\n\n if (isMiss) {\n this.#store.delete(request.url);\n return;\n }\n\n const isStale = age > maxAge;\n\n headers.set('cache', isStale ? 'STALE' : 'HIT');\n headers.set('date', new Date(timestamp).toUTCString());\n\n return new Response(body, {\n status: metadata.status ?? 200,\n headers,\n });\n }\n\n async delete(request: Request) {\n if (this.#store.has(request.url)) {\n this.#store.delete(request.url);\n return true;\n }\n return false;\n }\n\n keys(request?: Request) {\n const cacheKeys = [] as Request[];\n\n for (const url of this.#store.keys()) {\n if (!request || request.url === url) {\n cacheKeys.push(new Request(url));\n }\n }\n\n return Promise.resolve(cacheKeys);\n }\n}\n","export function getRedirectUrl(requestUrl?: string): string | undefined {\n if (!requestUrl) return;\n\n const {pathname, search} = new URL(requestUrl);\n const redirectFrom = pathname + search;\n\n const searchParams = new URLSearchParams(search);\n const redirectTo =\n searchParams.get('return_to') || searchParams.get('redirect');\n\n if (redirectTo) {\n if (isLocalPath(requestUrl, redirectTo)) {\n return redirectTo;\n } else {\n console.warn(\n `Cross-domain redirects are not supported. Tried to redirect from ${redirectFrom} to ${redirectTo}`,\n );\n }\n }\n}\n\nfunction isLocalPath(requestUrl: string, redirectUrl: string) {\n // We don't want to redirect cross domain,\n // doing so could create phishing vulnerability\n // Test for protocols, e.g. https://, http://, //\n // and uris: mailto:, tel:, javascript:, etc.\n try {\n return (\n new URL(requestUrl).origin === new URL(redirectUrl, requestUrl).origin\n );\n } catch (e) {\n return false;\n }\n}\n","import type {UrlRedirectConnection} from '@shopify/hydrogen-react/storefront-api-types';\nimport type {I18nBase, Storefront} from '../storefront';\nimport {getRedirectUrl} from '../utils/get-redirect-url';\n\ntype StorefrontRedirect = {\n /** The [Storefront client](/docs/api/hydrogen/2024-01/utilities/createstorefrontclient) instance */\n storefront: Storefront<I18nBase>;\n /** The [MDN Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object that was passed to the `server.ts` request handler. */\n request: Request;\n /** The [MDN Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object created by `handleRequest` */\n response?: Response;\n /** By default the `/admin` route is redirected to the Shopify Admin page for the current storefront. Disable this redirect by passing `true`. */\n noAdminRedirect?: boolean;\n};\n\n/**\n * Queries the Storefront API to see if there is any redirect\n * created for the current route and performs it. Otherwise,\n * it returns the response passed in the parameters. Useful for\n * conditionally redirecting after a 404 response.\n *\n * @see {@link https://help.shopify.com/en/manual/online-store/menus-and-links/url-redirect Creating URL redirects in Shopify}\n */\nexport async function storefrontRedirect(\n options: StorefrontRedirect,\n): Promise<Response> {\n const {\n storefront,\n request,\n noAdminRedirect,\n response = new Response('Not Found', {status: 404}),\n } = options;\n\n const url = new URL(request.url);\n const isSoftNavigation = url.searchParams.has('_data');\n\n url.searchParams.delete('_data');\n\n const redirectFrom = url.toString().replace(url.origin, '');\n\n if (url.pathname === '/admin' && !noAdminRedirect) {\n return createRedirectResponse(\n `${storefront.getShopifyDomain()}/admin`,\n isSoftNavigation,\n );\n }\n\n try {\n const {urlRedirects} = await storefront.query<{\n urlRedirects: UrlRedirectConnection;\n }>(REDIRECT_QUERY, {\n variables: {query: 'path:' + redirectFrom},\n });\n\n const location = urlRedirects?.edges?.[0]?.node?.target;\n\n if (location) {\n return createRedirectResponse(location, isSoftNavigation);\n }\n\n const redirectTo = getRedirectUrl(request.url);\n\n if (redirectTo) {\n return createRedirectResponse(redirectTo, isSoftNavigation);\n }\n } catch (error) {\n console.error(\n `Failed to fetch redirects from Storefront API for route ${redirectFrom}`,\n error,\n );\n }\n\n return response;\n}\n\nfunction createRedirectResponse(location: string, isSoftNavigation: boolean) {\n if (isSoftNavigation) {\n return new Response(null, {\n status: 200,\n headers: {'X-Remix-Redirect': location, 'X-Remix-Status': '302'},\n });\n } else {\n return new Response(null, {\n status: 302,\n headers: {location: location},\n });\n }\n}\n\nconst REDIRECT_QUERY = `#graphql\n query redirects($query: String) {\n urlRedirects(first: 1, query: $query) {\n edges {\n node {\n target\n }\n }\n }\n }\n`;\n","import type {LoaderFunctionArgs} from '@remix-run/server-runtime';\nimport type {Storefront} from '../storefront';\nimport type {CustomerAccount} from '../customer/types';\n\ntype GraphiQLLoader = (args: LoaderFunctionArgs) => Promise<Response>;\n\nexport const graphiqlLoader: GraphiQLLoader = async function graphiqlLoader({\n request,\n context,\n}: LoaderFunctionArgs) {\n // For some reason, types are properly recognized by the editor,\n // but not at build time on CI. Cast types here to ensure it builds.\n const storefront = context.storefront as undefined | Storefront;\n const customerAccount = context.customerAccount as\n | undefined\n | CustomerAccount;\n\n const url = new URL(request.url);\n\n if (!storefront) {\n throw new Error(\n `GraphiQL: Hydrogen's storefront client must be injected in the loader context.`,\n );\n }\n\n const schemas: {\n [key: string]: {\n name: string;\n value?: object;\n accessToken?: string;\n authHeader: string;\n apiUrl: string;\n icon: string;\n };\n } = {};\n\n if (storefront) {\n const authHeader = 'X-Shopify-Storefront-Access-Token';\n schemas.storefront = {\n name: 'Storefront API',\n authHeader,\n accessToken: storefront.getPublicTokenHeaders()[authHeader],\n apiUrl: storefront.getApiUrl(),\n icon: 'SF',\n };\n }\n\n if (customerAccount) {\n // CustomerAccount API does not support introspection to the same URL.\n // Read it from a file using the asset server:\n const customerAccountSchema = await (\n await fetch(url.origin + '/graphiql/customer-account.schema.json')\n ).json();\n\n const accessToken = await customerAccount.getAccessToken();\n\n if (customerAccountSchema) {\n schemas['customer-account'] = {\n name: 'Customer Account API',\n value: customerAccountSchema,\n authHeader: 'Authorization',\n accessToken,\n apiUrl: customerAccount.getApiUrl(),\n icon: 'CA',\n };\n }\n }\n\n // GraphiQL icon from their GitHub repo\n const favicon = `https://avatars.githubusercontent.com/u/12972006?s=48&v=4`;\n\n // Add code highlighting to the HTML template\n const html = String.raw;\n\n return new Response(\n html`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <title>GraphiQL</title>\n <link rel=\"icon\" type=\"image/x-icon\" href=\"${favicon}\" />\n <style>\n body {\n height: 100%;\n margin: 0;\n width: 100%;\n overflow: hidden;\n background-color: hsl(219, 29%, 18%);\n }\n\n #graphiql {\n height: 100vh;\n }\n\n #graphiql > .placeholder {\n color: slategray;\n width: fit-content;\n margin: 40px auto;\n font-family: Arial;\n }\n\n .graphiql-api-toolbar-label {\n position: absolute;\n bottom: -6px;\n right: -4px;\n font-size: 8px;\n }\n </style>\n\n <script\n crossorigin\n src=\"https://unpkg.com/react@18/umd/react.development.js\"\n ></script>\n <script\n crossorigin\n src=\"https://unpkg.com/react-dom@18/umd/react-dom.development.js\"\n ></script>\n <link\n rel=\"stylesheet\"\n href=\"https://unpkg.com/graphiql@3/graphiql.min.css\"\n />\n <link\n rel=\"stylesheet\"\n href=\"https://unpkg.com/@graphiql/plugin-explorer/dist/style.css\"\n />\n </head>\n\n <body>\n <div id=\"graphiql\">\n <div class=\"placeholder\">Loading GraphiQL...</div>\n </div>\n\n <script\n src=\"https://unpkg.com/graphiql@3/graphiql.min.js\"\n type=\"application/javascript\"\n crossorigin=\"anonymous\"\n ></script>\n <script\n src=\"https://unpkg.com/@graphiql/plugin-explorer/dist/index.umd.js\"\n type=\"application/javascript\"\n crossorigin=\"anonymous\"\n ></script>\n\n <script>\n const windowUrl = new URL(document.URL);\n const startingSchemaKey =\n windowUrl.searchParams.get('schema') || 'storefront';\n\n let query = '{ shop { name } }';\n if (windowUrl.searchParams.has('query')) {\n query = decodeURIComponent(\n windowUrl.searchParams.get('query') ?? query,\n );\n }\n\n // Prettify query\n query = GraphiQL.GraphQL.print(GraphiQL.GraphQL.parse(query));\n\n let variables;\n if (windowUrl.searchParams.has('variables')) {\n variables = decodeURIComponent(\n windowUrl.searchParams.get('variables') ?? '',\n );\n }\n\n // Prettify variables\n if (variables) {\n variables = JSON.stringify(JSON.parse(variables), null, 2);\n }\n\n const schemas = ${JSON.stringify(schemas)};\n let lastActiveTabIndex = -1;\n let lastTabAmount = -1;\n\n const root = ReactDOM.createRoot(\n document.getElementById('graphiql'),\n );\n\n root.render(React.createElement(RootWrapper));\n\n const TAB_STATE_KEY = 'graphiql:tabState';\n const storage = {\n getTabState: () =>\n JSON.parse(localStorage.getItem(TAB_STATE_KEY)),\n setTabState: (state) =>\n localStorage.setItem(TAB_STATE_KEY, JSON.stringify(state)),\n };\n\n let nextSchemaKey;\n\n function RootWrapper() {\n const [activeSchema, setActiveSchema] =\n React.useState(startingSchemaKey);\n\n const schema = schemas[activeSchema];\n if (!schema) {\n throw new Error('No schema found for ' + activeSchema);\n }\n\n const keys = Object.keys(schemas);\n\n return React.createElement(\n GraphiQL,\n {\n fetcher: GraphiQL.createFetcher({\n url: schema.apiUrl,\n headers: {[schema.authHeader]: schema.accessToken},\n }),\n defaultEditorToolsVisibility: true,\n query,\n variables,\n schema: schema.value,\n plugins: [GraphiQLPluginExplorer.explorerPlugin()],\n onTabChange: (state) => {\n const {activeTabIndex, tabs} = state;\n const activeTab = tabs[activeTabIndex];\n\n if (\n activeTabIndex === lastActiveTabIndex &&\n lastTabAmount === tabs.length\n ) {\n if (\n nextSchemaKey &&\n activeTab &&\n activeTab.schemaKey !== nextSchemaKey\n ) {\n activeTab.schemaKey = nextSchemaKey;\n nextSchemaKey = undefined;\n\n // Sync state to localStorage. GraphiQL resets the state\n // asynchronously, so we need to do it in a timeout.\n storage.setTabState(state);\n setTimeout(() => storage.setTabState(state), 500);\n }\n\n // React rerrendering, skip\n return;\n }\n\n if (activeTab) {\n if (!activeTab.schemaKey) {\n // Creating a new tab\n if (lastTabAmount < tabs.length) {\n activeTab.schemaKey = activeSchema;\n storage.setTabState(state);\n }\n }\n\n const nextSchema = activeTab.schemaKey || 'storefront';\n\n if (nextSchema !== activeSchema) {\n setActiveSchema(nextSchema);\n }\n }\n\n lastActiveTabIndex = activeTabIndex;\n lastTabAmount = tabs.length;\n },\n toolbar: {\n additionalComponent: function () {\n const schema = schemas[activeSchema];\n\n return React.createElement(\n GraphiQL.React.ToolbarButton,\n {\n onClick: () => {\n const activeKeyIndex = keys.indexOf(activeSchema);\n nextSchemaKey =\n keys[(activeKeyIndex + 1) % keys.length];\n\n // This triggers onTabChange\n if (nextSchemaKey) setActiveSchema(nextSchemaKey);\n },\n label: 'Toggle between different API schemas',\n },\n React.createElement(\n 'div',\n {\n key: 'api-wrapper',\n className: 'graphiql-toolbar-icon',\n style: {position: 'relative', fontWeight: 'bolder'},\n },\n [\n React.createElement(\n 'div',\n {key: 'icon', style: {textAlign: 'center'}},\n [\n schema.icon,\n React.createElement(\n 'div',\n {\n key: 'icon-label',\n className: 'graphiql-api-toolbar-label',\n },\n 'API',\n ),\n ],\n ),\n ],\n ),\n );\n },\n },\n },\n [\n React.createElement(\n GraphiQL.Logo,\n {\n key: 'Logo replacement',\n },\n [\n React.createElement(\n 'div',\n {\n key: 'Logo wrapper',\n style: {display: 'flex', alignItems: 'center'},\n },\n [\n React.createElement(\n 'div',\n {\n key: 'api',\n className: 'graphiql-logo',\n style: {\n paddingRight: 0,\n whiteSpace: 'nowrap',\n },\n },\n [schema.name],\n ),\n React.createElement(GraphiQL.Logo, {key: 'logo'}),\n ],\n ),\n ],\n ),\n ],\n );\n }\n </script>\n </body>\n </html>\n `,\n {status: 200, headers: {'content-type': 'text/html'}},\n );\n};\n","import {createElement, Fragment, lazy, Suspense, useMemo} from 'react';\nimport {\n type Location,\n type Params,\n useLocation,\n useMatches,\n} from '@remix-run/react';\nimport {generateSeoTags, type SeoConfig} from './generate-seo-tags';\nimport {type Thing} from 'schema-dts';\n\nimport type {LoaderFunction, SerializeFrom} from '@remix-run/server-runtime';\n\nconst SeoLogger = lazy(() => import('./log-seo-tags'));\n\nexport interface SeoHandleFunction<\n Loader extends LoaderFunction | unknown = unknown,\n StructuredDataSchema extends Thing = Thing,\n> {\n (args: {\n data: Loader extends LoaderFunction ? SerializeFrom<Loader> : unknown;\n id: string;\n params: Params;\n pathname: Location['pathname'];\n search: Location['search'];\n hash: Location['hash'];\n key: string;\n }): Partial<SeoConfig<StructuredDataSchema>>;\n}\n\ninterface SeoProps {\n /** Enable debug mode that prints SEO properties for route in the console */\n debug?: boolean;\n}\n\ntype SeoWrapper = undefined | {seo: any};\n\nexport function Seo({debug}: SeoProps) {\n const matches = useMatches();\n const location = useLocation();\n\n // Capture the seo and jsonLd configs from the route matches\n const seoConfig = useMemo(() => {\n return (\n matches\n .flatMap((match) => {\n const {handle, ...routeMatch} = match;\n const routeData = {...routeMatch, ...location};\n const handleSeo = (handle as SeoWrapper)?.seo;\n const loaderSeo = (routeMatch?.data as SeoWrapper)?.seo;\n\n if (!handleSeo && !loaderSeo) {\n return [];\n }\n\n // if seo is defined in the handle, invoke it with the route data\n if (handleSeo) {\n return recursivelyInvokeOrReturn(handleSeo, routeData);\n } else {\n return [loaderSeo];\n }\n })\n // merge route seo (priority) with the root seo if both are present\n // jsonLd definitions are instead concatenated because there can be\n // multiple jsonLd tags on any given root+route. e.g root renders Organization\n // schema and a product page renders Product schema\n .reduce((acc, current) => {\n // remove seo properties with falsy values\n Object.keys(current).forEach(\n (key) => !current[key] && delete current[key],\n );\n\n const {jsonLd} = current;\n\n if (!jsonLd) {\n return {...acc, ...current};\n }\n\n // concatenate jsonLds if present\n if (!acc?.jsonLd) {\n return {...acc, ...current, jsonLd: [jsonLd]};\n } else {\n if (Array.isArray(jsonLd)) {\n return {\n ...acc,\n ...current,\n jsonLd: [...acc.jsonLd, ...jsonLd],\n };\n } else {\n return {\n ...acc,\n ...current,\n jsonLd: [...acc.jsonLd, jsonLd],\n };\n }\n }\n }, {} as SeoConfig<Thing>)\n );\n }, [matches, location]);\n\n // Generate seo and jsonLd tags from the route seo configs\n // and return the jsx elements as html\n const {html, loggerMarkup} = useMemo(() => {\n const headTags = generateSeoTags(seoConfig);\n const html = headTags.map((tag) => {\n if (tag.tag === 'script') {\n return createElement(tag.tag, {\n ...tag.props,\n key: tag.key,\n dangerouslySetInnerHTML: {__html: tag.children},\n });\n }\n\n return createElement(tag.tag, {...tag.props, key: tag.key}, tag.children);\n });\n\n const loggerMarkup = createElement(\n Suspense,\n {fallback: null},\n createElement(SeoLogger, {headTags}),\n );\n\n return {html, loggerMarkup};\n }, [seoConfig]);\n\n return createElement(Fragment, null, html, debug && loggerMarkup);\n}\n\n/**\n * Recursively invoke a function or return the value\n * @param value\n * @param rest\n * @returns\n */\nexport function recursivelyInvokeOrReturn<T, R extends any[]>(\n value: T | ((...rest: R) => T),\n ...rest: R\n): T | Record<string, T> {\n if (value instanceof Function) {\n return recursivelyInvokeOrReturn<T, R>(value(...rest), ...rest);\n }\n\n let result: Record<string, T> = {};\n\n if (Array.isArray(value)) {\n result = value.reduce((acc, item) => {\n return [...acc, recursivelyInvokeOrReturn(item)];\n }, []);\n\n return result;\n }\n\n if (value instanceof Object) {\n const entries = Object.entries(value);\n\n entries.forEach(([key, val]) => {\n // @ts-expect-error\n result[key] = recursivelyInvokeOrReturn<T, R>(val, ...rest);\n });\n\n return result;\n }\n\n return value;\n}\n","// This is taken from remix: https://github.com/remix-run/remix/blob/main/packages/remix-server-runtime/markup.ts\n\nconst ESCAPE_LOOKUP: {[match: string]: string} = {\n '&': '\\\\u0026',\n '>': '\\\\u003e',\n '<': '\\\\u003c',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n};\n\nconst ESCAPE_REGEX = /[&><\\u2028\\u2029]/g;\n\nexport function escapeHtml(html: string) {\n return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);\n}\n","import type {ComponentPropsWithoutRef} from 'react';\nimport type {Maybe} from '@shopify/hydrogen-react/storefront-api-types';\nimport type {Thing, WithContext} from 'schema-dts';\nimport {escapeHtml} from './escape';\n\nconst ERROR_PREFIX = 'Error in SEO input: ';\n\n// TODO: Refactor this into more reusable validators or use a library like zod to do this if we decide to use it in\n// other places. @cartogram\nexport const schema = {\n title: {\n validate: <T>(value: Maybe<T>): NonNullable<T> => {\n if (typeof value !== 'string') {\n throw new Error(ERROR_PREFIX.concat('`title` should be a string'));\n }\n\n if (typeof value === 'string' && value.length > 120) {\n throw new Error(\n ERROR_PREFIX.concat(\n '`title` should not be longer than 120 characters',\n ),\n );\n }\n\n return value;\n },\n },\n description: {\n validate: <T>(value: Maybe<T>): NonNullable<T> => {\n if (typeof value !== 'string') {\n throw new Error(\n ERROR_PREFIX.concat('`description` should be a string'),\n );\n }\n\n if (typeof value === 'string' && value.length > 155) {\n throw new Error(\n ERROR_PREFIX.concat(\n '`description` should not be longer than 155 characters',\n ),\n );\n }\n\n return value;\n },\n },\n url: {\n validate: <T>(value: Maybe<T>): NonNullable<T> => {\n if (typeof value !== 'string') {\n throw new Error(ERROR_PREFIX.concat('`url` should be a string'));\n }\n\n if (typeof value === 'string' && !value.startsWith('http')) {\n throw new Error(ERROR_PREFIX.concat('`url` should be a valid URL'));\n }\n\n return value;\n },\n },\n handle: {\n validate: <T>(value: Maybe<T>): NonNullable<T> => {\n if (typeof value !== 'string') {\n throw new Error(ERROR_PREFIX.concat('`handle` should be a string'));\n }\n\n if (typeof value === 'string' && !value.startsWith('@')) {\n throw new Error(ERROR_PREFIX.concat('`handle` should start with `@`'));\n }\n\n return value;\n },\n },\n};\n\nexport interface SeoConfig<Schema extends Thing = Thing> {\n /**\n * The <title> HTML element defines the document's title that is shown in a browser's title bar or a page's tab. It\n * only contains text; tags within the element are ignored.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title\n */\n title?: Maybe<string>;\n /**\n * Generate the title from a template that includes a `%s` placeholder for the title.\n *\n * @example\n * ```js\n * {\n * title: 'My Page',\n * titleTemplate: 'My Site - %s',\n * }\n * ```\n */\n titleTemplate?: Maybe<string> | null;\n /**\n * The media associated with the given page (images, videos, etc). If you pass a string, it will be used as the\n * `og:image` meta tag. If you pass an object or an array of objects, that will be used to generate `og:<type of\n * media>` meta tags. The `url` property should be the URL of the media. The `height` and `width` properties are\n * optional and should be the height and width of the media. The `altText` property is optional and should be a\n * description of the media.\n *\n * @example\n * ```js\n * {\n * media: [\n * {\n * url: 'https://example.com/image.jpg',\n * type: 'image',\n * height: '400',\n * width: '400',\n * altText: 'A custom snowboard with an alpine color pallet.',\n * }\n * ]\n * }\n * ```\n *\n */\n media?:\n | Maybe<string>\n | Partial<SeoMedia>\n | (Partial<SeoMedia> | Maybe<string>)[];\n /**\n * The description of the page. This is used in the `name=\"description\"` meta tag as well as the `og:description` meta\n * tag.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta\n */\n description?: Maybe<string>;\n /**\n * The canonical URL of the page. This is used to tell search engines which URL is the canonical version of a page.\n * This is useful when you have multiple URLs that point to the same page. The value here will be used in the\n * `rel=\"canonical\"` link tag as well as the `og:url` meta tag.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link\n */\n url?: Maybe<string>;\n /**\n * The handle is used to generate the `twitter:site` and `twitter:creator` meta tags. Include the `@` symbol in the\n * handle.\n *\n * @example\n * ```js\n * {\n * handle: '@shopify'\n * }\n * ```\n */\n handle?: Maybe<string>;\n /**\n * The `jsonLd` property is used to generate the `application/ld+json` script tag. This is used to provide structured\n * data to search engines. The value should be an object that conforms to the schema.org spec. The `type` property\n * should be the type of schema you are using. The `type` property is required and should be one of the following:\n *\n * - `Product`\n * - `ItemList`\n * - `Organization`\n * - `WebSite`\n * - `WebPage`\n * - `BlogPosting`\n * - `Thing`\n *\n * @example\n * ```js\n * {\n * jsonLd: {\n * '@context': 'https://schema.org',\n * '@type': 'Product',\n * name: 'My Product',\n * image: 'https://hydrogen.shop/image.jpg',\n * description: 'A product that is great',\n * sku: '12345',\n * mpn: '12345',\n * brand: {\n * '@type': 'Thing',\n * name: 'My Brand',\n * },\n * aggregateRating: {\n * '@type': 'AggregateRating',\n * ratingValue: '4.5',\n * reviewCount: '100',\n * },\n * offers: {\n * '@type': 'Offer',\n * priceCurrency: 'USD',\n * price: '100',\n * priceValidUntil: '2020-11-05',\n * itemCondition: 'https://schema.org/NewCondition',\n * availability: 'https://schema.org/InStock',\n * seller: {\n * '@type': 'Organization',\n * name: 'My Brand',\n * },\n * },\n * }\n * }\n * ```\n *\n * @see https://schema.org/docs/schemas.html\n * @see https://developers.google.com/search/docs/guides/intro-structured-data\n * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script\n *\n */\n jsonLd?: WithContext<Schema> | WithContext<Schema>[];\n /**\n * The `alternates` property is used to specify the language and geographical targeting when you have multiple\n * versions of the same page in different languages. The `url` property tells search engines about these variations\n * and helps them to serve the correct version to their users.\n *\n * @example\n * ```js\n * {\n * alternates: [\n * {\n * language: 'en-US',\n * url: 'https://hydrogen.shop/en-us',\n * default: true,\n * },\n * {\n * language: 'fr-CA',\n * url: 'https://hydrogen.shop/fr-ca',\n * },\n * ]\n * }\n * ```\n *\n * @see https://support.google.com/webmasters/answer/189077?hl=en\n */\n alternates?: LanguageAlternate | LanguageAlternate[];\n /**\n * The `robots` property is used to specify the robots meta tag. This is used to tell search engines which pages\n * should be indexed and which should not.\n *\n * @see https://developers.google.com/search/reference/robots_meta_tag\n */\n robots?: RobotsOptions;\n}\n\n/**\n * @see https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag\n */\nexport interface RobotsOptions {\n /**\n * Set the maximum size of an image preview for this page in a search results Can be one of the following:\n *\n * - `none` - No image preview is to be shown.\n * - `standard` - A default image preview may be shown.\n * - `large` - A larger image preview, up to the width of the viewport, may be shown.\n *\n * If no value is specified a default image preview size is used.\n */\n maxImagePreview?: 'none' | 'standard' | 'large';\n /**\n * A number representing the maximum of amount characters to use as a textual snippet for a search result. This value\n * can also be set to one of the following special values:\n *\n * - 0 - No snippet is to be shown. Equivalent to nosnippet.\n * - 1 - The Search engine will choose the snippet length that it believes is most effective to help users discover\n * your content and direct users to your site\n * - -1 - No limit on the number of characters that can be shown in the snippet.\n */\n maxSnippet?: number;\n /**\n * The maximum number of seconds for videos on this page to show in search results. This value can also be set to one\n * of the following special values:\n *\n * - 0 - A static image may be used with the `maxImagePreview` setting.\n * - 1 - There is no limit to the size of the video preview.\n *\n * This applies to all forms of search results (at Google: web search, Google Images, Google Videos, Discover,\n * Assistant).\n */\n maxVideoPreview?: number;\n /**\n * Do not show a cached link in search results.\n */\n noArchive?: boolean;\n /**\n * Do not follow the links on this page.\n *\n * @see https://developers.google.com/search/docs/advanced/guidelines/qualify-outbound-links\n */\n noFollow?: boolean;\n /**\n * Do not index images on this page.\n */\n noImageIndex?: boolean;\n /**\n * Do not show this page, media, or resource in search results.\n */\n noIndex?: boolean;\n /**\n * Do not show a text snippet or video preview in the search results for this page.\n */\n noSnippet?: boolean;\n /**\n * Do not offer translation of this page in search results.\n */\n noTranslate?: boolean;\n /**\n * Do not show this page in search results after the specified date/time.\n */\n unavailableAfter?: string;\n}\n\nexport interface LanguageAlternate {\n /**\n * Language code for the alternate page. This is used to generate the hreflang meta tag property.\n */\n language: string;\n /**\n * Whether the alternate page is the default page. This will add the `x-default` attribution to the language code.\n */\n default?: boolean;\n /**\n * The url of the alternate page. This is used to generate the hreflang meta tag property.\n */\n url: string;\n}\n\nexport type SeoMedia = {\n /**\n * Used to generate og:<type of media> meta tag\n */\n type: 'image' | 'video' | 'audio';\n /**\n * The url value populates both url and secure_url and is used to infer the og:<type of media>:type meta tag.\n */\n url: Maybe<string> | undefined;\n /**\n * The height in pixels of the media. This is used to generate the og:<type of media>:height meta tag.\n */\n height: Maybe<number> | undefined;\n /**\n * The width in pixels of the media. This is used to generate the og:<type of media>:width meta tag.\n */\n width: Maybe<number> | undefined;\n /**\n * The alt text for the media. This is used to generate the og:<type of media>:alt meta tag.\n */\n altText: Maybe<string> | undefined;\n};\n\ntype TagKey = 'title' | 'base' | 'meta' | 'link' | 'script';\n\nexport interface CustomHeadTagObject {\n tag: TagKey;\n props: Record<string, unknown>;\n children?: string;\n key: string;\n}\n\n/**\n * The `generateSeoTags` function generates the SEO title, meta, link and script (JSON Linking Data) tags for a page. It\n * pairs well with the SEO component in `@shopify/hydrogen` when building a Hydrogen Remix app, but can be used on its\n * own if you want to generate the tags yourself.\n */\nexport function generateSeoTags<\n Schema extends Thing,\n T extends SeoConfig<Schema> = SeoConfig<Schema>,\n>(seoInput: T): CustomHeadTagObject[] {\n const tagResults: CustomHeadTagObject[] = [];\n\n for (const seoKey of Object.keys(seoInput)) {\n switch (seoKey) {\n case 'title': {\n const content = validate(schema.title, seoInput.title);\n const title = renderTitle(seoInput?.titleTemplate, content);\n\n if (!title) {\n break;\n }\n\n tagResults.push(\n generateTag('title', {title}),\n generateTag('meta', {property: 'og:title', content: title}),\n generateTag('meta', {name: 'twitter:title', content: title}),\n );\n\n break;\n }\n\n case 'description': {\n const content = validate(schema.description, seoInput.description);\n\n if (!content) {\n break;\n }\n\n tagResults.push(\n generateTag('meta', {\n name: 'description',\n content,\n }),\n generateTag('meta', {\n property: 'og:description',\n content,\n }),\n generateTag('meta', {\n name: 'twitter:description',\n content,\n }),\n );\n\n break;\n }\n\n case 'url': {\n const content = validate(schema.url, seoInput.url);\n\n if (!content) {\n break;\n }\n\n const urlWithoutParams = content.split('?')[0];\n const urlWithoutTrailingSlash = urlWithoutParams.replace(/\\/$/, '');\n\n tagResults.push(\n generateTag('link', {\n rel: 'canonical',\n href: urlWithoutTrailingSlash,\n }),\n generateTag('meta', {\n property: 'og:url',\n content: urlWithoutTrailingSlash,\n }),\n );\n\n break;\n }\n\n case 'handle': {\n const content = validate(schema.handle, seoInput.handle);\n\n if (!content) {\n break;\n }\n\n tagResults.push(\n generateTag('meta', {name: 'twitter:site', content}),\n generateTag('meta', {name: 'twitter:creator', content}),\n );\n\n break;\n }\n\n case 'media': {\n let content;\n const values = ensureArray(seoInput.media);\n\n for (const media of values) {\n if (typeof media === 'string') {\n tagResults.push(\n generateTag('meta', {name: 'og:image', content: media}),\n );\n }\n\n if (media && typeof media === 'object') {\n const type = media.type || 'image';\n\n // Order matters here when adding multiple media tags @see https://ogp.me/#array\n const normalizedMedia = media\n ? {\n url: media?.url,\n secure_url: media?.url,\n type: inferMimeType(media.url),\n width: media?.width,\n height: media?.height,\n alt: media?.altText,\n }\n : {};\n\n for (const key of Object.keys(normalizedMedia)) {\n if (normalizedMedia[key as keyof typeof normalizedMedia]) {\n content = normalizedMedia[\n key as keyof typeof normalizedMedia\n ] as string;\n\n tagResults.push(\n generateTag(\n 'meta',\n {\n property: `og:${type}:${key}`,\n content,\n },\n normalizedMedia.url as string,\n ),\n );\n }\n }\n }\n }\n break;\n }\n\n case 'jsonLd': {\n const jsonLdBlocks = ensureArray(seoInput.jsonLd);\n let index = 0;\n for (const block of jsonLdBlocks) {\n if (typeof block !== 'object') {\n continue;\n }\n\n const tag = generateTag(\n 'script',\n {\n type: 'application/ld+json',\n children: JSON.stringify(block, (k, value) => {\n return typeof value === 'string' ? escapeHtml(value) : value;\n }),\n },\n // @ts-expect-error\n `json-ld-${block?.['@type'] || block?.name || index++}`,\n );\n\n tagResults.push(tag);\n }\n\n break;\n }\n\n case 'alternates': {\n const alternates = ensureArray(seoInput.alternates);\n\n for (const alternate of alternates) {\n if (!alternate) {\n continue;\n }\n\n const {language, url, default: defaultLang} = alternate;\n\n const hrefLang = language\n ? `${language}${defaultLang ? '-default' : ''}`\n : undefined;\n\n tagResults.push(\n generateTag('link', {\n rel: 'alternate',\n hrefLang,\n href: url,\n }),\n );\n }\n\n break;\n }\n\n case 'robots': {\n if (!seoInput.robots) {\n break;\n }\n\n const {\n maxImagePreview,\n maxSnippet,\n maxVideoPreview,\n noArchive,\n noFollow,\n noImageIndex,\n noIndex,\n noSnippet,\n noTranslate,\n unavailableAfter,\n } = seoInput.robots;\n\n const robotsParams = [\n noArchive && 'noarchive',\n noImageIndex && 'noimageindex',\n noSnippet && 'nosnippet',\n noTranslate && `notranslate`,\n maxImagePreview && `max-image-preview:${maxImagePreview}`,\n maxSnippet && `max-snippet:${maxSnippet}`,\n maxVideoPreview && `max-video-preview:${maxVideoPreview}`,\n unavailableAfter && `unavailable_after:${unavailableAfter}`,\n ];\n\n let robotsParam =\n (noIndex ? 'noindex' : 'index') +\n ',' +\n (noFollow ? 'nofollow' : 'follow');\n\n for (let param of robotsParams) {\n if (param) {\n robotsParam += `,${param}`;\n }\n }\n\n tagResults.push(\n generateTag('meta', {name: 'robots', content: robotsParam}),\n );\n\n break;\n }\n\n default: {\n // TODO: We should be able to catch unaccounted for keys at compile time\n // let exhaustiveCheck: never = seoKey;\n\n break;\n }\n }\n }\n\n return tagResults.flat().sort((a, b) => a.key.localeCompare(b.key));\n}\n\nexport function generateTag<T extends TagKey>(\n tagName: T,\n input: ComponentPropsWithoutRef<T>,\n group?: string,\n): CustomHeadTagObject {\n const tag: CustomHeadTagObject = {tag: tagName, props: {}, key: ''};\n\n // title tags don't have props so move to children\n if (tagName === 'title') {\n tag.children = input.title as string;\n tag.key = generateKey(tag);\n\n return tag;\n }\n\n // also move the input children to children and delete it\n if (tagName === 'script') {\n tag.children = typeof input.children === 'string' ? input.children : '';\n tag.key = generateKey(tag, group);\n delete input.children;\n tag.props = input;\n return tag;\n }\n\n // the rest goes on props\n tag.props = input;\n\n // remove empty props\n Object.keys(tag.props).forEach(\n (key) => !tag.props[key] && delete tag.props[key],\n );\n\n tag.key = generateKey(tag, group);\n\n return tag;\n}\n\n//**\n// * Generate a unique key for a tag\n// * @param tag - a generated tag object\n// * @param group? - the group the tag belongs to\n// * @returns - a unique key to be used for react\n// */\nexport function generateKey(tag: CustomHeadTagObject, group?: string) {\n const {tag: tagName, props} = tag;\n\n if (tagName === 'title') {\n // leading 0 moves title to the top when sorting\n return '0-title';\n }\n\n if (tagName === 'meta') {\n // leading 0 moves meta to the top when sorting exclude secure_url from the logic because the content is the same as\n // url\n const priority =\n props.content === group &&\n typeof props.property === 'string' &&\n !props.property.endsWith('secure_url') &&\n '0';\n const groupName = [group, priority];\n\n return [tagName, ...groupName, props.property || props.name]\n .filter((x) => x)\n .join('-');\n }\n\n if (tagName === 'link') {\n const key = [tagName, props.rel, props.hrefLang || props.media]\n .filter((x) => x)\n .join('-');\n\n // replace spaces with dashes, needed for media prop\n return key.replace(/\\s+/g, '-');\n }\n\n if (tagName === 'script') {\n return `${tagName}-${group}`;\n }\n\n return `${tagName}-${props.type}`;\n}\n\nfunction renderTitle<T extends CustomHeadTagObject['children']>(\n template?:\n | string\n | ((title: string) => string | undefined)\n | undefined\n | null,\n title?: T | null,\n): string | undefined {\n if (!title) {\n return undefined;\n }\n\n if (!template) {\n return title;\n }\n\n if (typeof template === 'function') {\n return template(title);\n }\n\n return template.replace('%s', title ?? '');\n}\n\nfunction inferMimeType(url: Maybe<string> | undefined) {\n const ext = url && url.split('.').pop();\n\n switch (ext) {\n case 'svg':\n return 'image/svg+xml';\n case 'png':\n return 'image/png';\n case 'gif':\n return 'image/gif';\n case 'swf':\n return 'application/x-shockwave-flash';\n case 'mp3':\n return 'audio/mpeg';\n case 'jpg':\n case 'jpeg':\n default:\n return 'image/jpeg';\n }\n}\n\nexport type SchemaType =\n | 'Product'\n | 'ItemList'\n | 'Organization'\n | 'WebSite'\n | 'WebPage'\n | 'BlogPosting'\n | 'Thing';\n\nfunction ensureArray<T>(value: T | T[]): T[] {\n return Array.isArray(value) ? value : [value];\n}\n\nfunction validate<T>(\n schema: {validate: <T>(data: T) => NonNullable<T>},\n data: T,\n): T {\n try {\n return schema.validate<T>(data);\n } catch (error: unknown) {\n console.warn((error as Error).message);\n return data;\n }\n}\n","import {\n createElement,\n useEffect,\n useMemo,\n useRef,\n forwardRef,\n type Ref,\n type FC,\n} from 'react';\nimport type {\n Maybe,\n PageInfo,\n} from '@shopify/hydrogen-react/storefront-api-types';\nimport {flattenConnection} from '@shopify/hydrogen-react';\nimport {\n Link,\n type LinkProps,\n useNavigation,\n useLocation,\n useNavigate,\n} from '@remix-run/react';\n\ndeclare global {\n interface Window {\n // Use a global variable to keep track\n // of when the page finishes hydrating\n __hydrogenHydrated?: boolean;\n }\n}\n\ntype Connection<NodesType> =\n | {\n nodes: Array<NodesType>;\n pageInfo: PageInfo;\n }\n | {\n edges: Array<{\n node: NodesType;\n }>;\n pageInfo: PageInfo;\n };\n\ntype PaginationState<NodesType> = {\n nodes?: Array<NodesType>;\n pageInfo?: PageInfo | null;\n};\n\ninterface PaginationInfo<NodesType> {\n /** The paginated array of nodes. You should map over and render this array. */\n nodes: Array<NodesType>;\n /** The `<NextLink>` is a helper component that makes it easy to navigate to the next page of paginated data. Alternatively you can build your own `<Link>` component: `<Link to={nextPageUrl} state={state} preventScrollReset />` */\n NextLink: FC<Omit<LinkProps, 'to'> & {ref?: Ref<HTMLAnchorElement>}>;\n /** The `<PreviousLink>` is a helper component that makes it easy to navigate to the previous page of paginated data. Alternatively you can build your own `<Link>` component: `<Link to={previousPageUrl} state={state} preventScrollReset />` */\n PreviousLink: FC<Omit<LinkProps, 'to'> & {ref?: Ref<HTMLAnchorElement>}>;\n /** The URL to the previous page of paginated data. Use this prop to build your own `<Link>` component. */\n previousPageUrl: string;\n /** The URL to the next page of paginated data. Use this prop to build your own `<Link>` component. */\n nextPageUrl: string;\n /** True if the cursor has next paginated data */\n hasNextPage: boolean;\n /** True if the cursor has previous paginated data */\n hasPreviousPage: boolean;\n /** True if we are in the process of fetching another page of data */\n isLoading: boolean;\n /** The `state` property is important to use when building your own `<Link>` component if you want paginated data to continuously append to the page. This means that every time the user clicks \"Next page\", the next page of data will be apppended inline with the previous page. If you want the whole page to re-render with only the next page results, do not pass the `state` prop to the Remix `<Link>` component. */\n state: {\n nodes: Array<NodesType>;\n pageInfo: {\n endCursor: Maybe<string> | undefined;\n startCursor: Maybe<string> | undefined;\n hasPreviousPage: boolean;\n };\n };\n}\n\ntype PaginationProps<NodesType> = {\n /** The response from `storefront.query` for a paginated request. Make sure the query is passed pagination variables and that the query has `pageInfo` with `hasPreviousPage`, `hasNextpage`, `startCursor`, and `endCursor` defined. */\n connection: Connection<NodesType>;\n /** A render prop that includes pagination data and helpers. */\n children: PaginationRenderProp<NodesType>;\n};\n\ntype PaginationRenderProp<NodesType> = FC<PaginationInfo<NodesType>>;\n\n/**\n *\n * The [Storefront API uses cursors](https://shopify.dev/docs/api/usage/pagination-graphql) to paginate through lists of data\n * and the \\`<Pagination />\\` component makes it easy to paginate data from the Storefront API.\n *\n * @prop connection The response from `storefront.query` for a paginated request. Make sure the query is passed pagination variables and that the query has `pageInfo` with `hasPreviousPage`, `hasNextpage`, `startCursor`, and `endCursor` defined.\n * @prop children A render prop that includes pagination data and helpers.\n */\nexport function Pagination<NodesType>({\n connection,\n children = () => {\n console.warn('<Pagination> requires children to work properly');\n return null;\n },\n}: PaginationProps<NodesType>): ReturnType<FC> {\n const transition = useNavigation();\n const isLoading = transition.state === 'loading';\n const {\n endCursor,\n hasNextPage,\n hasPreviousPage,\n nextPageUrl,\n nodes,\n previousPageUrl,\n startCursor,\n } = usePagination<NodesType>(connection);\n\n const state = useMemo(\n () => ({\n pageInfo: {\n endCursor,\n hasPreviousPage,\n hasNextPage,\n startCursor,\n },\n nodes,\n }),\n [endCursor, hasNextPage, hasPreviousPage, startCursor, nodes],\n );\n\n const NextLink = useMemo(\n () =>\n forwardRef<HTMLAnchorElement, Omit<LinkProps, 'to'>>(function NextLink(\n props,\n ref,\n ) {\n return hasNextPage\n ? createElement(Link, {\n preventScrollReset: true,\n ...props,\n to: nextPageUrl,\n state,\n replace: true,\n ref,\n })\n : null;\n }),\n [hasNextPage, nextPageUrl, state],\n );\n\n const PreviousLink = useMemo(\n () =>\n forwardRef<HTMLAnchorElement, Omit<LinkProps, 'to'>>(function PrevLink(\n props,\n ref,\n ) {\n return hasPreviousPage\n ? createElement(Link, {\n preventScrollReset: true,\n ...props,\n to: previousPageUrl,\n state,\n replace: true,\n ref,\n })\n : null;\n }),\n [hasPreviousPage, previousPageUrl, state],\n );\n\n return children({\n state,\n hasNextPage,\n hasPreviousPage,\n isLoading,\n nextPageUrl,\n nodes,\n previousPageUrl,\n NextLink,\n PreviousLink,\n });\n}\n\nfunction getParamsWithoutPagination(paramsString?: string) {\n const params = new URLSearchParams(paramsString);\n params.delete('cursor');\n params.delete('direction');\n return params.toString();\n}\n\nfunction makeError(prop: string) {\n throw new Error(\n `The Pagination component requires ${\n '`' + prop + '`'\n } to be a part of your query. See the guide on how to setup your query to include ${\n '`' + prop + '`'\n }: https://shopify.dev/docs/custom-storefronts/hydrogen/data-fetching/pagination#setup-the-paginated-query`,\n );\n}\n\n/**\n * Get cumulative pagination logic for a given connection\n */\nexport function usePagination<NodesType>(\n connection: Connection<NodesType>,\n): Omit<\n PaginationInfo<NodesType>,\n 'isLoading' | 'state' | 'NextLink' | 'PreviousLink'\n> & {\n startCursor: Maybe<string> | undefined;\n endCursor: Maybe<string> | undefined;\n} {\n if (!connection.pageInfo) {\n makeError('pageInfo');\n }\n\n if (typeof connection.pageInfo.startCursor === 'undefined') {\n makeError('pageInfo.startCursor');\n }\n\n if (typeof connection.pageInfo.endCursor === 'undefined') {\n makeError('pageInfo.endCursor');\n }\n\n if (typeof connection.pageInfo.hasNextPage === 'undefined') {\n makeError('pageInfo.hasNextPage');\n }\n\n if (typeof connection.pageInfo.hasPreviousPage === 'undefined') {\n makeError('pageInfo.hasPreviousPage');\n }\n\n const navigate = useNavigate();\n const {state, search, pathname} = useLocation() as {\n state?: PaginationState<NodesType>;\n search?: string;\n pathname?: string;\n };\n\n const params = new URLSearchParams(search);\n const direction = params.get('direction');\n const isPrevious = direction === 'previous';\n\n const nodes = useMemo(() => {\n if (!globalThis?.window?.__hydrogenHydrated || !state || !state?.nodes) {\n return flattenConnection(connection);\n }\n\n if (isPrevious) {\n return [...flattenConnection(connection), ...state.nodes];\n } else {\n return [...state.nodes, ...flattenConnection(connection)];\n }\n }, [state, connection]);\n\n const currentPageInfo = useMemo(() => {\n const hydrogenHydrated = globalThis?.window?.__hydrogenHydrated;\n let pageStartCursor =\n !hydrogenHydrated || state?.pageInfo?.startCursor === undefined\n ? connection.pageInfo.startCursor\n : state.pageInfo.startCursor;\n\n let pageEndCursor =\n !hydrogenHydrated || state?.pageInfo?.endCursor === undefined\n ? connection.pageInfo.endCursor\n : state.pageInfo.endCursor;\n\n let previousPageExists =\n !hydrogenHydrated || state?.pageInfo?.hasPreviousPage === undefined\n ? connection.pageInfo.hasPreviousPage\n : state.pageInfo.hasPreviousPage;\n\n let nextPageExists =\n !hydrogenHydrated || state?.pageInfo?.hasNextPage === undefined\n ? connection.pageInfo.hasNextPage\n : state.pageInfo.hasNextPage;\n\n // if (!hydrogenHydrated) {\n if (state?.nodes) {\n if (isPrevious) {\n pageStartCursor = connection.pageInfo.startCursor;\n previousPageExists = connection.pageInfo.hasPreviousPage;\n } else {\n pageEndCursor = connection.pageInfo.endCursor;\n nextPageExists = connection.pageInfo.hasNextPage;\n }\n }\n // }\n\n return {\n startCursor: pageStartCursor,\n endCursor: pageEndCursor,\n hasPreviousPage: previousPageExists,\n hasNextPage: nextPageExists,\n };\n }, [\n isPrevious,\n state,\n connection.pageInfo.hasNextPage,\n connection.pageInfo.hasPreviousPage,\n connection.pageInfo.startCursor,\n connection.pageInfo.endCursor,\n ]);\n\n // Keep track of the current URL state, to compare whenever the URL changes\n const urlRef = useRef({\n params: getParamsWithoutPagination(search),\n pathname,\n });\n\n useEffect(() => {\n // Set a global variable to keep track of when the page finishes hydrating.\n // We can't use local state or a ref because it will be reset on soft navigations\n // to the page. This variable allows us to use the SSR'd data on the first render,\n // preventing hydration errors. On soft navigations, like browser back/forward\n // navigation, instead of using the SSR'd data, we use the data from location state.\n window.__hydrogenHydrated = true;\n }, []);\n\n useEffect(() => {\n if (\n // If the URL changes (independent of pagination params)\n // then reset the pagination params in the URL\n getParamsWithoutPagination(search) !== urlRef.current.params ||\n pathname !== urlRef.current.pathname\n ) {\n urlRef.current = {\n pathname,\n params: getParamsWithoutPagination(search),\n };\n navigate(`${pathname}?${getParamsWithoutPagination(search)}`, {\n replace: true,\n preventScrollReset: true,\n state: {nodes: undefined, pageInfo: undefined},\n });\n }\n }, [pathname, search]);\n\n const previousPageUrl = useMemo(() => {\n const params = new URLSearchParams(search);\n params.set('direction', 'previous');\n currentPageInfo.startCursor &&\n params.set('cursor', currentPageInfo.startCursor);\n return `?${params.toString()}`;\n }, [search, currentPageInfo.startCursor]);\n\n const nextPageUrl = useMemo(() => {\n const params = new URLSearchParams(search);\n params.set('direction', 'next');\n currentPageInfo.endCursor &&\n params.set('cursor', currentPageInfo.endCursor);\n return `?${params.toString()}`;\n }, [search, currentPageInfo.endCursor]);\n\n return {...currentPageInfo, previousPageUrl, nextPageUrl, nodes};\n}\n\n/**\n * @param request The request object passed to your Remix loader function.\n * @param options Options for how to configure the pagination variables. Includes the ability to change how many nodes are within each page.\n *\n * @returns Variables to be used with the `storefront.query` function\n */\nexport function getPaginationVariables(\n request: Request,\n options: {pageBy: number} = {pageBy: 20},\n) {\n if (typeof request?.url === 'undefined') {\n throw new Error(\n 'getPaginationVariables must be called with the Request object passed to your loader function',\n );\n }\n\n const {pageBy} = options;\n const searchParams = new URLSearchParams(new URL(request.url).search);\n\n const cursor = searchParams.get('cursor') ?? undefined;\n const direction =\n searchParams.get('direction') === 'previous' ? 'previous' : 'next';\n const isPrevious = direction === 'previous';\n\n const prevPage = {\n last: pageBy,\n startCursor: cursor ?? null,\n };\n\n const nextPage = {\n first: pageBy,\n endCursor: cursor ?? null,\n };\n\n const variables = isPrevious ? prevPage : nextPage;\n\n return variables;\n}\n","import {LIB_VERSION} from '../version';\n\nexport const DEFAULT_CUSTOMER_API_VERSION = '2024-01';\nexport const USER_AGENT = `Shopify Hydrogen ${LIB_VERSION}`;\nexport const CUSTOMER_API_CLIENT_ID = '30243aa5-17c1-465a-8493-944bcc4e88aa';\nexport const CUSTOMER_ACCOUNT_SESSION_KEY = 'customerAccount';\n","export class BadRequest extends Response {\n constructor(message?: string, helpMessage?: string, headers?: HeadersInit) {\n // A lot of things can go wrong when configuring the customer account api\n // oauth flow. In dev mode, log a helper message.\n if (helpMessage && process.env.NODE_ENV === 'development') {\n console.error('Customer Account API Error: ' + helpMessage);\n }\n\n super(`Bad request: ${message}`, {status: 400, headers});\n }\n}\n","import type {HydrogenSession} from '../hydrogen';\nimport {BadRequest} from './BadRequest';\nimport {\n USER_AGENT,\n CUSTOMER_API_CLIENT_ID,\n CUSTOMER_ACCOUNT_SESSION_KEY,\n} from './constants';\n\ntype H2OEvent = Parameters<NonNullable<typeof __H2O_LOG_EVENT>>[0];\n\nexport interface Locks {\n refresh?: Promise<any>;\n}\n\nexport const logSubRequestEvent =\n process.env.NODE_ENV === 'development'\n ? ({\n url,\n response,\n startTime,\n query,\n variables,\n ...debugInfo\n }: {\n url: H2OEvent['url'];\n response: Response;\n startTime: H2OEvent['startTime'];\n query?: string;\n variables?: Record<string, any> | null;\n } & Partial<H2OEvent>) => {\n globalThis.__H2O_LOG_EVENT?.({\n ...debugInfo,\n eventType: 'subrequest',\n url,\n startTime,\n graphql: query\n ? JSON.stringify({query, variables, schema: 'customer-account'})\n : undefined,\n responseInit: {\n status: response.status || 0,\n statusText: response.statusText || '',\n headers: Array.from(response.headers.entries() || []),\n },\n });\n }\n : undefined;\n\nexport function redirect(\n path: string,\n options: {status?: number; headers?: {}} = {},\n) {\n const headers = options.headers\n ? new Headers(options.headers)\n : new Headers({});\n headers.set('location', path);\n\n return new Response(null, {status: options.status || 302, headers});\n}\n\nexport interface AccessTokenResponse {\n access_token: string;\n expires_in: number;\n id_token: string;\n refresh_token: string;\n error?: string;\n error_description?: string;\n}\n\nexport async function refreshToken({\n session,\n customerAccountId,\n customerAccountUrl,\n origin,\n debugInfo,\n}: {\n session: HydrogenSession;\n customerAccountId: string;\n customerAccountUrl: string;\n origin: string;\n debugInfo?: Partial<H2OEvent>;\n}) {\n const newBody = new URLSearchParams();\n\n const customerAccount = session.get(CUSTOMER_ACCOUNT_SESSION_KEY);\n const refreshToken = customerAccount?.refreshToken;\n\n if (!refreshToken)\n throw new BadRequest(\n 'Unauthorized',\n 'No refreshToken found in the session. Make sure your session is configured correctly and passed to `createCustomerAccountClient`.',\n );\n\n newBody.append('grant_type', 'refresh_token');\n newBody.append('refresh_token', refreshToken);\n newBody.append('client_id', customerAccountId);\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n 'User-Agent': USER_AGENT,\n Origin: origin,\n };\n\n const startTime = new Date().getTime();\n const url = `${customerAccountUrl}/auth/oauth/token`;\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: newBody,\n });\n\n logSubRequestEvent?.({\n displayName: 'Customer Account API: access token refresh',\n url,\n startTime,\n response,\n ...debugInfo,\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Response(text, {\n status: response.status,\n headers: {\n 'Content-Type': 'text/html; charset=utf-8',\n },\n });\n }\n\n const {access_token, expires_in, id_token, refresh_token} =\n await response.json<AccessTokenResponse>();\n\n const accessToken = await exchangeAccessToken(\n access_token,\n customerAccountId,\n customerAccountUrl,\n origin,\n debugInfo,\n );\n\n session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {\n accessToken,\n // Store the date in future the token expires, separated by two minutes\n expiresAt:\n new Date(new Date().getTime() + (expires_in - 120) * 1000).getTime() + '',\n refreshToken: refresh_token,\n idToken: id_token,\n });\n}\n\nexport function clearSession(session: HydrogenSession): void {\n session.unset(CUSTOMER_ACCOUNT_SESSION_KEY);\n}\n\nexport async function checkExpires({\n locks,\n expiresAt,\n session,\n customerAccountId,\n customerAccountUrl,\n origin,\n debugInfo,\n}: {\n locks: Locks;\n expiresAt: string;\n session: HydrogenSession;\n customerAccountId: string;\n customerAccountUrl: string;\n origin: string;\n debugInfo?: Partial<H2OEvent>;\n}) {\n if (parseInt(expiresAt, 10) - 1000 < new Date().getTime()) {\n try {\n // Makes sure that only one refresh request is sent at a time\n if (!locks.refresh)\n locks.refresh = refreshToken({\n session,\n customerAccountId,\n customerAccountUrl,\n origin,\n debugInfo,\n });\n\n await locks.refresh;\n delete locks.refresh;\n } catch (error) {\n clearSession(session);\n\n if (error && (error as Response).status !== 401) {\n throw error;\n } else {\n throw new BadRequest(\n 'Unauthorized',\n 'Login before querying the Customer Account API.',\n {\n 'Set-Cookie': await session.commit(),\n },\n );\n }\n }\n }\n}\n\nexport async function generateCodeVerifier() {\n const rando = generateRandomCode();\n return base64UrlEncode(rando);\n}\n\nexport async function generateCodeChallenge(codeVerifier: string) {\n const digestOp = await crypto.subtle.digest(\n {name: 'SHA-256'},\n new TextEncoder().encode(codeVerifier),\n );\n const hash = convertBufferToString(digestOp);\n return base64UrlEncode(hash);\n}\n\nexport function generateRandomCode() {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return String.fromCharCode.apply(null, Array.from(array));\n}\n\nfunction base64UrlEncode(str: string) {\n const base64 = btoa(str);\n // This is to ensure that the encoding does not have +, /, or = characters in it.\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nfunction convertBufferToString(hash: ArrayBuffer) {\n const uintArray = new Uint8Array(hash);\n const numberArray = Array.from(uintArray);\n return String.fromCharCode(...numberArray);\n}\n\nexport async function generateState(): Promise<string> {\n const timestamp = Date.now().toString();\n const randomString = Math.random().toString(36).substring(2);\n return timestamp + randomString;\n}\n\nexport async function exchangeAccessToken(\n authAccessToken: string | undefined,\n customerAccountId: string,\n customerAccountUrl: string,\n origin: string,\n debugInfo?: Partial<H2OEvent>,\n) {\n const clientId = customerAccountId;\n\n if (!authAccessToken)\n throw new BadRequest(\n 'Unauthorized',\n 'oAuth access token was not provided during token exchange.',\n );\n\n const body = new URLSearchParams();\n\n body.append('grant_type', 'urn:ietf:params:oauth:grant-type:token-exchange');\n body.append('client_id', clientId);\n body.append('audience', CUSTOMER_API_CLIENT_ID);\n body.append('subject_token', authAccessToken);\n body.append(\n 'subject_token_type',\n 'urn:ietf:params:oauth:token-type:access_token',\n );\n body.append('scopes', 'https://api.customers.com/auth/customer.graphql');\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n 'User-Agent': USER_AGENT,\n Origin: origin,\n };\n\n const startTime = new Date().getTime();\n const url = `${customerAccountUrl}/auth/oauth/token`;\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body,\n });\n\n logSubRequestEvent?.({\n displayName: 'Customer Account API: access token exchange',\n url,\n startTime,\n response,\n ...debugInfo,\n });\n\n const data = await response.json<AccessTokenResponse>();\n\n if (data.error) {\n throw new BadRequest(data.error_description);\n }\n\n return data.access_token;\n}\n\nexport function getNonce(token: string) {\n return decodeJwt(token).payload.nonce;\n}\n\nfunction decodeJwt(token: string) {\n const [header, payload, signature] = token.split('.');\n\n const decodedHeader = JSON.parse(atob(header));\n const decodedPayload = JSON.parse(atob(payload));\n\n return {\n header: decodedHeader,\n payload: decodedPayload,\n signature,\n };\n}\n","export function generateNonce(): string {\n return toHexString(randomUint8Array());\n}\n\nfunction randomUint8Array() {\n try {\n return crypto.getRandomValues(new Uint8Array(16));\n } catch (e) {\n return new Uint8Array(16).map(() => (Math.random() * 255) | 0);\n }\n}\n\nfunction toHexString(byteArray: Uint8Array) {\n return Array.from(byteArray, function (byte) {\n return ('0' + (byte & 0xff).toString(16)).slice(-2);\n }).join('');\n}\n","import type {GenericVariables} from '@shopify/hydrogen-codegen';\nimport type {WritableDeep} from 'type-fest';\nimport {\n DEFAULT_CUSTOMER_API_VERSION,\n CUSTOMER_ACCOUNT_SESSION_KEY,\n USER_AGENT,\n} from './constants';\nimport {\n clearSession,\n generateCodeChallenge,\n generateCodeVerifier,\n generateState,\n checkExpires,\n exchangeAccessToken,\n AccessTokenResponse,\n getNonce,\n redirect,\n Locks,\n logSubRequestEvent,\n} from './auth.helpers';\nimport {BadRequest} from './BadRequest';\nimport {generateNonce} from '../csp/nonce';\nimport {\n minifyQuery,\n assertQuery,\n assertMutation,\n throwErrorWithGqlLink,\n type GraphQLErrorOptions,\n GraphQLError,\n} from '../utils/graphql';\nimport {parseJSON} from '../utils/parse-json';\nimport {\n CrossRuntimeRequest,\n getHeader,\n getDebugHeaders,\n} from '../utils/request';\nimport {getCallerStackLine, withSyncStack} from '../utils/callsites';\nimport {getRedirectUrl} from '../utils/get-redirect-url';\nimport type {\n CustomerAccountOptions,\n CustomerAccount,\n CustomerAPIResponse,\n} from './types';\n\nconst DEFAULT_LOGIN_URL = '/account/login';\nconst DEFAULT_AUTH_URL = '/account/authorize';\nconst DEFAULT_REDIRECT_PATH = '/account';\n\nfunction defaultAuthStatusHandler(request: CrossRuntimeRequest) {\n if (!request.url) return DEFAULT_LOGIN_URL;\n\n const {pathname} = new URL(request.url);\n\n const redirectTo =\n DEFAULT_LOGIN_URL +\n `?${new URLSearchParams({return_to: pathname}).toString()}`;\n\n return redirect(redirectTo);\n}\n\nexport function createCustomerAccountClient({\n session,\n customerAccountId,\n customerAccountUrl,\n customerApiVersion = DEFAULT_CUSTOMER_API_VERSION,\n request,\n waitUntil,\n authUrl = DEFAULT_AUTH_URL,\n customAuthStatusHandler,\n logErrors = true,\n}: CustomerAccountOptions): CustomerAccount {\n if (customerApiVersion !== DEFAULT_CUSTOMER_API_VERSION) {\n console.warn(\n `[h2:warn:createCustomerAccountClient] You are using Customer Account API version ${customerApiVersion} when this version of Hydrogen was built for ${DEFAULT_CUSTOMER_API_VERSION}.`,\n );\n }\n\n if (!customerAccountId || !customerAccountUrl) {\n console.warn(\n \"[h2:warn:createCustomerAccountClient] `customerAccountId` and `customerAccountUrl` need to be provided to use Customer Account API. Mock.shop doesn't automatically supply these variables.\\nUse `npx shopify hydrogen env pull` to link your store credentials.\",\n );\n }\n\n if (!request?.url) {\n throw new Error(\n '[h2:error:createCustomerAccountClient] The request object does not contain a URL.',\n );\n }\n const authStatusHandler = customAuthStatusHandler\n ? customAuthStatusHandler\n : () => defaultAuthStatusHandler(request);\n\n const requestUrl = new URL(request.url);\n const origin =\n requestUrl.protocol === 'http:'\n ? requestUrl.origin.replace('http', 'https')\n : requestUrl.origin;\n const redirectUri = authUrl.startsWith('/') ? origin + authUrl : authUrl;\n const customerAccountApiUrl = `${customerAccountUrl}/account/customer/api/${customerApiVersion}/graphql`;\n const locks: Locks = {};\n\n async function fetchCustomerAPI<T>({\n query,\n type,\n variables = {},\n }: {\n query: string;\n type: 'query' | 'mutation';\n variables?: GenericVariables;\n }) {\n const accessToken = await getAccessToken();\n if (!accessToken) {\n throw authStatusHandler();\n }\n\n // Get stack trace before losing it with any async operation.\n // Since this is an internal function that is always called from\n // the public query/mutate wrappers, add 1 to the stack offset.\n const stackInfo = getCallerStackLine?.();\n\n const startTime = new Date().getTime();\n\n const response = await fetch(customerAccountApiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n Origin: origin,\n Authorization: accessToken,\n },\n body: JSON.stringify({query, variables}),\n });\n\n logSubRequestEvent?.({\n url: customerAccountApiUrl,\n startTime,\n response,\n waitUntil,\n stackInfo,\n query,\n variables,\n ...getDebugHeaders(request),\n });\n\n const body = await response.text();\n\n const errorOptions: GraphQLErrorOptions<T> = {\n url: customerAccountApiUrl,\n response,\n type,\n query,\n queryVariables: variables,\n errors: undefined,\n client: 'customer',\n };\n\n if (!response.ok) {\n if (response.status === 401) {\n // clear session because current access token is invalid\n clearSession(session);\n\n const authFailResponse = authStatusHandler();\n if (authFailResponse instanceof Response) {\n authFailResponse.headers.set('Set-Cookie', await session.commit());\n }\n throw authFailResponse;\n }\n\n /**\n * The Customer API might return a string error, or a JSON-formatted {error: string}.\n * We try both and conform them to a single {errors} format.\n */\n let errors;\n try {\n errors = parseJSON(body);\n } catch (_e) {\n errors = [{message: body}];\n }\n\n throwErrorWithGqlLink({...errorOptions, errors});\n }\n\n try {\n const APIresponse = parseJSON(body) as CustomerAPIResponse<T>;\n const {errors} = APIresponse;\n\n const gqlErrors = errors?.map(\n ({message, ...rest}) =>\n new GraphQLError(message, {\n ...(rest as WritableDeep<typeof rest>),\n clientOperation: `customerAccount.${errorOptions.type}`,\n requestId: response.headers.get('x-request-id'),\n queryVariables: variables,\n query,\n }),\n );\n\n return {...APIresponse, ...(errors && {errors: gqlErrors})};\n } catch (e) {\n throwErrorWithGqlLink({...errorOptions, errors: [{message: body}]});\n }\n }\n\n async function isLoggedIn() {\n const customerAccount = session.get(CUSTOMER_ACCOUNT_SESSION_KEY);\n const accessToken = customerAccount?.accessToken;\n const expiresAt = customerAccount?.expiresAt;\n\n if (!accessToken || !expiresAt) return false;\n\n // Get stack trace before losing it with any async operation.\n const stackInfo = getCallerStackLine?.();\n\n try {\n await checkExpires({\n locks,\n expiresAt,\n session,\n customerAccountId,\n customerAccountUrl,\n origin,\n debugInfo: {\n waitUntil,\n stackInfo,\n ...getDebugHeaders(request),\n },\n });\n } catch {\n return false;\n }\n\n return true;\n }\n\n async function handleAuthStatus() {\n if (!(await isLoggedIn())) {\n throw authStatusHandler();\n }\n }\n\n async function getAccessToken() {\n const hasAccessToken = await isLoggedIn();\n\n if (hasAccessToken)\n return session.get(CUSTOMER_ACCOUNT_SESSION_KEY)?.accessToken;\n }\n\n return {\n login: async () => {\n const loginUrl = new URL(customerAccountUrl + '/auth/oauth/authorize');\n\n const state = await generateState();\n const nonce = await generateNonce();\n\n loginUrl.searchParams.set('client_id', customerAccountId);\n loginUrl.searchParams.set('scope', 'openid email');\n loginUrl.searchParams.append('response_type', 'code');\n loginUrl.searchParams.append('redirect_uri', redirectUri);\n loginUrl.searchParams.set(\n 'scope',\n 'openid email https://api.customers.com/auth/customer.graphql',\n );\n loginUrl.searchParams.append('state', state);\n loginUrl.searchParams.append('nonce', nonce);\n\n const verifier = await generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n\n session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {\n ...session.get(CUSTOMER_ACCOUNT_SESSION_KEY),\n codeVerifier: verifier,\n state,\n nonce,\n redirectPath:\n getRedirectUrl(request.url) ||\n getHeader(request, 'Referer') ||\n DEFAULT_REDIRECT_PATH,\n });\n\n loginUrl.searchParams.append('code_challenge', challenge);\n loginUrl.searchParams.append('code_challenge_method', 'S256');\n\n return redirect(loginUrl.toString(), {\n headers: {\n 'Set-Cookie': await session.commit(),\n },\n });\n },\n logout: async () => {\n const idToken = session.get(CUSTOMER_ACCOUNT_SESSION_KEY)?.idToken;\n\n clearSession(session);\n\n return redirect(\n `${customerAccountUrl}/auth/logout?id_token_hint=${idToken}`,\n {\n status: 302,\n\n headers: {\n 'Set-Cookie': await session.commit(),\n },\n },\n );\n },\n isLoggedIn,\n handleAuthStatus,\n getAccessToken,\n getApiUrl: () => customerAccountApiUrl,\n mutate(mutation, options?) {\n mutation = minifyQuery(mutation);\n assertMutation(mutation, 'customer.mutate');\n\n return withSyncStack(\n fetchCustomerAPI({query: mutation, type: 'mutation', ...options}),\n {logErrors},\n );\n },\n query(query, options?) {\n query = minifyQuery(query);\n assertQuery(query, 'customer.query');\n\n return withSyncStack(\n fetchCustomerAPI({query, type: 'query', ...options}),\n {logErrors},\n );\n },\n authorize: async () => {\n const code = requestUrl.searchParams.get('code');\n const state = requestUrl.searchParams.get('state');\n\n if (!code || !state) {\n clearSession(session);\n\n throw new BadRequest(\n 'Unauthorized',\n 'No code or state parameter found in the redirect URL.',\n {\n 'Set-Cookie': await session.commit(),\n },\n );\n }\n\n if (session.get(CUSTOMER_ACCOUNT_SESSION_KEY)?.state !== state) {\n clearSession(session);\n\n throw new BadRequest(\n 'Unauthorized',\n 'The session state does not match the state parameter. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.',\n {\n 'Set-Cookie': await session.commit(),\n },\n );\n }\n\n const clientId = customerAccountId;\n const body = new URLSearchParams();\n\n body.append('grant_type', 'authorization_code');\n body.append('client_id', clientId);\n body.append('redirect_uri', redirectUri);\n body.append('code', code);\n\n // Public Client\n const codeVerifier = session.get(\n CUSTOMER_ACCOUNT_SESSION_KEY,\n )?.codeVerifier;\n\n if (!codeVerifier)\n throw new BadRequest(\n 'Unauthorized',\n 'No code verifier found in the session. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.',\n );\n\n body.append('code_verifier', codeVerifier);\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n 'User-Agent': USER_AGENT,\n Origin: origin,\n };\n\n const stackInfo = getCallerStackLine?.();\n const startTime = new Date().getTime();\n const url = `${customerAccountUrl}/auth/oauth/token`;\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body,\n });\n\n logSubRequestEvent?.({\n url,\n displayName: 'Customer Account API: authorize',\n startTime,\n response,\n waitUntil,\n stackInfo,\n ...getDebugHeaders(request),\n });\n\n if (!response.ok) {\n throw new Response(await response.text(), {\n status: response.status,\n headers: {\n 'Content-Type': 'text/html; charset=utf-8',\n },\n });\n }\n\n const {access_token, expires_in, id_token, refresh_token} =\n await response.json<AccessTokenResponse>();\n\n const sessionNonce = session.get(CUSTOMER_ACCOUNT_SESSION_KEY)?.nonce;\n const responseNonce = await getNonce(id_token);\n\n if (sessionNonce !== responseNonce) {\n throw new BadRequest(\n 'Unauthorized',\n `Returned nonce does not match: ${sessionNonce} !== ${responseNonce}`,\n );\n }\n\n const customerAccessToken = await exchangeAccessToken(\n access_token,\n customerAccountId,\n customerAccountUrl,\n origin,\n {\n waitUntil,\n stackInfo,\n ...getDebugHeaders(request),\n },\n );\n\n const redirectPath = session.get(\n CUSTOMER_ACCOUNT_SESSION_KEY,\n )?.redirectPath;\n\n session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {\n accessToken: customerAccessToken,\n expiresAt:\n new Date(\n new Date().getTime() + (expires_in! - 120) * 1000,\n ).getTime() + '',\n refreshToken: refresh_token,\n idToken: id_token,\n redirectPath: undefined,\n });\n\n return redirect(redirectPath || DEFAULT_REDIRECT_PATH, {\n headers: {\n 'Set-Cookie': await session.commit(),\n },\n });\n },\n };\n}\n","const DEFAULT_GITHUB_CHANGELOG_URL =\n 'https://raw.githubusercontent.com/Shopify/hydrogen/main/docs/changelog.json';\n\n/**\n * A custom Remix loader handler that fetches the changelog.json from GitHub.\n * It is used by the `upgrade` command inside the route `https://hydrogen.shopify.dev/changelog.json`\n */\nexport async function changelogHandler({\n request,\n changelogUrl,\n}: {\n request: Request;\n changelogUrl?: string;\n}) {\n const searchParams = new URL(request.url).searchParams;\n const GITHUB_CHANGELOG_URL = changelogUrl || DEFAULT_GITHUB_CHANGELOG_URL;\n return fetch(GITHUB_CHANGELOG_URL);\n}\n","import {type FetcherWithComponents, useFetcher} from '@remix-run/react';\nimport {type MetafieldWithoutOwnerId} from './queries/cart-types';\nimport type {ReactNode} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CartSelectedDeliveryOptionInput,\n Scalars,\n} from '@shopify/hydrogen-react/storefront-api-types';\n\ntype OtherFormData = {\n [key: string]: unknown;\n};\n\ntype CartAttributesUpdateProps = {\n action: 'AttributesUpdateInput';\n inputs?: {\n attributes: AttributeInput[];\n } & OtherFormData;\n};\ntype CartAttributesUpdateRequire = {\n action: 'AttributesUpdateInput';\n inputs: {\n attributes: AttributeInput[];\n } & OtherFormData;\n};\n\ntype CartBuyerIdentityUpdateProps = {\n action: 'BuyerIdentityUpdate';\n inputs?: {\n buyerIdentity: CartBuyerIdentityInput;\n } & OtherFormData;\n};\ntype CartBuyerIdentityUpdateRequire = {\n action: 'BuyerIdentityUpdate';\n inputs: {\n buyerIdentity: CartBuyerIdentityInput;\n } & OtherFormData;\n};\n\ntype CartCreateProps = {\n action: 'Create';\n inputs?: {\n input: CartInput;\n } & OtherFormData;\n};\ntype CartCreateRequire = {\n action: 'Create';\n inputs: {\n input: CartInput;\n } & OtherFormData;\n};\n\ntype CartDiscountCodesUpdateProps = {\n action: 'DiscountCodesUpdate';\n inputs?: {\n discountCodes: string[];\n } & OtherFormData;\n};\ntype CartDiscountCodesUpdateRequire = {\n action: 'DiscountCodesUpdate';\n inputs: {\n discountCodes: string[];\n } & OtherFormData;\n};\n\ntype CartLinesAddProps = {\n action: 'LinesAdd';\n inputs?: {\n lines: CartLineInput[];\n } & OtherFormData;\n};\ntype CartLinesAddRequire = {\n action: 'LinesAdd';\n inputs: {\n lines: CartLineInput[];\n } & OtherFormData;\n};\n\ntype CartLinesUpdateProps = {\n action: 'LinesUpdate';\n inputs?: {\n lines: CartLineUpdateInput[];\n } & OtherFormData;\n};\ntype CartLinesUpdateRequire = {\n action: 'LinesUpdate';\n inputs: {\n lines: CartLineUpdateInput[];\n } & OtherFormData;\n};\n\ntype CartLinesRemoveProps = {\n action: 'LinesRemove';\n inputs?: {\n lineIds: string[];\n } & OtherFormData;\n};\ntype CartLinesRemoveRequire = {\n action: 'LinesRemove';\n inputs: {\n lineIds: string[];\n } & OtherFormData;\n};\n\ntype CartNoteUpdateProps = {\n action: 'NoteUpdate';\n inputs?: {\n note: string;\n } & OtherFormData;\n};\ntype CartNoteUpdateRequire = {\n action: 'NoteUpdate';\n inputs: {\n note: string;\n } & OtherFormData;\n};\n\ntype CartSelectedDeliveryOptionsUpdateProps = {\n action: 'SelectedDeliveryOptionsUpdate';\n inputs?: {\n selectedDeliveryOptions: CartSelectedDeliveryOptionInput[];\n } & OtherFormData;\n};\n\ntype CartSelectedDeliveryOptionsUpdateRequire = {\n action: 'SelectedDeliveryOptionsUpdate';\n inputs: {\n selectedDeliveryOptions: CartSelectedDeliveryOptionInput[];\n } & OtherFormData;\n};\n\ntype CartMetafieldsSetProps = {\n action: 'MetafieldsSet';\n inputs?: {\n metafields: MetafieldWithoutOwnerId[];\n } & OtherFormData;\n};\ntype CartMetafieldsSetRequire = {\n action: 'MetafieldsSet';\n inputs: {\n metafields: MetafieldWithoutOwnerId[];\n } & OtherFormData;\n};\n\ntype CartMetafieldDeleteProps = {\n action: 'MetafieldsDelete';\n inputs?: {\n key: Scalars['String']['input'];\n } & OtherFormData;\n};\ntype CartMetafieldDeleteRequire = {\n action: 'MetafieldsDelete';\n inputs: {\n key: Scalars['String']['input'];\n } & OtherFormData;\n};\n\ntype CartCustomProps = {\n action: `Custom${string}`;\n inputs?: Record<string, unknown>;\n};\ntype CartCustomRequire = {\n action: `Custom${string}`;\n inputs: Record<string, unknown>;\n};\n\ntype CartFormCommonProps = {\n /**\n * Children nodes of CartForm.\n * Children can be a render prop that receives the fetcher.\n */\n children: ReactNode | ((fetcher: FetcherWithComponents<any>) => ReactNode);\n /**\n * The route to submit the form to. Defaults to the current route.\n */\n route?: string;\n /**\n * Optional key to use for the fetcher.\n * @see https://remix.run/hooks/use-fetcher#key\n */\n fetcherKey?: string;\n};\n\ntype CartActionInputProps =\n | CartAttributesUpdateProps\n | CartBuyerIdentityUpdateProps\n | CartCreateProps\n | CartDiscountCodesUpdateProps\n | CartLinesAddProps\n | CartLinesUpdateProps\n | CartLinesRemoveProps\n | CartNoteUpdateProps\n | CartSelectedDeliveryOptionsUpdateProps\n | CartMetafieldsSetProps\n | CartMetafieldDeleteProps\n | CartCustomProps;\n\nexport type CartActionInput =\n | CartAttributesUpdateRequire\n | CartBuyerIdentityUpdateRequire\n | CartCreateRequire\n | CartDiscountCodesUpdateRequire\n | CartLinesAddRequire\n | CartLinesUpdateRequire\n | CartLinesRemoveRequire\n | CartNoteUpdateRequire\n | CartSelectedDeliveryOptionsUpdateRequire\n | CartMetafieldsSetRequire\n | CartMetafieldDeleteRequire\n | CartCustomRequire;\n\ntype CartFormProps = CartActionInputProps & CartFormCommonProps;\n\nconst INPUT_NAME = 'cartFormInput';\n\nexport function CartForm({\n children,\n action,\n inputs,\n route,\n fetcherKey,\n}: CartFormProps): JSX.Element {\n const fetcher = useFetcher({key: fetcherKey});\n\n return (\n <fetcher.Form action={route || ''} method=\"post\">\n {(action || inputs) && (\n <input\n type=\"hidden\"\n name={INPUT_NAME}\n value={JSON.stringify({action, inputs})}\n />\n )}\n {typeof children === 'function' ? children(fetcher) : children}\n </fetcher.Form>\n );\n}\nCartForm.INPUT_NAME = INPUT_NAME;\nCartForm.ACTIONS = {\n AttributesUpdateInput: 'AttributesUpdateInput',\n BuyerIdentityUpdate: 'BuyerIdentityUpdate',\n Create: 'Create',\n DiscountCodesUpdate: 'DiscountCodesUpdate',\n LinesAdd: 'LinesAdd',\n LinesRemove: 'LinesRemove',\n LinesUpdate: 'LinesUpdate',\n NoteUpdate: 'NoteUpdate',\n SelectedDeliveryOptionsUpdate: 'SelectedDeliveryOptionsUpdate',\n MetafieldsSet: 'MetafieldsSet',\n MetafieldDelete: 'MetafieldDelete',\n} as const;\n\nfunction getFormInput(formData: FormData): CartActionInput {\n // Get all form data\n const data: Record<string, unknown> = {};\n for (const pair of formData.entries()) {\n const key = pair[0];\n const values = formData.getAll(key);\n\n data[key] = values.length > 1 ? values : pair[1];\n }\n\n // Parse cartFormInput\n const {cartFormInput, ...otherData} = data;\n const {action, inputs}: CartActionInput = cartFormInput\n ? JSON.parse(String(cartFormInput))\n : {};\n\n return {\n action,\n inputs: {\n ...inputs,\n ...otherData,\n },\n } as unknown as CartActionInput;\n}\n\nCartForm.getFormInput = getFormInput;\n","export const USER_ERROR_FRAGMENT = `#graphql\n fragment CartApiError on CartUserError {\n message\n field\n code\n }\n`;\n\nexport const MINIMAL_CART_FRAGMENT = `#graphql\n fragment CartApiMutation on Cart {\n id\n totalQuantity\n }\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartQueryData,\n CartQueryOptions,\n CartOptionalInput,\n CartQueryDataReturn,\n} from './cart-types';\nimport type {CartInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartCreateFunction = (\n input: CartInput,\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartCreateDefault(\n options: CartQueryOptions,\n): CartCreateFunction {\n return async (input, optionalParams) => {\n const {cartId, ...restOfOptionalParams} = optionalParams || {};\n const {cartCreate, errors} = await options.storefront.mutate<{\n cartCreate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_CREATE_MUTATION(options.cartFragment), {\n variables: {\n input,\n ...restOfOptionalParams,\n },\n });\n return formatAPIResult(cartCreate, errors);\n };\n}\n\n//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartCreate\nexport const CART_CREATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartCreate(\n $input: CartInput!\n $country: CountryCode = ZZ\n $language: LanguageCode\n ) @inContext(country: $country, language: $language) {\n cartCreate(input: $input) {\n cart {\n ...CartApiMutation\n checkoutUrl\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport type {CustomerAccount} from '../../customer/types';\nimport type {CartQueryOptions, CartReturn} from './cart-types';\nimport type {\n Cart,\n CountryCode,\n LanguageCode,\n} from '@shopify/hydrogen-react/storefront-api-types';\n\ntype CartGetProps = {\n /**\n * The cart ID.\n * @default cart.getCartId();\n */\n cartId?: string;\n /**\n * The country code.\n * @default storefront.i18n.country\n */\n country?: CountryCode;\n /**\n * The language code.\n * @default storefront.i18n.language\n */\n language?: LanguageCode;\n /**\n * The number of cart lines to be returned.\n * @default 100\n */\n numCartLines?: number;\n};\n\nexport type CartGetFunction = (\n cartInput?: CartGetProps,\n) => Promise<CartReturn | null>;\n\ntype CartGetOptions = CartQueryOptions & {\n /**\n * The customer account client instance created by [`createCustomerAccountClient`](docs/api/hydrogen/latest/utilities/createcustomeraccountclient).\n */\n customerAccount?: CustomerAccount;\n};\n\nexport function cartGetDefault({\n storefront,\n customerAccount,\n getCartId,\n cartFragment,\n}: CartGetOptions): CartGetFunction {\n return async (cartInput?: CartGetProps) => {\n const cartId = getCartId();\n\n if (!cartId) return null;\n\n const [isCustomerLoggedIn, {cart, errors}] = await Promise.all([\n customerAccount ? customerAccount.isLoggedIn() : false,\n storefront.query<{\n cart: Cart;\n errors: StorefrontApiErrors;\n }>(CART_QUERY(cartFragment), {\n variables: {\n cartId,\n ...cartInput,\n },\n cache: storefront.CacheNone(),\n }),\n ]);\n\n return formatAPIResult(\n addCustomerLoggedInParam(isCustomerLoggedIn, cart),\n errors,\n );\n };\n}\n\nfunction addCustomerLoggedInParam(isCustomerLoggedIn: boolean, cart: Cart) {\n if (isCustomerLoggedIn && cart && cart.checkoutUrl) {\n const finalCheckoutUrl = new URL(cart.checkoutUrl);\n finalCheckoutUrl.searchParams.set('logged_in', 'true');\n cart.checkoutUrl = finalCheckoutUrl.toString();\n }\n\n return cart;\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/queries/cart\nconst CART_QUERY = (cartFragment = DEFAULT_CART_FRAGMENT) => `#graphql\n query CartQuery(\n $cartId: ID!\n $numCartLines: Int = 100\n $country: CountryCode = ZZ\n $language: LanguageCode\n ) @inContext(country: $country, language: $language) {\n cart(id: $cartId) {\n ...CartApiQuery\n }\n }\n\n ${cartFragment}\n`;\n\nexport const DEFAULT_CART_FRAGMENT = `#graphql\n fragment CartApiQuery on Cart {\n id\n checkoutUrl\n totalQuantity\n buyerIdentity {\n countryCode\n customer {\n id\n email\n firstName\n lastName\n displayName\n }\n email\n phone\n }\n lines(first: $numCartLines) {\n edges {\n node {\n id\n quantity\n attributes {\n key\n value\n }\n cost {\n totalAmount {\n amount\n currencyCode\n }\n amountPerQuantity {\n amount\n currencyCode\n }\n compareAtAmountPerQuantity {\n amount\n currencyCode\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n availableForSale\n compareAtPrice {\n ...CartApiMoney\n }\n price {\n ...CartApiMoney\n }\n requiresShipping\n title\n image {\n ...CartApiImage\n }\n product {\n handle\n title\n id\n }\n selectedOptions {\n name\n value\n }\n }\n }\n }\n }\n }\n cost {\n subtotalAmount {\n ...CartApiMoney\n }\n totalAmount {\n ...CartApiMoney\n }\n totalDutyAmount {\n ...CartApiMoney\n }\n totalTaxAmount {\n ...CartApiMoney\n }\n }\n note\n attributes {\n key\n value\n }\n discountCodes {\n applicable\n code\n }\n }\n\n fragment CartApiMoney on MoneyV2 {\n currencyCode\n amount\n }\n\n fragment CartApiImage on Image {\n id\n url\n altText\n width\n height\n }\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\nimport type {CartLineInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartLinesAddFunction = (\n lines: CartLineInput[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartLinesAddDefault(\n options: CartQueryOptions,\n): CartLinesAddFunction {\n return async (lines, optionalParams) => {\n const {cartLinesAdd, errors} = await options.storefront.mutate<{\n cartLinesAdd: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_LINES_ADD_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n lines,\n ...optionalParams,\n },\n });\n\n return formatAPIResult(cartLinesAdd, errors);\n };\n}\n\n//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesAdd\nexport const CART_LINES_ADD_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartLinesAdd(\n $cartId: ID!\n $lines: [CartLineInput!]!\n $country: CountryCode = ZZ\n $language: LanguageCode\n ) @inContext(country: $country, language: $language) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\nimport type {CartLineUpdateInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartLinesUpdateFunction = (\n lines: CartLineUpdateInput[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartLinesUpdateDefault(\n options: CartQueryOptions,\n): CartLinesUpdateFunction {\n return async (lines, optionalParams) => {\n const {cartLinesUpdate, errors} = await options.storefront.mutate<{\n cartLinesUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_LINES_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n lines,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartLinesUpdate, errors);\n };\n}\n\n//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesUpdate\nexport const CART_LINES_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartLinesUpdate(\n $cartId: ID!\n $lines: [CartLineUpdateInput!]!\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\n\nexport type CartLinesRemoveFunction = (\n lineIds: string[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartLinesRemoveDefault(\n options: CartQueryOptions,\n): CartLinesRemoveFunction {\n return async (lineIds, optionalParams) => {\n const {cartLinesRemove, errors} = await options.storefront.mutate<{\n cartLinesRemove: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_LINES_REMOVE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n lineIds,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartLinesRemove, errors);\n };\n}\n\n//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesRemove\nexport const CART_LINES_REMOVE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartLinesRemove(\n $cartId: ID!\n $lineIds: [ID!]!\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\n\nexport type CartDiscountCodesUpdateFunction = (\n discountCodes: string[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartDiscountCodesUpdateDefault(\n options: CartQueryOptions,\n): CartDiscountCodesUpdateFunction {\n return async (discountCodes, optionalParams) => {\n // Ensure the discount codes are unique\n const uniqueCodes = discountCodes.filter((value, index, array) => {\n return array.indexOf(value) === index;\n });\n\n const {cartDiscountCodesUpdate, errors} = await options.storefront.mutate<{\n cartDiscountCodesUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_DISCOUNT_CODE_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n discountCodes: uniqueCodes,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartDiscountCodesUpdate, errors);\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartDiscountCodesUpdate\nexport const CART_DISCOUNT_CODE_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartDiscountCodesUpdate(\n $cartId: ID!\n $discountCodes: [String!]\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\nimport type {CartBuyerIdentityInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartBuyerIdentityUpdateFunction = (\n buyerIdentity: CartBuyerIdentityInput,\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartBuyerIdentityUpdateDefault(\n options: CartQueryOptions,\n): CartBuyerIdentityUpdateFunction {\n return async (buyerIdentity, optionalParams) => {\n const {cartBuyerIdentityUpdate, errors} = await options.storefront.mutate<{\n cartBuyerIdentityUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_BUYER_IDENTITY_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n buyerIdentity,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartBuyerIdentityUpdate, errors);\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartBuyerIdentityUpdate\nexport const CART_BUYER_IDENTITY_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartBuyerIdentityUpdate(\n $cartId: ID!\n $buyerIdentity: CartBuyerIdentityInput!\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\n\nexport type CartNoteUpdateFunction = (\n note: string,\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartNoteUpdateDefault(\n options: CartQueryOptions,\n): CartNoteUpdateFunction {\n return async (note, optionalParams) => {\n const {cartNoteUpdate, errors} = await options.storefront.mutate<{\n cartNoteUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_NOTE_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n note,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartNoteUpdate, errors);\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartNoteUpdate\nexport const CART_NOTE_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartNoteUpdate(\n $cartId: ID!\n $note: String\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartNoteUpdate(cartId: $cartId, note: $note) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\nimport type {CartSelectedDeliveryOptionInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartSelectedDeliveryOptionsUpdateFunction = (\n selectedDeliveryOptions: CartSelectedDeliveryOptionInput[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartSelectedDeliveryOptionsUpdateDefault(\n options: CartQueryOptions,\n): CartSelectedDeliveryOptionsUpdateFunction {\n return async (selectedDeliveryOptions, optionalParams) => {\n const {cartSelectedDeliveryOptionsUpdate, errors} =\n await options.storefront.mutate<{\n cartSelectedDeliveryOptionsUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_SELECTED_DELIVERY_OPTIONS_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: options.getCartId(),\n selectedDeliveryOptions,\n ...optionalParams,\n },\n });\n return formatAPIResult(cartSelectedDeliveryOptionsUpdate, errors);\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartSelectedDeliveryOptionsUpdate\nexport const CART_SELECTED_DELIVERY_OPTIONS_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartSelectedDeliveryOptionsUpdate(\n $cartId: ID!\n $selectedDeliveryOptions: [CartSelectedDeliveryOptionInput!]!\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartSelectedDeliveryOptionsUpdate(cartId: $cartId, selectedDeliveryOptions: $selectedDeliveryOptions) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport {MINIMAL_CART_FRAGMENT, USER_ERROR_FRAGMENT} from './cart-fragments';\nimport type {\n CartOptionalInput,\n CartQueryData,\n CartQueryDataReturn,\n CartQueryOptions,\n} from './cart-types';\nimport type {AttributeInput} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartAttributesUpdateFunction = (\n attributes: AttributeInput[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartAttributesUpdateDefault(\n options: CartQueryOptions,\n): CartAttributesUpdateFunction {\n return async (attributes, optionalParams) => {\n const {cartAttributesUpdate, errors} = await options.storefront.mutate<{\n cartAttributesUpdate: CartQueryData;\n errors: StorefrontApiErrors;\n }>(CART_ATTRIBUTES_UPDATE_MUTATION(options.cartFragment), {\n variables: {\n cartId: optionalParams?.cartId || options.getCartId(),\n attributes,\n },\n });\n return formatAPIResult(cartAttributesUpdate, errors);\n };\n}\n\nexport const CART_ATTRIBUTES_UPDATE_MUTATION = (\n cartFragment = MINIMAL_CART_FRAGMENT,\n) => `#graphql\n mutation cartAttributesUpdate(\n $cartId: ID!\n $attributes: [AttributeInput!]!\n ) {\n cartAttributesUpdate(cartId: $cartId, attributes: $attributes) {\n cart {\n ...CartApiMutation\n }\n userErrors {\n ...CartApiError\n }\n }\n }\n ${cartFragment}\n ${USER_ERROR_FRAGMENT}\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport type {\n CartOptionalInput,\n CartQueryOptions,\n MetafieldWithoutOwnerId,\n CartQueryDataReturn,\n} from './cart-types';\nimport type {\n Cart,\n MetafieldsSetUserError,\n} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartMetafieldsSetFunction = (\n metafields: MetafieldWithoutOwnerId[],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartMetafieldsSetDefault(\n options: CartQueryOptions,\n): CartMetafieldsSetFunction {\n return async (metafields, optionalParams) => {\n const ownerId = optionalParams?.cartId || options.getCartId();\n const metafieldsWithOwnerId = metafields.map(\n (metafield: MetafieldWithoutOwnerId) => ({\n ...metafield,\n ownerId,\n }),\n );\n const {cartMetafieldsSet, errors} = await options.storefront.mutate<{\n cartMetafieldsSet: {\n userErrors: MetafieldsSetUserError[];\n };\n errors: StorefrontApiErrors;\n }>(CART_METAFIELD_SET_MUTATION(), {\n variables: {metafields: metafieldsWithOwnerId},\n });\n\n return formatAPIResult(\n {\n cart: {\n id: ownerId,\n } as Cart,\n ...cartMetafieldsSet,\n },\n errors,\n );\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartMetafieldsSet\nexport const CART_METAFIELD_SET_MUTATION = () => `#graphql\n mutation cartMetafieldsSet(\n $metafields: [CartMetafieldsSetInput!]!\n $language: LanguageCode\n $country: CountryCode\n ) @inContext(country: $country, language: $language) {\n cartMetafieldsSet(metafields: $metafields) {\n userErrors {\n code\n elementIndex\n field\n message\n }\n }\n }\n`;\n","import {StorefrontApiErrors, formatAPIResult} from '../../storefront';\nimport type {\n CartQueryOptions,\n CartOptionalInput,\n CartQueryDataReturn,\n} from './cart-types';\nimport type {\n Cart,\n MetafieldDeleteUserError,\n Scalars,\n} from '@shopify/hydrogen-react/storefront-api-types';\n\nexport type CartMetafieldDeleteFunction = (\n key: Scalars['String']['input'],\n optionalParams?: CartOptionalInput,\n) => Promise<CartQueryDataReturn>;\n\nexport function cartMetafieldDeleteDefault(\n options: CartQueryOptions,\n): CartMetafieldDeleteFunction {\n return async (key, optionalParams) => {\n const ownerId = optionalParams?.cartId || options.getCartId();\n const {cartMetafieldDelete, errors} = await options.storefront.mutate<{\n cartMetafieldDelete: {\n userErrors: MetafieldDeleteUserError[];\n };\n errors: StorefrontApiErrors;\n }>(CART_METAFIELD_DELETE_MUTATION(), {\n variables: {\n input: {\n ownerId,\n key,\n },\n },\n });\n return formatAPIResult(\n {\n cart: {\n id: ownerId,\n } as Cart,\n ...cartMetafieldDelete,\n },\n errors,\n );\n };\n}\n\n//! @see https://shopify.dev/docs/api/storefront/2024-01/mutations/cartMetafieldDelete\nexport const CART_METAFIELD_DELETE_MUTATION = () => `#graphql\n mutation cartMetafieldDelete(\n $input: CartMetafieldDeleteInput!\n ) {\n cartMetafieldDelete(input: $input) {\n userErrors {\n code\n field\n message\n }\n }\n }\n`;\n","// src/cookie.ts\nvar g = new Set([\n \"domain\",\n \"path\",\n \"max-age\",\n \"expires\",\n \"samesite\",\n \"secure\",\n \"httponly\"\n]);\nfunction u(a) {\n let r = {}, e, t, n = 0, m = a.split(/;\\s*/g), s, i;\n for (; n < m.length; n++)\n if (t = m[n], e = t.indexOf(\"=\"), ~e) {\n if (s = t.substring(0, e++).trim(), i = t.substring(e).trim(), i[0] === '\"' && (i = i.substring(1, i.length - 1)), ~i.indexOf(\"%\"))\n try {\n i = decodeURIComponent(i);\n } catch (f) {\n }\n g.has(t = s.toLowerCase()) ? t === \"expires\" ? r.expires = new Date(i) : t === \"max-age\" ? r.maxage = +i : r[t] = i : r[s] = i;\n } else\n (s = t.trim().toLowerCase()) && (s === \"httponly\" || s === \"secure\") && (r[s] = !0);\n return r;\n}\nfunction l(a, r, e = {}) {\n let t = a + \"=\" + encodeURIComponent(r);\n return e.expires && (t += \"; Expires=\" + new Date(e.expires).toUTCString()), e.maxage != null && e.maxage >= 0 && (t += \"; Max-Age=\" + (e.maxage | 0)), e.domain && (t += \"; Domain=\" + e.domain), e.path && (t += \"; Path=\" + e.path), e.samesite && (t += \"; SameSite=\" + e.samesite), (e.secure || e.samesite === \"None\") && (t += \"; Secure\"), e.httponly && (t += \"; HttpOnly\"), t;\n}\nexport {\n u as parse,\n l as stringify\n};\n","import {parse} from 'worktop/cookie';\n\nexport const cartGetIdDefault = (requestHeaders: Headers) => {\n const cookies = parse(requestHeaders.get('Cookie') || '');\n return () => {\n return cookies.cart ? `gid://shopify/Cart/${cookies.cart}` : undefined;\n };\n};\n","import {stringify} from 'worktop/cookie';\n\nexport type CookieOptions = {\n maxage?: number;\n expires?: Date | number | string;\n samesite?: 'Lax' | 'Strict' | 'None';\n secure?: boolean;\n httponly?: boolean;\n domain?: string;\n path?: string;\n};\n\nexport const cartSetIdDefault = (cookieOptions?: CookieOptions) => {\n return (cartId: string) => {\n const headers = new Headers();\n headers.append(\n 'Set-Cookie',\n stringify('cart', cartId.split('/').pop() || '', {\n path: '/',\n ...cookieOptions,\n }),\n );\n return headers;\n };\n};\n","import {Storefront} from '../storefront';\nimport type {CustomerAccount} from '../customer/types';\nimport {type CartGetFunction, cartGetDefault} from './queries/cartGetDefault';\nimport {\n type CartCreateFunction,\n cartCreateDefault,\n} from './queries/cartCreateDefault';\nimport {\n type CartLinesAddFunction,\n cartLinesAddDefault,\n} from './queries/cartLinesAddDefault';\nimport {\n type CartLinesUpdateFunction,\n cartLinesUpdateDefault,\n} from './queries/cartLinesUpdateDefault';\nimport {\n type CartLinesRemoveFunction,\n cartLinesRemoveDefault,\n} from './queries/cartLinesRemoveDefault';\nimport {\n type CartDiscountCodesUpdateFunction,\n cartDiscountCodesUpdateDefault,\n} from './queries/cartDiscountCodesUpdateDefault';\nimport {\n type CartBuyerIdentityUpdateFunction,\n cartBuyerIdentityUpdateDefault,\n} from './queries/cartBuyerIdentityUpdateDefault';\nimport {\n type CartNoteUpdateFunction,\n cartNoteUpdateDefault,\n} from './queries/cartNoteUpdateDefault';\nimport {\n type CartSelectedDeliveryOptionsUpdateFunction,\n cartSelectedDeliveryOptionsUpdateDefault,\n} from './queries/cartSelectedDeliveryOptionsUpdateDefault';\nimport {\n type CartAttributesUpdateFunction,\n cartAttributesUpdateDefault,\n} from './queries/cartAttributesUpdateDefault';\nimport {\n type CartMetafieldsSetFunction,\n cartMetafieldsSetDefault,\n} from './queries/cartMetafieldsSetDefault';\nimport {\n type CartMetafieldDeleteFunction,\n cartMetafieldDeleteDefault,\n} from './queries/cartMetafieldDeleteDefault';\n\nexport type CartHandlerOptions = {\n storefront: Storefront;\n customerAccount?: CustomerAccount;\n getCartId: () => string | undefined;\n setCartId: (cartId: string) => Headers;\n cartQueryFragment?: string;\n cartMutateFragment?: string;\n};\n\nexport type CustomMethodsBase = Record<string, Function>;\nexport type CartHandlerOptionsWithCustom<\n TCustomMethods extends CustomMethodsBase,\n> = CartHandlerOptions & {\n customMethods?: TCustomMethods;\n};\n\nexport type HydrogenCart = {\n get: ReturnType<typeof cartGetDefault>;\n getCartId: () => string | undefined;\n setCartId: (cartId: string) => Headers;\n create: ReturnType<typeof cartCreateDefault>;\n addLines: ReturnType<typeof cartLinesAddDefault>;\n updateLines: ReturnType<typeof cartLinesUpdateDefault>;\n removeLines: ReturnType<typeof cartLinesRemoveDefault>;\n updateDiscountCodes: ReturnType<typeof cartDiscountCodesUpdateDefault>;\n updateBuyerIdentity: ReturnType<typeof cartBuyerIdentityUpdateDefault>;\n updateNote: ReturnType<typeof cartNoteUpdateDefault>;\n updateSelectedDeliveryOption: ReturnType<\n typeof cartSelectedDeliveryOptionsUpdateDefault\n >;\n updateAttributes: ReturnType<typeof cartAttributesUpdateDefault>;\n setMetafields: ReturnType<typeof cartMetafieldsSetDefault>;\n deleteMetafield: ReturnType<typeof cartMetafieldDeleteDefault>;\n};\n\nexport type HydrogenCartCustom<\n TCustomMethods extends Partial<HydrogenCart> & CustomMethodsBase,\n> = Omit<HydrogenCart, keyof TCustomMethods> & TCustomMethods;\nexport type CartHandlerReturn<TCustomMethods extends CustomMethodsBase> =\n | HydrogenCartCustom<TCustomMethods>\n | HydrogenCart;\n\nexport function createCartHandler(options: CartHandlerOptions): HydrogenCart;\nexport function createCartHandler<TCustomMethods extends CustomMethodsBase>(\n options: CartHandlerOptionsWithCustom<TCustomMethods>,\n): HydrogenCartCustom<TCustomMethods>;\nexport function createCartHandler<TCustomMethods extends CustomMethodsBase>(\n options: CartHandlerOptions | CartHandlerOptionsWithCustom<TCustomMethods>,\n): CartHandlerReturn<TCustomMethods> {\n const {\n getCartId,\n setCartId,\n storefront,\n customerAccount,\n cartQueryFragment,\n cartMutateFragment,\n } = options;\n\n const mutateOptions = {\n storefront,\n getCartId,\n cartFragment: cartMutateFragment,\n };\n\n const cartId = getCartId();\n const cartCreate = cartCreateDefault(mutateOptions);\n\n const methods: HydrogenCart = {\n get: cartGetDefault({\n storefront,\n customerAccount,\n getCartId,\n cartFragment: cartQueryFragment,\n }),\n getCartId,\n setCartId,\n create: cartCreate,\n addLines: async (lines, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartLinesAddDefault(mutateOptions)(lines, optionalParams)\n : await cartCreate({lines}, optionalParams);\n },\n updateLines: cartLinesUpdateDefault(mutateOptions),\n removeLines: cartLinesRemoveDefault(mutateOptions),\n updateDiscountCodes: async (discountCodes, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartDiscountCodesUpdateDefault(mutateOptions)(\n discountCodes,\n optionalParams,\n )\n : await cartCreate({discountCodes}, optionalParams);\n },\n updateBuyerIdentity: async (buyerIdentity, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartBuyerIdentityUpdateDefault(mutateOptions)(\n buyerIdentity,\n optionalParams,\n )\n : await cartCreate({buyerIdentity}, optionalParams);\n },\n updateNote: async (note, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartNoteUpdateDefault(mutateOptions)(note, optionalParams)\n : await cartCreate({note}, optionalParams);\n },\n updateSelectedDeliveryOption:\n cartSelectedDeliveryOptionsUpdateDefault(mutateOptions),\n updateAttributes: async (attributes, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartAttributesUpdateDefault(mutateOptions)(\n attributes,\n optionalParams,\n )\n : await cartCreate({attributes}, optionalParams);\n },\n setMetafields: async (metafields, optionalParams) => {\n return cartId || optionalParams?.cartId\n ? await cartMetafieldsSetDefault(mutateOptions)(\n metafields,\n optionalParams,\n )\n : await cartCreate({metafields}, optionalParams);\n },\n deleteMetafield: cartMetafieldDeleteDefault(mutateOptions),\n };\n\n if ('customMethods' in options) {\n return {\n ...methods,\n ...(options.customMethods ?? {}),\n };\n } else {\n return methods;\n }\n}\n\nexport type CartHandlerOptionsForDocs<\n TCustomMethods extends CustomMethodsBase,\n> = {\n /**\n * A function that returns the cart id in the form of `gid://shopify/Cart/c1-123`.\n */\n getCartId: () => string | undefined;\n /**\n * A function that sets the cart ID.\n */\n setCartId: (cartId: string) => Headers;\n /**\n * The storefront client instance created by [`createStorefrontClient`](docs/api/hydrogen/latest/utilities/createstorefrontclient).\n */\n storefront: Storefront;\n /**\n * The cart mutation fragment used in most mutation requests, except for `setMetafields` and `deleteMetafield`.\n * See the [example usage](/docs/api/hydrogen/2024-01/utilities/createcarthandler#example-cart-fragments) in the documentation.\n */\n cartMutateFragment?: string;\n /**\n * The cart query fragment used by `cart.get()`.\n * See the [example usage](/docs/api/hydrogen/2024-01/utilities/createcarthandler#example-cart-fragments) in the documentation.\n */\n cartQueryFragment?: string;\n /**\n * Define custom methods or override existing methods for your cart API instance.\n * See the [example usage](/docs/api/hydrogen/2024-01/utilities/createcarthandler#example-custom-methods) in the documentation.\n */\n customMethods?: TCustomMethods;\n};\n\nexport type HydrogenCartForDocs = {\n /**\n * Adds items to the cart.\n * If the cart doesn't exist, a new one will be created.\n */\n addLines?: CartLinesAddFunction;\n /**\n * Creates a new cart.\n */\n create?: CartCreateFunction;\n /**\n * Removes a custom field (metafield) from the cart.\n */\n deleteMetafield?: CartMetafieldDeleteFunction;\n /**\n * Retrieves the cart information.\n */\n get?: CartGetFunction;\n /**\n * Retrieves the unique identifier of the cart.\n * By default, it gets the ID from the request cookie.\n */\n getCartId?: () => string | undefined;\n /**\n * Removes items from the cart.\n */\n removeLines?: CartLinesRemoveFunction;\n /**\n * Sets the unique identifier of the cart.\n * By default, it sets the ID in the header cookie.\n */\n setCartId?: (cartId: string) => Headers;\n /**\n * Adds extra information (metafields) to the cart.\n * If the cart doesn't exist, a new one will be created.\n */\n setMetafields?: CartMetafieldsSetFunction;\n /**\n * Updates additional information (attributes) in the cart.\n */\n updateAttributes?: CartAttributesUpdateFunction;\n /**\n * Updates the buyer's information in the cart.\n * If the cart doesn't exist, a new one will be created.\n */\n updateBuyerIdentity?: CartBuyerIdentityUpdateFunction;\n /**\n * Updates discount codes in the cart.\n */\n updateDiscountCodes?: CartDiscountCodesUpdateFunction;\n /**\n * Updates items in the cart.\n */\n updateLines?: CartLinesUpdateFunction;\n /**\n * Updates the note in the cart.\n * If the cart doesn't exist, a new one will be created.\n */\n updateNote?: CartNoteUpdateFunction;\n /**\n * Updates the selected delivery options in the cart.\n * Only available for carts associated with a customer access token.\n */\n updateSelectedDeliveryOption?: CartSelectedDeliveryOptionsUpdateFunction;\n};\n","import {useLocation} from '@remix-run/react';\nimport {flattenConnection} from '@shopify/hydrogen-react';\nimport type {\n ProductOption,\n ProductVariant,\n ProductVariantConnection,\n SelectedOptionInput,\n} from '@shopify/hydrogen-react/storefront-api-types';\nimport {type ReactNode, useMemo, createElement, Fragment} from 'react';\nimport type {PartialDeep} from 'type-fest';\n\nexport type VariantOption = {\n name: string;\n value?: string;\n values: Array<VariantOptionValue>;\n};\n\nexport type VariantOptionValue = {\n value: string;\n isAvailable: boolean;\n to: string;\n search: string;\n isActive: boolean;\n};\n\ntype VariantSelectorProps = {\n /** The product handle for all of the variants */\n handle: string;\n /** Product options from the [Storefront API](/docs/api/storefront/2024-01/objects/ProductOption). Make sure both `name` and `values` are apart of your query. */\n options: Array<PartialDeep<ProductOption>> | undefined;\n /** Product variants from the [Storefront API](/docs/api/storefront/2024-01/objects/ProductVariant). You only need to pass this prop if you want to show product availability. If a product option combination is not found within `variants`, it is assumed to be available. Make sure to include `availableForSale` and `selectedOptions.name` and `selectedOptions.value`. */\n variants?:\n | PartialDeep<ProductVariantConnection>\n | Array<PartialDeep<ProductVariant>>;\n /** By default all products are under /products. Use this prop to provide a custom path. */\n productPath?: string;\n children: ({option}: {option: VariantOption}) => ReactNode;\n};\n\nexport function VariantSelector({\n handle,\n options = [],\n variants: _variants = [],\n productPath = 'products',\n children,\n}: VariantSelectorProps) {\n const variants =\n _variants instanceof Array ? _variants : flattenConnection(_variants);\n\n const {searchParams, path, alreadyOnProductPage} = useVariantPath(\n handle,\n productPath,\n );\n\n // If an option only has one value, it doesn't need a UI to select it\n // But instead it always needs to be added to the product options so\n // the SFAPI properly finds the variant\n const optionsWithOnlyOneValue = options.filter(\n (option) => option?.values?.length === 1,\n );\n\n return createElement(\n Fragment,\n null,\n ...useMemo(() => {\n return (\n options\n // Only show options with more than one value\n .filter((option) => option?.values?.length! > 1)\n .map((option) => {\n let activeValue;\n let availableValues: VariantOptionValue[] = [];\n\n for (let value of option.values!) {\n // The clone the search params for each value, so we can calculate\n // a new URL for each option value pair\n const clonedSearchParams = new URLSearchParams(\n alreadyOnProductPage ? searchParams : undefined,\n );\n clonedSearchParams.set(option.name!, value!);\n\n // Because we hide options with only one value, they aren't selectable,\n // but they still need to get into the URL\n optionsWithOnlyOneValue.forEach((option) => {\n clonedSearchParams.set(option.name!, option.values![0]!);\n });\n\n // Find a variant that matches all selected options.\n const variant = variants.find((variant) =>\n variant?.selectedOptions?.every(\n (selectedOption) =>\n clonedSearchParams.get(selectedOption?.name!) ===\n selectedOption?.value,\n ),\n );\n\n const currentParam = searchParams.get(option.name!);\n\n const calculatedActiveValue = currentParam\n ? // If a URL parameter exists for the current option, check if it equals the current value\n currentParam === value!\n : false;\n\n if (calculatedActiveValue) {\n // Save out the current value if it's active. This should only ever happen once.\n // Should we throw if it happens a second time?\n activeValue = value;\n }\n\n const searchString = '?' + clonedSearchParams.toString();\n\n availableValues.push({\n value: value!,\n isAvailable: variant ? variant.availableForSale! : true,\n to: path + searchString,\n search: searchString,\n isActive: calculatedActiveValue,\n });\n }\n\n return children({\n option: {\n name: option.name!,\n value: activeValue,\n values: availableValues,\n },\n });\n })\n );\n }, [options, variants, children]),\n );\n}\n\ntype GetSelectedProductOptions = (request: Request) => SelectedOptionInput[];\n\nexport const getSelectedProductOptions: GetSelectedProductOptions = (\n request,\n) => {\n if (typeof request?.url === 'undefined')\n throw new TypeError(`Expected a Request instance, got ${typeof request}`);\n\n const searchParams = new URL(request.url).searchParams;\n\n const selectedOptions: SelectedOptionInput[] = [];\n\n searchParams.forEach((value, name) => {\n selectedOptions.push({name, value});\n });\n\n return selectedOptions;\n};\n\nfunction useVariantPath(handle: string, productPath: string) {\n const {pathname, search} = useLocation();\n\n return useMemo(() => {\n const match = /(\\/[a-zA-Z]{2}-[a-zA-Z]{2}\\/)/g.exec(pathname);\n const isLocalePathname = match && match.length > 0;\n productPath = productPath.startsWith('/')\n ? productPath.substring(1)\n : productPath;\n\n const path = isLocalePathname\n ? `${match![0]}${productPath}/${handle}`\n : `/${productPath}/${handle}`;\n\n const searchParams = new URLSearchParams(search);\n\n return {\n searchParams,\n // If the current pathname matches the product page, we need to make sure\n // that we append to the current search params. Otherwise all the search\n // params can be generated new.\n alreadyOnProductPage: path === pathname,\n path,\n };\n }, [pathname, search, handle, productPath]);\n}\n","import {\n type ComponentType,\n createContext,\n createElement,\n type ReactNode,\n useContext,\n} from 'react';\nimport cspBuilder from 'content-security-policy-builder';\nimport {generateNonce} from './nonce';\n\nexport const NonceContext = createContext<string | undefined>(undefined);\nexport const NonceProvider = NonceContext.Provider;\n\nexport const useNonce = () => useContext(NonceContext);\n\ntype ContentSecurityPolicy = {\n /** A randomly generated nonce string that should be passed to any custom `script` element */\n nonce: string;\n /** The content security policy header */\n header: string;\n NonceProvider: ComponentType<{children: ReactNode}>;\n};\n\n/**\n * @param directives - Pass custom [content security policy directives](https://content-security-policy.com/). This is important if you load content in your app from third-party domains.\n */\nexport function createContentSecurityPolicy(\n directives: Record<string, string[] | string | boolean> = {},\n): ContentSecurityPolicy {\n const nonce = generateNonce();\n const header = createCSPHeader(nonce, directives);\n\n const Provider = ({children}: {children: ReactNode}) => {\n return createElement(NonceProvider, {value: nonce}, children);\n };\n\n return {\n nonce,\n header,\n NonceProvider: Provider,\n };\n}\n\nfunction createCSPHeader(\n nonce: string,\n directives: Record<string, string[] | string | boolean> = {},\n): string {\n const nonceString = `'nonce-${nonce}'`;\n const styleSrc = [\"'self'\", \"'unsafe-inline'\", 'https://cdn.shopify.com'];\n const connectSrc = [\"'self'\", 'https://monorail-edge.shopifysvc.com'];\n const defaultSrc = [\n \"'self'\",\n nonceString,\n 'https://cdn.shopify.com',\n // Used for the Customer Account API\n 'https://shopify.com',\n ];\n\n const defaultDirectives: Record<string, string[] | string | boolean> = {\n baseUri: [\"'self'\"],\n defaultSrc,\n frameAncestors: ['none'],\n styleSrc,\n connectSrc,\n };\n\n // Support localhost in development\n if (process.env.NODE_ENV === 'development') {\n defaultDirectives.styleSrc = [...styleSrc, 'http://localhost:*'];\n defaultDirectives.defaultSrc = [...defaultSrc, 'http://localhost:*'];\n defaultDirectives.connectSrc = [\n ...connectSrc,\n 'http://localhost:*',\n // For HMR:\n 'ws://localhost:*',\n 'ws://127.0.0.1:*',\n ];\n }\n\n const combinedDirectives = Object.assign({}, defaultDirectives, directives);\n\n //add defaults if it was override\n for (const key in defaultDirectives) {\n if (directives[key]) {\n combinedDirectives[key] = addCspDirective(\n directives[key],\n defaultDirectives[key],\n );\n }\n }\n\n // Make sure that at least script-src includes a nonce directive.\n // If someone doesn't want a nonce in their CSP, they probably\n // shouldn't use our utilities and just manually create their CSP.\n if (\n combinedDirectives.scriptSrc instanceof Array &&\n !combinedDirectives.scriptSrc.includes(nonceString)\n ) {\n combinedDirectives.scriptSrc.push(nonceString);\n } else if (\n combinedDirectives.defaultSrc instanceof Array &&\n !combinedDirectives.defaultSrc.includes(nonceString)\n ) {\n combinedDirectives.defaultSrc.push(nonceString);\n }\n\n return cspBuilder({\n directives: combinedDirectives,\n });\n}\n\nfunction addCspDirective(\n currentValue: string[] | string | boolean,\n value: string[] | string | boolean,\n): boolean | string[] {\n const normalizedValue = typeof value === 'string' ? [value] : value;\n const normalizedCurrentValue = Array.isArray(currentValue)\n ? currentValue\n : [String(currentValue)];\n\n const newValue = Array.isArray(normalizedValue)\n ? [...normalizedCurrentValue, ...normalizedValue]\n : normalizedValue;\n\n return newValue;\n}\n","import {forwardRef} from 'react';\nimport {useNonce} from './csp';\n\ntype ScriptProps = JSX.IntrinsicElements['script'];\n\nexport const Script = forwardRef<HTMLScriptElement, ScriptProps>(\n (props, ref) => {\n const nonce = useNonce();\n return (\n <script suppressHydrationWarning {...props} nonce={nonce} ref={ref} />\n );\n },\n);\n","import {useFetchers} from '@remix-run/react';\n\nexport function useOptimisticData<T>(identifier: string) {\n const fetchers = useFetchers();\n const data: Record<string, unknown> = {};\n\n for (const {formData} of fetchers) {\n if (formData?.get('optimistic-identifier') === identifier) {\n try {\n if (formData.has('optimistic-data')) {\n const dataInForm: unknown = JSON.parse(\n String(formData.get('optimistic-data')),\n );\n Object.assign(data, dataInForm);\n }\n } catch {\n // do nothing\n }\n }\n }\n return data as T;\n}\n\nexport type OptimisticInputProps = {\n /**\n * A unique identifier for the optimistic input. Use the same identifier in `useOptimisticData`\n * to retrieve the optimistic data from actions.\n */\n id: string;\n /**\n * The data to be stored in the optimistic input. Use for creating an optimistic successful state\n * of this form action.\n */\n data: Record<string, unknown>;\n};\n\nexport function OptimisticInput({id, data}: OptimisticInputProps) {\n return (\n <>\n <input type=\"hidden\" name=\"optimistic-identifier\" value={id} />\n <input\n type=\"hidden\"\n name=\"optimistic-data\"\n value={JSON.stringify(data)}\n />\n </>\n );\n}\n","import {ShopPayButton as ShopPayButtonBase} from '@shopify/hydrogen-react';\nimport {ComponentProps} from 'react';\n\nexport function ShopPayButton(props: ComponentProps<typeof ShopPayButtonBase>) {\n return <ShopPayButtonBase channel=\"hydrogen\" {...props} />;\n}\n","export * from './storefront';\nexport * from './with-cache';\nexport {\n CacheCustom,\n CacheLong,\n CacheNone,\n CacheShort,\n generateCacheControlHeader,\n type CachingStrategy,\n type NoStoreStrategy,\n} from './cache/strategies';\nexport {InMemoryCache} from './cache/in-memory';\nexport {type CacheKey} from './cache/fetch';\n\nexport {storefrontRedirect} from './routing/redirect';\nexport {graphiqlLoader} from './routing/graphiql';\nexport {Seo} from './seo/seo';\nexport {type SeoConfig} from './seo/generate-seo-tags';\nexport type {SeoHandleFunction} from './seo/seo';\nexport {Pagination, getPaginationVariables} from './pagination/Pagination';\nexport {createCustomerAccountClient} from './customer/customer';\nexport type {\n CustomerAccount,\n // CustomerClient is a deprecated type that will be remove after 2024-01\n CustomerAccount as CustomerClient,\n CustomerAccountQueries,\n CustomerAccountMutations,\n} from './customer/types';\nexport {changelogHandler} from './changelogHandler';\n\nexport {CartForm, type CartActionInput} from './cart/CartForm';\nexport {cartCreateDefault} from './cart/queries/cartCreateDefault';\nexport {cartGetDefault} from './cart/queries/cartGetDefault';\nexport {cartLinesAddDefault} from './cart/queries/cartLinesAddDefault';\nexport {cartLinesUpdateDefault} from './cart/queries/cartLinesUpdateDefault';\nexport {cartLinesRemoveDefault} from './cart/queries/cartLinesRemoveDefault';\nexport {cartDiscountCodesUpdateDefault} from './cart/queries/cartDiscountCodesUpdateDefault';\nexport {cartBuyerIdentityUpdateDefault} from './cart/queries/cartBuyerIdentityUpdateDefault';\nexport {cartNoteUpdateDefault} from './cart/queries/cartNoteUpdateDefault';\nexport {cartSelectedDeliveryOptionsUpdateDefault} from './cart/queries/cartSelectedDeliveryOptionsUpdateDefault';\nexport {cartAttributesUpdateDefault} from './cart/queries/cartAttributesUpdateDefault';\nexport {cartMetafieldsSetDefault} from './cart/queries/cartMetafieldsSetDefault';\nexport {cartMetafieldDeleteDefault} from './cart/queries/cartMetafieldDeleteDefault';\nexport {cartGetIdDefault} from './cart/cartGetIdDefault';\nexport {cartSetIdDefault, type CookieOptions} from './cart/cartSetIdDefault';\nexport {\n type HydrogenCartCustom,\n type HydrogenCart,\n createCartHandler,\n} from './cart/createCartHandler';\nexport type {\n MetafieldWithoutOwnerId,\n CartReturn,\n CartQueryDataReturn,\n CartQueryOptions,\n CartQueryReturn,\n} from './cart/queries/cart-types';\n\nexport {\n VariantSelector,\n getSelectedProductOptions,\n} from './product/VariantSelector';\n\nexport type {\n VariantOption,\n VariantOptionValue,\n} from './product/VariantSelector';\n\nexport {createContentSecurityPolicy, useNonce} from './csp/csp';\nexport {Script} from './csp/Script';\n\nexport {\n useOptimisticData,\n OptimisticInput,\n} from './optimistic-ui/optimistic-ui';\n\nexport {ShopPayButton} from './shop/ShopPayButton';\n\nexport {\n AnalyticsEventName,\n AnalyticsPageType,\n ExternalVideo,\n flattenConnection,\n getClientBrowserParameters,\n getShopifyCookies,\n Image,\n IMAGE_FRAGMENT,\n MediaFile,\n ModelViewer,\n Money,\n parseGid,\n parseMetafield,\n sendShopifyAnalytics,\n ShopifySalesChannel,\n storefrontApiCustomScalars,\n customerAccountApiCustomScalars,\n useLoadScript,\n useMoney,\n useShopifyCookies,\n Video,\n} from '@shopify/hydrogen-react';\n\nexport type {\n ClientBrowserParameters,\n ParsedMetafields,\n ShopifyAddToCart,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyAnalyticsPayload,\n ShopifyAnalyticsProduct,\n ShopifyCookies,\n ShopifyPageView,\n ShopifyPageViewPayload,\n StorefrontApiResponse,\n StorefrontApiResponseError,\n StorefrontApiResponseOk,\n StorefrontApiResponseOkPartial,\n StorefrontApiResponsePartial,\n} from '@shopify/hydrogen-react';\n\nexport type {HydrogenSessionData, HydrogenSession} from './hydrogen';\n"]}