UNPKG

@shopify/hydrogen-react

Version:

React components, hooks, and utilities for creating custom Shopify storefronts

1,387 lines (1,375 loc) • 117 kB
(function(global, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("react")) : typeof define === "function" && define.amd ? define(["exports", "react"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.hydrogenreact = {}, global.React)); })(this, function(exports2, React) { "use strict"; const _interopDefaultLegacy = (e2) => e2 && typeof e2 === "object" && "default" in e2 ? e2 : { default: e2 }; function _interopNamespace(e2) { if (e2 && e2.__esModule) return e2; const n2 = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } }); if (e2) { for (const k in e2) { if (k !== "default") { const d = Object.getOwnPropertyDescriptor(e2, k); Object.defineProperty(n2, k, d.get ? d : { enumerable: true, get: () => e2[k] }); } } } n2.default = e2; return Object.freeze(n2); } const React__default = /* @__PURE__ */ _interopDefaultLegacy(React); const React__namespace = /* @__PURE__ */ _interopNamespace(React); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function t(t2, n2) { var e2 = "function" == typeof Symbol && t2[Symbol.iterator]; if (!e2) return t2; var r2, i2, o2 = e2.call(t2), a2 = []; try { for (; (void 0 === n2 || n2-- > 0) && !(r2 = o2.next()).done; ) a2.push(r2.value); } catch (t3) { i2 = { error: t3 }; } finally { try { r2 && !r2.done && (e2 = o2.return) && e2.call(o2); } finally { if (i2) throw i2.error; } } return a2; } var n; !function(t2) { t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped"; }(n || (n = {})); var e = { type: "xstate.init" }; function r(t2) { return void 0 === t2 ? [] : [].concat(t2); } function i(t2) { return { type: "xstate.assign", assignment: t2 }; } function o(t2, n2) { return "string" == typeof (t2 = "string" == typeof t2 && n2 && n2[t2] ? n2[t2] : t2) ? { type: t2 } : "function" == typeof t2 ? { type: t2.name, exec: t2 } : t2; } function a(t2) { return function(n2) { return t2 === n2; }; } function u$1(t2) { return "string" == typeof t2 ? { type: t2 } : t2; } function c(t2, n2) { return { value: t2, context: n2, actions: [], changed: false, matches: a(t2) }; } function f(t2, n2, e2) { var r2 = n2, i2 = false; return [t2.filter(function(t3) { if ("xstate.assign" === t3.type) { i2 = true; var n3 = Object.assign({}, r2); return "function" == typeof t3.assignment ? n3 = t3.assignment(r2, e2) : Object.keys(t3.assignment).forEach(function(i3) { n3[i3] = "function" == typeof t3.assignment[i3] ? t3.assignment[i3](r2, e2) : t3.assignment[i3]; }), r2 = n3, false; } return true; }), r2, i2]; } function s(n2, i2) { void 0 === i2 && (i2 = {}); var s2 = t(f(r(n2.states[n2.initial].entry).map(function(t2) { return o(t2, i2.actions); }), n2.context, e), 2), l2 = s2[0], v2 = s2[1], y = { config: n2, _options: i2, initialState: { value: n2.initial, actions: l2, context: v2, matches: a(n2.initial) }, transition: function(e2, i3) { var s3, l3, v3 = "string" == typeof e2 ? { value: e2, context: n2.context } : e2, p = v3.value, g2 = v3.context, d = u$1(i3), x = n2.states[p]; if (x.on) { var m = r(x.on[d.type]); try { for (var h = function(t2) { var n3 = "function" == typeof Symbol && Symbol.iterator, e3 = n3 && t2[n3], r2 = 0; if (e3) return e3.call(t2); if (t2 && "number" == typeof t2.length) return { next: function() { return t2 && r2 >= t2.length && (t2 = void 0), { value: t2 && t2[r2++], done: !t2 }; } }; throw new TypeError(n3 ? "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, g2); 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 true; } : N, _ = void 0 === j, k = null != j ? j : p, T = n2.states[k]; if (O(g2, d)) { var q = t(f((_ ? r(R) : [].concat(x.exit, R, T.entry).filter(function(t2) { return t2; })).map(function(t2) { return o(t2, y._options.actions); }), g2, 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 (t2) { s3 = { error: t2 }; } finally { try { b && !b.done && (l3 = h.return) && l3.call(h); } finally { if (s3) throw s3.error; } } } return c(p, g2); } }; return y; } var l = function(t2, n2) { return t2.actions.forEach(function(e2) { var r2 = e2.exec; return r2 && r2(t2.context, n2); }); }; function v(t2) { var r2 = t2.initialState, i2 = n.NotStarted, o2 = /* @__PURE__ */ new Set(), c2 = { _machine: t2, send: function(e2) { i2 === n.Running && (r2 = t2.transition(r2, e2), l(r2, u$1(e2)), o2.forEach(function(t3) { return t3(r2); })); }, subscribe: function(t3) { return o2.add(t3), t3(r2), { unsubscribe: function() { return o2.delete(t3); } }; }, start: function(o3) { if (o3) { var u2 = "object" == typeof o3 ? o3 : { context: t2.config.context, value: o3 }; r2 = { value: u2.value, actions: [], context: u2.context, matches: a(u2.value) }; } else r2 = t2.initialState; return i2 = n.Running, l(r2, e), c2; }, stop: function() { return i2 = n.Stopped, o2.clear(), c2; }, get state() { return r2; }, get status() { return i2; } }; return c2; } var index = React.useLayoutEffect; var withSelector = { exports: {} }; var withSelector_production_min = {}; var shim = { exports: {} }; var useSyncExternalStoreShim_production_min = {}; /** * @license React * use-sync-external-store-shim.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredUseSyncExternalStoreShim_production_min; function requireUseSyncExternalStoreShim_production_min() { if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min; hasRequiredUseSyncExternalStoreShim_production_min = 1; var e2 = React__default.default; function h(a2, b) { return a2 === b && (0 !== a2 || 1 / a2 === 1 / b) || a2 !== a2 && b !== b; } var k = "function" === typeof Object.is ? Object.is : h, l2 = e2.useState, m = e2.useEffect, n2 = e2.useLayoutEffect, p = e2.useDebugValue; function q(a2, b) { var d = b(), f2 = l2({ inst: { value: d, getSnapshot: b } }), c2 = f2[0].inst, g2 = f2[1]; n2(function() { c2.value = d; c2.getSnapshot = b; r2(c2) && g2({ inst: c2 }); }, [a2, d, b]); m(function() { r2(c2) && g2({ inst: c2 }); return a2(function() { r2(c2) && g2({ inst: c2 }); }); }, [a2]); p(d); return d; } function r2(a2) { var b = a2.getSnapshot; a2 = a2.value; try { var d = b(); return !k(a2, d); } catch (f2) { return true; } } function t2(a2, b) { return b(); } var u2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? t2 : q; useSyncExternalStoreShim_production_min.useSyncExternalStore = void 0 !== e2.useSyncExternalStore ? e2.useSyncExternalStore : u2; return useSyncExternalStoreShim_production_min; } var useSyncExternalStoreShim_development = {}; /** * @license React * use-sync-external-store-shim.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredUseSyncExternalStoreShim_development; function requireUseSyncExternalStoreShim_development() { if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development; hasRequiredUseSyncExternalStoreShim_development = 1; if (process.env.NODE_ENV !== "production") { (function() { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var React2 = React__default.default; var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } function is(x, y) { return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; } var objectIs = typeof Object.is === "function" ? Object.is : is; var useState = React2.useState, useEffect = React2.useEffect, useLayoutEffect = React2.useLayoutEffect, useDebugValue = React2.useDebugValue; var didWarnOld18Alpha = false; var didWarnUncachedGetSnapshot = false; function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { { if (!didWarnOld18Alpha) { if (React2.startTransition !== void 0) { didWarnOld18Alpha = true; 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."); } } } var value = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedValue = getSnapshot(); if (!objectIs(value, cachedValue)) { error("The result of getSnapshot should be cached to avoid an infinite loop"); didWarnUncachedGetSnapshot = true; } } } var _useState = useState({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1]; useLayoutEffect(function() { inst.value = value; inst.getSnapshot = getSnapshot; if (checkIfSnapshotChanged(inst)) { forceUpdate({ inst }); } }, [subscribe, value, getSnapshot]); useEffect(function() { if (checkIfSnapshotChanged(inst)) { forceUpdate({ inst }); } var handleStoreChange = function() { if (checkIfSnapshotChanged(inst)) { forceUpdate({ inst }); } }; return subscribe(handleStoreChange); }, [subscribe]); useDebugValue(value); return value; } function checkIfSnapshotChanged(inst) { var latestGetSnapshot = inst.getSnapshot; var prevValue = inst.value; try { var nextValue = latestGetSnapshot(); return !objectIs(prevValue, nextValue); } catch (error2) { return true; } } function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) { return getSnapshot(); } var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); var isServerEnvironment = !canUseDOM; var shim2 = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore; var useSyncExternalStore$2 = React2.useSyncExternalStore !== void 0 ? React2.useSyncExternalStore : shim2; useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } return useSyncExternalStoreShim_development; } var hasRequiredShim; function requireShim() { if (hasRequiredShim) return shim.exports; hasRequiredShim = 1; (function(module2) { if (process.env.NODE_ENV === "production") { module2.exports = requireUseSyncExternalStoreShim_production_min(); } else { module2.exports = requireUseSyncExternalStoreShim_development(); } })(shim); return shim.exports; } /** * @license React * use-sync-external-store-shim/with-selector.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredWithSelector_production_min; function requireWithSelector_production_min() { if (hasRequiredWithSelector_production_min) return withSelector_production_min; hasRequiredWithSelector_production_min = 1; var h = React__default.default, n2 = requireShim(); function p(a2, b) { return a2 === b && (0 !== a2 || 1 / a2 === 1 / b) || a2 !== a2 && b !== b; } var q = "function" === typeof Object.is ? Object.is : p, r2 = n2.useSyncExternalStore, t2 = h.useRef, u2 = h.useEffect, v2 = h.useMemo, w = h.useDebugValue; withSelector_production_min.useSyncExternalStoreWithSelector = function(a2, b, e2, l2, g2) { var c2 = t2(null); if (null === c2.current) { var f2 = { hasValue: false, value: null }; c2.current = f2; } else f2 = c2.current; c2 = v2(function() { function a3(a4) { if (!c3) { c3 = true; d2 = a4; a4 = l2(a4); if (void 0 !== g2 && f2.hasValue) { var b2 = f2.value; if (g2(b2, a4)) return k = b2; } return k = a4; } b2 = k; if (q(d2, a4)) return b2; var e3 = l2(a4); if (void 0 !== g2 && g2(b2, e3)) return b2; d2 = a4; return k = e3; } var c3 = false, d2, k, m = void 0 === e2 ? null : e2; return [function() { return a3(b()); }, null === m ? void 0 : function() { return a3(m()); }]; }, [b, e2, l2, g2]); var d = r2(a2, c2[0], c2[1]); u2(function() { f2.hasValue = true; f2.value = d; }, [d]); w(d); return d; }; return withSelector_production_min; } var withSelector_development = {}; /** * @license React * use-sync-external-store-shim/with-selector.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredWithSelector_development; function requireWithSelector_development() { if (hasRequiredWithSelector_development) return withSelector_development; hasRequiredWithSelector_development = 1; if (process.env.NODE_ENV !== "production") { (function() { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var React2 = React__default.default; var shim2 = requireShim(); function is(x, y) { return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; } var objectIs = typeof Object.is === "function" ? Object.is : is; var useSyncExternalStore = shim2.useSyncExternalStore; var useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue; function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual2) { var instRef = useRef(null); var inst; if (instRef.current === null) { inst = { hasValue: false, value: null }; instRef.current = inst; } else { inst = instRef.current; } var _useMemo = useMemo(function() { var hasMemo = false; var memoizedSnapshot; var memoizedSelection; var memoizedSelector = function(nextSnapshot) { if (!hasMemo) { hasMemo = true; memoizedSnapshot = nextSnapshot; var _nextSelection = selector(nextSnapshot); if (isEqual2 !== void 0) { if (inst.hasValue) { var currentSelection = inst.value; if (isEqual2(currentSelection, _nextSelection)) { memoizedSelection = currentSelection; return currentSelection; } } } memoizedSelection = _nextSelection; return _nextSelection; } var prevSnapshot = memoizedSnapshot; var prevSelection = memoizedSelection; if (objectIs(prevSnapshot, nextSnapshot)) { return prevSelection; } var nextSelection = selector(nextSnapshot); if (isEqual2 !== void 0 && isEqual2(prevSelection, nextSelection)) { return prevSelection; } memoizedSnapshot = nextSnapshot; memoizedSelection = nextSelection; return nextSelection; }; var maybeGetServerSnapshot = getServerSnapshot === void 0 ? null : getServerSnapshot; var getSnapshotWithSelector = function() { return memoizedSelector(getSnapshot()); }; var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? void 0 : function() { return memoizedSelector(maybeGetServerSnapshot()); }; return [getSnapshotWithSelector, getServerSnapshotWithSelector]; }, [getSnapshot, getServerSnapshot, selector, isEqual2]), getSelection = _useMemo[0], getServerSelection = _useMemo[1]; var value = useSyncExternalStore(subscribe, getSelection, getServerSelection); useEffect(function() { inst.hasValue = true; inst.value = value; }, [value]); useDebugValue(value); return value; } withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } return withSelector_development; } (function(module2) { if (process.env.NODE_ENV === "production") { module2.exports = requireWithSelector_production_min(); } else { module2.exports = requireWithSelector_development(); } })(withSelector); function useConstant(fn) { var ref = React__namespace.useRef(); if (!ref.current) { ref.current = { v: fn() }; } return ref.current.v; } var __read = globalThis && globalThis.__read || function(o2, n2) { var m = typeof Symbol === "function" && o2[Symbol.iterator]; if (!m) return o2; var i2 = m.call(o2), r2, ar = [], e2; try { while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done) ar.push(r2.value); } catch (error) { e2 = { error }; } finally { try { if (r2 && !r2.done && (m = i2["return"])) m.call(i2); } finally { if (e2) throw e2.error; } } return ar; }; function identity(a2) { return a2; } var getServiceState = function(service) { var currentValue; service.subscribe(function(state) { currentValue = state; }).unsubscribe(); return currentValue; }; function useMachine(stateMachine, options) { var persistedStateRef = React.useRef(); if (process.env.NODE_ENV !== "production") { var _a = __read(React.useState(stateMachine), 1), initialMachine = _a[0]; if (stateMachine !== initialMachine) { console.warn("Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\nPlease make sure that you pass the same Machine as argument each time."); } } var _b = __read(useConstant(function() { var queue2 = []; var service2 = v(s(stateMachine.config, options ? options : stateMachine._options)); var send = service2.send; service2.send = function(event) { if (service2.status === n.NotStarted) { queue2.push(event); return; } send(event); persistedStateRef.current = service2.state; }; return [service2, queue2]; }), 2), service = _b[0], queue = _b[1]; index(function() { if (options) { service._machine._options = options; } }); var useServiceResult = useService(service); React.useEffect(function() { service.start(persistedStateRef.current); queue.forEach(service.send); persistedStateRef.current = service.state; return function() { service.stop(); }; }, []); return useServiceResult; } var isEqual = function(_prevState, nextState) { return nextState.changed === false; }; function useService(service) { var getSnapshot = React.useCallback(function() { return getServiceState(service); }, [service]); var subscribe = React.useCallback(function(handleStoreChange) { var unsubscribe = service.subscribe(handleStoreChange).unsubscribe; return unsubscribe; }, [service]); var storeSnapshot = withSelector.exports.useSyncExternalStoreWithSelector(subscribe, getSnapshot, getSnapshot, identity, isEqual); return [storeSnapshot, service.send, service]; } function flattenConnection(connection) { if (!connection) { const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${connection}' instead`; { throw new Error(noConnectionErr); } } if (connection.nodes) { return connection.nodes; } if (connection.edges) { return connection.edges.map((edge) => { if (!(edge == null ? void 0 : edge.node)) { throw new Error("Connection edges must contain nodes"); } return edge.node; }); } { console.warn( `The connection did not contain either "nodes" or "edges.node". A empty array will be returned in its place.` ); } return []; } const CartLineAdd = (cartFragment) => ` mutation CartLineAdd($cartId: ID!, $lines: [CartLineInput!]!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartLinesAdd(cartId: $cartId, lines: $lines) { cart { ...CartFragment } } } ${cartFragment} `; const CartCreate = (cartFragment) => ` mutation CartCreate($input: CartInput!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartCreate(input: $input) { cart { ...CartFragment } } } ${cartFragment} `; const CartLineRemove = (cartFragment) => ` mutation CartLineRemove($cartId: ID!, $lines: [ID!]!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartLinesRemove(cartId: $cartId, lineIds: $lines) { cart { ...CartFragment } } } ${cartFragment} `; const CartLineUpdate = (cartFragment) => ` mutation CartLineUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { ...CartFragment } } } ${cartFragment} `; const CartNoteUpdate = (cartFragment) => ` mutation CartNoteUpdate($cartId: ID!, $note: String, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartNoteUpdate(cartId: $cartId, note: $note) { cart { ...CartFragment } } } ${cartFragment} `; const CartBuyerIdentityUpdate = (cartFragment) => ` mutation CartBuyerIdentityUpdate( $cartId: ID! $buyerIdentity: CartBuyerIdentityInput! $numCartLines: Int = 250 $country: CountryCode = ZZ ) @inContext(country: $country) { cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) { cart { ...CartFragment } } } ${cartFragment} `; const CartAttributesUpdate = (cartFragment) => ` mutation CartAttributesUpdate($attributes: [AttributeInput!]!, $cartId: ID!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartAttributesUpdate(attributes: $attributes, cartId: $cartId) { cart { ...CartFragment } } } ${cartFragment} `; const CartDiscountCodesUpdate = (cartFragment) => ` mutation CartDiscountCodesUpdate($cartId: ID!, $discountCodes: [String!], $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) { cart { ...CartFragment } } } ${cartFragment} `; const CartQuery = (cartFragment) => ` query CartQuery($id: ID!, $numCartLines: Int = 250, $country: CountryCode = ZZ) @inContext(country: $country) { cart(id: $id) { ...CartFragment } } ${cartFragment} `; const SFAPI_VERSION = "2022-10"; var _jsxFileName$b = "/home/runner/work/hydrogen-ui/hydrogen-ui/packages/react/src/ShopifyProvider.tsx"; const ShopifyContext = React.createContext({ storeDomain: "test.myshopify.com", storefrontToken: "abc123", storefrontApiVersion: SFAPI_VERSION, country: { isoCode: "US" }, language: { isoCode: "EN" }, locale: "EN-US" }); function ShopifyProvider({ children, shopifyConfig }) { if (!shopifyConfig) { throw new Error(`The 'shopifyConfig' prop must be passed to '<ShopifyProvider/>'`); } if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) { console.warn(`This version of Hydrogen-UI 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-UI and the Storefront API.`); } const finalConfig = React.useMemo(() => ({ ...shopifyConfig, storeDomain: shopifyConfig.storeDomain.replace(/^https?:\/\//, "") }), [shopifyConfig]); return /* @__PURE__ */ React__default.default.createElement(ShopifyContext.Provider, { value: finalConfig, __self: this, __source: { fileName: _jsxFileName$b, lineNumber: 49, columnNumber: 5 } }, children); } function useShop() { const shopContext = React.useContext(ShopifyContext); if (!shopContext) { throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`); } return shopContext; } const CART_ID_STORAGE_KEY = "shopifyCartId"; const STOREFRONT_API_PUBLIC_TOKEN_HEADER = "X-Shopify-Storefront-Access-Token"; const SHOPIFY_STOREFRONT_ID_HEADER = "Shopify-Storefront-Id"; const SHOPIFY_STOREFRONT_Y_HEADER = "Shopify-Storefront-Y"; const SHOPIFY_STOREFRONT_S_HEADER = "Shopify-Storefront-S"; const SHOPIFY_Y = "_shopify_y"; const SHOPIFY_S = "_shopify_s"; var g = /* @__PURE__ */ new Set([ "domain", "path", "max-age", "expires", "samesite", "secure", "httponly" ]); function u(a2) { let r2 = {}, e2, t2, n2 = 0, m = a2.split(/;\s*/g), s2, i2; for (; n2 < m.length; n2++) if (t2 = m[n2], e2 = t2.indexOf("="), ~e2) { if (s2 = t2.substring(0, e2++).trim(), i2 = t2.substring(e2).trim(), i2[0] === '"' && (i2 = i2.substring(1, i2.length - 1)), ~i2.indexOf("%")) try { i2 = decodeURIComponent(i2); } catch (f2) { } g.has(t2 = s2.toLowerCase()) ? t2 === "expires" ? r2.expires = new Date(i2) : t2 === "max-age" ? r2.maxage = +i2 : r2[t2] = i2 : r2[s2] = i2; } else (s2 = t2.trim().toLowerCase()) && (s2 === "httponly" || s2 === "secure") && (r2[s2] = true); return r2; } function useCartFetch() { const { storeDomain, storefrontApiVersion, storefrontToken, storefrontId } = useShop(); return React.useCallback(({ query, variables }) => { const headers = { "Content-Type": "application/json", "X-SDK-Variant": "hydrogen", "X-SDK-Version": storefrontApiVersion, [STOREFRONT_API_PUBLIC_TOKEN_HEADER]: storefrontToken }; if (storefrontId) { headers[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId; } const cookieData = u(document.cookie); if (cookieData[SHOPIFY_Y] && cookieData[SHOPIFY_S]) { headers[SHOPIFY_STOREFRONT_Y_HEADER] = cookieData[SHOPIFY_Y]; headers[SHOPIFY_STOREFRONT_S_HEADER] = cookieData[SHOPIFY_S]; } return fetch(`https://${storeDomain}/api/${storefrontApiVersion}/graphql.json`, { method: "POST", headers, body: JSON.stringify({ query: query.toString(), variables }) }).then((res) => res.json()).catch((error) => { return { data: void 0, errors: error.toString() }; }); }, [storeDomain, storefrontApiVersion, storefrontToken, storefrontId]); } function useCartActions({ numCartLines, cartFragment, countryCode = "US" }) { const fetchCart = useCartFetch(); const cartFetch = React.useCallback((cartId) => { return fetchCart({ query: CartQuery(cartFragment), variables: { id: cartId, numCartLines, country: countryCode } }); }, [fetchCart, cartFragment, numCartLines, countryCode]); const cartCreate = React.useCallback((cart) => { return fetchCart({ query: CartCreate(cartFragment), variables: { input: cart, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const cartLineAdd = React.useCallback((cartId, lines) => { return fetchCart({ query: CartLineAdd(cartFragment), variables: { cartId, lines, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const cartLineUpdate = React.useCallback((cartId, lines) => { return fetchCart({ query: CartLineUpdate(cartFragment), variables: { cartId, lines, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const cartLineRemove = React.useCallback((cartId, lines) => { return fetchCart({ query: CartLineRemove(cartFragment), variables: { cartId, lines, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const noteUpdate = React.useCallback((cartId, note) => { return fetchCart({ query: CartNoteUpdate(cartFragment), variables: { cartId, note, numCartLines, country: countryCode } }); }, [fetchCart, cartFragment, numCartLines, countryCode]); const buyerIdentityUpdate = React.useCallback((cartId, buyerIdentity) => { return fetchCart({ query: CartBuyerIdentityUpdate(cartFragment), variables: { cartId, buyerIdentity, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const cartAttributesUpdate = React.useCallback((cartId, attributes) => { return fetchCart({ query: CartAttributesUpdate(cartFragment), variables: { cartId, attributes, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); const discountCodesUpdate = React.useCallback((cartId, discountCodes) => { return fetchCart({ query: CartDiscountCodesUpdate(cartFragment), variables: { cartId, discountCodes, numCartLines, country: countryCode } }); }, [cartFragment, countryCode, fetchCart, numCartLines]); return React.useMemo(() => ({ cartFetch, cartCreate, cartLineAdd, cartLineUpdate, cartLineRemove, noteUpdate, buyerIdentityUpdate, cartAttributesUpdate, discountCodesUpdate, cartFragment }), [cartFetch, cartCreate, cartLineAdd, cartLineUpdate, cartLineRemove, noteUpdate, buyerIdentityUpdate, cartAttributesUpdate, discountCodesUpdate, cartFragment]); } function invokeCart(action, options) { return { entry: [...(options == null ? void 0 : options.entryActions) || [], "onCartActionEntry", "onCartActionOptimisticUI", action], on: { RESOLVE: { target: (options == null ? void 0 : options.resolveTarget) || "idle", actions: [i({ prevCart: (context) => context == null ? void 0 : context.cart, cart: (_, event) => { var _a; return (_a = event == null ? void 0 : event.payload) == null ? void 0 : _a.cart; }, rawCartResult: (_, event) => { var _a; return (_a = event == null ? void 0 : event.payload) == null ? void 0 : _a.rawCartResult; }, errors: (_) => void 0 })] }, ERROR: { target: (options == null ? void 0 : options.errorTarget) || "error", actions: [i({ prevCart: (context) => context == null ? void 0 : context.cart, cart: (context) => context == null ? void 0 : context.lastValidCart, errors: (_, event) => { var _a; return (_a = event == null ? void 0 : event.payload) == null ? void 0 : _a.errors; } })] }, CART_COMPLETED: { target: "cartCompleted", actions: i({ prevCart: (_) => void 0, cart: (_) => void 0, lastValidCart: (_) => void 0, errors: (_) => void 0 }) } }, exit: ["onCartActionComplete", ...(options == null ? void 0 : options.exitActions) || []] }; } const INITIALIZING_CART_EVENTS = { CART_FETCH: { target: "cartFetching" }, CART_CREATE: { target: "cartCreating" }, CART_SET: { target: "idle", actions: [i({ rawCartResult: (_, event) => event.payload.cart, cart: (_, event) => cartFromGraphQL(event.payload.cart) })] } }; const UPDATING_CART_EVENTS = { CARTLINE_ADD: { target: "cartLineAdding" }, CARTLINE_UPDATE: { target: "cartLineUpdating" }, CARTLINE_REMOVE: { target: "cartLineRemoving" }, NOTE_UPDATE: { target: "noteUpdating" }, BUYER_IDENTITY_UPDATE: { target: "buyerIdentityUpdating" }, CART_ATTRIBUTES_UPDATE: { target: "cartAttributesUpdating" }, DISCOUNT_CODES_UPDATE: { target: "discountCodesUpdating" } }; function createCartMachine(initialCart) { return s({ id: "Cart", initial: initialCart ? "idle" : "uninitialized", context: { cart: initialCart && cartFromGraphQL(initialCart) }, states: { uninitialized: { on: INITIALIZING_CART_EVENTS }, cartCompleted: { on: INITIALIZING_CART_EVENTS }, initializationError: { on: INITIALIZING_CART_EVENTS }, idle: { on: { ...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS } }, error: { on: { ...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS } }, cartFetching: invokeCart("cartFetchAction", { errorTarget: "initializationError" }), cartCreating: invokeCart("cartCreateAction", { errorTarget: "initializationError" }), cartLineRemoving: invokeCart("cartLineRemoveAction"), cartLineUpdating: invokeCart("cartLineUpdateAction"), cartLineAdding: invokeCart("cartLineAddAction"), noteUpdating: invokeCart("noteUpdateAction"), buyerIdentityUpdating: invokeCart("buyerIdentityUpdateAction"), cartAttributesUpdating: invokeCart("cartAttributesUpdateAction"), discountCodesUpdating: invokeCart("discountCodesUpdateAction") } }); } function useCartAPIStateMachine({ numCartLines, onCartActionEntry, onCartActionOptimisticUI, onCartActionComplete, data: cart, cartFragment, countryCode }) { const { cartFetch, cartCreate, cartLineAdd, cartLineUpdate, cartLineRemove, noteUpdate, buyerIdentityUpdate, cartAttributesUpdate, discountCodesUpdate } = useCartActions({ numCartLines, cartFragment, countryCode }); const cartMachine = React.useMemo(() => createCartMachine(cart), [cart]); const [state, send, service] = useMachine(cartMachine, { actions: { cartFetchAction: async (_, event) => { var _a; if (event.type !== "CART_FETCH") return; const { data, errors } = await cartFetch((_a = event == null ? void 0 : event.payload) == null ? void 0 : _a.cartId); const resultEvent = eventFromFetchResult(event, data == null ? void 0 : data.cart, errors); send(resultEvent); }, cartCreateAction: async (_, event) => { var _a; if (event.type !== "CART_CREATE") return; const { data, errors } = await cartCreate(event == null ? void 0 : event.payload); const resultEvent = eventFromFetchResult(event, (_a = data == null ? void 0 : data.cartCreate) == null ? void 0 : _a.cart, errors); send(resultEvent); }, cartLineAddAction: async (context, event) => { var _a, _b; if (event.type !== "CARTLINE_ADD" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await cartLineAdd(context.cart.id, event.payload.lines); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _b.cart, errors); send(resultEvent); }, cartLineUpdateAction: async (context, event) => { var _a, _b; if (event.type !== "CARTLINE_UPDATE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await cartLineUpdate(context.cart.id, event.payload.lines); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _b.cart, errors); send(resultEvent); }, cartLineRemoveAction: async (context, event) => { var _a, _b; if (event.type !== "CARTLINE_REMOVE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await cartLineRemove(context.cart.id, event.payload.lines); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _b.cart, errors); send(resultEvent); }, noteUpdateAction: async (context, event) => { var _a, _b; if (event.type !== "NOTE_UPDATE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await noteUpdate(context.cart.id, event.payload.note); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartNoteUpdate) == null ? void 0 : _b.cart, errors); send(resultEvent); }, buyerIdentityUpdateAction: async (context, event) => { var _a, _b; if (event.type !== "BUYER_IDENTITY_UPDATE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await buyerIdentityUpdate(context.cart.id, event.payload.buyerIdentity); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartBuyerIdentityUpdate) == null ? void 0 : _b.cart, errors); send(resultEvent); }, cartAttributesUpdateAction: async (context, event) => { var _a, _b; if (event.type !== "CART_ATTRIBUTES_UPDATE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await cartAttributesUpdate(context.cart.id, event.payload.attributes); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartAttributesUpdate) == null ? void 0 : _b.cart, errors); send(resultEvent); }, discountCodesUpdateAction: async (context, event) => { var _a, _b; if (event.type !== "DISCOUNT_CODES_UPDATE" || !((_a = context == null ? void 0 : context.cart) == null ? void 0 : _a.id)) return; const { data, errors } = await discountCodesUpdate(context.cart.id, event.payload.discountCodes); const resultEvent = eventFromFetchResult(event, (_b = data == null ? void 0 : data.cartDiscountCodesUpdate) == null ? void 0 : _b.cart, errors); send(resultEvent); }, ...onCartActionEntry && { onCartActionEntry: (context, event) => { if (isCartActionEvent(event)) { onCartActionEntry(context, event); } } }, ...onCartActionOptimisticUI && { onCartActionOptimisticUI: i((context, event) => { return onCartActionOptimisticUI(context, event); }) }, ...onCartActionComplete && { onCartActionComplete: (context, event) => { if (isCartFetchResultEvent(event)) { onCartActionComplete(context, event); } } } } }); return React.useMemo(() => [state, send, service], [state, send, service]); } function cartFromGraphQL(cart) { var _a; return { ...cart, lines: flattenConnection(cart == null ? void 0 : cart.lines), note: (_a = cart.note) != null ? _a : void 0 }; } function eventFromFetchResult(cartActionEvent, cart, errors) { if (errors) { return { type: "ERROR", payload: { errors, cartActionEvent } }; } if (!cart) { return { type: "CART_COMPLETED", payload: { cartActionEvent } }; } return { type: "RESOLVE", payload: { cart: cartFromGraphQL(cart), rawCartResult: cart, cartActionEvent } }; } function isCartActionEvent(event) { return event.type === "CART_CREATE" || event.type === "CARTLINE_ADD" || event.type === "CARTLINE_UPDATE" || event.type === "CARTLINE_REMOVE" || event.type === "NOTE_UPDATE" || event.type === "BUYER_IDENTITY_UPDATE" || event.type === "CART_ATTRIBUTES_UPDATE" || event.type === "DISCOUNT_CODES_UPDATE"; } function isCartFetchResultEvent(event) { return event.type === "RESOLVE" || event.type === "ERROR" || event.type === "CART_COMPLETED"; } var _jsxFileName$a = "/home/runner/work/hydrogen-ui/hydrogen-ui/packages/react/src/CartProvider.tsx"; const CartContext = React.createContext(null); function useCart() { const context = React.useContext(CartContext); if (!context) { throw new Error("Expected a Cart Context, but no Cart Context was found"); } return context; } function CartProvider({ children, numCartLines, onCreate, onLineAdd, onLineRemove, onLineUpdate, onNoteUpdate, onBuyerIdentityUpdate, onAttributesUpdate, onDiscountCodesUpdate, onCreateComplete, onLineAddComplete, onLineRemoveComplete, onLineUpdateComplete, onNoteUpdateComplete, onBuyerIdentityUpdateComplete, onAttributesUpdateComplete, onDiscountCodesUpdateComplete, data: cart, cartFragment = defaultCartFragment, customerAccessToken, countryCode = "US" }) { var _a, _b, _c, _d, _e, _f, _g; if (countryCode) countryCode = countryCode.toUpperCase(); const [prevCountryCode, setPrevCountryCode] = React.useState(countryCode); const [prevCustomerAccessToken, setPrevCustomerAccessToken] = React.useState(customerAccessToken); const customerOverridesCountryCode = React.useRef(false); if (prevCountryCode !== countryCode || prevCustomerAccessToken !== customerAccessToken) { setPrevCountryCode(countryCode); setPrevCustomerAccessToken(customerAccessToken); customerOverridesCountryCode.current = false; } const [cartState, cartSend] = useCartAPIStateMachine({ numCartLines, data: cart, cartFragment, countryCode, onCartActionEntry(context, event) { try { switch (event.type) { case "CART_CREATE": return onCreate == null ? void 0 : onCreate(); case "CARTLINE_ADD": return onLineAdd == null ? void 0 : onLineAdd(); case "CARTLINE_REMOVE": return onLineRemove == null ? void 0 : onLineRemove(); case "CARTLINE_UPDATE": return onLineUpdate == null ? void 0 : onLineUpdate(); case "NOTE_UPDATE": return onNoteUpdate == null ? void 0 : onNoteUpdate(); case "BUYER_IDENTITY_UPDATE": return onBuyerIdentityUpdate == null ? void 0 : onBuyerIdentityUpdate(); case "CART_ATTRIBUTES_UPDATE": return onAttributesUpdate == null ? void 0 : onAttributesUpdate(); case "DISCOUNT_CODES_UPDATE": return onDiscountCodesUpdate == null ? void 0 : onDiscountCodesUpdate(); } } catch (error) { console.error("Cart entry action failed", error); }