@shopify/hydrogen-react 2023.4.1 → 2023.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"hydrogen-react.dev.js","sources":["../../../../node_modules/@xstate/fsm/es/index.js","../../../../node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../../../../node_modules/use-sync-external-store/shim/index.js","../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js","../../../../node_modules/use-sync-external-store/shim/with-selector.js","../../../../node_modules/@xstate/react/es/useConstant.js","../../../../node_modules/@xstate/react/es/fsm.js","../../src/flatten-connection.ts","../../src/cart-queries.ts","../../src/storefront-api-constants.ts","../../src/storefront-client.ts","../../src/ShopifyProvider.tsx","../../src/cart-constants.ts","../../../../node_modules/worktop/cookie/index.mjs","../../src/cookies-utils.tsx","../../src/cart-hooks.tsx","../../src/useCartActions.tsx","../../src/useCartAPIStateMachine.tsx","../../src/CartProvider.tsx","../../src/ProductProvider.tsx","../../src/BaseButton.tsx","../../src/AddToCartButton.tsx","../../src/analytics-constants.ts","../../src/analytics-utils.ts","../../src/analytics-schema-trekkie-storefront-page-view.ts","../../src/analytics-schema-custom-storefront-customer-tracking.ts","../../src/analytics.ts","../../src/BuyNowButton.tsx","../../src/CartCheckoutButton.tsx","../../src/useMoney.tsx","../../src/Money.tsx","../../src/CartCost.tsx","../../src/CartLineProvider.tsx","../../src/CartLineQuantity.tsx","../../src/CartLineQuantityAdjustButton.tsx","../../src/codegen.helpers.ts","../../src/ExternalVideo.tsx","../../src/Image.tsx","../../src/Video.tsx","../../src/load-script.tsx","../../src/ModelViewer.tsx","../../src/MediaFile.tsx","../../src/parse-metafield.ts","../../src/ProductPrice.tsx","../../src/ShopPayButton.tsx","../../src/useShopifyCookies.tsx"],"sourcesContent":["/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\nfunction t(t,n){var e=\"function\"==typeof Symbol&&t[Symbol.iterator];if(!e)return t;var r,i,o=e.call(t),a=[];try{for(;(void 0===n||n-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(e=o.return)&&e.call(o)}finally{if(i)throw i.error}}return a}var n;!function(t){t[t.NotStarted=0]=\"NotStarted\",t[t.Running=1]=\"Running\",t[t.Stopped=2]=\"Stopped\"}(n||(n={}));var e={type:\"xstate.init\"};function r(t){return void 0===t?[]:[].concat(t)}function i(t){return{type:\"xstate.assign\",assignment:t}}function o(t,n){return\"string\"==typeof(t=\"string\"==typeof t&&n&&n[t]?n[t]:t)?{type:t}:\"function\"==typeof t?{type:t.name,exec:t}:t}function a(t){return function(n){return t===n}}function u(t){return\"string\"==typeof t?{type:t}:t}function c(t,n){return{value:t,context:n,actions:[],changed:!1,matches:a(t)}}function f(t,n,e){var r=n,i=!1;return[t.filter((function(t){if(\"xstate.assign\"===t.type){i=!0;var n=Object.assign({},r);return\"function\"==typeof t.assignment?n=t.assignment(r,e):Object.keys(t.assignment).forEach((function(i){n[i]=\"function\"==typeof t.assignment[i]?t.assignment[i](r,e):t.assignment[i]})),r=n,!1}return!0})),r,i]}function s(n,i){void 0===i&&(i={});var s=t(f(r(n.states[n.initial].entry).map((function(t){return o(t,i.actions)})),n.context,e),2),l=s[0],v=s[1],y={config:n,_options:i,initialState:{value:n.initial,actions:l,context:v,matches:a(n.initial)},transition:function(e,i){var s,l,v=\"string\"==typeof e?{value:e,context:n.context}:e,p=v.value,g=v.context,d=u(i),x=n.states[p];if(x.on){var m=r(x.on[d.type]);try{for(var h=function(t){var n=\"function\"==typeof Symbol&&Symbol.iterator,e=n&&t[n],r=0;if(e)return e.call(t);if(t&&\"number\"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(n?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(m),b=h.next();!b.done;b=h.next()){var S=b.value;if(void 0===S)return c(p,g);var w=\"string\"==typeof S?{target:S}:S,j=w.target,E=w.actions,R=void 0===E?[]:E,N=w.cond,O=void 0===N?function(){return!0}:N,_=void 0===j,k=null!=j?j:p,T=n.states[k];if(O(g,d)){var q=t(f((_?r(R):[].concat(x.exit,R,T.entry).filter((function(t){return t}))).map((function(t){return o(t,y._options.actions)})),g,d),3),z=q[0],A=q[1],B=q[2],C=null!=j?j:p;return{value:C,context:A,actions:z,changed:j!==p||z.length>0||B,matches:a(C)}}}}catch(t){s={error:t}}finally{try{b&&!b.done&&(l=h.return)&&l.call(h)}finally{if(s)throw s.error}}}return c(p,g)}};return y}var l=function(t,n){return t.actions.forEach((function(e){var r=e.exec;return r&&r(t.context,n)}))};function v(t){var r=t.initialState,i=n.NotStarted,o=new Set,c={_machine:t,send:function(e){i===n.Running&&(r=t.transition(r,e),l(r,u(e)),o.forEach((function(t){return t(r)})))},subscribe:function(t){return o.add(t),t(r),{unsubscribe:function(){return o.delete(t)}}},start:function(o){if(o){var u=\"object\"==typeof o?o:{context:t.config.context,value:o};r={value:u.value,actions:[],context:u.context,matches:a(u.value)}}else r=t.initialState;return i=n.Running,l(r,e),c},stop:function(){return i=n.Stopped,o.clear(),c},get state(){return r},get status(){return i}};return c}export{n as InterpreterStatus,i as assign,s as createMachine,v as interpret};\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport default index;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\n// dispatch for CommonJS interop named imports.\n\nvar useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nvar didWarnOld18Alpha = false;\nvar didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works\n// because of a very particular set of implementation details and assumptions\n// -- change any one of them and it will break. The most important assumption\n// is that updates are always synchronous, because concurrent rendering is\n// only available in versions of React that also have a built-in\n// useSyncExternalStore API. And we only use this shim when the built-in API\n// does not exist.\n//\n// Do not assume that the clever hacks used by this hook also work in general.\n// The point of this shim is to replace the need for hacks by other libraries.\n\nfunction useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n// React do not expose a way to check if we're hydrating. So users of the shim\n// will need to track that themselves and return the correct value\n// from `getSnapshot`.\ngetServerSnapshot) {\n {\n if (!didWarnOld18Alpha) {\n if (React.startTransition !== undefined) {\n didWarnOld18Alpha = true;\n\n error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');\n }\n }\n } // Read the current snapshot from the store on every render. Again, this\n // breaks the rules of React, and only works here because of specific\n // implementation details, most importantly that updates are\n // always synchronous.\n\n\n var value = getSnapshot();\n\n {\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n\n if (!objectIs(value, cachedValue)) {\n error('The result of getSnapshot should be cached to avoid an infinite loop');\n\n didWarnUncachedGetSnapshot = true;\n }\n }\n } // Because updates are synchronous, we don't queue them. Instead we force a\n // re-render whenever the subscribed state changes by updating an some\n // arbitrary useState hook. Then, during render, we call getSnapshot to read\n // the current value.\n //\n // Because we don't actually use the state returned by the useState hook, we\n // can save a bit of memory by storing other stuff in that slot.\n //\n // To implement the early bailout, we need to track some things on a mutable\n // object. Usually, we would put that in a useRef hook, but we can stash it in\n // our useState hook instead.\n //\n // To force a re-render, we call forceUpdate({inst}). That works because the\n // new object always fails an equality check.\n\n\n var _useState = useState({\n inst: {\n value: value,\n getSnapshot: getSnapshot\n }\n }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated\n // in the layout phase so we can access it during the tearing check that\n // happens on subscribe.\n\n\n useLayoutEffect(function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the\n // commit phase if there was an interleaved mutation. In concurrent mode\n // this can happen all the time, but even in synchronous mode, an earlier\n // effect may have mutated the store.\n\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }, [subscribe, value, getSnapshot]);\n useEffect(function () {\n // Check for changes right before subscribing. Subsequent changes will be\n // detected in the subscription handler.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n\n var handleStoreChange = function () {\n // TODO: Because there is no cross-renderer API for batching updates, it's\n // up to the consumer of this library to wrap their subscription event\n // with unstable_batchedUpdates. Should we try to detect when this isn't\n // the case and print a warning in development?\n // The store changed. Check if the snapshot changed since the last time we\n // read from the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }; // Subscribe to the store and return a clean-up function.\n\n\n return subscribe(handleStoreChange);\n }, [subscribe]);\n useDebugValue(value);\n return value;\n}\n\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n var prevValue = inst.value;\n\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(prevValue, nextValue);\n } catch (error) {\n return true;\n }\n}\n\nfunction useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {\n // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n // React do not expose a way to check if we're hydrating. So users of the shim\n // will need to track that themselves and return the correct value\n // from `getSnapshot`.\n return getSnapshot();\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar isServerEnvironment = !canUseDOM;\n\nvar shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;\nvar useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;\n\nexports.useSyncExternalStore = useSyncExternalStore$2;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\nvar shim = require('use-sync-external-store/shim');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = shim.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","import * as React from 'react';\nexport default function useConstant(fn) {\n var ref = React.useRef();\n if (!ref.current) {\n ref.current = { v: fn() };\n }\n return ref.current.v;\n}\n","var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nimport { createMachine, interpret, InterpreterStatus } from '@xstate/fsm';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport useConstant from './useConstant';\nfunction identity(a) {\n return a;\n}\nvar getServiceState = function (service) {\n var currentValue;\n service\n .subscribe(function (state) {\n currentValue = state;\n })\n .unsubscribe();\n return currentValue;\n};\nexport function useMachine(stateMachine, options) {\n var persistedStateRef = useRef();\n if (process.env.NODE_ENV !== 'production') {\n var _a = __read(useState(stateMachine), 1), initialMachine = _a[0];\n if (stateMachine !== initialMachine) {\n console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\\n' +\n 'Please make sure that you pass the same Machine as argument each time.');\n }\n }\n var _b = __read(useConstant(function () {\n var queue = [];\n var service = interpret(createMachine(stateMachine.config, options ? options : stateMachine._options));\n var send = service.send;\n service.send = function (event) {\n if (service.status === InterpreterStatus.NotStarted) {\n queue.push(event);\n return;\n }\n send(event);\n persistedStateRef.current = service.state;\n };\n return [service, queue];\n }), 2), service = _b[0], queue = _b[1];\n useIsomorphicLayoutEffect(function () {\n if (options) {\n service._machine._options = options;\n }\n });\n var useServiceResult = useService(service);\n useEffect(function () {\n service.start(persistedStateRef.current);\n queue.forEach(service.send);\n persistedStateRef.current = service.state;\n return function () {\n service.stop();\n };\n }, []);\n return useServiceResult;\n}\nvar isEqual = function (_prevState, nextState) { return nextState.changed === false; };\nexport function useService(service) {\n var getSnapshot = useCallback(function () { return getServiceState(service); }, [service]);\n var subscribe = useCallback(function (handleStoreChange) {\n var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;\n return unsubscribe;\n }, [service]);\n var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, identity, isEqual);\n return [storeSnapshot, service.send, service];\n}\n","import type {PartialDeep} from 'type-fest';\n\n/**\n * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](https://shopify.dev/api/storefront/reference/products/product)) into a flat array of nodes.\n * The utility works with either `nodes` or `edges.node`.\n *\n * If `connection` is null or undefined, will return an empty array instead in production. In development, an error will be thrown.\n */\nexport function flattenConnection<\n ConnectionGeneric extends\n | PartialDeep<ConnectionEdges, {recurseIntoArrays: true}>\n | PartialDeep<ConnectionNodes, {recurseIntoArrays: true}>\n | ConnectionEdges\n | ConnectionNodes,\n>(\n connection?: ConnectionGeneric,\n): ConnectionGeneric extends\n | {\n edges: {node: Array<infer ConnectionBaseType>};\n }\n | {\n nodes: Array<infer ConnectionBaseType>;\n }\n ? // if it's not a PartialDeep, then return the infered type\n ConnectionBaseType[]\n : ConnectionGeneric extends\n | PartialDeep<\n {edges: {node: Array<infer ConnectionBaseType>}},\n {recurseIntoArrays: true}\n >\n | PartialDeep<\n {\n nodes: Array<infer ConnectionBaseType>;\n },\n {recurseIntoArrays: true}\n >\n ? // if it is a PartialDeep, return a PartialDeep inferred type\n PartialDeep<ConnectionBaseType[], {recurseIntoArrays: true}>\n : never {\n if (!connection) {\n const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${\n connection ?? ''\n }' instead.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noConnectionErr);\n } else {\n console.error(noConnectionErr + ` Returning an empty array`);\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n }\n }\n\n if ('nodes' in connection) {\n // @ts-expect-error return type is failing\n return connection.nodes;\n }\n\n if ('edges' in connection && Array.isArray(connection.edges)) {\n // @ts-expect-error return type is failing\n return connection.edges.map((edge) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!edge?.node) {\n throw new Error(\n 'flattenConnection(): Connection edges must contain nodes',\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access\n return edge.node;\n }) as Array<unknown>;\n }\n\n if (__HYDROGEN_DEV__) {\n console.warn(\n `flattenConnection(): The connection did not contain either \"nodes\" or \"edges.node\". Returning an empty array.`,\n );\n }\n\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n}\n\ntype ConnectionEdges = {\n edges: {node: Array<unknown>};\n};\n\ntype ConnectionNodes = {\n nodes: Array<unknown>;\n};\n\n// This is only for documentation purposes, and it is not used in the code.\nexport interface ConnectionGenericForDoc {\n connection?: ConnectionEdges | ConnectionNodes;\n}\nexport type FlattenConnectionReturnForDoc = Array<unknown>;\n","export const CartLineAdd = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineAdd(\n $cartId: ID!\n $lines: [CartLineInput!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartCreate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartCreate(\n $input: CartInput!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartCreate(input: $input) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartLineRemove = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineRemove(\n $cartId: ID!\n $lines: [ID!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesRemove(cartId: $cartId, lineIds: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartLineUpdate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineUpdate(\n $cartId: ID!\n $lines: [CartLineUpdateInput!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartNoteUpdate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartNoteUpdate(\n $cartId: ID!\n $note: String\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartNoteUpdate(cartId: $cartId, note: $note) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartBuyerIdentityUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartBuyerIdentityUpdate(\n $cartId: ID!\n $buyerIdentity: CartBuyerIdentityInput!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartAttributesUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartAttributesUpdate(\n $attributes: [AttributeInput!]!\n $cartId: ID!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartAttributesUpdate(attributes: $attributes, cartId: $cartId) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartDiscountCodesUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartDiscountCodesUpdate(\n $cartId: ID!\n $discountCodes: [String!]\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartQuery = (cartFragment: string): string => /* GraphQL */ `\n query CartQuery(\n $id: ID!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cart(id: $id) {\n ...CartFragment\n }\n }\n\n ${cartFragment}\n`;\n\nexport const defaultCartFragment = /* GraphQL */ `\n fragment CartFragment 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 compareAtAmountPerQuantity {\n amount\n currencyCode\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n availableForSale\n compareAtPrice {\n ...MoneyFragment\n }\n price {\n ...MoneyFragment\n }\n requiresShipping\n title\n image {\n ...ImageFragment\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 ...MoneyFragment\n }\n totalAmount {\n ...MoneyFragment\n }\n totalDutyAmount {\n ...MoneyFragment\n }\n totalTaxAmount {\n ...MoneyFragment\n }\n }\n note\n attributes {\n key\n value\n }\n discountCodes {\n code\n }\n }\n\n fragment MoneyFragment on MoneyV2 {\n currencyCode\n amount\n }\n fragment ImageFragment on Image {\n id\n url\n altText\n width\n height\n }\n`;\n","export const SFAPI_VERSION = '2023-04';\n","import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n","import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n return overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n }\n\n return {\n ...shopifyConfig,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = getShopifyDomain({\n storeDomain: overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase,\n ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n","export const CART_ID_STORAGE_KEY = 'shopifyCartId';\nexport const CART_COOKIE_TTL_DAYS = 14;\n\n// Needed for cart analytics within Shopify\nexport const SHOPIFY_STOREFRONT_ID_HEADER = 'Shopify-Storefront-Id';\nexport const SHOPIFY_STOREFRONT_Y_HEADER = 'Shopify-Storefront-Y';\nexport const SHOPIFY_STOREFRONT_S_HEADER = 'Shopify-Storefront-S';\nexport const SHOPIFY_Y = '_shopify_y';\nexport const SHOPIFY_S = '_shopify_s';\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';\nimport {ShopifyCookies} from './analytics-types.js';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\n\nconst tokenHash = 'xxxx-4xxx-xxxx-xxxxxxxxxxxx';\n\nexport function buildUUID(): string {\n let hash = '';\n\n try {\n const crypto: Crypto = window.crypto;\n const randomValuesArray = new Uint16Array(31);\n crypto.getRandomValues(randomValuesArray);\n\n // Generate a strong UUID\n let i = 0;\n hash = tokenHash\n .replace(/[x]/g, (c: string): string => {\n const r = randomValuesArray[i] % 16;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n i++;\n return v.toString(16);\n })\n .toUpperCase();\n } catch (err) {\n // crypto not available, generate weak UUID\n hash = tokenHash\n .replace(/[x]/g, (c: string): string => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n })\n .toUpperCase();\n }\n\n return `${hexTime()}-${hash}`;\n}\n\nexport function hexTime(): string {\n // 32 bit representations of new Date().getTime() and performance.now()\n let dateNumber = 0;\n let perfNumber = 0;\n\n // Result of zero-fill right shift is always positive\n dateNumber = new Date().getTime() >>> 0;\n\n try {\n perfNumber = performance.now() >>> 0;\n } catch (err) {\n perfNumber = 0;\n }\n\n const output = Math.abs(dateNumber + perfNumber)\n .toString(16)\n .toLowerCase();\n\n return output.padStart(8 - output.length, '0');\n}\n\nexport function getShopifyCookies(cookies: string): ShopifyCookies {\n const cookieData = parse(cookies);\n return {\n [SHOPIFY_Y]: cookieData[SHOPIFY_Y] || '',\n [SHOPIFY_S]: cookieData[SHOPIFY_S] || '',\n };\n}\n","import {useState, useCallback} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {CartInput, Cart as CartType} from './storefront-api-types.js';\nimport {CartCreate, defaultCartFragment} from './cart-queries.js';\nimport {Cart} from './cart-types.js';\nimport {\n SHOPIFY_STOREFRONT_ID_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_Y,\n SHOPIFY_S,\n} from './cart-constants.js';\nimport type {StorefrontApiResponseOkPartial} from './storefront-api-response.types.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartFetch() {\n const {storefrontId, getPublicTokenHeaders, getStorefrontApiUrl} = useShop();\n\n return useCallback(\n <ReturnDataGeneric,>({\n query,\n variables,\n }: {\n query: string;\n variables: Record<string, unknown>;\n }): Promise<StorefrontApiResponseOkPartial<ReturnDataGeneric>> => {\n const headers = getPublicTokenHeaders({contentType: 'json'});\n\n if (storefrontId) {\n headers[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId;\n }\n\n // Find Shopify cookies\n const cookieData = getShopifyCookies(document.cookie);\n headers[SHOPIFY_STOREFRONT_Y_HEADER] = cookieData[SHOPIFY_Y];\n headers[SHOPIFY_STOREFRONT_S_HEADER] = cookieData[SHOPIFY_S];\n\n return fetch(getStorefrontApiUrl(), {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query: query.toString(),\n variables,\n }),\n })\n .then(\n (res) =>\n res.json() as StorefrontApiResponseOkPartial<ReturnDataGeneric>,\n )\n .catch((error) => {\n return {\n data: undefined,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n errors: error?.toString(),\n };\n });\n },\n [getPublicTokenHeaders, storefrontId, getStorefrontApiUrl],\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useInstantCheckout() {\n const [cart, updateCart] = useState<Cart | undefined>();\n const [checkoutUrl, updateCheckoutUrl] = useState<Cart['checkoutUrl']>();\n const [error, updateError] = useState<string | undefined>();\n\n const fetch = useCartFetch();\n\n const createInstantCheckout = useCallback(\n async (cartInput: CartInput) => {\n const {data, errors} = await fetch<{\n cartCreate: {cart: CartType};\n }>({\n query: CartCreate(defaultCartFragment),\n variables: {\n input: cartInput,\n },\n });\n\n if (errors) {\n updateError(errors.toString());\n updateCart(undefined);\n updateCheckoutUrl(undefined);\n }\n\n if (data?.cartCreate?.cart) {\n const dataCart = data.cartCreate.cart;\n updateCart({\n ...dataCart,\n lines: flattenConnection(dataCart.lines),\n note: dataCart.note ?? undefined,\n });\n updateCheckoutUrl(dataCart.checkoutUrl);\n }\n },\n [fetch],\n );\n\n return {cart, checkoutUrl, error, createInstantCheckout};\n}\n","import {useCallback, useMemo} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n Cart as CartType,\n MutationCartDiscountCodesUpdateArgs,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n CartAttributesUpdate,\n CartBuyerIdentityUpdate,\n CartCreate,\n CartDiscountCodesUpdate,\n CartLineAdd,\n CartLineRemove,\n CartLineUpdate,\n CartNoteUpdate,\n CartQuery,\n} from './cart-queries.js';\nimport {useCartFetch} from './cart-hooks.js';\nimport {PartialDeep} from 'type-fest';\n\ntype CartResponse = PartialDeep<CartType, {recurseIntoArrays: true}>;\n\n/**\n * The `useCartActions` hook returns helper graphql functions for Storefront Cart API\n *\n * See [cart API graphql mutations](https://shopify.dev/api/storefront/2023-04/objects/Cart)\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartActions({\n numCartLines,\n cartFragment,\n countryCode = 'US',\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n}) {\n const fetchCart = useCartFetch();\n\n const cartFetch = useCallback(\n (cartId: string) => {\n return fetchCart<{cart: CartResponse}>({\n query: CartQuery(cartFragment),\n variables: {\n id: cartId,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode],\n );\n\n const cartCreate = useCallback(\n (cart: CartInput) => {\n return fetchCart<{cartCreate: {cart: CartResponse}}>({\n query: CartCreate(cartFragment),\n variables: {\n input: cart,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineAdd = useCallback(\n (cartId: string, lines: CartLineInput[]) => {\n return fetchCart<{cartLinesAdd: {cart: CartResponse}}>({\n query: CartLineAdd(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineUpdate = useCallback(\n (cartId: string, lines: CartLineUpdateInput[]) => {\n return fetchCart<{cartLinesUpdate: {cart: CartResponse}}>({\n query: CartLineUpdate(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineRemove = useCallback(\n (cartId: string, lines: string[]) => {\n return fetchCart<{cartLinesRemove: {cart: CartResponse}}>({\n query: CartLineRemove(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const noteUpdate = useCallback(\n (cartId: string, note: MutationCartNoteUpdateArgs['note']) => {\n return fetchCart<{cartNoteUpdate: {cart: CartResponse}}>({\n query: CartNoteUpdate(cartFragment),\n variables: {\n cartId,\n note,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode],\n );\n\n const buyerIdentityUpdate = useCallback(\n (cartId: string, buyerIdentity: CartBuyerIdentityInput) => {\n return fetchCart<{cartBuyerIdentityUpdate: {cart: CartResponse}}>({\n query: CartBuyerIdentityUpdate(cartFragment),\n variables: {\n cartId,\n buyerIdentity,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartAttributesUpdate = useCallback(\n (cartId: string, attributes: AttributeInput[]) => {\n return fetchCart<{cartAttributesUpdate: {cart: CartResponse}}>({\n query: CartAttributesUpdate(cartFragment),\n variables: {\n cartId,\n attributes,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const discountCodesUpdate = useCallback(\n (\n cartId: string,\n discountCodes: MutationCartDiscountCodesUpdateArgs['discountCodes'],\n ) => {\n return fetchCart<{cartDiscountCodesUpdate: {cart: CartResponse}}>({\n query: CartDiscountCodesUpdate(cartFragment),\n variables: {\n cartId,\n discountCodes,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n return useMemo(\n () => ({\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n }),\n [\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n ],\n );\n}\n","import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {CountryCode, Cart as CartType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n createContext,\n useContext,\n} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n Cart as CartType,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n BuyerIdentityUpdateEvent,\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState,\n CartWithActions,\n} from './cart-types.js';\nimport {useCartAPIStateMachine} from './useCartAPIStateMachine.js';\nimport {CART_ID_STORAGE_KEY} from './cart-constants.js';\nimport {PartialDeep} from 'type-fest';\nimport {defaultCartFragment} from './cart-queries.js';\n\nexport const CartContext = createContext<CartWithActions | null>(null);\n\n/**\n * The `useCart` hook provides access to the cart object. It must be a descendent of a `CartProvider` component.\n */\nexport function useCart(): CartWithActions {\n const context = useContext(CartContext);\n\n if (!context) {\n throw new Error('Expected a Cart Context, but no Cart Context was found');\n }\n\n return context;\n}\n\ntype CartProviderProps = {\n /** Any `ReactNode` elements. */\n children: React.ReactNode;\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked when the process to create a cart begins, but before the cart is created in the Storefront API. */\n onCreate?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart begins, but before the line item is added to the Storefront API. */\n onLineAdd?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart begins, but before the line item is removed from the Storefront API. */\n onLineRemove?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart begins, but before the line item is updated in the Storefront API. */\n onLineUpdate?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart begins, but before the note is added or updated in the Storefront API. */\n onNoteUpdate?: () => void;\n /** A callback that is invoked when the process to update the buyer identity begins, but before the buyer identity is updated in the Storefront API. */\n onBuyerIdentityUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart attributes begins, but before the attributes are updated in the Storefront API. */\n onAttributesUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes begins, but before the discount codes are updated in the Storefront API. */\n onDiscountCodesUpdate?: () => void;\n /** A callback that is invoked when the process to create a cart completes */\n onCreateComplete?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart completes */\n onLineAddComplete?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart completes */\n onLineRemoveComplete?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart completes */\n onLineUpdateComplete?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart completes */\n onNoteUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the buyer identity completes */\n onBuyerIdentityUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart attributes completes */\n onAttributesUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes completes */\n onDiscountCodesUpdateComplete?: () => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment?: string;\n /** A customer access token that's accessible on the server if there's a customer login. */\n customerAccessToken?: CartBuyerIdentityInput['customerAccessToken'];\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n};\n\n/**\n * The `CartProvider` component synchronizes the state of the Storefront API Cart and a customer's cart,\n * and allows you to more easily manipulate the cart by adding, removing, and updating it.\n * It could be placed at the root of your app so that your whole app is able to use the `useCart()` hook anywhere.\n *\n * There are props that trigger when a call to the Storefront API is made, such as `onLineAdd={}` when a line is added to the cart.\n * There are also props that trigger when a call to the Storefront API is completed, such as `onLineAddComplete={}` when the fetch request for adding a line to the cart completes.\n *\n * The `CartProvider` component must be a descendant of the `ShopifyProvider` component.\n */\nexport function CartProvider({\n children,\n numCartLines,\n onCreate,\n onLineAdd,\n onLineRemove,\n onLineUpdate,\n onNoteUpdate,\n onBuyerIdentityUpdate,\n onAttributesUpdate,\n onDiscountCodesUpdate,\n onCreateComplete,\n onLineAddComplete,\n onLineRemoveComplete,\n onLineUpdateComplete,\n onNoteUpdateComplete,\n onBuyerIdentityUpdateComplete,\n onAttributesUpdateComplete,\n onDiscountCodesUpdateComplete,\n data: cart,\n cartFragment = defaultCartFragment,\n customerAccessToken,\n countryCode = 'US',\n}: CartProviderProps): JSX.Element {\n if (countryCode) countryCode = countryCode.toUpperCase() as CountryCode;\n const [prevCountryCode, setPrevCountryCode] = useState(countryCode);\n const [prevCustomerAccessToken, setPrevCustomerAccessToken] =\n useState(customerAccessToken);\n const customerOverridesCountryCode = useRef(false);\n\n if (\n prevCountryCode !== countryCode ||\n prevCustomerAccessToken !== customerAccessToken\n ) {\n setPrevCountryCode(countryCode);\n setPrevCustomerAccessToken(customerAccessToken);\n customerOverridesCountryCode.current = false;\n }\n\n const [cartState, cartSend] = useCartAPIStateMachine({\n numCartLines,\n data: cart,\n cartFragment,\n countryCode,\n onCartActionEntry(_, event) {\n try {\n switch (event.type) {\n case 'CART_CREATE':\n return onCreate?.();\n case 'CARTLINE_ADD':\n return onLineAdd?.();\n case 'CARTLINE_REMOVE':\n return onLineRemove?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdate?.();\n case 'NOTE_UPDATE':\n return onNoteUpdate?.();\n case 'BUYER_IDENTITY_UPDATE':\n return onBuyerIdentityUpdate?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdate?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdate?.();\n }\n } catch (error) {\n console.error('Cart entry action failed', error);\n }\n },\n onCartActionOptimisticUI(context, event) {\n if (!context.cart) return {...context};\n switch (event.type) {\n case 'CARTLINE_REMOVE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.filter(\n (line) => line?.id && !event.payload.lines.includes(line?.id),\n ),\n },\n };\n case 'CARTLINE_UPDATE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.map((line) => {\n const updatedLine = event.payload.lines.find(\n ({id}) => id === line?.id,\n );\n\n if (updatedLine && updatedLine.quantity) {\n return {\n ...line,\n quantity: updatedLine.quantity,\n };\n }\n\n return line;\n }),\n },\n };\n }\n return {...context};\n },\n onCartActionComplete(context, event) {\n const cartActionEvent = event.payload.cartActionEvent;\n try {\n switch (event.type) {\n case 'RESOLVE':\n switch (cartActionEvent.type) {\n case 'CART_CREATE':\n return onCreateComplete?.();\n case 'CARTLINE_ADD':\n return onLineAddComplete?.();\n case 'CARTLINE_REMOVE':\n return onLineRemoveComplete?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdateComplete?.();\n case 'NOTE_UPDATE':\n return onNoteUpdateComplete?.();\n case 'BUYER_IDENTITY_UPDATE':\n if (countryCodeNotUpdated(context, cartActionEvent)) {\n customerOverridesCountryCode.current = true;\n }\n return onBuyerIdentityUpdateComplete?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdateComplete?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdateComplete?.();\n }\n }\n } catch (error) {\n console.error('onCartActionComplete failed', error);\n }\n },\n });\n\n const cartReady = useRef(false);\n const cartCompleted = cartState.matches('cartCompleted');\n\n const countryChanged =\n (cartState.value === 'idle' ||\n cartState.value === 'error' ||\n cartState.value === 'cartCompleted') &&\n countryCode !== cartState?.context?.cart?.buyerIdentity?.countryCode &&\n !cartState.context.errors;\n\n const fetchingFromStorage = useRef(false);\n\n /**\n * Initializes cart with priority in this order:\n * 1. cart props\n * 2. localStorage cartId\n */\n useEffect(() => {\n if (!cartReady.current && !fetchingFromStorage.current) {\n if (!cart && storageAvailable('localStorage')) {\n fetchingFromStorage.current = true;\n try {\n const cartId = window.localStorage.getItem(CART_ID_STORAGE_KEY);\n if (cartId) {\n cartSend({type: 'CART_FETCH', payload: {cartId}});\n }\n } catch (error) {\n console.warn('error fetching cartId');\n console.warn(error);\n }\n }\n cartReady.current = true;\n }\n }, [cart, cartReady, cartSend]);\n\n // Update cart country code if cart and props countryCode's as different\n useEffect(() => {\n if (!countryChanged || customerOverridesCountryCode.current) return;\n cartSend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {buyerIdentity: {countryCode, customerAccessToken}},\n });\n }, [\n countryCode,\n customerAccessToken,\n countryChanged,\n customerOverridesCountryCode,\n cartSend,\n ]);\n\n // send cart events when ready\n const onCartReadySend = useCallback(\n (cartEvent: CartMachineEvent) => {\n if (!cartReady.current) {\n return console.warn(\"Cart isn't ready yet\");\n }\n cartSend(cartEvent);\n },\n [cartSend],\n );\n\n // save cart id to local storage\n useEffect(() => {\n if (cartState?.context?.cart?.id && storageAvailable('localStorage')) {\n try {\n window.localStorage.setItem(\n CART_ID_STORAGE_KEY,\n cartState.context.cart?.id,\n );\n } catch (error) {\n console.warn('Failed to save cartId to localStorage', error);\n }\n }\n }, [cartState?.context?.cart?.id]);\n\n // delete cart from local storage if cart fetched has been completed\n useEffect(() => {\n if (cartCompleted && storageAvailable('localStorage')) {\n try {\n window.localStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch (error) {\n console.warn('Failed to delete cartId from localStorage', error);\n }\n }\n }, [cartCompleted]);\n\n const cartCreate = useCallback(\n (cartInput: CartInput) => {\n if (countryCode && !cartInput.buyerIdentity?.countryCode) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.countryCode = countryCode;\n }\n\n if (\n customerAccessToken &&\n !cartInput.buyerIdentity?.customerAccessToken\n ) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.customerAccessToken = customerAccessToken;\n }\n onCartReadySend({\n type: 'CART_CREATE',\n payload: cartInput,\n });\n },\n [countryCode, customerAccessToken, onCartReadySend],\n );\n\n // Delays the cart state in the context if the page is hydrating\n // preventing suspense boundary errors.\n const cartDisplayState = useDelayedStateUntilHydration(cartState);\n\n const cartContextValue = useMemo<CartWithActions>(() => {\n return {\n ...(cartDisplayState?.context?.cart ?? {lines: [], attributes: []}),\n status: transposeStatus(cartDisplayState.value),\n error: cartDisplayState?.context?.errors,\n totalQuantity: cartDisplayState?.context?.cart?.totalQuantity ?? 0,\n cartCreate,\n linesAdd(lines: CartLineInput[]): void {\n if (cartDisplayState?.context?.cart?.id) {\n onCartReadySend({\n type: 'CARTLINE_ADD',\n payload: {lines},\n });\n } else {\n cartCreate({lines});\n }\n },\n linesRemove(lines: string[]): void {\n onCartReadySend({\n type: 'CARTLINE_REMOVE',\n payload: {\n lines,\n },\n });\n },\n linesUpdate(lines: CartLineUpdateInput[]): void {\n onCartReadySend({\n type: 'CARTLINE_UPDATE',\n payload: {\n lines,\n },\n });\n },\n noteUpdate(note: MutationCartNoteUpdateArgs['note']): void {\n onCartReadySend({\n type: 'NOTE_UPDATE',\n payload: {\n note,\n },\n });\n },\n buyerIdentityUpdate(buyerIdentity: CartBuyerIdentityInput): void {\n onCartReadySend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {\n buyerIdentity,\n },\n });\n },\n cartAttributesUpdate(attributes: AttributeInput[]): void {\n onCartReadySend({\n type: 'CART_ATTRIBUTES_UPDATE',\n payload: {\n attributes,\n },\n });\n },\n discountCodesUpdate(discountCodes: string[]): void {\n onCartReadySend({\n type: 'DISCOUNT_CODES_UPDATE',\n payload: {\n discountCodes,\n },\n });\n },\n cartFragment,\n };\n }, [\n cartCreate,\n cartDisplayState?.context?.cart,\n cartDisplayState?.context?.errors,\n cartDisplayState.value,\n cartFragment,\n onCartReadySend,\n ]);\n\n return (\n <CartContext.Provider value={cartContextValue}>\n {children}\n </CartContext.Provider>\n );\n}\n\nfunction transposeStatus(\n status: CartMachineTypeState['value'],\n): CartWithActions['status'] {\n switch (status) {\n case 'uninitialized':\n case 'initializationError':\n return 'uninitialized';\n case 'idle':\n case 'cartCompleted':\n case 'error':\n return 'idle';\n case 'cartFetching':\n return 'fetching';\n case 'cartCreating':\n return 'creating';\n case 'cartLineAdding':\n case 'cartLineRemoving':\n case 'cartLineUpdating':\n case 'noteUpdating':\n case 'buyerIdentityUpdating':\n case 'cartAttributesUpdating':\n case 'discountCodesUpdating':\n return 'updating';\n }\n}\n\n/**\n * Delays a state update until hydration finishes. Useful for preventing suspense boundaries errors when updating a context\n * @remarks this uses startTransition and waits for it to finish.\n */\nfunction useDelayedStateUntilHydration<T>(state: T): T {\n const [isPending, startTransition] = useTransition();\n const [delayedState, setDelayedState] = useState(state);\n\n const firstTimePending = useRef(false);\n if (isPending) {\n firstTimePending.current = true;\n }\n\n const firstTimePendingFinished = useRef(false);\n if (!isPending && firstTimePending.current) {\n firstTimePendingFinished.current = true;\n }\n\n useEffect(() => {\n startTransition(() => {\n if (!firstTimePendingFinished.current) {\n setDelayedState(state);\n }\n });\n }, [state]);\n\n const displayState = firstTimePendingFinished.current ? state : delayedState;\n\n return displayState;\n}\n\n/** Check for storage availability funciton obtained from\n * https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API\n */\nexport function storageAvailable(\n type: 'localStorage' | 'sessionStorage',\n): boolean {\n let storage;\n try {\n storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return true;\n } catch (e) {\n return !!(\n e instanceof DOMException &&\n // everything except Firefox\n (e.code === 22 ||\n // Firefox\n e.code === 1014 ||\n // test name field too, because code might not be present\n // everything except Firefox\n e.name === 'QuotaExceededError' ||\n // Firefox\n e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&\n // acknowledge QuotaExceededError only if there's something already stored\n storage &&\n storage.length !== 0\n );\n }\n}\n\nfunction countryCodeNotUpdated(\n context: CartMachineContext,\n event: BuyerIdentityUpdateEvent,\n): boolean {\n return !!(\n event.payload.buyerIdentity.countryCode &&\n context.cart?.buyerIdentity?.countryCode !==\n event.payload.buyerIdentity.countryCode\n );\n}\n","import {\n useMemo,\n useState,\n useEffect,\n useCallback,\n createContext,\n useContext,\n} from 'react';\nimport type {\n SelectedOption as SelectedOptionType,\n SellingPlan,\n SellingPlanAllocation,\n Product,\n ProductVariant as ProductVariantType,\n ProductVariantConnection,\n SellingPlan as SellingPlanType,\n SellingPlanAllocation as SellingPlanAllocationType,\n SellingPlanGroup as SellingPlanGroupType,\n SellingPlanGroupConnection,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nconst ProductOptionsContext = createContext<ProductHookValue | null>(null);\n\ntype InitialVariantId = ProductVariantType['id'] | null;\n\ninterface ProductProviderProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** A `ReactNode` element. */\n children: React.ReactNode;\n /**\n * The initially selected variant.\n * The following logic applies to `initialVariantId`:\n * 1. If `initialVariantId` is provided, then it's used even if it's out of stock.\n * 2. If `initialVariantId` is provided but is `null`, then no variant is used.\n * 3. If nothing is passed to `initialVariantId` then the first available / in-stock variant is used.\n * 4. If nothing is passed to `initialVariantId` and no variants are in stock, then the first variant is used.\n */\n initialVariantId?: InitialVariantId;\n}\n\n/**\n * `<ProductProvider />` is a context provider that enables use of the `useProduct()` hook.\n *\n * It helps manage selected options and variants for a product.\n */\nexport function ProductProvider({\n children,\n data: product,\n initialVariantId: explicitVariantId,\n}: ProductProviderProps): JSX.Element {\n // The flattened variants\n const variants = useMemo(\n () => flattenConnection(product.variants ?? {}),\n [product.variants],\n );\n\n if (!isProductVariantArray(variants)) {\n throw new Error(\n `<ProductProvider/> requires 'product.variants.nodes' or 'product.variants.edges'`,\n );\n }\n\n // All the options available for a product, based on all the variants\n const options = useMemo(() => getOptions(variants), [variants]);\n\n /**\n * Track the selectedVariant within the provider.\n */\n const [selectedVariant, setSelectedVariant] = useState<\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null\n >(() => getVariantBasedOnIdProp(explicitVariantId, variants));\n\n /**\n * Track the selectedOptions within the provider. If a `initialVariantId`\n * is passed, use that to select initial options.\n */\n const [selectedOptions, setSelectedOptions] = useState<SelectedOptions>(() =>\n getSelectedOptions(selectedVariant),\n );\n\n /**\n * When the initialVariantId changes, we need to make sure we\n * update the selected variant and selected options. If not,\n * then the selected variant and options will reference incorrect\n * values.\n */\n useEffect(() => {\n const newSelectedVariant = getVariantBasedOnIdProp(\n explicitVariantId,\n variants,\n );\n setSelectedVariant(newSelectedVariant);\n setSelectedOptions(getSelectedOptions(newSelectedVariant));\n }, [explicitVariantId, variants]);\n\n /**\n * Allow the developer to select an option.\n */\n const setSelectedOption = useCallback(\n (name: string, value: string) => {\n setSelectedOptions((selectedOptions) => {\n const opts = {...selectedOptions, [name]: value};\n setSelectedVariant(getSelectedVariant(variants, opts));\n return opts;\n });\n },\n [setSelectedOptions, variants],\n );\n\n const isOptionInStock = useCallback(\n (option: string, value: string) => {\n const proposedVariant = getSelectedVariant(variants, {\n ...selectedOptions,\n ...{[option]: value},\n });\n\n return proposedVariant?.availableForSale ?? true;\n },\n [selectedOptions, variants],\n );\n\n const sellingPlanGroups = useMemo(\n () =>\n flattenConnection(product.sellingPlanGroups ?? {}).map(\n (sellingPlanGroup) => ({\n ...sellingPlanGroup,\n sellingPlans: flattenConnection(sellingPlanGroup?.sellingPlans ?? {}),\n }),\n ),\n [product.sellingPlanGroups],\n );\n\n /**\n * Track the selectedSellingPlan within the hook. If `initialSellingPlanId`\n * is passed, use that as an initial value. Look it up from the `selectedVariant`, since\n * that is also a requirement.\n */\n const [selectedSellingPlan, setSelectedSellingPlan] = useState<\n PartialDeep<SellingPlan, {recurseIntoArrays: true}> | undefined\n >(undefined);\n\n const selectedSellingPlanAllocation = useMemo<\n PartialDeep<SellingPlanAllocation, {recurseIntoArrays: true}> | undefined\n >(() => {\n if (!selectedVariant || !selectedSellingPlan) {\n return;\n }\n\n if (\n !selectedVariant.sellingPlanAllocations?.nodes &&\n !selectedVariant.sellingPlanAllocations?.edges\n ) {\n throw new Error(\n `<ProductProvider/>: You must include 'sellingPlanAllocations.nodes' or 'sellingPlanAllocations.edges' in your variants in order to calculate selectedSellingPlanAllocation`,\n );\n }\n\n return flattenConnection(selectedVariant.sellingPlanAllocations).find(\n (allocation) => allocation?.sellingPlan?.id === selectedSellingPlan.id,\n );\n }, [selectedVariant, selectedSellingPlan]);\n\n const value = useMemo<ProductHookValue>(\n () => ({\n product,\n variants,\n variantsConnection: product.variants,\n options,\n selectedVariant,\n setSelectedVariant,\n selectedOptions,\n setSelectedOption,\n setSelectedOptions,\n isOptionInStock,\n selectedSellingPlan,\n setSelectedSellingPlan,\n selectedSellingPlanAllocation,\n sellingPlanGroups,\n sellingPlanGroupsConnection: product.sellingPlanGroups,\n }),\n [\n product,\n isOptionInStock,\n options,\n selectedOptions,\n selectedSellingPlan,\n selectedSellingPlanAllocation,\n selectedVariant,\n sellingPlanGroups,\n setSelectedOption,\n variants,\n ],\n );\n\n return (\n <ProductOptionsContext.Provider value={value}>\n {children}\n </ProductOptionsContext.Provider>\n );\n}\n\n/**\n * Provides access to the context value provided by `<ProductProvider />`. Must be a descendent of `<ProductProvider />`.\n */\nexport function useProduct(): ProductHookValue {\n const context = useContext(ProductOptionsContext);\n\n if (!context) {\n throw new Error(`'useProduct' must be a child of <ProductProvider />`);\n }\n\n return context;\n}\n\nfunction getSelectedVariant(\n variants: PartialDeep<ProductVariantType, {recurseIntoArrays: true}>[],\n choices: SelectedOptions,\n): PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined {\n /**\n * Ensure the user has selected all the required options, not just some.\n */\n if (\n !variants.length ||\n variants?.[0]?.selectedOptions?.length !== Object.keys(choices).length\n ) {\n return;\n }\n\n return variants?.find((variant) => {\n return Object.entries(choices).every(([name, value]) => {\n return variant?.selectedOptions?.some(\n (option) => option?.name === name && option?.value === value,\n );\n });\n });\n}\n\nfunction getOptions(\n variants: PartialDeep<ProductVariantType, {recurseIntoArrays: true}>[],\n): OptionWithValues[] {\n const map = variants.reduce((memo, variant) => {\n if (!variant.selectedOptions) {\n throw new Error(`'getOptions' requires 'variant.selectedOptions'`);\n }\n variant?.selectedOptions?.forEach((opt) => {\n memo[opt?.name ?? ''] = memo[opt?.name ?? ''] || new Set();\n memo[opt?.name ?? ''].add(opt?.value ?? '');\n });\n\n return memo;\n }, {} as Record<string, Set<string>>);\n\n return Object.keys(map).map((option) => {\n return {\n name: option,\n values: Array.from(map[option]),\n };\n });\n}\n\nfunction getVariantBasedOnIdProp(\n explicitVariantId: InitialVariantId | undefined,\n variants: Array<\n PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined\n >,\n):\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null {\n // get the initial variant based on the logic outlined in the comments for 'initialVariantId' above\n // * 1. If `initialVariantId` is provided, then it's used even if it's out of stock.\n if (explicitVariantId) {\n const foundVariant = variants.find(\n (variant) => variant?.id === explicitVariantId,\n );\n if (!foundVariant) {\n console.warn(\n `<ProductProvider/> received a 'initialVariantId' prop, but could not actually find a variant with that ID`,\n );\n }\n return foundVariant;\n }\n // * 2. If `initialVariantId` is provided but is `null`, then no variant is used.\n if (explicitVariantId === null) {\n return null;\n }\n // * 3. If nothing is passed to `initialVariantId` then the first available / in-stock variant is used.\n // * 4. If nothing is passed to `initialVariantId` and no variants are in stock, then the first variant is used.\n if (explicitVariantId === undefined) {\n return variants.find((variant) => variant?.availableForSale) || variants[0];\n }\n}\n\nfunction getSelectedOptions(\n selectedVariant:\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null,\n): SelectedOptions {\n return selectedVariant?.selectedOptions\n ? selectedVariant.selectedOptions.reduce<SelectedOptions>(\n (memo, optionSet) => {\n memo[optionSet?.name ?? ''] = optionSet?.value ?? '';\n return memo;\n },\n {},\n )\n : {};\n}\n\nfunction isProductVariantArray(\n maybeVariantArray:\n | (PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined)[]\n | undefined,\n): maybeVariantArray is PartialDeep<\n ProductVariantType,\n {recurseIntoArrays: true}\n>[] {\n if (!maybeVariantArray || !Array.isArray(maybeVariantArray)) {\n return false;\n }\n\n return true;\n}\n\nexport interface OptionWithValues {\n name: SelectedOptionType['name'];\n values: SelectedOptionType['value'][];\n}\n\ntype UseProductObjects = {\n /** The raw product from the Storefront API */\n product: Product;\n /** An array of the variant `nodes` from the `VariantConnection`. */\n variants: ProductVariantType[];\n variantsConnection?: ProductVariantConnection;\n /** An array of the product's options and values. */\n options: OptionWithValues[];\n /** The selected variant. */\n selectedVariant?: ProductVariantType | null;\n selectedOptions: SelectedOptions;\n /** The selected selling plan. */\n selectedSellingPlan?: SellingPlanType;\n /** The selected selling plan allocation. */\n selectedSellingPlanAllocation?: SellingPlanAllocationType;\n /** The selling plan groups. */\n sellingPlanGroups?: (Omit<SellingPlanGroupType, 'sellingPlans'> & {\n sellingPlans: SellingPlanType[];\n })[];\n sellingPlanGroupsConnection?: SellingPlanGroupConnection;\n};\n\ntype UseProductFunctions = {\n /** A callback to set the selected variant to the variant passed as an argument. */\n setSelectedVariant: (\n variant: PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | null,\n ) => void;\n /** A callback to set the selected option. */\n setSelectedOption: (\n name: SelectedOptionType['name'],\n value: SelectedOptionType['value'],\n ) => void;\n /** A callback to set multiple selected options at once. */\n setSelectedOptions: (options: SelectedOptions) => void;\n /** A callback to set the selected selling plan to the one passed as an argument. */\n setSelectedSellingPlan: (\n sellingPlan: PartialDeep<SellingPlanType, {recurseIntoArrays: true}>,\n ) => void;\n /** A callback that returns a boolean indicating if the option is in stock. */\n isOptionInStock: (\n name: SelectedOptionType['name'],\n value: SelectedOptionType['value'],\n ) => boolean;\n};\n\ntype ProductHookValue = PartialDeep<\n UseProductObjects,\n {recurseIntoArrays: true}\n> &\n UseProductFunctions;\n\nexport type SelectedOptions = {\n [key: string]: string;\n};\n","import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n Omit<\n React.ComponentPropsWithoutRef<AsType>,\n keyof CustomBaseButtonProps<AsType>\n >;\n\nexport function BaseButton<AsType extends React.ElementType = 'button'>(\n props: BaseButtonProps<AsType>,\n): JSX.Element {\n const {\n as,\n onClick,\n defaultOnClick,\n children,\n buttonRef,\n ...passthroughProps\n } = props;\n\n const handleOnClick = useCallback(\n (event?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (onClick) {\n const clickShouldContinue = onClick(event);\n if (\n (typeof clickShouldContinue === 'boolean' &&\n clickShouldContinue === false) ||\n event?.defaultPrevented\n )\n return;\n }\n\n defaultOnClick?.(event);\n },\n [defaultOnClick, onClick],\n );\n\n const Component = as || 'button';\n\n return (\n <Component ref={buttonRef} onClick={handleOnClick} {...passthroughProps}>\n {children}\n </Component>\n );\n}\n","import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n passthroughProps.disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n","export const AnalyticsEventName: AnalyticsEventName = {\n PAGE_VIEW: 'PAGE_VIEW',\n ADD_TO_CART: 'ADD_TO_CART',\n} as const;\n\nexport const AnalyticsPageType: AnalyticsPageType = {\n article: 'article',\n blog: 'blog',\n captcha: 'captcha',\n cart: 'cart',\n collection: 'collection',\n customersAccount: 'customers/account',\n customersActivateAccount: 'customers/activate_account',\n customersAddresses: 'customers/addresses',\n customersLogin: 'customers/login',\n customersOrder: 'customers/order',\n customersRegister: 'customers/register',\n customersResetPassword: 'customers/reset_password',\n giftCard: 'gift_card',\n home: 'index',\n listCollections: 'list-collections',\n forbidden: '403',\n notFound: '404',\n page: 'page',\n password: 'password',\n product: 'product',\n policy: 'policy',\n search: 'search',\n} as const;\n\nexport const ShopifySalesChannel: ShopifySalesChannel = {\n hydrogen: 'hydrogen',\n headless: 'headless',\n} as const;\n\nexport const ShopifyAppId = {\n hydrogen: '6167201',\n headless: '12875497473',\n} as const;\n\n/**\n * These duplicated interface declaration is so that we can generate proper documentation\n * for these public facing constants\n */\ninterface AnalyticsEventName {\n /** Page view */\n PAGE_VIEW: 'PAGE_VIEW';\n /** Add to cart */\n ADD_TO_CART: 'ADD_TO_CART';\n}\n\ninterface AnalyticsPageType {\n article: 'article';\n blog: 'blog';\n captcha: 'captcha';\n cart: 'cart';\n collection: 'collection';\n customersAccount: 'customers/account';\n customersActivateAccount: 'customers/activate_account';\n customersAddresses: 'customers/addresses';\n customersLogin: 'customers/login';\n customersOrder: 'customers/order';\n customersRegister: 'customers/register';\n customersResetPassword: 'customers/reset_password';\n giftCard: 'gift_card';\n home: 'index';\n listCollections: 'list-collections';\n forbidden: '403';\n notFound: '404';\n page: 'page';\n password: 'password';\n product: 'product';\n policy: 'policy';\n search: 'search';\n}\n\ninterface ShopifySalesChannel {\n /** Shopify Hydrogen sales channel */\n hydrogen: 'hydrogen';\n /** Shopify Headless sales channel */\n headless: 'headless';\n}\n","import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n ShopifyGid,\n} from './analytics-types.js';\n\n/**\n * Builds a Shopify Monorail event from a Shopify Monorail payload and a schema ID.\n * @param payload - The Monorail payload\n * @param schemaId - The schema ID to use\n * @returns The formatted payload\n **/\nexport function schemaWrapper(\n schemaId: string,\n payload: ShopifyMonorailPayload,\n): ShopifyMonorailEvent {\n return {\n schema_id: schemaId,\n payload,\n metadata: {\n event_created_at_ms: Date.now(),\n },\n };\n}\n\n/**\n * Parses global id (gid) and returns the resource type and id.\n * @see https://shopify.dev/api/usage/gids\n * @param gid - A shopify GID (string)\n *\n * @example\n * ```ts\n * const {id, resource} = parseGid('gid://shopify/Order/123')\n * // => id = \"123\", resource = 'Order'\n *\n * * const {id, resource} = parseGid('gid://shopify/Cart/abc123')\n * // => id = \"abc123\", resource = 'Cart'\n * ```\n **/\nexport function parseGid(gid: string | undefined): ShopifyGid {\n const defaultReturn = {id: '', resource: null};\n\n if (typeof gid !== 'string') {\n return defaultReturn;\n }\n\n // TODO: add support for parsing query parameters on complex gids\n // Reference: https://shopify.dev/api/usage/gids\n const matches = gid.match(/^gid:\\/\\/shopify\\/(\\w+)\\/([^/]+)/);\n\n if (!matches || matches.length === 1) {\n return defaultReturn;\n }\n const id = matches[2] ?? null;\n const resource = matches[1] ?? null;\n\n return {id, resource};\n}\n\n/**\n * Filters properties from an object and returns a new object with only the properties that have a truthy value.\n * @param keyValuePairs - An object of key-value pairs\n * @param formattedData - An object which will hold the truthy values\n * @returns The formatted object\n **/\nexport function addDataIf(\n keyValuePairs: ShopifyMonorailPayload,\n formattedData: ShopifyMonorailPayload,\n): ShopifyMonorailPayload {\n if (typeof keyValuePairs !== 'object') {\n return {};\n }\n Object.entries(keyValuePairs).forEach(([key, value]) => {\n if (value) {\n formattedData[key] = value;\n }\n });\n return formattedData;\n}\n\n/**\n * Utility that errors if a function is called on the server.\n * @param fnName - The name of the function\n * @returns A boolean\n **/\nexport function errorIfServer(fnName: string): boolean {\n if (typeof document === 'undefined') {\n console.error(\n `${fnName} should only be used within the useEffect callback or event handlers`,\n );\n return true;\n }\n return false;\n}\n","import {\n ShopifyPageViewPayload,\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {ShopifyAppId} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\n\nconst SCHEMA_ID = 'trekkie_storefront_page_view/1.4';\nconst OXYGEN_DOMAIN = 'myshopify.dev';\n\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const {id, resource} = parseGid(pageViewPayload.resourceId);\n const resourceType = resource ? resource.toLowerCase() : undefined;\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n pageType: pageViewPayload.pageType,\n customerId: pageViewPayload.customerId,\n resourceType,\n resourceId: parseInt(id),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailPayload {\n return {\n appClientId: payload.shopifySalesChannel\n ? ShopifyAppId[payload.shopifySalesChannel]\n : ShopifyAppId.headless,\n isMerchantRequest: isMerchantRequest(payload.url),\n hydrogenSubchannelId: payload.storefrontId || '0',\n\n isPersistentCookie: payload.hasUserConsent,\n uniqToken: payload.uniqueToken,\n visitToken: payload.visitToken,\n microSessionId: buildUUID(),\n microSessionCount: 1,\n\n url: payload.url,\n path: payload.path,\n search: payload.search,\n referrer: payload.referrer,\n title: payload.title,\n\n shopId: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n contentLanguage: payload.acceptedLanguage || 'en',\n };\n}\n\nfunction isMerchantRequest(url: string): boolean {\n if (typeof url !== 'string') {\n return false;\n }\n const hostname = new URL(url).hostname;\n if (hostname.indexOf(OXYGEN_DOMAIN) !== -1 || hostname === 'localhost') {\n return true;\n }\n return false;\n}\n","import {\n ShopifyAnalyticsPayload,\n ShopifyPageViewPayload,\n ShopifyAddToCartPayload,\n ShopifyMonorailPayload,\n ShopifyAnalyticsProduct,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsPageType, ShopifySalesChannel} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\n\nconst SCHEMA_ID = 'custom_storefront_customer_tracking/1.0';\nconst PAGE_RENDERED_EVENT_NAME = 'page_rendered';\nconst COLLECTION_PAGE_RENDERED_EVENT_NAME = 'collection_page_rendered';\nconst PRODUCT_PAGE_RENDERED_EVENT_NAME = 'product_page_rendered';\nconst PRODUCT_ADDED_TO_CART_EVENT_NAME = 'product_added_to_cart';\nconst SEARCH_SUBMITTED_EVENT_NAME = 'search_submitted';\n\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = {\n canonical_url: pageViewPayload.canonicalUrl || pageViewPayload.url,\n customer_id: pageViewPayload.customerId,\n };\n const pageType = pageViewPayload.pageType;\n const pageViewEvents = [];\n\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n\n switch (pageType) {\n case AnalyticsPageType.collection:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.product:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.search:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n }\n\n return pageViewEvents;\n}\n\nexport function addToCart(\n payload: ShopifyAddToCartPayload,\n): ShopifyMonorailEvent[] {\n const addToCartPayload = payload;\n const cartToken = parseGid(addToCartPayload.cartId);\n const cart_token = cartToken?.id ? `${cartToken.id}` : null;\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_ADDED_TO_CART_EVENT_NAME,\n customerId: addToCartPayload.customerId,\n cart_token,\n total_value: addToCartPayload.totalValue,\n products: formatProductPayload(addToCartPayload.products),\n },\n formatPayload(addToCartPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyAnalyticsPayload,\n): ShopifyMonorailPayload {\n return {\n source: payload.shopifySalesChannel || ShopifySalesChannel.headless,\n hydrogenSubchannelId: payload.storefrontId || '0',\n\n is_persistent_cookie: payload.hasUserConsent,\n ccpa_enforced: false,\n gdpr_enforced: false,\n unique_token: payload.uniqueToken,\n event_time: Date.now(),\n event_id: buildUUID(),\n\n event_source_url: payload.url,\n referrer: payload.referrer,\n user_agent: payload.userAgent,\n navigation_type: payload.navigationType,\n navigation_api: payload.navigationApi,\n\n shop_id: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n };\n}\n\nfunction formatProductPayload(products?: ShopifyAnalyticsProduct[]): string[] {\n return products\n ? products.map((p: ShopifyAnalyticsProduct) => {\n const product = addDataIf(\n {\n variant_gid: p.variantGid,\n category: p.category,\n sku: p.sku,\n product_id: parseInt(parseGid(p.productGid).id),\n variant_id: parseInt(parseGid(p.variantGid).id),\n },\n {\n product_gid: p.productGid,\n name: p.name,\n variant: p.variantName || '',\n brand: p.brand,\n price: p.price,\n quantity: Number(p.quantity || 0),\n },\n );\n return JSON.stringify(product);\n })\n : [];\n}\n","import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n const pageViewPayload = payload as ShopifyPageViewPayload;\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n break;\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n break;\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n break;\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n","import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n","import {ReactNode, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ntype ChildrenProps = {\n /** A `ReactNode` element. */\n children: ReactNode;\n};\ntype CartCheckoutButtonProps = Omit<BaseButtonProps<'button'>, 'onClick'> &\n ChildrenProps;\n\n/**\n * The `CartCheckoutButton` component renders a button that redirects to the checkout URL for the cart.\n * It must be a descendent of a `CartProvider` component.\n */\nexport function CartCheckoutButton(\n props: CartCheckoutButtonProps,\n): JSX.Element {\n const [requestedCheckout, setRequestedCheckout] = useState(false);\n const {status, checkoutUrl} = useCart();\n const {children, ...passthroughProps} = props;\n\n useEffect(() => {\n if (requestedCheckout && checkoutUrl && status === 'idle') {\n window.location.href = checkoutUrl;\n }\n }, [requestedCheckout, status, checkoutUrl]);\n\n return (\n <BaseButton\n {...passthroughProps}\n disabled={requestedCheckout || passthroughProps.disabled}\n onClick={(): void => setRequestedCheckout(true)}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documentation purposes, and it is not used in the code.\n// we ignore this issue because it makes the documentation look better than the equivalent `type` that it wants us to convert to\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface CartCheckoutButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends Omit<CustomBaseButtonProps<AsType>, 'onClick'> {}\n","import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {CurrencyCode, MoneyV2} from './storefront-api-types.js';\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n const options = useMemo(\n () => ({\n style: 'currency',\n currency: money.currencyCode,\n }),\n [money.currencyCode],\n );\n\n const defaultFormatter = useLazyFormatter(locale, options);\n\n const nameFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n });\n\n const narrowSymbolFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n });\n\n const withoutTrailingZerosFormatter = useLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const withoutCurrencyFormatter = useLazyFormatter(locale);\n\n const withoutTrailingZerosOrCurrencyFormatter = useLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: () => money,\n currencyCode: () => money.currencyCode,\n\n localizedString: () => defaultFormatter().format(amount),\n\n parts: () => defaultFormatter().formatToParts(amount),\n\n withoutTrailingZeros: () =>\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount),\n\n withoutTrailingZerosAndCurrency: () =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: () =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: () =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: () =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: () =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nfunction useLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n return useMemo(() => {\n let memoized: Intl.NumberFormat;\n return () => (memoized ??= new Intl.NumberFormat(locale, options));\n }, [locale, options]);\n}\n","import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2023-04/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >;\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) according to the\n * `locale` in the `ShopifyProvider` component.\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n","import {Money, type MoneyPropsBase} from './Money.js';\nimport {useCart} from './CartProvider.js';\n\ninterface CartCostPropsBase {\n /** A string type that defines the type of cost needed. Valid values: `total`, `subtotal`, `tax`, or `duty`. */\n amountType?: 'total' | 'subtotal' | 'tax' | 'duty';\n /** Any `ReactNode` elements. */\n children?: React.ReactNode;\n}\n\ntype CartCostProps = Omit<React.ComponentProps<typeof Money>, 'data'> &\n CartCostPropsBase;\n\n/**\n * The `CartCost` component renders a `Money` component with the cost associated with the `amountType` prop.\n * If no `amountType` prop is specified, then it defaults to `totalAmount`.\n * Depends on `useCart()` and must be a child of `<CartProvider/>`\n */\nexport function CartCost(props: CartCostProps): JSX.Element | null {\n const {cost} = useCart();\n const {amountType = 'total', children, ...passthroughProps} = props;\n let amount;\n\n if (amountType == 'total') {\n amount = cost?.totalAmount;\n } else if (amountType == 'subtotal') {\n amount = cost?.subtotalAmount;\n } else if (amountType == 'tax') {\n amount = cost?.totalTaxAmount;\n } else if (amountType == 'duty') {\n amount = cost?.totalDutyAmount;\n }\n\n if (amount == null) {\n return null;\n }\n\n return (\n <Money {...passthroughProps} data={amount}>\n {children}\n </Money>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface CartCostPropsForDocs<AsType extends React.ElementType = 'div'>\n extends Omit<MoneyPropsBase<AsType>, 'data'>,\n CartCostPropsBase {}\n","import {useContext, createContext, type ReactNode} from 'react';\nimport type {CartLine} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ntype CartLinePartialDeep = PartialDeep<CartLine, {recurseIntoArrays: true}>;\n\nexport const CartLineContext = createContext<CartLinePartialDeep | null>(null);\n\n/**\n * The `useCartLine` hook provides access to the [CartLine object](https://shopify.dev/api/storefront/unstable/objects/cartline) from the Storefront API. It must be a descendent of a `CartProvider` component.\n */\nexport function useCartLine(): CartLinePartialDeep {\n const context = useContext(CartLineContext);\n\n if (context == null) {\n throw new Error('Expected a cart line context but none was found');\n }\n\n return context;\n}\n\ntype CartLineProviderProps = {\n /** Any `ReactNode` elements. */\n children: ReactNode;\n /** A cart line object. */\n line: CartLinePartialDeep;\n};\n\n/**\n * The `CartLineProvider` component creates a context for using a cart line.\n */\nexport function CartLineProvider({\n children,\n line,\n}: CartLineProviderProps): JSX.Element {\n return (\n <CartLineContext.Provider value={line}>{children}</CartLineContext.Provider>\n );\n}\n","import type {ComponentPropsWithoutRef, ElementType} from 'react';\nimport {useCartLine} from './CartLineProvider.js';\n\ninterface CartLineQuantityBaseProps<\n ComponentGeneric extends ElementType = 'span',\n> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `span`. */\n as?: ComponentGeneric;\n}\n\nexport type CartLineQuantityProps<ComponentGeneric extends ElementType> =\n CartLineQuantityBaseProps<ComponentGeneric> &\n Omit<\n ComponentPropsWithoutRef<ComponentGeneric>,\n keyof CartLineQuantityBaseProps<ComponentGeneric>\n >;\n\n/**\n * The `<CartLineQuantity/>` component renders a `span` (or another element / component that can be customized by the `as` prop) with the cart line's quantity.\n *\n * It must be a descendent of a `<CartLineProvider/>` component, and uses the `useCartLine()` hook internally.\n */\nexport function CartLineQuantity<ComponentGeneric extends ElementType = 'span'>(\n props: CartLineQuantityProps<ComponentGeneric>,\n): JSX.Element {\n const cartLine = useCartLine();\n const {as, ...passthroughProps} = props;\n\n const Wrapper = as ? as : 'span';\n\n return <Wrapper {...passthroughProps}>{cartLine.quantity}</Wrapper>;\n}\n","import {useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useCartLine} from './CartLineProvider.js';\nimport {BaseButton, type BaseButtonProps} from './BaseButton.js';\nimport type {CartLineUpdateInput} from './storefront-api-types.js';\n\ninterface CartLineQuantityAdjustButtonBaseProps {\n /** The adjustment for a cart line's quantity. Valid values: `increase` (default), `decrease`, or `remove`. */\n adjust?: 'increase' | 'decrease' | 'remove';\n}\n\ntype CartLineQuantityAdjustButtonProps<\n AsType extends React.ElementType = 'button',\n> = BaseButtonProps<AsType> & CartLineQuantityAdjustButtonBaseProps;\n\n/**\n * The `<CartLineQuantityAdjustButton />` component renders a button that adjusts the cart line's quantity when pressed.\n *\n * It must be a descendent of `<CartLineProvider/>` and `<CartProvider/>`.\n */\nexport function CartLineQuantityAdjustButton<\n AsType extends React.ElementType = 'button',\n>(props: CartLineQuantityAdjustButtonProps<AsType>): JSX.Element {\n const {status, linesRemove, linesUpdate} = useCart();\n const cartLine = useCartLine();\n const {children, adjust, onClick, ...passthroughProps} = props;\n\n const handleAdjust = useCallback(() => {\n if (adjust === 'remove') {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const quantity =\n adjust === 'decrease'\n ? (cartLine?.quantity ?? 0) - 1\n : (cartLine?.quantity ?? 0) + 1;\n\n if (quantity <= 0) {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const lineUpdate = {\n id: cartLine?.id ?? '',\n quantity,\n attributes: (cartLine?.attributes ??\n []) as CartLineUpdateInput['attributes'],\n } satisfies CartLineUpdateInput;\n\n linesUpdate([lineUpdate]);\n }, [\n adjust,\n cartLine?.attributes,\n cartLine?.id,\n cartLine?.quantity,\n linesRemove,\n linesUpdate,\n ]);\n\n return (\n <BaseButton\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleAdjust}\n disabled={\n typeof passthroughProps.disabled !== 'undefined'\n ? passthroughProps.disabled\n : status !== 'idle'\n }\n >\n {children}\n </BaseButton>\n );\n}\n","/** Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n","import type {ExternalVideo as ExternalVideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ninterface ExternalVideoBaseProps {\n /**\n * An object with fields that correspond to the Storefront API's [ExternalVideo object](https://shopify.dev/api/storefront/reference/products/externalvideo).\n */\n data: PartialDeep<ExternalVideoType, {recurseIntoArrays: true}>;\n /** An object containing the options available for either\n * [YouTube](https://developers.google.com/youtube/player_parameters#Parameters) or\n * [Vimeo](https://vimeo.zendesk.com/hc/en-us/articles/360001494447-Using-Player-Parameters).\n */\n options?: YouTube | Vimeo;\n}\n\nexport type ExternalVideoProps = Omit<JSX.IntrinsicElements['iframe'], 'src'> &\n ExternalVideoBaseProps;\n\n/**\n * The `ExternalVideo` component renders an embedded video for the Storefront\n * API's [ExternalVideo object](https://shopify.dev/api/storefront/reference/products/externalvideo).\n */\nexport function ExternalVideo(props: ExternalVideoProps): JSX.Element {\n const {\n data,\n options,\n id = data.id,\n frameBorder = '0',\n allow = 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture',\n allowFullScreen = true,\n loading = 'lazy',\n ...passthroughProps\n } = props;\n\n if (!data.embedUrl) {\n throw new Error(`<ExternalVideo/> requires the 'embedUrl' property`);\n }\n\n let finalUrl: string = data.embedUrl;\n\n if (options) {\n const urlObject = new URL(data.embedUrl);\n for (const key of Object.keys(options) as (keyof typeof options)[]) {\n // @ts-expect-error https://github.com/microsoft/TypeScript/issues/32951\n urlObject.searchParams.set(key, options[key]);\n }\n finalUrl = urlObject.toString();\n }\n\n return (\n <iframe\n {...passthroughProps}\n id={id ?? data.embedUrl}\n title={data.alt ?? data.id ?? 'external video'}\n frameBorder={frameBorder}\n allow={allow}\n allowFullScreen={allowFullScreen}\n src={finalUrl}\n loading={loading}\n ></iframe>\n );\n}\n\ninterface YouTube {\n autoplay?: 0 | 1;\n cc_lang_pref?: string;\n cc_load_policy?: 1;\n color?: 'red' | 'white';\n controls?: 0 | 1;\n disablekb?: 0 | 1;\n enablejsapi?: 0 | 1;\n end?: number;\n fs?: 0 | 1;\n hl?: string;\n iv_load_policy?: 1 | 3;\n list?: string;\n list_type?: 'playlist' | 'user_uploads';\n loop?: 0 | 1;\n modest_branding?: 1;\n origin?: string;\n playlist?: string;\n plays_inline?: 0 | 1;\n rel?: 0 | 1;\n start?: number;\n widget_referrer?: string;\n}\n\ntype VimeoBoolean = 0 | 1 | boolean;\n\ninterface Vimeo {\n autopause?: VimeoBoolean;\n autoplay?: VimeoBoolean;\n background?: VimeoBoolean;\n byline?: VimeoBoolean;\n color?: string;\n controls?: VimeoBoolean;\n dnt?: VimeoBoolean;\n loop?: VimeoBoolean;\n muted?: VimeoBoolean;\n pip?: VimeoBoolean;\n playsinline?: VimeoBoolean;\n portrait?: VimeoBoolean;\n quality?: '240p' | '360p' | '540p' | '720p' | '1080p' | '2k' | '4k';\n speed?: VimeoBoolean;\n '#t'?: string;\n texttrack?: string;\n title?: VimeoBoolean;\n transparent?: VimeoBoolean;\n}\n","/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\n>;\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2023-04/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n}\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n","import {type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2023-04/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport function Video(\n props: JSX.IntrinsicElements['video'] & VideoProps,\n): JSX.Element {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n}\n","import {useState, useEffect} from 'react';\n\nconst SCRIPTS_LOADED: Record<string, Promise<boolean>> = {};\n\nexport function loadScript(\n src: string,\n options?: {module?: boolean; in?: 'head' | 'body'},\n): Promise<boolean> {\n const isScriptLoaded = SCRIPTS_LOADED[src];\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n if (isScriptLoaded) {\n return isScriptLoaded;\n }\n\n const promise = new Promise<boolean>((resolve, reject) => {\n const script = document.createElement('script');\n if (options?.module) {\n script.type = 'module';\n } else {\n script.type = 'text/javascript';\n }\n script.src = src;\n script.onload = (): void => {\n resolve(true);\n };\n script.onerror = (): void => {\n reject(false);\n };\n if (options?.in === 'head') {\n document.head.appendChild(script);\n } else {\n document.body.appendChild(script);\n }\n });\n\n SCRIPTS_LOADED[src] = promise;\n\n return promise;\n}\n\ntype LoadScriptParams = Parameters<typeof loadScript>;\n\n/**\n * The `useLoadScript` hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.\n */\nexport function useLoadScript(\n url: LoadScriptParams[0],\n options?: LoadScriptParams[1],\n): ScriptState {\n const [status, setStatus] = useState<ScriptState>('loading');\n const stringifiedOptions = JSON.stringify(options);\n\n useEffect(() => {\n async function loadScriptWrapper(): Promise<void> {\n try {\n setStatus('loading');\n await loadScript(url, options);\n setStatus('done');\n } catch (error) {\n setStatus('error');\n }\n }\n\n loadScriptWrapper().catch(() => {\n setStatus('error');\n });\n }, [url, stringifiedOptions, options]);\n\n return status;\n}\n\ntype ScriptState = 'loading' | 'done' | 'error';\n","import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2023-04/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n if (!modelViewer) {\n return;\n }\n if (passthroughProps.onError)\n modelViewer.addEventListener('error', passthroughProps.onError);\n if (passthroughProps.onLoad)\n modelViewer.addEventListener('load', passthroughProps.onLoad);\n if (passthroughProps.onPreload)\n modelViewer.addEventListener('preload', passthroughProps.onPreload);\n if (passthroughProps.onModelVisibility)\n modelViewer.addEventListener(\n 'model-visibility',\n passthroughProps.onModelVisibility,\n );\n if (passthroughProps.onProgress)\n modelViewer.addEventListener('progress', passthroughProps.onProgress);\n if (passthroughProps.onArStatus)\n modelViewer.addEventListener('ar-status', passthroughProps.onArStatus);\n if (passthroughProps.onArTracking)\n modelViewer.addEventListener(\n 'ar-tracking',\n passthroughProps.onArTracking,\n );\n if (passthroughProps.onQuickLookButtonTapped)\n modelViewer.addEventListener(\n 'quick-look-button-tapped',\n passthroughProps.onQuickLookButtonTapped,\n );\n if (passthroughProps.onCameraChange)\n modelViewer.addEventListener(\n 'camera-change',\n passthroughProps.onCameraChange,\n );\n if (passthroughProps.onEnvironmentChange)\n modelViewer.addEventListener(\n 'environment-change',\n passthroughProps.onEnvironmentChange,\n );\n if (passthroughProps.onPlay)\n modelViewer.addEventListener('play', passthroughProps.onPlay);\n if (passthroughProps.onPause)\n modelViewer.addEventListener('ar-status', passthroughProps.onPause);\n if (passthroughProps.onSceneGraphReady)\n modelViewer.addEventListener(\n 'scene-graph-ready',\n passthroughProps.onSceneGraphReady,\n );\n\n return () => {\n if (modelViewer == null) {\n return;\n }\n if (passthroughProps.onError)\n modelViewer.removeEventListener('error', passthroughProps.onError);\n if (passthroughProps.onLoad)\n modelViewer.removeEventListener('load', passthroughProps.onLoad);\n if (passthroughProps.onPreload)\n modelViewer.removeEventListener('preload', passthroughProps.onPreload);\n if (passthroughProps.onModelVisibility)\n modelViewer.removeEventListener(\n 'model-visibility',\n passthroughProps.onModelVisibility,\n );\n if (passthroughProps.onProgress)\n modelViewer.removeEventListener(\n 'progress',\n passthroughProps.onProgress,\n );\n if (passthroughProps.onArStatus)\n modelViewer.removeEventListener(\n 'ar-status',\n passthroughProps.onArStatus,\n );\n if (passthroughProps.onArTracking)\n modelViewer.removeEventListener(\n 'ar-tracking',\n passthroughProps.onArTracking,\n );\n if (passthroughProps.onQuickLookButtonTapped)\n modelViewer.removeEventListener(\n 'quick-look-button-tapped',\n passthroughProps.onQuickLookButtonTapped,\n );\n if (passthroughProps.onCameraChange)\n modelViewer.removeEventListener(\n 'camera-change',\n passthroughProps.onCameraChange,\n );\n if (passthroughProps.onEnvironmentChange)\n modelViewer.removeEventListener(\n 'environment-change',\n passthroughProps.onEnvironmentChange,\n );\n if (passthroughProps.onPlay)\n modelViewer.removeEventListener('play', passthroughProps.onPlay);\n if (passthroughProps.onPause)\n modelViewer.removeEventListener('ar-status', passthroughProps.onPause);\n if (passthroughProps.onSceneGraphReady)\n modelViewer.removeEventListener(\n 'scene-graph-ready',\n passthroughProps.onSceneGraphReady,\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n // @ts-expect-error ref should exist\n ref={callbackRef}\n {...passthroughProps}\n className={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // @ts-expect-error arPlacement should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-attributes-arPlacement\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n interaction-policy={passthroughProps.interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n bounds={passthroughProps.bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n","import {Image, type HydrogenImageProps} from './Image.js';\nimport {Video} from './Video.js';\nimport {ExternalVideo} from './ExternalVideo.js';\nimport {ModelViewer} from './ModelViewer.js';\nimport type {MediaEdge as MediaEdgeType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ntype BaseProps = React.HTMLAttributes<\n HTMLImageElement | HTMLVideoElement | HTMLIFrameElement | ModelViewerElement\n>;\nexport interface MediaFileProps extends BaseProps {\n /** An object with fields that correspond to the Storefront API's [Media object](https://shopify.dev/api/storefront/reference/products/media). */\n data: PartialDeep<MediaEdgeType['node'], {recurseIntoArrays: true}>;\n /** The options for the `Image`, `Video`, `ExternalVideo`, or `ModelViewer` components. */\n mediaOptions?: MediaOptions;\n}\n\ntype MediaOptions = {\n /** Props that will only apply when an `<Image />` is rendered */\n image?: Omit<HydrogenImageProps, 'data'>;\n /** Props that will only apply when a `<Video />` is rendered */\n video?: Omit<React.ComponentProps<typeof Video>, 'data'>;\n /** Props that will only apply when an `<ExternalVideo />` is rendered */\n externalVideo?: Omit<\n React.ComponentProps<typeof ExternalVideo>['options'],\n 'data'\n >;\n /** Props that will only apply when a `<ModelViewer />` is rendered */\n modelViewer?: Omit<typeof ModelViewer, 'data'>;\n};\n\n/**\n * The `MediaFile` component renders the media for the Storefront API's\n * [Media object](https://shopify.dev/api/storefront/reference/products/media). It renders an `Image`, a\n * `Video`, an `ExternalVideo`, or a `ModelViewer` depending on the `__typename` of the `data` prop.\n */\nexport function MediaFile({\n data,\n mediaOptions,\n ...passthroughProps\n}: MediaFileProps): JSX.Element | null {\n switch (data.__typename) {\n case 'MediaImage': {\n if (!data.image) {\n const noDataImage = `<MediaFile/>: 'data.image' does not exist for __typename of 'MediaImage'; rendering 'null' by default.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noDataImage);\n } else {\n console.warn(noDataImage);\n return null;\n }\n }\n\n return (\n <Image\n {...passthroughProps}\n {...mediaOptions?.image}\n data={data.image}\n />\n );\n }\n case 'Video': {\n return (\n <Video {...passthroughProps} {...mediaOptions?.video} data={data} />\n );\n }\n case 'ExternalVideo': {\n return (\n <ExternalVideo\n {...passthroughProps}\n {...mediaOptions?.externalVideo}\n data={data}\n />\n );\n }\n case 'Model3d': {\n return (\n // @ts-expect-error There are issues with the inferred HTML attribute types here for ModelViewer (and contentEditable), but I think that's a little bit beyond me at the moment\n <ModelViewer\n {...passthroughProps}\n {...mediaOptions?.modelViewer}\n data={data}\n />\n );\n }\n default: {\n const typenameMissingMessage = `<MediaFile /> requires the '__typename' property to exist on the 'data' prop in order to render the matching sub-component for this type of media.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typenameMissingMessage);\n } else {\n console.error(`${typenameMissingMessage} Rendering 'null' by default`);\n return null;\n }\n }\n }\n}\n","import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n","import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice<ComponentGeneric extends React.ElementType>(\n props: ProductPriceProps &\n Omit<MoneyProps<ComponentGeneric>, 'data' | 'measurement'>,\n): JSX.Element | null {\n const {\n priceType = 'regular',\n variantId,\n valueType = 'min',\n data: product,\n ...passthroughProps\n } = props;\n\n if (product == null) {\n throw new Error(`<ProductPrice/> requires a product as the 'data' prop`);\n }\n\n let price: Partial<MoneyV2> | undefined | null;\n let measurement: Partial<UnitPriceMeasurement> | undefined | null;\n\n const variant = variantId\n ? flattenConnection(product?.variants ?? {}).find(\n (variant) => variant?.id === variantId,\n ) ?? null\n : null;\n\n if (priceType === 'compareAt') {\n if (variantId && variant) {\n if (variant.compareAtPriceV2?.amount === variant.priceV2?.amount) {\n return null;\n }\n price = variant.compareAtPriceV2;\n } else if (valueType === 'max') {\n price = product?.compareAtPriceRange?.maxVariantPrice;\n } else {\n price = product?.compareAtPriceRange?.minVariantPrice;\n }\n } else {\n if (variantId && variant) {\n price = variant.priceV2;\n if (valueType === 'unit') {\n price = variant.unitPrice;\n measurement = variant.unitPriceMeasurement;\n }\n } else if (valueType === 'max') {\n price = product.priceRange?.maxVariantPrice;\n } else {\n price = product.priceRange?.minVariantPrice;\n }\n }\n\n if (!price) {\n return null;\n }\n\n if (measurement) {\n return (\n <Money {...passthroughProps} data={price} measurement={measurement} />\n );\n }\n\n return <Money {...passthroughProps} data={price} />;\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface ProductPricePropsForDocs<\n AsType extends React.ElementType = 'div',\n> extends Omit<MoneyPropsBase<AsType>, 'data' | 'measurement'>,\n ProductPriceProps {}\n","import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain} variants={ids.join(',')} />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\n","import {useEffect} from 'react';\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID, getShopifyCookies} from './cookies-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = {\n /**\n * If set to `false`, Shopify cookies will be removed.\n * If set to `true`, Shopify unique user token cookie will have cookie expiry of 1 year.\n * Defaults to false.\n **/\n hasUserConsent?: boolean;\n /**\n * The domain scope of the cookie. Defaults to empty string.\n **/\n domain?: string;\n};\n\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): void {\n const {hasUserConsent = false, domain = ''} = options || {};\n useEffect(() => {\n const cookies = getShopifyCookies(document.cookie);\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n setCookie(\n SHOPIFY_Y,\n cookies[SHOPIFY_Y] || buildUUID(),\n longTermLength,\n domain,\n );\n setCookie(\n SHOPIFY_S,\n cookies[SHOPIFY_S] || buildUUID(),\n shortTermLength,\n domain,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domain);\n setCookie(SHOPIFY_S, '', 0, domain);\n }\n });\n}\n\nfunction setCookie(\n name: string,\n value: string,\n maxage: number,\n domain: string,\n): void {\n document.cookie = stringify(name, value, {\n maxage,\n domain,\n samesite: 'Lax',\n path: '/',\n });\n}\n"],"names":["t","n","e","r","i","o","a","u","s","l","v","g","c","useLayoutEffect","React","require$$0","error","shim","module","require$$1","isEqual","this","useRef","useState","queue","service","interpret","createMachine","InterpreterStatus","useIsomorphicLayoutEffect","useEffect","useCallback","useSyncExternalStoreWithSelector","createContext","useMemo","useContext","f","parse","assign","_b","_a","_d","_c","useTransition","value","selectedOptions","SCHEMA_ID","pageView","formatPayload","trekkiePageView","customerPageView","customerAddToCart","variant","stringify"],"mappings":";;;;;;;;;;;;;;;;;;;;;EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"hydrogen-react.dev.js","sources":["../../../../node_modules/@xstate/fsm/es/index.js","../../../../node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../../../../node_modules/use-sync-external-store/shim/index.js","../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js","../../../../node_modules/use-sync-external-store/shim/with-selector.js","../../../../node_modules/@xstate/react/es/useConstant.js","../../../../node_modules/@xstate/react/es/fsm.js","../../src/flatten-connection.ts","../../src/cart-queries.ts","../../src/storefront-api-constants.ts","../../src/storefront-client.ts","../../src/ShopifyProvider.tsx","../../src/cart-constants.ts","../../../../node_modules/worktop/cookie/index.mjs","../../src/cookies-utils.tsx","../../src/cart-hooks.tsx","../../src/useCartActions.tsx","../../src/useCartAPIStateMachine.tsx","../../src/CartProvider.tsx","../../src/ProductProvider.tsx","../../src/BaseButton.tsx","../../src/AddToCartButton.tsx","../../src/analytics-constants.ts","../../src/analytics-utils.ts","../../src/analytics-schema-trekkie-storefront-page-view.ts","../../src/analytics-schema-custom-storefront-customer-tracking.ts","../../src/analytics.ts","../../src/BuyNowButton.tsx","../../src/CartCheckoutButton.tsx","../../src/useMoney.tsx","../../src/Money.tsx","../../src/CartCost.tsx","../../src/CartLineProvider.tsx","../../src/CartLineQuantity.tsx","../../src/CartLineQuantityAdjustButton.tsx","../../src/codegen.helpers.ts","../../src/ExternalVideo.tsx","../../src/Image.tsx","../../src/Video.tsx","../../src/load-script.tsx","../../src/ModelViewer.tsx","../../src/MediaFile.tsx","../../src/parse-metafield.ts","../../src/ProductPrice.tsx","../../src/ShopPayButton.tsx","../../src/useShopifyCookies.tsx"],"sourcesContent":["/*! *****************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\nfunction t(t,n){var e=\"function\"==typeof Symbol&&t[Symbol.iterator];if(!e)return t;var r,i,o=e.call(t),a=[];try{for(;(void 0===n||n-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(e=o.return)&&e.call(o)}finally{if(i)throw i.error}}return a}var n;!function(t){t[t.NotStarted=0]=\"NotStarted\",t[t.Running=1]=\"Running\",t[t.Stopped=2]=\"Stopped\"}(n||(n={}));var e={type:\"xstate.init\"};function r(t){return void 0===t?[]:[].concat(t)}function i(t){return{type:\"xstate.assign\",assignment:t}}function o(t,n){return\"string\"==typeof(t=\"string\"==typeof t&&n&&n[t]?n[t]:t)?{type:t}:\"function\"==typeof t?{type:t.name,exec:t}:t}function a(t){return function(n){return t===n}}function u(t){return\"string\"==typeof t?{type:t}:t}function c(t,n){return{value:t,context:n,actions:[],changed:!1,matches:a(t)}}function f(t,n,e){var r=n,i=!1;return[t.filter((function(t){if(\"xstate.assign\"===t.type){i=!0;var n=Object.assign({},r);return\"function\"==typeof t.assignment?n=t.assignment(r,e):Object.keys(t.assignment).forEach((function(i){n[i]=\"function\"==typeof t.assignment[i]?t.assignment[i](r,e):t.assignment[i]})),r=n,!1}return!0})),r,i]}function s(n,i){void 0===i&&(i={});var s=t(f(r(n.states[n.initial].entry).map((function(t){return o(t,i.actions)})),n.context,e),2),l=s[0],v=s[1],y={config:n,_options:i,initialState:{value:n.initial,actions:l,context:v,matches:a(n.initial)},transition:function(e,i){var s,l,v=\"string\"==typeof e?{value:e,context:n.context}:e,p=v.value,g=v.context,d=u(i),x=n.states[p];if(x.on){var m=r(x.on[d.type]);try{for(var h=function(t){var n=\"function\"==typeof Symbol&&Symbol.iterator,e=n&&t[n],r=0;if(e)return e.call(t);if(t&&\"number\"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(n?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(m),b=h.next();!b.done;b=h.next()){var S=b.value;if(void 0===S)return c(p,g);var w=\"string\"==typeof S?{target:S}:S,j=w.target,E=w.actions,R=void 0===E?[]:E,N=w.cond,O=void 0===N?function(){return!0}:N,_=void 0===j,k=null!=j?j:p,T=n.states[k];if(O(g,d)){var q=t(f((_?r(R):[].concat(x.exit,R,T.entry).filter((function(t){return t}))).map((function(t){return o(t,y._options.actions)})),g,d),3),z=q[0],A=q[1],B=q[2],C=null!=j?j:p;return{value:C,context:A,actions:z,changed:j!==p||z.length>0||B,matches:a(C)}}}}catch(t){s={error:t}}finally{try{b&&!b.done&&(l=h.return)&&l.call(h)}finally{if(s)throw s.error}}}return c(p,g)}};return y}var l=function(t,n){return t.actions.forEach((function(e){var r=e.exec;return r&&r(t.context,n)}))};function v(t){var r=t.initialState,i=n.NotStarted,o=new Set,c={_machine:t,send:function(e){i===n.Running&&(r=t.transition(r,e),l(r,u(e)),o.forEach((function(t){return t(r)})))},subscribe:function(t){return o.add(t),t(r),{unsubscribe:function(){return o.delete(t)}}},start:function(o){if(o){var u=\"object\"==typeof o?o:{context:t.config.context,value:o};r={value:u.value,actions:[],context:u.context,matches:a(u.value)}}else r=t.initialState;return i=n.Running,l(r,e),c},stop:function(){return i=n.Stopped,o.clear(),c},get state(){return r},get status(){return i}};return c}export{n as InterpreterStatus,i as assign,s as createMachine,v as interpret};\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport default index;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\n// dispatch for CommonJS interop named imports.\n\nvar useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nvar didWarnOld18Alpha = false;\nvar didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works\n// because of a very particular set of implementation details and assumptions\n// -- change any one of them and it will break. The most important assumption\n// is that updates are always synchronous, because concurrent rendering is\n// only available in versions of React that also have a built-in\n// useSyncExternalStore API. And we only use this shim when the built-in API\n// does not exist.\n//\n// Do not assume that the clever hacks used by this hook also work in general.\n// The point of this shim is to replace the need for hacks by other libraries.\n\nfunction useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n// React do not expose a way to check if we're hydrating. So users of the shim\n// will need to track that themselves and return the correct value\n// from `getSnapshot`.\ngetServerSnapshot) {\n {\n if (!didWarnOld18Alpha) {\n if (React.startTransition !== undefined) {\n didWarnOld18Alpha = true;\n\n error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');\n }\n }\n } // Read the current snapshot from the store on every render. Again, this\n // breaks the rules of React, and only works here because of specific\n // implementation details, most importantly that updates are\n // always synchronous.\n\n\n var value = getSnapshot();\n\n {\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n\n if (!objectIs(value, cachedValue)) {\n error('The result of getSnapshot should be cached to avoid an infinite loop');\n\n didWarnUncachedGetSnapshot = true;\n }\n }\n } // Because updates are synchronous, we don't queue them. Instead we force a\n // re-render whenever the subscribed state changes by updating an some\n // arbitrary useState hook. Then, during render, we call getSnapshot to read\n // the current value.\n //\n // Because we don't actually use the state returned by the useState hook, we\n // can save a bit of memory by storing other stuff in that slot.\n //\n // To implement the early bailout, we need to track some things on a mutable\n // object. Usually, we would put that in a useRef hook, but we can stash it in\n // our useState hook instead.\n //\n // To force a re-render, we call forceUpdate({inst}). That works because the\n // new object always fails an equality check.\n\n\n var _useState = useState({\n inst: {\n value: value,\n getSnapshot: getSnapshot\n }\n }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated\n // in the layout phase so we can access it during the tearing check that\n // happens on subscribe.\n\n\n useLayoutEffect(function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the\n // commit phase if there was an interleaved mutation. In concurrent mode\n // this can happen all the time, but even in synchronous mode, an earlier\n // effect may have mutated the store.\n\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }, [subscribe, value, getSnapshot]);\n useEffect(function () {\n // Check for changes right before subscribing. Subsequent changes will be\n // detected in the subscription handler.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n\n var handleStoreChange = function () {\n // TODO: Because there is no cross-renderer API for batching updates, it's\n // up to the consumer of this library to wrap their subscription event\n // with unstable_batchedUpdates. Should we try to detect when this isn't\n // the case and print a warning in development?\n // The store changed. Check if the snapshot changed since the last time we\n // read from the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }; // Subscribe to the store and return a clean-up function.\n\n\n return subscribe(handleStoreChange);\n }, [subscribe]);\n useDebugValue(value);\n return value;\n}\n\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n var prevValue = inst.value;\n\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(prevValue, nextValue);\n } catch (error) {\n return true;\n }\n}\n\nfunction useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {\n // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n // React do not expose a way to check if we're hydrating. So users of the shim\n // will need to track that themselves and return the correct value\n // from `getSnapshot`.\n return getSnapshot();\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar isServerEnvironment = !canUseDOM;\n\nvar shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;\nvar useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;\n\nexports.useSyncExternalStore = useSyncExternalStore$2;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\nvar shim = require('use-sync-external-store/shim');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = shim.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","import * as React from 'react';\nexport default function useConstant(fn) {\n var ref = React.useRef();\n if (!ref.current) {\n ref.current = { v: fn() };\n }\n return ref.current.v;\n}\n","var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nimport { createMachine, interpret, InterpreterStatus } from '@xstate/fsm';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport useConstant from './useConstant';\nfunction identity(a) {\n return a;\n}\nvar getServiceState = function (service) {\n var currentValue;\n service\n .subscribe(function (state) {\n currentValue = state;\n })\n .unsubscribe();\n return currentValue;\n};\nexport function useMachine(stateMachine, options) {\n var persistedStateRef = useRef();\n if (process.env.NODE_ENV !== 'production') {\n var _a = __read(useState(stateMachine), 1), initialMachine = _a[0];\n if (stateMachine !== initialMachine) {\n console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\\n' +\n 'Please make sure that you pass the same Machine as argument each time.');\n }\n }\n var _b = __read(useConstant(function () {\n var queue = [];\n var service = interpret(createMachine(stateMachine.config, options ? options : stateMachine._options));\n var send = service.send;\n service.send = function (event) {\n if (service.status === InterpreterStatus.NotStarted) {\n queue.push(event);\n return;\n }\n send(event);\n persistedStateRef.current = service.state;\n };\n return [service, queue];\n }), 2), service = _b[0], queue = _b[1];\n useIsomorphicLayoutEffect(function () {\n if (options) {\n service._machine._options = options;\n }\n });\n var useServiceResult = useService(service);\n useEffect(function () {\n service.start(persistedStateRef.current);\n queue.forEach(service.send);\n persistedStateRef.current = service.state;\n return function () {\n service.stop();\n };\n }, []);\n return useServiceResult;\n}\nvar isEqual = function (_prevState, nextState) { return nextState.changed === false; };\nexport function useService(service) {\n var getSnapshot = useCallback(function () { return getServiceState(service); }, [service]);\n var subscribe = useCallback(function (handleStoreChange) {\n var unsubscribe = service.subscribe(handleStoreChange).unsubscribe;\n return unsubscribe;\n }, [service]);\n var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, identity, isEqual);\n return [storeSnapshot, service.send, service];\n}\n","import type {PartialDeep} from 'type-fest';\n\n/**\n * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](https://shopify.dev/api/storefront/reference/products/product)) into a flat array of nodes.\n * The utility works with either `nodes` or `edges.node`.\n *\n * If `connection` is null or undefined, will return an empty array instead in production. In development, an error will be thrown.\n */\nexport function flattenConnection<\n ConnectionGeneric extends\n | PartialDeep<ConnectionEdges, {recurseIntoArrays: true}>\n | PartialDeep<ConnectionNodes, {recurseIntoArrays: true}>\n | ConnectionEdges\n | ConnectionNodes,\n>(\n connection?: ConnectionGeneric,\n): ConnectionGeneric extends\n | {\n edges: {node: Array<infer ConnectionBaseType>};\n }\n | {\n nodes: Array<infer ConnectionBaseType>;\n }\n ? // if it's not a PartialDeep, then return the infered type\n ConnectionBaseType[]\n : ConnectionGeneric extends\n | PartialDeep<\n {edges: {node: Array<infer ConnectionBaseType>}},\n {recurseIntoArrays: true}\n >\n | PartialDeep<\n {\n nodes: Array<infer ConnectionBaseType>;\n },\n {recurseIntoArrays: true}\n >\n ? // if it is a PartialDeep, return a PartialDeep inferred type\n PartialDeep<ConnectionBaseType[], {recurseIntoArrays: true}>\n : never {\n if (!connection) {\n const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${\n connection ?? ''\n }' instead.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noConnectionErr);\n } else {\n console.error(noConnectionErr + ` Returning an empty array`);\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n }\n }\n\n if ('nodes' in connection) {\n // @ts-expect-error return type is failing\n return connection.nodes;\n }\n\n if ('edges' in connection && Array.isArray(connection.edges)) {\n // @ts-expect-error return type is failing\n return connection.edges.map((edge) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!edge?.node) {\n throw new Error(\n 'flattenConnection(): Connection edges must contain nodes',\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access\n return edge.node;\n }) as Array<unknown>;\n }\n\n if (__HYDROGEN_DEV__) {\n console.warn(\n `flattenConnection(): The connection did not contain either \"nodes\" or \"edges.node\". Returning an empty array.`,\n );\n }\n\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n}\n\ntype ConnectionEdges = {\n edges: {node: Array<unknown>};\n};\n\ntype ConnectionNodes = {\n nodes: Array<unknown>;\n};\n\n// This is only for documentation purposes, and it is not used in the code.\nexport interface ConnectionGenericForDoc {\n connection?: ConnectionEdges | ConnectionNodes;\n}\nexport type FlattenConnectionReturnForDoc = Array<unknown>;\n","export const CartLineAdd = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineAdd(\n $cartId: ID!\n $lines: [CartLineInput!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartCreate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartCreate(\n $input: CartInput!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartCreate(input: $input) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartLineRemove = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineRemove(\n $cartId: ID!\n $lines: [ID!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesRemove(cartId: $cartId, lineIds: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartLineUpdate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartLineUpdate(\n $cartId: ID!\n $lines: [CartLineUpdateInput!]!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartNoteUpdate = (cartFragment: string): string => /* GraphQL */ `\n mutation CartNoteUpdate(\n $cartId: ID!\n $note: String\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartNoteUpdate(cartId: $cartId, note: $note) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartBuyerIdentityUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartBuyerIdentityUpdate(\n $cartId: ID!\n $buyerIdentity: CartBuyerIdentityInput!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartAttributesUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartAttributesUpdate(\n $attributes: [AttributeInput!]!\n $cartId: ID!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartAttributesUpdate(attributes: $attributes, cartId: $cartId) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartDiscountCodesUpdate = (\n cartFragment: string,\n): string => /* GraphQL */ `\n mutation CartDiscountCodesUpdate(\n $cartId: ID!\n $discountCodes: [String!]\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {\n cart {\n ...CartFragment\n }\n }\n }\n\n ${cartFragment}\n`;\n\nexport const CartQuery = (cartFragment: string): string => /* GraphQL */ `\n query CartQuery(\n $id: ID!\n $numCartLines: Int = 250\n $country: CountryCode = ZZ\n ) @inContext(country: $country) {\n cart(id: $id) {\n ...CartFragment\n }\n }\n\n ${cartFragment}\n`;\n\nexport const defaultCartFragment = /* GraphQL */ `\n fragment CartFragment 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 compareAtAmountPerQuantity {\n amount\n currencyCode\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n availableForSale\n compareAtPrice {\n ...MoneyFragment\n }\n price {\n ...MoneyFragment\n }\n requiresShipping\n title\n image {\n ...ImageFragment\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 ...MoneyFragment\n }\n totalAmount {\n ...MoneyFragment\n }\n totalDutyAmount {\n ...MoneyFragment\n }\n totalTaxAmount {\n ...MoneyFragment\n }\n }\n note\n attributes {\n key\n value\n }\n discountCodes {\n code\n }\n }\n\n fragment MoneyFragment on MoneyV2 {\n currencyCode\n amount\n }\n fragment ImageFragment on Image {\n id\n url\n altText\n width\n height\n }\n`;\n","export const SFAPI_VERSION = '2023-04';\n","import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n","import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n return overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n }\n\n return {\n ...shopifyConfig,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = getShopifyDomain({\n storeDomain: overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase,\n ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n","export const CART_ID_STORAGE_KEY = 'shopifyCartId';\nexport const CART_COOKIE_TTL_DAYS = 14;\n\n// Needed for cart analytics within Shopify\nexport const SHOPIFY_STOREFRONT_ID_HEADER = 'Shopify-Storefront-Id';\nexport const SHOPIFY_STOREFRONT_Y_HEADER = 'Shopify-Storefront-Y';\nexport const SHOPIFY_STOREFRONT_S_HEADER = 'Shopify-Storefront-S';\nexport const SHOPIFY_Y = '_shopify_y';\nexport const SHOPIFY_S = '_shopify_s';\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';\nimport {ShopifyCookies} from './analytics-types.js';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\n\nconst tokenHash = 'xxxx-4xxx-xxxx-xxxxxxxxxxxx';\n\nexport function buildUUID(): string {\n let hash = '';\n\n try {\n const crypto: Crypto = window.crypto;\n const randomValuesArray = new Uint16Array(31);\n crypto.getRandomValues(randomValuesArray);\n\n // Generate a strong UUID\n let i = 0;\n hash = tokenHash\n .replace(/[x]/g, (c: string): string => {\n const r = randomValuesArray[i] % 16;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n i++;\n return v.toString(16);\n })\n .toUpperCase();\n } catch (err) {\n // crypto not available, generate weak UUID\n hash = tokenHash\n .replace(/[x]/g, (c: string): string => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n })\n .toUpperCase();\n }\n\n return `${hexTime()}-${hash}`;\n}\n\nexport function hexTime(): string {\n // 32 bit representations of new Date().getTime() and performance.now()\n let dateNumber = 0;\n let perfNumber = 0;\n\n // Result of zero-fill right shift is always positive\n dateNumber = new Date().getTime() >>> 0;\n\n try {\n perfNumber = performance.now() >>> 0;\n } catch (err) {\n perfNumber = 0;\n }\n\n const output = Math.abs(dateNumber + perfNumber)\n .toString(16)\n .toLowerCase();\n\n return output.padStart(8 - output.length, '0');\n}\n\nexport function getShopifyCookies(cookies: string): ShopifyCookies {\n const cookieData = parse(cookies);\n return {\n [SHOPIFY_Y]: cookieData[SHOPIFY_Y] || '',\n [SHOPIFY_S]: cookieData[SHOPIFY_S] || '',\n };\n}\n","import {useState, useCallback} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {CartInput, Cart as CartType} from './storefront-api-types.js';\nimport {CartCreate, defaultCartFragment} from './cart-queries.js';\nimport {Cart} from './cart-types.js';\nimport {\n SHOPIFY_STOREFRONT_ID_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_Y,\n SHOPIFY_S,\n} from './cart-constants.js';\nimport type {StorefrontApiResponseOkPartial} from './storefront-api-response.types.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartFetch() {\n const {storefrontId, getPublicTokenHeaders, getStorefrontApiUrl} = useShop();\n\n return useCallback(\n <ReturnDataGeneric,>({\n query,\n variables,\n }: {\n query: string;\n variables: Record<string, unknown>;\n }): Promise<StorefrontApiResponseOkPartial<ReturnDataGeneric>> => {\n const headers = getPublicTokenHeaders({contentType: 'json'});\n\n if (storefrontId) {\n headers[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId;\n }\n\n // Find Shopify cookies\n const cookieData = getShopifyCookies(document.cookie);\n headers[SHOPIFY_STOREFRONT_Y_HEADER] = cookieData[SHOPIFY_Y];\n headers[SHOPIFY_STOREFRONT_S_HEADER] = cookieData[SHOPIFY_S];\n\n return fetch(getStorefrontApiUrl(), {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query: query.toString(),\n variables,\n }),\n })\n .then(\n (res) =>\n res.json() as StorefrontApiResponseOkPartial<ReturnDataGeneric>,\n )\n .catch((error) => {\n return {\n data: undefined,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n errors: error?.toString(),\n };\n });\n },\n [getPublicTokenHeaders, storefrontId, getStorefrontApiUrl],\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useInstantCheckout() {\n const [cart, updateCart] = useState<Cart | undefined>();\n const [checkoutUrl, updateCheckoutUrl] = useState<Cart['checkoutUrl']>();\n const [error, updateError] = useState<string | undefined>();\n\n const fetch = useCartFetch();\n\n const createInstantCheckout = useCallback(\n async (cartInput: CartInput) => {\n const {data, errors} = await fetch<{\n cartCreate: {cart: CartType};\n }>({\n query: CartCreate(defaultCartFragment),\n variables: {\n input: cartInput,\n },\n });\n\n if (errors) {\n updateError(errors.toString());\n updateCart(undefined);\n updateCheckoutUrl(undefined);\n }\n\n if (data?.cartCreate?.cart) {\n const dataCart = data.cartCreate.cart;\n updateCart({\n ...dataCart,\n lines: flattenConnection(dataCart.lines),\n note: dataCart.note ?? undefined,\n });\n updateCheckoutUrl(dataCart.checkoutUrl);\n }\n },\n [fetch],\n );\n\n return {cart, checkoutUrl, error, createInstantCheckout};\n}\n","import {useCallback, useMemo} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n Cart as CartType,\n MutationCartDiscountCodesUpdateArgs,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n CartAttributesUpdate,\n CartBuyerIdentityUpdate,\n CartCreate,\n CartDiscountCodesUpdate,\n CartLineAdd,\n CartLineRemove,\n CartLineUpdate,\n CartNoteUpdate,\n CartQuery,\n} from './cart-queries.js';\nimport {useCartFetch} from './cart-hooks.js';\nimport {PartialDeep} from 'type-fest';\n\ntype CartResponse = PartialDeep<CartType, {recurseIntoArrays: true}>;\n\n/**\n * The `useCartActions` hook returns helper graphql functions for Storefront Cart API\n *\n * See [cart API graphql mutations](https://shopify.dev/api/storefront/2023-04/objects/Cart)\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartActions({\n numCartLines,\n cartFragment,\n countryCode = 'US',\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n}) {\n const fetchCart = useCartFetch();\n\n const cartFetch = useCallback(\n (cartId: string) => {\n return fetchCart<{cart: CartResponse}>({\n query: CartQuery(cartFragment),\n variables: {\n id: cartId,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode],\n );\n\n const cartCreate = useCallback(\n (cart: CartInput) => {\n return fetchCart<{cartCreate: {cart: CartResponse}}>({\n query: CartCreate(cartFragment),\n variables: {\n input: cart,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineAdd = useCallback(\n (cartId: string, lines: CartLineInput[]) => {\n return fetchCart<{cartLinesAdd: {cart: CartResponse}}>({\n query: CartLineAdd(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineUpdate = useCallback(\n (cartId: string, lines: CartLineUpdateInput[]) => {\n return fetchCart<{cartLinesUpdate: {cart: CartResponse}}>({\n query: CartLineUpdate(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartLineRemove = useCallback(\n (cartId: string, lines: string[]) => {\n return fetchCart<{cartLinesRemove: {cart: CartResponse}}>({\n query: CartLineRemove(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const noteUpdate = useCallback(\n (cartId: string, note: MutationCartNoteUpdateArgs['note']) => {\n return fetchCart<{cartNoteUpdate: {cart: CartResponse}}>({\n query: CartNoteUpdate(cartFragment),\n variables: {\n cartId,\n note,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode],\n );\n\n const buyerIdentityUpdate = useCallback(\n (cartId: string, buyerIdentity: CartBuyerIdentityInput) => {\n return fetchCart<{cartBuyerIdentityUpdate: {cart: CartResponse}}>({\n query: CartBuyerIdentityUpdate(cartFragment),\n variables: {\n cartId,\n buyerIdentity,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const cartAttributesUpdate = useCallback(\n (cartId: string, attributes: AttributeInput[]) => {\n return fetchCart<{cartAttributesUpdate: {cart: CartResponse}}>({\n query: CartAttributesUpdate(cartFragment),\n variables: {\n cartId,\n attributes,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n const discountCodesUpdate = useCallback(\n (\n cartId: string,\n discountCodes: MutationCartDiscountCodesUpdateArgs['discountCodes'],\n ) => {\n return fetchCart<{cartDiscountCodesUpdate: {cart: CartResponse}}>({\n query: CartDiscountCodesUpdate(cartFragment),\n variables: {\n cartId,\n discountCodes,\n numCartLines,\n country: countryCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines],\n );\n\n return useMemo(\n () => ({\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n }),\n [\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n ],\n );\n}\n","import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {CountryCode, Cart as CartType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n createContext,\n useContext,\n} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n Cart as CartType,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n BuyerIdentityUpdateEvent,\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState,\n CartWithActions,\n} from './cart-types.js';\nimport {useCartAPIStateMachine} from './useCartAPIStateMachine.js';\nimport {CART_ID_STORAGE_KEY} from './cart-constants.js';\nimport {PartialDeep} from 'type-fest';\nimport {defaultCartFragment} from './cart-queries.js';\n\nexport const CartContext = createContext<CartWithActions | null>(null);\n\n/**\n * The `useCart` hook provides access to the cart object. It must be a descendent of a `CartProvider` component.\n */\nexport function useCart(): CartWithActions {\n const context = useContext(CartContext);\n\n if (!context) {\n throw new Error('Expected a Cart Context, but no Cart Context was found');\n }\n\n return context;\n}\n\ntype CartProviderProps = {\n /** Any `ReactNode` elements. */\n children: React.ReactNode;\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked when the process to create a cart begins, but before the cart is created in the Storefront API. */\n onCreate?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart begins, but before the line item is added to the Storefront API. */\n onLineAdd?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart begins, but before the line item is removed from the Storefront API. */\n onLineRemove?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart begins, but before the line item is updated in the Storefront API. */\n onLineUpdate?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart begins, but before the note is added or updated in the Storefront API. */\n onNoteUpdate?: () => void;\n /** A callback that is invoked when the process to update the buyer identity begins, but before the buyer identity is updated in the Storefront API. */\n onBuyerIdentityUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart attributes begins, but before the attributes are updated in the Storefront API. */\n onAttributesUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes begins, but before the discount codes are updated in the Storefront API. */\n onDiscountCodesUpdate?: () => void;\n /** A callback that is invoked when the process to create a cart completes */\n onCreateComplete?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart completes */\n onLineAddComplete?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart completes */\n onLineRemoveComplete?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart completes */\n onLineUpdateComplete?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart completes */\n onNoteUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the buyer identity completes */\n onBuyerIdentityUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart attributes completes */\n onAttributesUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes completes */\n onDiscountCodesUpdateComplete?: () => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2023-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment?: string;\n /** A customer access token that's accessible on the server if there's a customer login. */\n customerAccessToken?: CartBuyerIdentityInput['customerAccessToken'];\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n};\n\n/**\n * The `CartProvider` component synchronizes the state of the Storefront API Cart and a customer's cart,\n * and allows you to more easily manipulate the cart by adding, removing, and updating it.\n * It could be placed at the root of your app so that your whole app is able to use the `useCart()` hook anywhere.\n *\n * There are props that trigger when a call to the Storefront API is made, such as `onLineAdd={}` when a line is added to the cart.\n * There are also props that trigger when a call to the Storefront API is completed, such as `onLineAddComplete={}` when the fetch request for adding a line to the cart completes.\n *\n * The `CartProvider` component must be a descendant of the `ShopifyProvider` component.\n */\nexport function CartProvider({\n children,\n numCartLines,\n onCreate,\n onLineAdd,\n onLineRemove,\n onLineUpdate,\n onNoteUpdate,\n onBuyerIdentityUpdate,\n onAttributesUpdate,\n onDiscountCodesUpdate,\n onCreateComplete,\n onLineAddComplete,\n onLineRemoveComplete,\n onLineUpdateComplete,\n onNoteUpdateComplete,\n onBuyerIdentityUpdateComplete,\n onAttributesUpdateComplete,\n onDiscountCodesUpdateComplete,\n data: cart,\n cartFragment = defaultCartFragment,\n customerAccessToken,\n countryCode = 'US',\n}: CartProviderProps): JSX.Element {\n if (countryCode) countryCode = countryCode.toUpperCase() as CountryCode;\n const [prevCountryCode, setPrevCountryCode] = useState(countryCode);\n const [prevCustomerAccessToken, setPrevCustomerAccessToken] =\n useState(customerAccessToken);\n const customerOverridesCountryCode = useRef(false);\n\n if (\n prevCountryCode !== countryCode ||\n prevCustomerAccessToken !== customerAccessToken\n ) {\n setPrevCountryCode(countryCode);\n setPrevCustomerAccessToken(customerAccessToken);\n customerOverridesCountryCode.current = false;\n }\n\n const [cartState, cartSend] = useCartAPIStateMachine({\n numCartLines,\n data: cart,\n cartFragment,\n countryCode,\n onCartActionEntry(_, event) {\n try {\n switch (event.type) {\n case 'CART_CREATE':\n return onCreate?.();\n case 'CARTLINE_ADD':\n return onLineAdd?.();\n case 'CARTLINE_REMOVE':\n return onLineRemove?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdate?.();\n case 'NOTE_UPDATE':\n return onNoteUpdate?.();\n case 'BUYER_IDENTITY_UPDATE':\n return onBuyerIdentityUpdate?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdate?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdate?.();\n }\n } catch (error) {\n console.error('Cart entry action failed', error);\n }\n },\n onCartActionOptimisticUI(context, event) {\n if (!context.cart) return {...context};\n switch (event.type) {\n case 'CARTLINE_REMOVE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.filter(\n (line) => line?.id && !event.payload.lines.includes(line?.id),\n ),\n },\n };\n case 'CARTLINE_UPDATE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.map((line) => {\n const updatedLine = event.payload.lines.find(\n ({id}) => id === line?.id,\n );\n\n if (updatedLine && updatedLine.quantity) {\n return {\n ...line,\n quantity: updatedLine.quantity,\n };\n }\n\n return line;\n }),\n },\n };\n }\n return {...context};\n },\n onCartActionComplete(context, event) {\n const cartActionEvent = event.payload.cartActionEvent;\n try {\n switch (event.type) {\n case 'RESOLVE':\n switch (cartActionEvent.type) {\n case 'CART_CREATE':\n return onCreateComplete?.();\n case 'CARTLINE_ADD':\n return onLineAddComplete?.();\n case 'CARTLINE_REMOVE':\n return onLineRemoveComplete?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdateComplete?.();\n case 'NOTE_UPDATE':\n return onNoteUpdateComplete?.();\n case 'BUYER_IDENTITY_UPDATE':\n if (countryCodeNotUpdated(context, cartActionEvent)) {\n customerOverridesCountryCode.current = true;\n }\n return onBuyerIdentityUpdateComplete?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdateComplete?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdateComplete?.();\n }\n }\n } catch (error) {\n console.error('onCartActionComplete failed', error);\n }\n },\n });\n\n const cartReady = useRef(false);\n const cartCompleted = cartState.matches('cartCompleted');\n\n const countryChanged =\n (cartState.value === 'idle' ||\n cartState.value === 'error' ||\n cartState.value === 'cartCompleted') &&\n countryCode !== cartState?.context?.cart?.buyerIdentity?.countryCode &&\n !cartState.context.errors;\n\n const fetchingFromStorage = useRef(false);\n\n /**\n * Initializes cart with priority in this order:\n * 1. cart props\n * 2. localStorage cartId\n */\n useEffect(() => {\n if (!cartReady.current && !fetchingFromStorage.current) {\n if (!cart && storageAvailable('localStorage')) {\n fetchingFromStorage.current = true;\n try {\n const cartId = window.localStorage.getItem(CART_ID_STORAGE_KEY);\n if (cartId) {\n cartSend({type: 'CART_FETCH', payload: {cartId}});\n }\n } catch (error) {\n console.warn('error fetching cartId');\n console.warn(error);\n }\n }\n cartReady.current = true;\n }\n }, [cart, cartReady, cartSend]);\n\n // Update cart country code if cart and props countryCode's as different\n useEffect(() => {\n if (!countryChanged || customerOverridesCountryCode.current) return;\n cartSend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {buyerIdentity: {countryCode, customerAccessToken}},\n });\n }, [\n countryCode,\n customerAccessToken,\n countryChanged,\n customerOverridesCountryCode,\n cartSend,\n ]);\n\n // send cart events when ready\n const onCartReadySend = useCallback(\n (cartEvent: CartMachineEvent) => {\n if (!cartReady.current) {\n return console.warn(\"Cart isn't ready yet\");\n }\n cartSend(cartEvent);\n },\n [cartSend],\n );\n\n // save cart id to local storage\n useEffect(() => {\n if (cartState?.context?.cart?.id && storageAvailable('localStorage')) {\n try {\n window.localStorage.setItem(\n CART_ID_STORAGE_KEY,\n cartState.context.cart?.id,\n );\n } catch (error) {\n console.warn('Failed to save cartId to localStorage', error);\n }\n }\n }, [cartState?.context?.cart?.id]);\n\n // delete cart from local storage if cart fetched has been completed\n useEffect(() => {\n if (cartCompleted && storageAvailable('localStorage')) {\n try {\n window.localStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch (error) {\n console.warn('Failed to delete cartId from localStorage', error);\n }\n }\n }, [cartCompleted]);\n\n const cartCreate = useCallback(\n (cartInput: CartInput) => {\n if (countryCode && !cartInput.buyerIdentity?.countryCode) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.countryCode = countryCode;\n }\n\n if (\n customerAccessToken &&\n !cartInput.buyerIdentity?.customerAccessToken\n ) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.customerAccessToken = customerAccessToken;\n }\n onCartReadySend({\n type: 'CART_CREATE',\n payload: cartInput,\n });\n },\n [countryCode, customerAccessToken, onCartReadySend],\n );\n\n // Delays the cart state in the context if the page is hydrating\n // preventing suspense boundary errors.\n const cartDisplayState = useDelayedStateUntilHydration(cartState);\n\n const cartContextValue = useMemo<CartWithActions>(() => {\n return {\n ...(cartDisplayState?.context?.cart ?? {lines: [], attributes: []}),\n status: transposeStatus(cartDisplayState.value),\n error: cartDisplayState?.context?.errors,\n totalQuantity: cartDisplayState?.context?.cart?.totalQuantity ?? 0,\n cartCreate,\n linesAdd(lines: CartLineInput[]): void {\n if (cartDisplayState?.context?.cart?.id) {\n onCartReadySend({\n type: 'CARTLINE_ADD',\n payload: {lines},\n });\n } else {\n cartCreate({lines});\n }\n },\n linesRemove(lines: string[]): void {\n onCartReadySend({\n type: 'CARTLINE_REMOVE',\n payload: {\n lines,\n },\n });\n },\n linesUpdate(lines: CartLineUpdateInput[]): void {\n onCartReadySend({\n type: 'CARTLINE_UPDATE',\n payload: {\n lines,\n },\n });\n },\n noteUpdate(note: MutationCartNoteUpdateArgs['note']): void {\n onCartReadySend({\n type: 'NOTE_UPDATE',\n payload: {\n note,\n },\n });\n },\n buyerIdentityUpdate(buyerIdentity: CartBuyerIdentityInput): void {\n onCartReadySend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {\n buyerIdentity,\n },\n });\n },\n cartAttributesUpdate(attributes: AttributeInput[]): void {\n onCartReadySend({\n type: 'CART_ATTRIBUTES_UPDATE',\n payload: {\n attributes,\n },\n });\n },\n discountCodesUpdate(discountCodes: string[]): void {\n onCartReadySend({\n type: 'DISCOUNT_CODES_UPDATE',\n payload: {\n discountCodes,\n },\n });\n },\n cartFragment,\n };\n }, [\n cartCreate,\n cartDisplayState?.context?.cart,\n cartDisplayState?.context?.errors,\n cartDisplayState.value,\n cartFragment,\n onCartReadySend,\n ]);\n\n return (\n <CartContext.Provider value={cartContextValue}>\n {children}\n </CartContext.Provider>\n );\n}\n\nfunction transposeStatus(\n status: CartMachineTypeState['value'],\n): CartWithActions['status'] {\n switch (status) {\n case 'uninitialized':\n case 'initializationError':\n return 'uninitialized';\n case 'idle':\n case 'cartCompleted':\n case 'error':\n return 'idle';\n case 'cartFetching':\n return 'fetching';\n case 'cartCreating':\n return 'creating';\n case 'cartLineAdding':\n case 'cartLineRemoving':\n case 'cartLineUpdating':\n case 'noteUpdating':\n case 'buyerIdentityUpdating':\n case 'cartAttributesUpdating':\n case 'discountCodesUpdating':\n return 'updating';\n }\n}\n\n/**\n * Delays a state update until hydration finishes. Useful for preventing suspense boundaries errors when updating a context\n * @remarks this uses startTransition and waits for it to finish.\n */\nfunction useDelayedStateUntilHydration<T>(state: T): T {\n const [isPending, startTransition] = useTransition();\n const [delayedState, setDelayedState] = useState(state);\n\n const firstTimePending = useRef(false);\n if (isPending) {\n firstTimePending.current = true;\n }\n\n const firstTimePendingFinished = useRef(false);\n if (!isPending && firstTimePending.current) {\n firstTimePendingFinished.current = true;\n }\n\n useEffect(() => {\n startTransition(() => {\n if (!firstTimePendingFinished.current) {\n setDelayedState(state);\n }\n });\n }, [state]);\n\n const displayState = firstTimePendingFinished.current ? state : delayedState;\n\n return displayState;\n}\n\n/** Check for storage availability funciton obtained from\n * https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API\n */\nexport function storageAvailable(\n type: 'localStorage' | 'sessionStorage',\n): boolean {\n let storage;\n try {\n storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return true;\n } catch (e) {\n return !!(\n e instanceof DOMException &&\n // everything except Firefox\n (e.code === 22 ||\n // Firefox\n e.code === 1014 ||\n // test name field too, because code might not be present\n // everything except Firefox\n e.name === 'QuotaExceededError' ||\n // Firefox\n e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&\n // acknowledge QuotaExceededError only if there's something already stored\n storage &&\n storage.length !== 0\n );\n }\n}\n\nfunction countryCodeNotUpdated(\n context: CartMachineContext,\n event: BuyerIdentityUpdateEvent,\n): boolean {\n return !!(\n event.payload.buyerIdentity.countryCode &&\n context.cart?.buyerIdentity?.countryCode !==\n event.payload.buyerIdentity.countryCode\n );\n}\n","import {\n useMemo,\n useState,\n useEffect,\n useCallback,\n createContext,\n useContext,\n} from 'react';\nimport type {\n SelectedOption as SelectedOptionType,\n SellingPlan,\n SellingPlanAllocation,\n Product,\n ProductVariant as ProductVariantType,\n ProductVariantConnection,\n SellingPlan as SellingPlanType,\n SellingPlanAllocation as SellingPlanAllocationType,\n SellingPlanGroup as SellingPlanGroupType,\n SellingPlanGroupConnection,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nconst ProductOptionsContext = createContext<ProductHookValue | null>(null);\n\ntype InitialVariantId = ProductVariantType['id'] | null;\n\ninterface ProductProviderProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** A `ReactNode` element. */\n children: React.ReactNode;\n /**\n * The initially selected variant.\n * The following logic applies to `initialVariantId`:\n * 1. If `initialVariantId` is provided, then it's used even if it's out of stock.\n * 2. If `initialVariantId` is provided but is `null`, then no variant is used.\n * 3. If nothing is passed to `initialVariantId` then the first available / in-stock variant is used.\n * 4. If nothing is passed to `initialVariantId` and no variants are in stock, then the first variant is used.\n */\n initialVariantId?: InitialVariantId;\n}\n\n/**\n * `<ProductProvider />` is a context provider that enables use of the `useProduct()` hook.\n *\n * It helps manage selected options and variants for a product.\n */\nexport function ProductProvider({\n children,\n data: product,\n initialVariantId: explicitVariantId,\n}: ProductProviderProps): JSX.Element {\n // The flattened variants\n const variants = useMemo(\n () => flattenConnection(product.variants ?? {}),\n [product.variants],\n );\n\n if (!isProductVariantArray(variants)) {\n throw new Error(\n `<ProductProvider/> requires 'product.variants.nodes' or 'product.variants.edges'`,\n );\n }\n\n // All the options available for a product, based on all the variants\n const options = useMemo(() => getOptions(variants), [variants]);\n\n /**\n * Track the selectedVariant within the provider.\n */\n const [selectedVariant, setSelectedVariant] = useState<\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null\n >(() => getVariantBasedOnIdProp(explicitVariantId, variants));\n\n /**\n * Track the selectedOptions within the provider. If a `initialVariantId`\n * is passed, use that to select initial options.\n */\n const [selectedOptions, setSelectedOptions] = useState<SelectedOptions>(() =>\n getSelectedOptions(selectedVariant),\n );\n\n /**\n * When the initialVariantId changes, we need to make sure we\n * update the selected variant and selected options. If not,\n * then the selected variant and options will reference incorrect\n * values.\n */\n useEffect(() => {\n const newSelectedVariant = getVariantBasedOnIdProp(\n explicitVariantId,\n variants,\n );\n setSelectedVariant(newSelectedVariant);\n setSelectedOptions(getSelectedOptions(newSelectedVariant));\n }, [explicitVariantId, variants]);\n\n /**\n * Allow the developer to select an option.\n */\n const setSelectedOption = useCallback(\n (name: string, value: string) => {\n setSelectedOptions((selectedOptions) => {\n const opts = {...selectedOptions, [name]: value};\n setSelectedVariant(getSelectedVariant(variants, opts));\n return opts;\n });\n },\n [setSelectedOptions, variants],\n );\n\n const isOptionInStock = useCallback(\n (option: string, value: string) => {\n const proposedVariant = getSelectedVariant(variants, {\n ...selectedOptions,\n ...{[option]: value},\n });\n\n return proposedVariant?.availableForSale ?? true;\n },\n [selectedOptions, variants],\n );\n\n const sellingPlanGroups = useMemo(\n () =>\n flattenConnection(product.sellingPlanGroups ?? {}).map(\n (sellingPlanGroup) => ({\n ...sellingPlanGroup,\n sellingPlans: flattenConnection(sellingPlanGroup?.sellingPlans ?? {}),\n }),\n ),\n [product.sellingPlanGroups],\n );\n\n /**\n * Track the selectedSellingPlan within the hook. If `initialSellingPlanId`\n * is passed, use that as an initial value. Look it up from the `selectedVariant`, since\n * that is also a requirement.\n */\n const [selectedSellingPlan, setSelectedSellingPlan] = useState<\n PartialDeep<SellingPlan, {recurseIntoArrays: true}> | undefined\n >(undefined);\n\n const selectedSellingPlanAllocation = useMemo<\n PartialDeep<SellingPlanAllocation, {recurseIntoArrays: true}> | undefined\n >(() => {\n if (!selectedVariant || !selectedSellingPlan) {\n return;\n }\n\n if (\n !selectedVariant.sellingPlanAllocations?.nodes &&\n !selectedVariant.sellingPlanAllocations?.edges\n ) {\n throw new Error(\n `<ProductProvider/>: You must include 'sellingPlanAllocations.nodes' or 'sellingPlanAllocations.edges' in your variants in order to calculate selectedSellingPlanAllocation`,\n );\n }\n\n return flattenConnection(selectedVariant.sellingPlanAllocations).find(\n (allocation) => allocation?.sellingPlan?.id === selectedSellingPlan.id,\n );\n }, [selectedVariant, selectedSellingPlan]);\n\n const value = useMemo<ProductHookValue>(\n () => ({\n product,\n variants,\n variantsConnection: product.variants,\n options,\n selectedVariant,\n setSelectedVariant,\n selectedOptions,\n setSelectedOption,\n setSelectedOptions,\n isOptionInStock,\n selectedSellingPlan,\n setSelectedSellingPlan,\n selectedSellingPlanAllocation,\n sellingPlanGroups,\n sellingPlanGroupsConnection: product.sellingPlanGroups,\n }),\n [\n product,\n isOptionInStock,\n options,\n selectedOptions,\n selectedSellingPlan,\n selectedSellingPlanAllocation,\n selectedVariant,\n sellingPlanGroups,\n setSelectedOption,\n variants,\n ],\n );\n\n return (\n <ProductOptionsContext.Provider value={value}>\n {children}\n </ProductOptionsContext.Provider>\n );\n}\n\n/**\n * Provides access to the context value provided by `<ProductProvider />`. Must be a descendent of `<ProductProvider />`.\n */\nexport function useProduct(): ProductHookValue {\n const context = useContext(ProductOptionsContext);\n\n if (!context) {\n throw new Error(`'useProduct' must be a child of <ProductProvider />`);\n }\n\n return context;\n}\n\nfunction getSelectedVariant(\n variants: PartialDeep<ProductVariantType, {recurseIntoArrays: true}>[],\n choices: SelectedOptions,\n): PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined {\n /**\n * Ensure the user has selected all the required options, not just some.\n */\n if (\n !variants.length ||\n variants?.[0]?.selectedOptions?.length !== Object.keys(choices).length\n ) {\n return;\n }\n\n return variants?.find((variant) => {\n return Object.entries(choices).every(([name, value]) => {\n return variant?.selectedOptions?.some(\n (option) => option?.name === name && option?.value === value,\n );\n });\n });\n}\n\nfunction getOptions(\n variants: PartialDeep<ProductVariantType, {recurseIntoArrays: true}>[],\n): OptionWithValues[] {\n const map = variants.reduce((memo, variant) => {\n if (!variant.selectedOptions) {\n throw new Error(`'getOptions' requires 'variant.selectedOptions'`);\n }\n variant?.selectedOptions?.forEach((opt) => {\n memo[opt?.name ?? ''] = memo[opt?.name ?? ''] || new Set();\n memo[opt?.name ?? ''].add(opt?.value ?? '');\n });\n\n return memo;\n }, {} as Record<string, Set<string>>);\n\n return Object.keys(map).map((option) => {\n return {\n name: option,\n values: Array.from(map[option]),\n };\n });\n}\n\nfunction getVariantBasedOnIdProp(\n explicitVariantId: InitialVariantId | undefined,\n variants: Array<\n PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined\n >,\n):\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null {\n // get the initial variant based on the logic outlined in the comments for 'initialVariantId' above\n // * 1. If `initialVariantId` is provided, then it's used even if it's out of stock.\n if (explicitVariantId) {\n const foundVariant = variants.find(\n (variant) => variant?.id === explicitVariantId,\n );\n if (!foundVariant) {\n console.warn(\n `<ProductProvider/> received a 'initialVariantId' prop, but could not actually find a variant with that ID`,\n );\n }\n return foundVariant;\n }\n // * 2. If `initialVariantId` is provided but is `null`, then no variant is used.\n if (explicitVariantId === null) {\n return null;\n }\n // * 3. If nothing is passed to `initialVariantId` then the first available / in-stock variant is used.\n // * 4. If nothing is passed to `initialVariantId` and no variants are in stock, then the first variant is used.\n if (explicitVariantId === undefined) {\n return variants.find((variant) => variant?.availableForSale) || variants[0];\n }\n}\n\nfunction getSelectedOptions(\n selectedVariant:\n | PartialDeep<ProductVariantType, {recurseIntoArrays: true}>\n | undefined\n | null,\n): SelectedOptions {\n return selectedVariant?.selectedOptions\n ? selectedVariant.selectedOptions.reduce<SelectedOptions>(\n (memo, optionSet) => {\n memo[optionSet?.name ?? ''] = optionSet?.value ?? '';\n return memo;\n },\n {},\n )\n : {};\n}\n\nfunction isProductVariantArray(\n maybeVariantArray:\n | (PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | undefined)[]\n | undefined,\n): maybeVariantArray is PartialDeep<\n ProductVariantType,\n {recurseIntoArrays: true}\n>[] {\n if (!maybeVariantArray || !Array.isArray(maybeVariantArray)) {\n return false;\n }\n\n return true;\n}\n\nexport interface OptionWithValues {\n name: SelectedOptionType['name'];\n values: SelectedOptionType['value'][];\n}\n\ntype UseProductObjects = {\n /** The raw product from the Storefront API */\n product: Product;\n /** An array of the variant `nodes` from the `VariantConnection`. */\n variants: ProductVariantType[];\n variantsConnection?: ProductVariantConnection;\n /** An array of the product's options and values. */\n options: OptionWithValues[];\n /** The selected variant. */\n selectedVariant?: ProductVariantType | null;\n selectedOptions: SelectedOptions;\n /** The selected selling plan. */\n selectedSellingPlan?: SellingPlanType;\n /** The selected selling plan allocation. */\n selectedSellingPlanAllocation?: SellingPlanAllocationType;\n /** The selling plan groups. */\n sellingPlanGroups?: (Omit<SellingPlanGroupType, 'sellingPlans'> & {\n sellingPlans: SellingPlanType[];\n })[];\n sellingPlanGroupsConnection?: SellingPlanGroupConnection;\n};\n\ntype UseProductFunctions = {\n /** A callback to set the selected variant to the variant passed as an argument. */\n setSelectedVariant: (\n variant: PartialDeep<ProductVariantType, {recurseIntoArrays: true}> | null,\n ) => void;\n /** A callback to set the selected option. */\n setSelectedOption: (\n name: SelectedOptionType['name'],\n value: SelectedOptionType['value'],\n ) => void;\n /** A callback to set multiple selected options at once. */\n setSelectedOptions: (options: SelectedOptions) => void;\n /** A callback to set the selected selling plan to the one passed as an argument. */\n setSelectedSellingPlan: (\n sellingPlan: PartialDeep<SellingPlanType, {recurseIntoArrays: true}>,\n ) => void;\n /** A callback that returns a boolean indicating if the option is in stock. */\n isOptionInStock: (\n name: SelectedOptionType['name'],\n value: SelectedOptionType['value'],\n ) => boolean;\n};\n\ntype ProductHookValue = PartialDeep<\n UseProductObjects,\n {recurseIntoArrays: true}\n> &\n UseProductFunctions;\n\nexport type SelectedOptions = {\n [key: string]: string;\n};\n","import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n Omit<\n React.ComponentPropsWithoutRef<AsType>,\n keyof CustomBaseButtonProps<AsType>\n >;\n\nexport function BaseButton<AsType extends React.ElementType = 'button'>(\n props: BaseButtonProps<AsType>,\n): JSX.Element {\n const {\n as,\n onClick,\n defaultOnClick,\n children,\n buttonRef,\n ...passthroughProps\n } = props;\n\n const handleOnClick = useCallback(\n (event?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (onClick) {\n const clickShouldContinue = onClick(event);\n if (\n (typeof clickShouldContinue === 'boolean' &&\n clickShouldContinue === false) ||\n event?.defaultPrevented\n )\n return;\n }\n\n defaultOnClick?.(event);\n },\n [defaultOnClick, onClick],\n );\n\n const Component = as || 'button';\n\n return (\n <Component ref={buttonRef} onClick={handleOnClick} {...passthroughProps}>\n {children}\n </Component>\n );\n}\n","import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n passthroughProps.disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n","export const AnalyticsEventName: AnalyticsEventName = {\n PAGE_VIEW: 'PAGE_VIEW',\n ADD_TO_CART: 'ADD_TO_CART',\n} as const;\n\nexport const AnalyticsPageType: AnalyticsPageType = {\n article: 'article',\n blog: 'blog',\n captcha: 'captcha',\n cart: 'cart',\n collection: 'collection',\n customersAccount: 'customers/account',\n customersActivateAccount: 'customers/activate_account',\n customersAddresses: 'customers/addresses',\n customersLogin: 'customers/login',\n customersOrder: 'customers/order',\n customersRegister: 'customers/register',\n customersResetPassword: 'customers/reset_password',\n giftCard: 'gift_card',\n home: 'index',\n listCollections: 'list-collections',\n forbidden: '403',\n notFound: '404',\n page: 'page',\n password: 'password',\n product: 'product',\n policy: 'policy',\n search: 'search',\n} as const;\n\nexport const ShopifySalesChannel: ShopifySalesChannel = {\n hydrogen: 'hydrogen',\n headless: 'headless',\n} as const;\n\nexport const ShopifyAppId = {\n hydrogen: '6167201',\n headless: '12875497473',\n} as const;\n\n/**\n * These duplicated interface declaration is so that we can generate proper documentation\n * for these public facing constants\n */\ninterface AnalyticsEventName {\n /** Page view */\n PAGE_VIEW: 'PAGE_VIEW';\n /** Add to cart */\n ADD_TO_CART: 'ADD_TO_CART';\n}\n\ninterface AnalyticsPageType {\n article: 'article';\n blog: 'blog';\n captcha: 'captcha';\n cart: 'cart';\n collection: 'collection';\n customersAccount: 'customers/account';\n customersActivateAccount: 'customers/activate_account';\n customersAddresses: 'customers/addresses';\n customersLogin: 'customers/login';\n customersOrder: 'customers/order';\n customersRegister: 'customers/register';\n customersResetPassword: 'customers/reset_password';\n giftCard: 'gift_card';\n home: 'index';\n listCollections: 'list-collections';\n forbidden: '403';\n notFound: '404';\n page: 'page';\n password: 'password';\n product: 'product';\n policy: 'policy';\n search: 'search';\n}\n\ninterface ShopifySalesChannel {\n /** Shopify Hydrogen sales channel */\n hydrogen: 'hydrogen';\n /** Shopify Headless sales channel */\n headless: 'headless';\n}\n","import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n ShopifyGid,\n} from './analytics-types.js';\n\n/**\n * Builds a Shopify Monorail event from a Shopify Monorail payload and a schema ID.\n * @param payload - The Monorail payload\n * @param schemaId - The schema ID to use\n * @returns The formatted payload\n **/\nexport function schemaWrapper(\n schemaId: string,\n payload: ShopifyMonorailPayload,\n): ShopifyMonorailEvent {\n return {\n schema_id: schemaId,\n payload,\n metadata: {\n event_created_at_ms: Date.now(),\n },\n };\n}\n\n/**\n * Parses global id (gid) and returns the resource type and id.\n * @see https://shopify.dev/api/usage/gids\n * @param gid - A shopify GID (string)\n *\n * @example\n * ```ts\n * const {id, resource} = parseGid('gid://shopify/Order/123')\n * // => id = \"123\", resource = 'Order'\n *\n * * const {id, resource} = parseGid('gid://shopify/Cart/abc123')\n * // => id = \"abc123\", resource = 'Cart'\n * ```\n **/\nexport function parseGid(gid: string | undefined): ShopifyGid {\n const defaultReturn = {id: '', resource: null};\n\n if (typeof gid !== 'string') {\n return defaultReturn;\n }\n\n // TODO: add support for parsing query parameters on complex gids\n // Reference: https://shopify.dev/api/usage/gids\n const matches = gid.match(/^gid:\\/\\/shopify\\/(\\w+)\\/([^/]+)/);\n\n if (!matches || matches.length === 1) {\n return defaultReturn;\n }\n const id = matches[2] ?? null;\n const resource = matches[1] ?? null;\n\n return {id, resource};\n}\n\n/**\n * Filters properties from an object and returns a new object with only the properties that have a truthy value.\n * @param keyValuePairs - An object of key-value pairs\n * @param formattedData - An object which will hold the truthy values\n * @returns The formatted object\n **/\nexport function addDataIf(\n keyValuePairs: ShopifyMonorailPayload,\n formattedData: ShopifyMonorailPayload,\n): ShopifyMonorailPayload {\n if (typeof keyValuePairs !== 'object') {\n return {};\n }\n Object.entries(keyValuePairs).forEach(([key, value]) => {\n if (value) {\n formattedData[key] = value;\n }\n });\n return formattedData;\n}\n\n/**\n * Utility that errors if a function is called on the server.\n * @param fnName - The name of the function\n * @returns A boolean\n **/\nexport function errorIfServer(fnName: string): boolean {\n if (typeof document === 'undefined') {\n console.error(\n `${fnName} should only be used within the useEffect callback or event handlers`,\n );\n return true;\n }\n return false;\n}\n","import {\n ShopifyPageViewPayload,\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {ShopifyAppId} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\n\nconst SCHEMA_ID = 'trekkie_storefront_page_view/1.4';\nconst OXYGEN_DOMAIN = 'myshopify.dev';\n\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const {id, resource} = parseGid(pageViewPayload.resourceId);\n const resourceType = resource ? resource.toLowerCase() : undefined;\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n pageType: pageViewPayload.pageType,\n customerId: pageViewPayload.customerId,\n resourceType,\n resourceId: parseInt(id),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailPayload {\n return {\n appClientId: payload.shopifySalesChannel\n ? ShopifyAppId[payload.shopifySalesChannel]\n : ShopifyAppId.headless,\n isMerchantRequest: isMerchantRequest(payload.url),\n hydrogenSubchannelId: payload.storefrontId || '0',\n\n isPersistentCookie: payload.hasUserConsent,\n uniqToken: payload.uniqueToken,\n visitToken: payload.visitToken,\n microSessionId: buildUUID(),\n microSessionCount: 1,\n\n url: payload.url,\n path: payload.path,\n search: payload.search,\n referrer: payload.referrer,\n title: payload.title,\n\n shopId: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n contentLanguage: payload.acceptedLanguage || 'en',\n };\n}\n\nfunction isMerchantRequest(url: string): boolean {\n if (typeof url !== 'string') {\n return false;\n }\n const hostname = new URL(url).hostname;\n if (hostname.indexOf(OXYGEN_DOMAIN) !== -1 || hostname === 'localhost') {\n return true;\n }\n return false;\n}\n","import {\n ShopifyAnalyticsPayload,\n ShopifyPageViewPayload,\n ShopifyAddToCartPayload,\n ShopifyMonorailPayload,\n ShopifyAnalyticsProduct,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsPageType, ShopifySalesChannel} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\n\nconst SCHEMA_ID = 'custom_storefront_customer_tracking/1.0';\nconst PAGE_RENDERED_EVENT_NAME = 'page_rendered';\nconst COLLECTION_PAGE_RENDERED_EVENT_NAME = 'collection_page_rendered';\nconst PRODUCT_PAGE_RENDERED_EVENT_NAME = 'product_page_rendered';\nconst PRODUCT_ADDED_TO_CART_EVENT_NAME = 'product_added_to_cart';\nconst SEARCH_SUBMITTED_EVENT_NAME = 'search_submitted';\n\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = {\n canonical_url: pageViewPayload.canonicalUrl || pageViewPayload.url,\n customer_id: pageViewPayload.customerId,\n };\n const pageType = pageViewPayload.pageType;\n const pageViewEvents = [];\n\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n\n switch (pageType) {\n case AnalyticsPageType.collection:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.product:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.search:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n }\n\n return pageViewEvents;\n}\n\nexport function addToCart(\n payload: ShopifyAddToCartPayload,\n): ShopifyMonorailEvent[] {\n const addToCartPayload = payload;\n const cartToken = parseGid(addToCartPayload.cartId);\n const cart_token = cartToken?.id ? `${cartToken.id}` : null;\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_ADDED_TO_CART_EVENT_NAME,\n customerId: addToCartPayload.customerId,\n cart_token,\n total_value: addToCartPayload.totalValue,\n products: formatProductPayload(addToCartPayload.products),\n },\n formatPayload(addToCartPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyAnalyticsPayload,\n): ShopifyMonorailPayload {\n return {\n source: payload.shopifySalesChannel || ShopifySalesChannel.headless,\n hydrogenSubchannelId: payload.storefrontId || '0',\n\n is_persistent_cookie: payload.hasUserConsent,\n ccpa_enforced: false,\n gdpr_enforced: false,\n unique_token: payload.uniqueToken,\n event_time: Date.now(),\n event_id: buildUUID(),\n\n event_source_url: payload.url,\n referrer: payload.referrer,\n user_agent: payload.userAgent,\n navigation_type: payload.navigationType,\n navigation_api: payload.navigationApi,\n\n shop_id: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n };\n}\n\nfunction formatProductPayload(products?: ShopifyAnalyticsProduct[]): string[] {\n return products\n ? products.map((p: ShopifyAnalyticsProduct) => {\n const product = addDataIf(\n {\n variant_gid: p.variantGid,\n category: p.category,\n sku: p.sku,\n product_id: parseInt(parseGid(p.productGid).id),\n variant_id: parseInt(parseGid(p.variantGid).id),\n },\n {\n product_gid: p.productGid,\n name: p.name,\n variant: p.variantName || '',\n brand: p.brand,\n price: p.price,\n quantity: Number(p.quantity || 0),\n },\n );\n return JSON.stringify(product);\n })\n : [];\n}\n","import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n const pageViewPayload = payload as ShopifyPageViewPayload;\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n break;\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n break;\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n break;\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n","import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (loading && checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [loading, checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n","import {ReactNode, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ntype ChildrenProps = {\n /** A `ReactNode` element. */\n children: ReactNode;\n};\ntype CartCheckoutButtonProps = Omit<BaseButtonProps<'button'>, 'onClick'> &\n ChildrenProps;\n\n/**\n * The `CartCheckoutButton` component renders a button that redirects to the checkout URL for the cart.\n * It must be a descendent of a `CartProvider` component.\n */\nexport function CartCheckoutButton(\n props: CartCheckoutButtonProps,\n): JSX.Element {\n const [requestedCheckout, setRequestedCheckout] = useState(false);\n const {status, checkoutUrl} = useCart();\n const {children, ...passthroughProps} = props;\n\n useEffect(() => {\n if (requestedCheckout && checkoutUrl && status === 'idle') {\n window.location.href = checkoutUrl;\n }\n }, [requestedCheckout, status, checkoutUrl]);\n\n return (\n <BaseButton\n {...passthroughProps}\n disabled={requestedCheckout || passthroughProps.disabled}\n onClick={(): void => setRequestedCheckout(true)}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documentation purposes, and it is not used in the code.\n// we ignore this issue because it makes the documentation look better than the equivalent `type` that it wants us to convert to\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface CartCheckoutButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends Omit<CustomBaseButtonProps<AsType>, 'onClick'> {}\n","import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {CurrencyCode, MoneyV2} from './storefront-api-types.js';\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n const options = useMemo(\n () => ({\n style: 'currency',\n currency: money.currencyCode,\n }),\n [money.currencyCode],\n );\n\n const defaultFormatter = useLazyFormatter(locale, options);\n\n const nameFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n });\n\n const narrowSymbolFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n });\n\n const withoutTrailingZerosFormatter = useLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const withoutCurrencyFormatter = useLazyFormatter(locale);\n\n const withoutTrailingZerosOrCurrencyFormatter = useLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: () => money,\n currencyCode: () => money.currencyCode,\n\n localizedString: () => defaultFormatter().format(amount),\n\n parts: () => defaultFormatter().formatToParts(amount),\n\n withoutTrailingZeros: () =>\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount),\n\n withoutTrailingZerosAndCurrency: () =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: () =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: () =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: () =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: () =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nfunction useLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n return useMemo(() => {\n let memoized: Intl.NumberFormat;\n return () => (memoized ??= new Intl.NumberFormat(locale, options));\n }, [locale, options]);\n}\n","import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2023-04/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >;\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) according to the\n * `locale` in the `ShopifyProvider` component.\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n","import {Money, type MoneyPropsBase} from './Money.js';\nimport {useCart} from './CartProvider.js';\n\ninterface CartCostPropsBase {\n /** A string type that defines the type of cost needed. Valid values: `total`, `subtotal`, `tax`, or `duty`. */\n amountType?: 'total' | 'subtotal' | 'tax' | 'duty';\n /** Any `ReactNode` elements. */\n children?: React.ReactNode;\n}\n\ntype CartCostProps = Omit<React.ComponentProps<typeof Money>, 'data'> &\n CartCostPropsBase;\n\n/**\n * The `CartCost` component renders a `Money` component with the cost associated with the `amountType` prop.\n * If no `amountType` prop is specified, then it defaults to `totalAmount`.\n * Depends on `useCart()` and must be a child of `<CartProvider/>`\n */\nexport function CartCost(props: CartCostProps): JSX.Element | null {\n const {cost} = useCart();\n const {amountType = 'total', children, ...passthroughProps} = props;\n let amount;\n\n if (amountType == 'total') {\n amount = cost?.totalAmount;\n } else if (amountType == 'subtotal') {\n amount = cost?.subtotalAmount;\n } else if (amountType == 'tax') {\n amount = cost?.totalTaxAmount;\n } else if (amountType == 'duty') {\n amount = cost?.totalDutyAmount;\n }\n\n if (amount == null) {\n return null;\n }\n\n return (\n <Money {...passthroughProps} data={amount}>\n {children}\n </Money>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface CartCostPropsForDocs<AsType extends React.ElementType = 'div'>\n extends Omit<MoneyPropsBase<AsType>, 'data'>,\n CartCostPropsBase {}\n","import {useContext, createContext, type ReactNode} from 'react';\nimport type {CartLine} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ntype CartLinePartialDeep = PartialDeep<CartLine, {recurseIntoArrays: true}>;\n\nexport const CartLineContext = createContext<CartLinePartialDeep | null>(null);\n\n/**\n * The `useCartLine` hook provides access to the [CartLine object](https://shopify.dev/api/storefront/unstable/objects/cartline) from the Storefront API. It must be a descendent of a `CartProvider` component.\n */\nexport function useCartLine(): CartLinePartialDeep {\n const context = useContext(CartLineContext);\n\n if (context == null) {\n throw new Error('Expected a cart line context but none was found');\n }\n\n return context;\n}\n\ntype CartLineProviderProps = {\n /** Any `ReactNode` elements. */\n children: ReactNode;\n /** A cart line object. */\n line: CartLinePartialDeep;\n};\n\n/**\n * The `CartLineProvider` component creates a context for using a cart line.\n */\nexport function CartLineProvider({\n children,\n line,\n}: CartLineProviderProps): JSX.Element {\n return (\n <CartLineContext.Provider value={line}>{children}</CartLineContext.Provider>\n );\n}\n","import type {ComponentPropsWithoutRef, ElementType} from 'react';\nimport {useCartLine} from './CartLineProvider.js';\n\ninterface CartLineQuantityBaseProps<\n ComponentGeneric extends ElementType = 'span',\n> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `span`. */\n as?: ComponentGeneric;\n}\n\nexport type CartLineQuantityProps<ComponentGeneric extends ElementType> =\n CartLineQuantityBaseProps<ComponentGeneric> &\n Omit<\n ComponentPropsWithoutRef<ComponentGeneric>,\n keyof CartLineQuantityBaseProps<ComponentGeneric>\n >;\n\n/**\n * The `<CartLineQuantity/>` component renders a `span` (or another element / component that can be customized by the `as` prop) with the cart line's quantity.\n *\n * It must be a descendent of a `<CartLineProvider/>` component, and uses the `useCartLine()` hook internally.\n */\nexport function CartLineQuantity<ComponentGeneric extends ElementType = 'span'>(\n props: CartLineQuantityProps<ComponentGeneric>,\n): JSX.Element {\n const cartLine = useCartLine();\n const {as, ...passthroughProps} = props;\n\n const Wrapper = as ? as : 'span';\n\n return <Wrapper {...passthroughProps}>{cartLine.quantity}</Wrapper>;\n}\n","import {useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useCartLine} from './CartLineProvider.js';\nimport {BaseButton, type BaseButtonProps} from './BaseButton.js';\nimport type {CartLineUpdateInput} from './storefront-api-types.js';\n\ninterface CartLineQuantityAdjustButtonBaseProps {\n /** The adjustment for a cart line's quantity. Valid values: `increase` (default), `decrease`, or `remove`. */\n adjust?: 'increase' | 'decrease' | 'remove';\n}\n\ntype CartLineQuantityAdjustButtonProps<\n AsType extends React.ElementType = 'button',\n> = BaseButtonProps<AsType> & CartLineQuantityAdjustButtonBaseProps;\n\n/**\n * The `<CartLineQuantityAdjustButton />` component renders a button that adjusts the cart line's quantity when pressed.\n *\n * It must be a descendent of `<CartLineProvider/>` and `<CartProvider/>`.\n */\nexport function CartLineQuantityAdjustButton<\n AsType extends React.ElementType = 'button',\n>(props: CartLineQuantityAdjustButtonProps<AsType>): JSX.Element {\n const {status, linesRemove, linesUpdate} = useCart();\n const cartLine = useCartLine();\n const {children, adjust, onClick, ...passthroughProps} = props;\n\n const handleAdjust = useCallback(() => {\n if (adjust === 'remove') {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const quantity =\n adjust === 'decrease'\n ? (cartLine?.quantity ?? 0) - 1\n : (cartLine?.quantity ?? 0) + 1;\n\n if (quantity <= 0) {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const lineUpdate = {\n id: cartLine?.id ?? '',\n quantity,\n attributes: (cartLine?.attributes ??\n []) as CartLineUpdateInput['attributes'],\n } satisfies CartLineUpdateInput;\n\n linesUpdate([lineUpdate]);\n }, [\n adjust,\n cartLine?.attributes,\n cartLine?.id,\n cartLine?.quantity,\n linesRemove,\n linesUpdate,\n ]);\n\n return (\n <BaseButton\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleAdjust}\n disabled={\n typeof passthroughProps.disabled !== 'undefined'\n ? passthroughProps.disabled\n : status !== 'idle'\n }\n >\n {children}\n </BaseButton>\n );\n}\n","/** Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n","import type {ExternalVideo as ExternalVideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ninterface ExternalVideoBaseProps {\n /**\n * An object with fields that correspond to the Storefront API's [ExternalVideo object](https://shopify.dev/api/storefront/reference/products/externalvideo).\n */\n data: PartialDeep<ExternalVideoType, {recurseIntoArrays: true}>;\n /** An object containing the options available for either\n * [YouTube](https://developers.google.com/youtube/player_parameters#Parameters) or\n * [Vimeo](https://vimeo.zendesk.com/hc/en-us/articles/360001494447-Using-Player-Parameters).\n */\n options?: YouTube | Vimeo;\n}\n\nexport type ExternalVideoProps = Omit<JSX.IntrinsicElements['iframe'], 'src'> &\n ExternalVideoBaseProps;\n\n/**\n * The `ExternalVideo` component renders an embedded video for the Storefront\n * API's [ExternalVideo object](https://shopify.dev/api/storefront/reference/products/externalvideo).\n */\nexport function ExternalVideo(props: ExternalVideoProps): JSX.Element {\n const {\n data,\n options,\n id = data.id,\n frameBorder = '0',\n allow = 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture',\n allowFullScreen = true,\n loading = 'lazy',\n ...passthroughProps\n } = props;\n\n if (!data.embedUrl) {\n throw new Error(`<ExternalVideo/> requires the 'embedUrl' property`);\n }\n\n let finalUrl: string = data.embedUrl;\n\n if (options) {\n const urlObject = new URL(data.embedUrl);\n for (const key of Object.keys(options) as (keyof typeof options)[]) {\n // @ts-expect-error https://github.com/microsoft/TypeScript/issues/32951\n urlObject.searchParams.set(key, options[key]);\n }\n finalUrl = urlObject.toString();\n }\n\n return (\n <iframe\n {...passthroughProps}\n id={id ?? data.embedUrl}\n title={data.alt ?? data.id ?? 'external video'}\n frameBorder={frameBorder}\n allow={allow}\n allowFullScreen={allowFullScreen}\n src={finalUrl}\n loading={loading}\n ></iframe>\n );\n}\n\ninterface YouTube {\n autoplay?: 0 | 1;\n cc_lang_pref?: string;\n cc_load_policy?: 1;\n color?: 'red' | 'white';\n controls?: 0 | 1;\n disablekb?: 0 | 1;\n enablejsapi?: 0 | 1;\n end?: number;\n fs?: 0 | 1;\n hl?: string;\n iv_load_policy?: 1 | 3;\n list?: string;\n list_type?: 'playlist' | 'user_uploads';\n loop?: 0 | 1;\n modest_branding?: 1;\n origin?: string;\n playlist?: string;\n plays_inline?: 0 | 1;\n rel?: 0 | 1;\n start?: number;\n widget_referrer?: string;\n}\n\ntype VimeoBoolean = 0 | 1 | boolean;\n\ninterface Vimeo {\n autopause?: VimeoBoolean;\n autoplay?: VimeoBoolean;\n background?: VimeoBoolean;\n byline?: VimeoBoolean;\n color?: string;\n controls?: VimeoBoolean;\n dnt?: VimeoBoolean;\n loop?: VimeoBoolean;\n muted?: VimeoBoolean;\n pip?: VimeoBoolean;\n playsinline?: VimeoBoolean;\n portrait?: VimeoBoolean;\n quality?: '240p' | '360p' | '540p' | '720p' | '1080p' | '2k' | '4k';\n speed?: VimeoBoolean;\n '#t'?: string;\n texttrack?: string;\n title?: VimeoBoolean;\n transparent?: VimeoBoolean;\n}\n","/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\n>;\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2023-04/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n}\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n","import {type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2023-04/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport function Video(\n props: JSX.IntrinsicElements['video'] & VideoProps,\n): JSX.Element {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n}\n","import {useState, useEffect} from 'react';\n\nconst SCRIPTS_LOADED: Record<string, Promise<boolean>> = {};\n\nexport function loadScript(\n src: string,\n options?: {module?: boolean; in?: 'head' | 'body'},\n): Promise<boolean> {\n const isScriptLoaded = SCRIPTS_LOADED[src];\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n if (isScriptLoaded) {\n return isScriptLoaded;\n }\n\n const promise = new Promise<boolean>((resolve, reject) => {\n const script = document.createElement('script');\n if (options?.module) {\n script.type = 'module';\n } else {\n script.type = 'text/javascript';\n }\n script.src = src;\n script.onload = (): void => {\n resolve(true);\n };\n script.onerror = (): void => {\n reject(false);\n };\n if (options?.in === 'head') {\n document.head.appendChild(script);\n } else {\n document.body.appendChild(script);\n }\n });\n\n SCRIPTS_LOADED[src] = promise;\n\n return promise;\n}\n\ntype LoadScriptParams = Parameters<typeof loadScript>;\n\n/**\n * The `useLoadScript` hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.\n */\nexport function useLoadScript(\n url: LoadScriptParams[0],\n options?: LoadScriptParams[1],\n): ScriptState {\n const [status, setStatus] = useState<ScriptState>('loading');\n const stringifiedOptions = JSON.stringify(options);\n\n useEffect(() => {\n async function loadScriptWrapper(): Promise<void> {\n try {\n setStatus('loading');\n await loadScript(url, options);\n setStatus('done');\n } catch (error) {\n setStatus('error');\n }\n }\n\n loadScriptWrapper().catch(() => {\n setStatus('error');\n });\n }, [url, stringifiedOptions, options]);\n\n return status;\n}\n\ntype ScriptState = 'loading' | 'done' | 'error';\n","import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2023-04/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n if (!modelViewer) {\n return;\n }\n if (passthroughProps.onError)\n modelViewer.addEventListener('error', passthroughProps.onError);\n if (passthroughProps.onLoad)\n modelViewer.addEventListener('load', passthroughProps.onLoad);\n if (passthroughProps.onPreload)\n modelViewer.addEventListener('preload', passthroughProps.onPreload);\n if (passthroughProps.onModelVisibility)\n modelViewer.addEventListener(\n 'model-visibility',\n passthroughProps.onModelVisibility,\n );\n if (passthroughProps.onProgress)\n modelViewer.addEventListener('progress', passthroughProps.onProgress);\n if (passthroughProps.onArStatus)\n modelViewer.addEventListener('ar-status', passthroughProps.onArStatus);\n if (passthroughProps.onArTracking)\n modelViewer.addEventListener(\n 'ar-tracking',\n passthroughProps.onArTracking,\n );\n if (passthroughProps.onQuickLookButtonTapped)\n modelViewer.addEventListener(\n 'quick-look-button-tapped',\n passthroughProps.onQuickLookButtonTapped,\n );\n if (passthroughProps.onCameraChange)\n modelViewer.addEventListener(\n 'camera-change',\n passthroughProps.onCameraChange,\n );\n if (passthroughProps.onEnvironmentChange)\n modelViewer.addEventListener(\n 'environment-change',\n passthroughProps.onEnvironmentChange,\n );\n if (passthroughProps.onPlay)\n modelViewer.addEventListener('play', passthroughProps.onPlay);\n if (passthroughProps.onPause)\n modelViewer.addEventListener('ar-status', passthroughProps.onPause);\n if (passthroughProps.onSceneGraphReady)\n modelViewer.addEventListener(\n 'scene-graph-ready',\n passthroughProps.onSceneGraphReady,\n );\n\n return () => {\n if (modelViewer == null) {\n return;\n }\n if (passthroughProps.onError)\n modelViewer.removeEventListener('error', passthroughProps.onError);\n if (passthroughProps.onLoad)\n modelViewer.removeEventListener('load', passthroughProps.onLoad);\n if (passthroughProps.onPreload)\n modelViewer.removeEventListener('preload', passthroughProps.onPreload);\n if (passthroughProps.onModelVisibility)\n modelViewer.removeEventListener(\n 'model-visibility',\n passthroughProps.onModelVisibility,\n );\n if (passthroughProps.onProgress)\n modelViewer.removeEventListener(\n 'progress',\n passthroughProps.onProgress,\n );\n if (passthroughProps.onArStatus)\n modelViewer.removeEventListener(\n 'ar-status',\n passthroughProps.onArStatus,\n );\n if (passthroughProps.onArTracking)\n modelViewer.removeEventListener(\n 'ar-tracking',\n passthroughProps.onArTracking,\n );\n if (passthroughProps.onQuickLookButtonTapped)\n modelViewer.removeEventListener(\n 'quick-look-button-tapped',\n passthroughProps.onQuickLookButtonTapped,\n );\n if (passthroughProps.onCameraChange)\n modelViewer.removeEventListener(\n 'camera-change',\n passthroughProps.onCameraChange,\n );\n if (passthroughProps.onEnvironmentChange)\n modelViewer.removeEventListener(\n 'environment-change',\n passthroughProps.onEnvironmentChange,\n );\n if (passthroughProps.onPlay)\n modelViewer.removeEventListener('play', passthroughProps.onPlay);\n if (passthroughProps.onPause)\n modelViewer.removeEventListener('ar-status', passthroughProps.onPause);\n if (passthroughProps.onSceneGraphReady)\n modelViewer.removeEventListener(\n 'scene-graph-ready',\n passthroughProps.onSceneGraphReady,\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n // @ts-expect-error ref should exist\n ref={callbackRef}\n {...passthroughProps}\n className={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // @ts-expect-error arPlacement should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-attributes-arPlacement\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n interaction-policy={passthroughProps.interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n bounds={passthroughProps.bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n","import {Image, type HydrogenImageProps} from './Image.js';\nimport {Video} from './Video.js';\nimport {ExternalVideo} from './ExternalVideo.js';\nimport {ModelViewer} from './ModelViewer.js';\nimport type {MediaEdge as MediaEdgeType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ntype BaseProps = React.HTMLAttributes<\n HTMLImageElement | HTMLVideoElement | HTMLIFrameElement | ModelViewerElement\n>;\nexport interface MediaFileProps extends BaseProps {\n /** An object with fields that correspond to the Storefront API's [Media object](https://shopify.dev/api/storefront/reference/products/media). */\n data: PartialDeep<MediaEdgeType['node'], {recurseIntoArrays: true}>;\n /** The options for the `Image`, `Video`, `ExternalVideo`, or `ModelViewer` components. */\n mediaOptions?: MediaOptions;\n}\n\ntype MediaOptions = {\n /** Props that will only apply when an `<Image />` is rendered */\n image?: Omit<HydrogenImageProps, 'data'>;\n /** Props that will only apply when a `<Video />` is rendered */\n video?: Omit<React.ComponentProps<typeof Video>, 'data'>;\n /** Props that will only apply when an `<ExternalVideo />` is rendered */\n externalVideo?: Omit<\n React.ComponentProps<typeof ExternalVideo>['options'],\n 'data'\n >;\n /** Props that will only apply when a `<ModelViewer />` is rendered */\n modelViewer?: Omit<typeof ModelViewer, 'data'>;\n};\n\n/**\n * The `MediaFile` component renders the media for the Storefront API's\n * [Media object](https://shopify.dev/api/storefront/reference/products/media). It renders an `Image`, a\n * `Video`, an `ExternalVideo`, or a `ModelViewer` depending on the `__typename` of the `data` prop.\n */\nexport function MediaFile({\n data,\n mediaOptions,\n ...passthroughProps\n}: MediaFileProps): JSX.Element | null {\n switch (data.__typename) {\n case 'MediaImage': {\n if (!data.image) {\n const noDataImage = `<MediaFile/>: 'data.image' does not exist for __typename of 'MediaImage'; rendering 'null' by default.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noDataImage);\n } else {\n console.warn(noDataImage);\n return null;\n }\n }\n\n return (\n <Image\n {...passthroughProps}\n {...mediaOptions?.image}\n data={data.image}\n />\n );\n }\n case 'Video': {\n return (\n <Video {...passthroughProps} {...mediaOptions?.video} data={data} />\n );\n }\n case 'ExternalVideo': {\n return (\n <ExternalVideo\n {...passthroughProps}\n {...mediaOptions?.externalVideo}\n data={data}\n />\n );\n }\n case 'Model3d': {\n return (\n // @ts-expect-error There are issues with the inferred HTML attribute types here for ModelViewer (and contentEditable), but I think that's a little bit beyond me at the moment\n <ModelViewer\n {...passthroughProps}\n {...mediaOptions?.modelViewer}\n data={data}\n />\n );\n }\n default: {\n const typenameMissingMessage = `<MediaFile /> requires the '__typename' property to exist on the 'data' prop in order to render the matching sub-component for this type of media.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typenameMissingMessage);\n } else {\n console.error(`${typenameMissingMessage} Rendering 'null' by default`);\n return null;\n }\n }\n }\n}\n","import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n","import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice<ComponentGeneric extends React.ElementType>(\n props: ProductPriceProps &\n Omit<MoneyProps<ComponentGeneric>, 'data' | 'measurement'>,\n): JSX.Element | null {\n const {\n priceType = 'regular',\n variantId,\n valueType = 'min',\n data: product,\n ...passthroughProps\n } = props;\n\n if (product == null) {\n throw new Error(`<ProductPrice/> requires a product as the 'data' prop`);\n }\n\n let price: Partial<MoneyV2> | undefined | null;\n let measurement: Partial<UnitPriceMeasurement> | undefined | null;\n\n const variant = variantId\n ? flattenConnection(product?.variants ?? {}).find(\n (variant) => variant?.id === variantId,\n ) ?? null\n : null;\n\n if (priceType === 'compareAt') {\n if (variantId && variant) {\n if (variant.compareAtPriceV2?.amount === variant.priceV2?.amount) {\n return null;\n }\n price = variant.compareAtPriceV2;\n } else if (valueType === 'max') {\n price = product?.compareAtPriceRange?.maxVariantPrice;\n } else {\n price = product?.compareAtPriceRange?.minVariantPrice;\n }\n } else {\n if (variantId && variant) {\n price = variant.priceV2;\n if (valueType === 'unit') {\n price = variant.unitPrice;\n measurement = variant.unitPriceMeasurement;\n }\n } else if (valueType === 'max') {\n price = product.priceRange?.maxVariantPrice;\n } else {\n price = product.priceRange?.minVariantPrice;\n }\n }\n\n if (!price) {\n return null;\n }\n\n if (measurement) {\n return (\n <Money {...passthroughProps} data={price} measurement={measurement} />\n );\n }\n\n return <Money {...passthroughProps} data={price} />;\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface ProductPricePropsForDocs<\n AsType extends React.ElementType = 'div',\n> extends Omit<MoneyPropsBase<AsType>, 'data' | 'measurement'>,\n ProductPriceProps {}\n","import {defaultShopifyContext, useShop} from './ShopifyProvider.js';\nimport {useLoadScript} from './load-script.js';\nimport {parseGid} from './analytics-utils.js';\n\n// By using 'never' in the \"or\" cases below, it makes these props \"exclusive\" and means that you cannot pass both of them; you must pass either one OR the other.\ntype ShopPayButtonProps = ShopPayButtonStyleProps &\n ShopPayDomainProps &\n (ShopPayVariantIds | ShopPayVariantAndQuantities);\n\ntype ShopPayButtonStyleProps = {\n /** A string of classes to apply to the `div` that wraps the Shop Pay button. */\n className?: string;\n /** A string that's applied to the [CSS custom property (variable)](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) `--shop-pay-button-width` for the [Buy with Shop Pay component](https://shopify.dev/custom-storefronts/tools/web-components#buy-with-shop-pay-component). */\n width?: string;\n};\n\ntype ShopPayDomainProps = {\n /** The domain of your Shopify storefront URL (eg: `your-store.myshopify.com`). */\n storeDomain?: string;\n};\n\ntype ShopPayVariantIds = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds: string[];\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities?: never;\n};\n\ntype ShopPayVariantAndQuantities = {\n /** An array of IDs of the variants to purchase with Shop Pay. This will only ever have a quantity of 1 for each variant. If you want to use other quantities, then use `variantIdsAndQuantities`. */\n variantIds?: never;\n /** An array of variant IDs and quantities to purchase with Shop Pay. */\n variantIdsAndQuantities: Array<{\n id: string;\n quantity: number;\n }>;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'shop-pay-button': {\n variants: string;\n 'store-url': string;\n };\n }\n }\n}\n\nconst SHOPJS_URL =\n 'https://cdn.shopify.com/shopifycloud/shop-js/v1.0/client.js';\n\n/**\n * The `ShopPayButton` component renders a button that redirects to the Shop Pay checkout.\n * It renders a [`<shop-pay-button>`](https://shopify.dev/custom-storefronts/tools/web-components) custom element, for which it will lazy-load the source code automatically.\n * It relies on the `<ShopProvider>` context provider.\n */\nexport function ShopPayButton({\n variantIds,\n className,\n variantIdsAndQuantities,\n width,\n storeDomain: _storeDomain,\n}: ShopPayButtonProps): JSX.Element {\n const shop = useShop();\n const storeDomain = _storeDomain || shop?.storeDomain;\n const shopPayLoadedStatus = useLoadScript(SHOPJS_URL);\n\n let ids: string[] = [];\n\n if (!storeDomain || storeDomain === defaultShopifyContext.storeDomain) {\n throw new Error(MissingStoreDomainErrorMessage);\n }\n\n if (variantIds && variantIdsAndQuantities) {\n throw new Error(DoublePropsErrorMessage);\n }\n\n if (!variantIds && !variantIdsAndQuantities) {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (variantIds) {\n ids = variantIds.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr).id;\n if (bareId) {\n prev.push(bareId);\n }\n return prev;\n }, []);\n } else if (variantIdsAndQuantities) {\n ids = variantIdsAndQuantities.reduce<string[]>((prev, curr) => {\n const bareId = parseGid(curr?.id).id;\n if (bareId) {\n prev.push(`${bareId}:${curr?.quantity ?? 1}`);\n }\n return prev;\n }, []);\n } else {\n throw new Error(MissingPropsErrorMessage);\n }\n\n if (ids.length === 0) {\n throw new Error(InvalidPropsErrorMessage);\n }\n\n const style = width\n ? ({\n '--shop-pay-button-width': width,\n } as React.CSSProperties)\n : undefined;\n\n return (\n <div className={className} style={style}>\n {shopPayLoadedStatus === 'done' && (\n <shop-pay-button store-url={storeDomain} variants={ids.join(',')} />\n )}\n </div>\n );\n}\n\nexport const MissingStoreDomainErrorMessage =\n 'You must pass a \"storeDomain\" prop to the \"ShopPayButton\" component, or wrap it in a \"ShopifyProvider\" component.';\nexport const InvalidPropsErrorMessage = `You must pass in \"variantIds\" in the form of [\"gid://shopify/ProductVariant/1\"]`;\nexport const MissingPropsErrorMessage = `You must pass in either \"variantIds\" or \"variantIdsAndQuantities\" to ShopPayButton`;\nexport const DoublePropsErrorMessage = `You must provide either a variantIds or variantIdsAndQuantities prop, but not both in the ShopPayButton component`;\n","import {useEffect} from 'react';\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID, getShopifyCookies} from './cookies-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = {\n /**\n * If set to `false`, Shopify cookies will be removed.\n * If set to `true`, Shopify unique user token cookie will have cookie expiry of 1 year.\n * Defaults to false.\n **/\n hasUserConsent?: boolean;\n /**\n * The domain scope of the cookie. Defaults to empty string.\n **/\n domain?: string;\n};\n\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): void {\n const {hasUserConsent = false, domain = ''} = options || {};\n useEffect(() => {\n const cookies = getShopifyCookies(document.cookie);\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n setCookie(\n SHOPIFY_Y,\n cookies[SHOPIFY_Y] || buildUUID(),\n longTermLength,\n domain,\n );\n setCookie(\n SHOPIFY_S,\n cookies[SHOPIFY_S] || buildUUID(),\n shortTermLength,\n domain,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domain);\n setCookie(SHOPIFY_S, '', 0, domain);\n }\n });\n}\n\nfunction setCookie(\n name: string,\n value: string,\n maxage: number,\n domain: string,\n): void {\n document.cookie = stringify(name, value, {\n maxage,\n domain,\n samesite: 'Lax',\n path: '/',\n });\n}\n"],"names":["t","n","e","r","i","o","a","u","s","l","v","g","c","useLayoutEffect","React","require$$0","error","shim","module","require$$1","isEqual","this","useRef","useState","queue","service","interpret","createMachine","InterpreterStatus","useIsomorphicLayoutEffect","useEffect","useCallback","useSyncExternalStoreWithSelector","createContext","useMemo","useContext","f","parse","assign","_b","_a","_d","_c","useTransition","value","selectedOptions","SCHEMA_ID","pageView","formatPayload","trekkiePageView","customerPageView","customerAddToCart","variant","stringify"],"mappings":";;;;;;;;;;;;;;;;;;;;;EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,WAAS,EAAEA,IAAEC,IAAE;AAAC,QAAIC,KAAE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