@rebuy/rebuy-hydrogen 2.3.1 → 3.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +195 -17
  2. package/dist/assets/Close.d.ts +2 -0
  3. package/dist/assets/Close.d.ts.map +1 -0
  4. package/dist/components/AddToCartBtn/AddToCartBtn.d.ts +3 -0
  5. package/dist/components/AddToCartBtn/AddToCartBtn.d.ts.map +1 -0
  6. package/dist/components/AddToCartBtn/HydrogenAddToCartBtn.d.ts +3 -0
  7. package/dist/components/AddToCartBtn/HydrogenAddToCartBtn.d.ts.map +1 -0
  8. package/dist/components/AddToCartBtn/HydrogenReactAddToCartBtn.d.ts +3 -0
  9. package/dist/components/AddToCartBtn/HydrogenReactAddToCartBtn.d.ts.map +1 -0
  10. package/dist/components/AddToCartBtn/index.d.ts +2 -0
  11. package/dist/components/AddToCartBtn/index.d.ts.map +1 -0
  12. package/dist/components/AddToCartBtn/types.d.ts +27 -0
  13. package/dist/components/AddToCartBtn/types.d.ts.map +1 -0
  14. package/dist/components/ProductCard/ProductCard.d.ts +3 -0
  15. package/dist/components/ProductCard/ProductCard.d.ts.map +1 -0
  16. package/dist/components/ProductCard/defaultSettings.d.ts +3 -0
  17. package/dist/components/ProductCard/defaultSettings.d.ts.map +1 -0
  18. package/dist/components/ProductCard/index.d.ts +3 -0
  19. package/dist/components/ProductCard/index.d.ts.map +1 -0
  20. package/dist/components/ProductCard/types.d.ts +52 -0
  21. package/dist/components/ProductCard/types.d.ts.map +1 -0
  22. package/dist/components/ProductCarousel/ProductCarousel.d.ts +16 -0
  23. package/dist/components/ProductCarousel/ProductCarousel.d.ts.map +1 -0
  24. package/dist/components/ProductCarousel/index.d.ts +2 -0
  25. package/dist/components/ProductCarousel/index.d.ts.map +1 -0
  26. package/dist/components/ProductPrice/ProductPrice.d.ts +3 -0
  27. package/dist/components/ProductPrice/ProductPrice.d.ts.map +1 -0
  28. package/dist/components/ProductPrice/index.d.ts +2 -0
  29. package/dist/components/ProductPrice/index.d.ts.map +1 -0
  30. package/dist/components/ProductPrice/types.d.ts +23 -0
  31. package/dist/components/ProductPrice/types.d.ts.map +1 -0
  32. package/dist/components/QuantityInput/QuantityInput.d.ts +3 -0
  33. package/dist/components/QuantityInput/QuantityInput.d.ts.map +1 -0
  34. package/dist/components/QuantityInput/index.d.ts +3 -0
  35. package/dist/components/QuantityInput/index.d.ts.map +1 -0
  36. package/dist/components/QuantityInput/types.d.ts +7 -0
  37. package/dist/components/QuantityInput/types.d.ts.map +1 -0
  38. package/dist/components/Timer/Timer.d.ts +3 -0
  39. package/dist/components/Timer/Timer.d.ts.map +1 -0
  40. package/dist/components/Timer/index.d.ts +3 -0
  41. package/dist/components/Timer/index.d.ts.map +1 -0
  42. package/dist/components/Timer/types.d.ts +16 -0
  43. package/dist/components/Timer/types.d.ts.map +1 -0
  44. package/dist/components/Title/Title.d.ts +3 -0
  45. package/dist/components/Title/Title.d.ts.map +1 -0
  46. package/dist/components/Title/index.d.ts +2 -0
  47. package/dist/components/Title/index.d.ts.map +1 -0
  48. package/dist/components/Title/types.d.ts +8 -0
  49. package/dist/components/Title/types.d.ts.map +1 -0
  50. package/dist/components/VariantSelect/VariantSelect.d.ts +3 -0
  51. package/dist/components/VariantSelect/VariantSelect.d.ts.map +1 -0
  52. package/dist/components/VariantSelect/index.d.ts +2 -0
  53. package/dist/components/VariantSelect/index.d.ts.map +1 -0
  54. package/dist/components/VariantSelect/types.d.ts +8 -0
  55. package/dist/components/VariantSelect/types.d.ts.map +1 -0
  56. package/dist/constants/api.d.ts +2 -0
  57. package/dist/constants/api.d.ts.map +1 -0
  58. package/dist/context/RebuyConfigContext.d.ts +21 -0
  59. package/dist/context/RebuyConfigContext.d.ts.map +1 -0
  60. package/dist/context/RebuyContext.d.ts +6 -0
  61. package/dist/context/RebuyContext.d.ts.map +1 -0
  62. package/dist/hooks/titleLevel.d.ts +3 -0
  63. package/dist/hooks/titleLevel.d.ts.map +1 -0
  64. package/dist/hooks/useBreakpoint.d.ts +5 -0
  65. package/dist/hooks/useBreakpoint.d.ts.map +1 -0
  66. package/dist/hooks/usePopupTrigger.d.ts +3 -0
  67. package/dist/hooks/usePopupTrigger.d.ts.map +1 -0
  68. package/dist/hooks/useRebuyTheme.d.ts +21 -0
  69. package/dist/hooks/useRebuyTheme.d.ts.map +1 -0
  70. package/dist/index.css +853 -0
  71. package/dist/index.css.map +7 -0
  72. package/dist/index.d.ts +14 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +3211 -0
  75. package/dist/index.js.map +7 -0
  76. package/dist/index.mjs +3178 -0
  77. package/dist/index.mjs.map +7 -0
  78. package/dist/providers/RebuyHydrogenContextProvider.d.ts +3 -0
  79. package/dist/providers/RebuyHydrogenContextProvider.d.ts.map +1 -0
  80. package/dist/providers/RebuyHydrogenReactContextProvider.d.ts +8 -0
  81. package/dist/providers/RebuyHydrogenReactContextProvider.d.ts.map +1 -0
  82. package/dist/providers/types.d.ts +71 -0
  83. package/dist/providers/types.d.ts.map +1 -0
  84. package/dist/queries/cart.queries.d.ts +5 -0
  85. package/dist/queries/cart.queries.d.ts.map +1 -0
  86. package/dist/types/common.d.ts +9 -0
  87. package/dist/types/common.d.ts.map +1 -0
  88. package/dist/types/rebuyCustom.d.ts +275 -0
  89. package/dist/types/rebuyCustom.d.ts.map +1 -0
  90. package/dist/types/rebuySmartCart.d.ts +184 -0
  91. package/dist/types/rebuySmartCart.d.ts.map +1 -0
  92. package/dist/types/shopify.d.ts +85 -0
  93. package/dist/types/shopify.d.ts.map +1 -0
  94. package/dist/types/widgets.d.ts +23 -0
  95. package/dist/types/widgets.d.ts.map +1 -0
  96. package/dist/utils/convertToRebuyProduct.d.ts +156 -0
  97. package/dist/utils/convertToRebuyProduct.d.ts.map +1 -0
  98. package/dist/utils/createContextParameters.d.ts +3 -0
  99. package/dist/utils/createContextParameters.d.ts.map +1 -0
  100. package/dist/utils/csp.d.ts +16 -0
  101. package/dist/utils/csp.d.ts.map +1 -0
  102. package/dist/utils/getEncodedAttributes.d.ts +3 -0
  103. package/dist/utils/getEncodedAttributes.d.ts.map +1 -0
  104. package/dist/utils/getRebuyConfig.d.ts +3 -0
  105. package/dist/utils/getRebuyConfig.d.ts.map +1 -0
  106. package/dist/utils/theme.d.ts +20 -0
  107. package/dist/utils/theme.d.ts.map +1 -0
  108. package/dist/widgetContainer/RebuyWidgetContainer.d.ts +8 -0
  109. package/dist/widgetContainer/RebuyWidgetContainer.d.ts.map +1 -0
  110. package/dist/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.d.ts +3 -0
  111. package/dist/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.d.ts.map +1 -0
  112. package/dist/widgets/RebuyCompleteTheLook/index.d.ts +2 -0
  113. package/dist/widgets/RebuyCompleteTheLook/index.d.ts.map +1 -0
  114. package/dist/widgets/RebuyCompleteTheLook/types.d.ts +5 -0
  115. package/dist/widgets/RebuyCompleteTheLook/types.d.ts.map +1 -0
  116. package/dist/widgets/RebuyDynamicBundleProducts/BundleImages.d.ts +5 -0
  117. package/dist/widgets/RebuyDynamicBundleProducts/BundleImages.d.ts.map +1 -0
  118. package/dist/widgets/RebuyDynamicBundleProducts/BundlePrice.d.ts +5 -0
  119. package/dist/widgets/RebuyDynamicBundleProducts/BundlePrice.d.ts.map +1 -0
  120. package/dist/widgets/RebuyDynamicBundleProducts/BundleSelection.d.ts +3 -0
  121. package/dist/widgets/RebuyDynamicBundleProducts/BundleSelection.d.ts.map +1 -0
  122. package/dist/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.d.ts +3 -0
  123. package/dist/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.d.ts.map +1 -0
  124. package/dist/widgets/RebuyDynamicBundleProducts/Select.d.ts +3 -0
  125. package/dist/widgets/RebuyDynamicBundleProducts/Select.d.ts.map +1 -0
  126. package/dist/widgets/RebuyDynamicBundleProducts/index.d.ts +2 -0
  127. package/dist/widgets/RebuyDynamicBundleProducts/index.d.ts.map +1 -0
  128. package/dist/widgets/RebuyDynamicBundleProducts/types.d.ts +19 -0
  129. package/dist/widgets/RebuyDynamicBundleProducts/types.d.ts.map +1 -0
  130. package/dist/widgets/RebuyProductAddOns/RebuyProductAddOnCard.d.ts +3 -0
  131. package/dist/widgets/RebuyProductAddOns/RebuyProductAddOnCard.d.ts.map +1 -0
  132. package/dist/widgets/RebuyProductAddOns/RebuyProductAddOns.d.ts +3 -0
  133. package/dist/widgets/RebuyProductAddOns/RebuyProductAddOns.d.ts.map +1 -0
  134. package/dist/widgets/RebuyProductAddOns/index.d.ts +2 -0
  135. package/dist/widgets/RebuyProductAddOns/index.d.ts.map +1 -0
  136. package/dist/widgets/RebuyProductAddOns/types.d.ts +19 -0
  137. package/dist/widgets/RebuyProductAddOns/types.d.ts.map +1 -0
  138. package/dist/widgets/RebuyProductRecommendations/RebuyProductRecommendations.d.ts +3 -0
  139. package/dist/widgets/RebuyProductRecommendations/RebuyProductRecommendations.d.ts.map +1 -0
  140. package/dist/widgets/RebuyProductRecommendations/index.d.ts +2 -0
  141. package/dist/widgets/RebuyProductRecommendations/index.d.ts.map +1 -0
  142. package/dist/widgets/RebuyProductRecommendations/types.d.ts +5 -0
  143. package/dist/widgets/RebuyProductRecommendations/types.d.ts.map +1 -0
  144. package/dist/widgets/RebuyWidget/RebuyWidget.d.ts +3 -0
  145. package/dist/widgets/RebuyWidget/RebuyWidget.d.ts.map +1 -0
  146. package/dist/widgets/RebuyWidget/WidgetContent.d.ts +3 -0
  147. package/dist/widgets/RebuyWidget/WidgetContent.d.ts.map +1 -0
  148. package/dist/widgets/RebuyWidget/index.d.ts +2 -0
  149. package/dist/widgets/RebuyWidget/index.d.ts.map +1 -0
  150. package/dist/widgets/RebuyWidget/types.d.ts +335 -0
  151. package/dist/widgets/RebuyWidget/types.d.ts.map +1 -0
  152. package/package.json +86 -47
  153. package/RebuyCompleteTheLook.client.jsx +0 -188
  154. package/RebuyContextProvider.client.jsx +0 -222
  155. package/RebuyContexts.client.jsx +0 -3
  156. package/RebuyDynamicBundleProducts.client.jsx +0 -415
  157. package/RebuyProductAddOnCard.client.jsx +0 -89
  158. package/RebuyProductAddOns.client.jsx +0 -227
  159. package/RebuyProductRecommendations.client.jsx +0 -68
  160. package/RebuyProductViewed.client.jsx +0 -62
  161. package/RebuyRecentlyViewedProducts.client.jsx +0 -68
  162. package/RebuyWidgetContainer.client.jsx +0 -136
package/dist/index.js ADDED
@@ -0,0 +1,3211 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ RebuyCompleteTheLook: () => RebuyCompleteTheLook,
34
+ RebuyConfigProvider: () => RebuyConfigProvider,
35
+ RebuyDynamicBundleProducts: () => RebuyDynamicBundleProducts,
36
+ RebuyHydrogenContextProvider: () => RebuyHydrogenContextProvider,
37
+ RebuyHydrogenReactContextProvider: () => RebuyHydrogenReactContextProvider,
38
+ RebuyProductAddOns: () => RebuyProductAddOns,
39
+ RebuyProductRecommendations: () => RebuyProductRecommendations,
40
+ RebuyWidget: () => RebuyWidget,
41
+ RebuyWidgetContainer: () => RebuyWidgetContainer,
42
+ getRebuyThemeStylesLink: () => getRebuyThemeStylesLink,
43
+ updateRebuyCsp: () => updateRebuyCsp,
44
+ useRebuyConfig: () => useRebuyConfig,
45
+ useRebuyTheme: () => useRebuyTheme
46
+ });
47
+ module.exports = __toCommonJS(index_exports);
48
+
49
+ // src/providers/RebuyHydrogenContextProvider.tsx
50
+ var Utilities2 = __toESM(require("@rebuy/rebuy/utilities"), 1);
51
+ var import_react3 = require("@remix-run/react");
52
+ var import_react4 = require("react");
53
+
54
+ // src/context/RebuyConfigContext.tsx
55
+ var import_react = require("react");
56
+
57
+ // src/utils/getRebuyConfig.ts
58
+ var import_rebuy = require("@rebuy/rebuy");
59
+ var getRebuyConfig = async (storeDomain) => {
60
+ try {
61
+ const request = {
62
+ parameters: { shop: storeDomain },
63
+ url: `/api/v1/user/config`
64
+ };
65
+ const { data: rebuy, ...response } = await new import_rebuy.RebuyClient(void 0, void 0, storeDomain).getShieldedAsset(
66
+ request.url,
67
+ request.parameters
68
+ );
69
+ if (!rebuy?.shop) {
70
+ throw new Error("Rebuy configuration is not properly set up - missing shop", { cause: response });
71
+ }
72
+ return rebuy;
73
+ } catch (error) {
74
+ const err = error;
75
+ console.warn("Error fetching Rebuy shop config");
76
+ console.error(err, err.cause);
77
+ throw err;
78
+ }
79
+ };
80
+
81
+ // src/context/RebuyConfigContext.tsx
82
+ var import_jsx_runtime = require("react/jsx-runtime");
83
+ var RebuyConfigContext = (0, import_react.createContext)(void 0);
84
+ var RebuyConfigProvider = ({ children, initialShopDomain, overrideApiKey }) => {
85
+ const [rebuyConfig, setRebuyConfig] = (0, import_react.useState)(null);
86
+ const [apiKey, setApiKey] = (0, import_react.useState)(overrideApiKey || null);
87
+ const [loadingStatus, setLoadingStatus] = (0, import_react.useState)("idle");
88
+ const [fetchError, setFetchError] = (0, import_react.useState)(null);
89
+ const [currentShopDomain, setCurrentShopDomain] = (0, import_react.useState)(initialShopDomain || null);
90
+ const isMounted = (0, import_react.useRef)(true);
91
+ const fetchRebuyConfig = async (domainToFetch) => {
92
+ if (!domainToFetch) {
93
+ console.warn("[RebuyConfigProvider] No shop domain provided to fetchRebuyConfig.");
94
+ setLoadingStatus("error");
95
+ setFetchError("Shop domain is required to fetch Rebuy config.");
96
+ return;
97
+ }
98
+ setCurrentShopDomain(domainToFetch);
99
+ setLoadingStatus("loading");
100
+ setFetchError(null);
101
+ try {
102
+ const config = await getRebuyConfig(domainToFetch);
103
+ if (isMounted.current) {
104
+ setRebuyConfig(config);
105
+ setApiKey(overrideApiKey || config?.shop?.api_key || null);
106
+ setLoadingStatus("success");
107
+ }
108
+ } catch (error) {
109
+ const errorMessage = error instanceof Error ? error.message : String(error);
110
+ console.error("[RebuyConfigProvider] Error fetching Rebuy config:", errorMessage, error);
111
+ if (isMounted.current) {
112
+ setFetchError(error instanceof Error ? error : errorMessage);
113
+ setLoadingStatus("error");
114
+ setRebuyConfig(null);
115
+ }
116
+ }
117
+ };
118
+ (0, import_react.useEffect)(() => {
119
+ isMounted.current = true;
120
+ if (initialShopDomain && loadingStatus === "idle") {
121
+ fetchRebuyConfig(initialShopDomain);
122
+ }
123
+ return () => {
124
+ isMounted.current = false;
125
+ };
126
+ }, [initialShopDomain]);
127
+ const contextValue = (0, import_react.useMemo)(
128
+ () => ({
129
+ apiKey,
130
+ fetchError,
131
+ fetchRebuyConfig,
132
+ loadingStatus,
133
+ rebuyConfig,
134
+ shopDomain: currentShopDomain
135
+ }),
136
+ [rebuyConfig, apiKey, loadingStatus, fetchError, currentShopDomain]
137
+ );
138
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RebuyConfigContext.Provider, { value: contextValue, children });
139
+ };
140
+ var useRebuyConfig = () => {
141
+ const context = (0, import_react.useContext)(RebuyConfigContext);
142
+ if (context === void 0) {
143
+ throw new Error("useRebuyConfig must be used within a RebuyConfigProvider");
144
+ }
145
+ return context;
146
+ };
147
+
148
+ // src/context/RebuyContext.tsx
149
+ var import_react2 = require("react");
150
+ var RebuyContext = (0, import_react2.createContext)(null);
151
+
152
+ // src/utils/createContextParameters.ts
153
+ var Utilities = __toESM(require("@rebuy/rebuy/utilities"), 1);
154
+
155
+ // src/utils/getEncodedAttributes.ts
156
+ var getEncodedAttributes = (attributes) => encodeURIComponent(
157
+ JSON.stringify(attributes.reduce((merged, { key, value }) => ({ ...merged, [key]: value }), {}))
158
+ );
159
+
160
+ // src/utils/createContextParameters.ts
161
+ var defaultMoney = (currencyCode = "USD") => ({
162
+ __typename: "MoneyV2",
163
+ amount: "0.0",
164
+ currencyCode
165
+ });
166
+ var defaultPageInfo = () => ({
167
+ __typename: "PageInfo",
168
+ endCursor: null,
169
+ hasNextPage: false,
170
+ hasPreviousPage: false,
171
+ startCursor: null
172
+ });
173
+ var defaultBuyerIdentity = () => ({
174
+ __typename: "CartBuyerIdentity",
175
+ countryCode: null,
176
+ customer: null,
177
+ deliveryAddressPreferences: [],
178
+ email: null,
179
+ phone: null
180
+ // preferences and purchasingCompany are not on the official type
181
+ });
182
+ var createContextParameters = ({
183
+ cacheKey,
184
+ /* Legacy props */
185
+ cartAttributes: legacyCartAttributes,
186
+ cartCost: legacyCartCost,
187
+ cartId: legacyCartId,
188
+ cartLines: legacyCartLines,
189
+ cartLinesLength: legacyCartLinesLength,
190
+ cartNote: legacyCartNote,
191
+ cartSubtotal: legacyCartSubtotal,
192
+ cartTotalQuantity: legacyCartTotalQuantity,
193
+ checkoutUrl: legacyCheckoutUrl,
194
+ discountCodes: legacyDiscountCodes,
195
+ /* Modern props */
196
+ hydrogenReactCartActions,
197
+ hydrogenReactCartError,
198
+ hydrogenReactCartStatus,
199
+ isHydrogenReact,
200
+ /* H-React specific */
201
+ queryObject,
202
+ sourceHydrogenCart,
203
+ windowUrl
204
+ }) => {
205
+ let solidifiedHydrogenCart = null;
206
+ const sourceCartCurrency = sourceHydrogenCart?.cost?.totalAmount?.currencyCode ?? "USD";
207
+ if (sourceHydrogenCart && sourceHydrogenCart.id) {
208
+ const builtCart = {
209
+ __typename: "Cart",
210
+ appliedGiftCards: sourceHydrogenCart.appliedGiftCards ?? [],
211
+ attributes: sourceHydrogenCart.attributes ?? [],
212
+ buyerIdentity: sourceHydrogenCart.buyerIdentity ?? defaultBuyerIdentity(),
213
+ checkoutUrl: sourceHydrogenCart.checkoutUrl ?? "",
214
+ cost: sourceHydrogenCart.cost ?? {
215
+ __typename: "CartCost",
216
+ checkoutChargeAmount: defaultMoney(sourceCartCurrency),
217
+ subtotalAmount: defaultMoney(sourceCartCurrency),
218
+ subtotalAmountEstimated: false,
219
+ totalAmount: defaultMoney(sourceCartCurrency),
220
+ totalAmountEstimated: false,
221
+ totalDutyAmount: null,
222
+ totalDutyAmountEstimated: false,
223
+ totalTaxAmount: null,
224
+ totalTaxAmountEstimated: false
225
+ },
226
+ createdAt: sourceHydrogenCart.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
227
+ deliveryGroups: sourceHydrogenCart.deliveryGroups ?? {
228
+ __typename: "CartDeliveryGroupConnection",
229
+ edges: [],
230
+ nodes: [],
231
+ pageInfo: defaultPageInfo()
232
+ },
233
+ discountAllocations: sourceHydrogenCart.discountAllocations ?? [],
234
+ discountCodes: sourceHydrogenCart.discountCodes ?? [],
235
+ id: sourceHydrogenCart.id,
236
+ lines: sourceHydrogenCart.lines ?? {
237
+ __typename: "BaseCartLineConnection",
238
+ edges: [],
239
+ nodes: [],
240
+ pageInfo: defaultPageInfo()
241
+ },
242
+ metafields: sourceHydrogenCart.metafields ?? [],
243
+ note: sourceHydrogenCart.note ?? null,
244
+ totalQuantity: sourceHydrogenCart.totalQuantity ?? 0,
245
+ updatedAt: sourceHydrogenCart.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
246
+ };
247
+ solidifiedHydrogenCart = builtCart;
248
+ }
249
+ let numericCartToken;
250
+ let cartSubtotalInCents = 0;
251
+ let linesForCounts = [];
252
+ let totalQuantity = 0;
253
+ let lineCount = 0;
254
+ let legacyNote = null;
255
+ let legacyAttributes = [];
256
+ let legacyCheckoutUrlValue;
257
+ let legacyDiscountCodesValue = [];
258
+ let legacyCartCostValue;
259
+ let legacyCartIdValue;
260
+ if (solidifiedHydrogenCart) {
261
+ numericCartToken = Utilities.getIdFromGraphUrl(solidifiedHydrogenCart.id, "Cart");
262
+ cartSubtotalInCents = solidifiedHydrogenCart.cost?.subtotalAmount?.amount ? Utilities.amountToCents(parseFloat(solidifiedHydrogenCart.cost.subtotalAmount.amount)) : 0;
263
+ linesForCounts = (solidifiedHydrogenCart.lines.nodes?.length ?? 0) > 0 ? solidifiedHydrogenCart.lines.nodes : solidifiedHydrogenCart.lines.edges?.map((e) => e.node) ?? [];
264
+ totalQuantity = solidifiedHydrogenCart.totalQuantity;
265
+ lineCount = linesForCounts.length;
266
+ legacyNote = solidifiedHydrogenCart.note ?? null;
267
+ legacyAttributes = [...solidifiedHydrogenCart.attributes];
268
+ legacyCheckoutUrlValue = solidifiedHydrogenCart.checkoutUrl;
269
+ legacyDiscountCodesValue = [...solidifiedHydrogenCart.discountCodes];
270
+ legacyCartCostValue = solidifiedHydrogenCart.cost;
271
+ legacyCartIdValue = solidifiedHydrogenCart.id;
272
+ } else {
273
+ numericCartToken = legacyCartId ? Utilities.getIdFromGraphUrl(legacyCartId, "Cart") : void 0;
274
+ const subtotalString = legacyCartCost?.subtotalAmount?.amount ?? legacyCartSubtotal;
275
+ cartSubtotalInCents = subtotalString ? Utilities.amountToCents(parseFloat(subtotalString)) : 0;
276
+ linesForCounts = Array.isArray(legacyCartLines) ? [...legacyCartLines] : [];
277
+ totalQuantity = legacyCartTotalQuantity ?? linesForCounts.reduce((sum, line) => sum + (line?.quantity ?? 0), 0);
278
+ lineCount = legacyCartLinesLength ?? linesForCounts.length;
279
+ legacyNote = legacyCartNote ?? null;
280
+ legacyAttributes = legacyCartAttributes ? [...legacyCartAttributes] : [];
281
+ legacyCheckoutUrlValue = legacyCheckoutUrl;
282
+ legacyDiscountCodesValue = legacyDiscountCodes ? [...legacyDiscountCodes] : [];
283
+ legacyCartCostValue = legacyCartCost;
284
+ legacyCartIdValue = legacyCartId;
285
+ }
286
+ const contextParametersOutput = {
287
+ cacheKey,
288
+ cart: void 0,
289
+ cartAttributes: legacyAttributes,
290
+ cartCost: legacyCartCostValue,
291
+ cartCount: totalQuantity,
292
+ cartId: legacyCartIdValue,
293
+ cartItemCount: totalQuantity,
294
+ cartLineCount: lineCount,
295
+ cartLines: linesForCounts,
296
+ cartNote: legacyNote,
297
+ cartSubtotal: cartSubtotalInCents,
298
+ cartToken: numericCartToken,
299
+ checkoutUrl: legacyCheckoutUrlValue,
300
+ discountCodes: legacyDiscountCodesValue,
301
+ hydrogenCart: solidifiedHydrogenCart,
302
+ hydrogenReactCartActions,
303
+ hydrogenReactCartError,
304
+ hydrogenReactCartStatus,
305
+ isHydrogenReact,
306
+ time: queryObject.time ?? "",
307
+ url: windowUrl
308
+ };
309
+ const cartContext = {
310
+ attributes: "",
311
+ item_count: totalQuantity,
312
+ items: [],
313
+ line_count: lineCount,
314
+ note: legacyNote ?? "",
315
+ subtotal: cartSubtotalInCents,
316
+ token: numericCartToken ?? ""
317
+ };
318
+ if (legacyAttributes.length > 0) {
319
+ const validAttributes = legacyAttributes.filter(
320
+ (attr) => typeof attr.key === "string" && typeof attr.value === "string"
321
+ );
322
+ cartContext.attributes = getEncodedAttributes(validAttributes);
323
+ }
324
+ if (linesForCounts.length > 0) {
325
+ cartContext.items = linesForCounts.map((line) => {
326
+ const item = {
327
+ attributes: line.attributes ? [...line.attributes] : [],
328
+ product_id: line.merchandise?.product?.id ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, "Product") : "",
329
+ properties: "",
330
+ quantity: line.quantity,
331
+ variant_id: line.merchandise?.id ? Utilities.getIdFromGraphUrl(line.merchandise.id, "ProductVariant") : ""
332
+ };
333
+ if (line.attributes?.length) {
334
+ const validLineAttributes = line.attributes.filter(
335
+ (attr) => typeof attr.key === "string" && typeof attr.value === "string"
336
+ );
337
+ item.properties = getEncodedAttributes(validLineAttributes);
338
+ }
339
+ return item;
340
+ });
341
+ }
342
+ return {
343
+ ...contextParametersOutput,
344
+ cart: cartContext
345
+ };
346
+ };
347
+
348
+ // src/providers/RebuyHydrogenContextProvider.tsx
349
+ var import_jsx_runtime2 = require("react/jsx-runtime");
350
+ var RebuyHydrogenContext = ({ children, shop, sourceHydrogenCart }) => {
351
+ const {
352
+ fetchError: configFetchError,
353
+ loadingStatus: configLoadingStatus,
354
+ rebuyConfig,
355
+ shopDomain: configShopDomain
356
+ } = useRebuyConfig();
357
+ const location = (0, import_react3.useLocation)();
358
+ const queryObject = Utilities2.queryStringToObject(location.search);
359
+ const windowUrl = `${shop}${location.pathname}${location.search}`;
360
+ const contextParameters = (0, import_react4.useMemo)(
361
+ () => createContextParameters({
362
+ cacheKey: rebuyConfig?.shop?.cache_key,
363
+ isHydrogenReact: false,
364
+ queryObject,
365
+ sourceHydrogenCart,
366
+ windowUrl
367
+ }),
368
+ [rebuyConfig?.shop?.cache_key, windowUrl, queryObject, sourceHydrogenCart]
369
+ );
370
+ const defaultContextValue = (0, import_react4.useMemo)(() => null, []);
371
+ const contextValue = (0, import_react4.useMemo)(
372
+ () => configLoadingStatus === "success" && rebuyConfig ? { contextParameters } : defaultContextValue,
373
+ [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]
374
+ );
375
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(RebuyContext.Provider, { value: contextValue, children: configLoadingStatus === "success" && rebuyConfig ? children : configLoadingStatus === "error" ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
376
+ (() => {
377
+ console.error(
378
+ `[Rebuy Provider] Failed to load Rebuy configuration for ${configShopDomain}. Rebuy features unavailable. Error:`,
379
+ configFetchError instanceof Error ? configFetchError.message : configFetchError
380
+ );
381
+ return null;
382
+ })(),
383
+ children
384
+ ] }) : null });
385
+ };
386
+ var RebuyHydrogenContextProvider = ({
387
+ cart,
388
+ children,
389
+ overrideApiKey,
390
+ publicStoreDomain,
391
+ shop
392
+ }) => {
393
+ if (!publicStoreDomain || !shop) {
394
+ console.warn('[Rebuy Provider Wrapper] Waiting for "publicStoreDomain" and "shop" props.');
395
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children });
396
+ }
397
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react3.Await, { resolve: cart, children: (resolvedCart) => {
398
+ const hydrogenCartFromRemix = resolvedCart;
399
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(RebuyConfigProvider, { initialShopDomain: publicStoreDomain, overrideApiKey, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(RebuyHydrogenContext, { shop, sourceHydrogenCart: hydrogenCartFromRemix, children }) });
400
+ } });
401
+ };
402
+
403
+ // src/providers/RebuyHydrogenReactContextProvider.tsx
404
+ var Utilities3 = __toESM(require("@rebuy/rebuy/utilities"), 1);
405
+ var import_react5 = require("@remix-run/react");
406
+ var import_hydrogen_react = require("@shopify/hydrogen-react");
407
+ var import_react6 = require("react");
408
+
409
+ // src/queries/cart.queries.ts
410
+ var OPTION_FRAGMENT = `#graphql
411
+ fragment OptionFragment on ProductOption {
412
+ id
413
+ name
414
+ optionValues {
415
+ id
416
+ name
417
+ swatch {
418
+ color
419
+ image {
420
+ mediaContentType
421
+ previewImage {
422
+ height
423
+ id
424
+ url
425
+ width
426
+ altText
427
+ }
428
+ id
429
+ alt
430
+ }
431
+ }
432
+ }
433
+ }
434
+ `;
435
+ var CART_LINE_FRAGMENT = `#graphql
436
+ fragment CartLineFragment on CartLine {
437
+ id
438
+ quantity
439
+ cost {
440
+ amountPerQuantity {
441
+ amount
442
+ currencyCode
443
+ }
444
+ compareAtAmountPerQuantity {
445
+ amount
446
+ currencyCode
447
+ }
448
+ totalAmount {
449
+ amount
450
+ currencyCode
451
+ }
452
+ subtotalAmount {
453
+ amount
454
+ currencyCode
455
+ }
456
+ }
457
+ attributes {
458
+ key
459
+ value
460
+ }
461
+ discountAllocations {
462
+ discountedAmount {
463
+ amount
464
+ currencyCode
465
+ }
466
+ ... on CartAutomaticDiscountAllocation {
467
+ __typename
468
+ discountedAmount {
469
+ amount
470
+ currencyCode
471
+ }
472
+ title
473
+ }
474
+ ... on CartCodeDiscountAllocation {
475
+ __typename
476
+ code
477
+ discountedAmount {
478
+ amount
479
+ currencyCode
480
+ }
481
+ }
482
+ ... on CartCustomDiscountAllocation {
483
+ __typename
484
+ discountedAmount {
485
+ amount
486
+ currencyCode
487
+ }
488
+ title
489
+ }
490
+ }
491
+ merchandise {
492
+ ... on ProductVariant {
493
+ availableForSale
494
+ id
495
+ sku
496
+ title
497
+ compareAtPrice {
498
+ amount
499
+ currencyCode
500
+ }
501
+ image {
502
+ altText
503
+ height
504
+ id
505
+ url
506
+ width
507
+ }
508
+ price {
509
+ amount
510
+ currencyCode
511
+ }
512
+ product {
513
+ handle
514
+ id
515
+ productType
516
+ tags
517
+ title
518
+ vendor
519
+ collections(first: 10) {
520
+ nodes {
521
+ handle
522
+ }
523
+ }
524
+ options {
525
+ ...OptionFragment
526
+ }
527
+ images(first: 20) {
528
+ nodes {
529
+ altText
530
+ height
531
+ id
532
+ url
533
+ width
534
+ }
535
+ }
536
+ }
537
+ selectedOptions {
538
+ name
539
+ value
540
+ }
541
+ }
542
+ }
543
+ }
544
+ `;
545
+ var CART_LINE_COMPONENT_FRAGMENT = `#graphql
546
+ fragment CartLineComponentFragment on ComponentizableCartLine {
547
+ id
548
+ quantity
549
+ cost {
550
+ amountPerQuantity {
551
+ amount
552
+ currencyCode
553
+ }
554
+ compareAtAmountPerQuantity {
555
+ amount
556
+ currencyCode
557
+ }
558
+ totalAmount {
559
+ amount
560
+ currencyCode
561
+ }
562
+ subtotalAmount {
563
+ amount
564
+ currencyCode
565
+ }
566
+ }
567
+ attributes {
568
+ key
569
+ value
570
+ }
571
+ discountAllocations {
572
+ discountedAmount {
573
+ amount
574
+ currencyCode
575
+ }
576
+ ... on CartAutomaticDiscountAllocation {
577
+ __typename
578
+ discountedAmount {
579
+ amount
580
+ currencyCode
581
+ }
582
+ title
583
+ }
584
+ ... on CartCodeDiscountAllocation {
585
+ __typename
586
+ code
587
+ discountedAmount {
588
+ amount
589
+ currencyCode
590
+ }
591
+ }
592
+ ... on CartCustomDiscountAllocation {
593
+ __typename
594
+ discountedAmount {
595
+ amount
596
+ currencyCode
597
+ }
598
+ title
599
+ }
600
+ }
601
+ merchandise {
602
+ ... on ProductVariant {
603
+ availableForSale
604
+ id
605
+ sku
606
+ title
607
+ compareAtPrice {
608
+ amount
609
+ currencyCode
610
+ }
611
+ image {
612
+ altText
613
+ height
614
+ id
615
+ url
616
+ width
617
+ }
618
+ price {
619
+ amount
620
+ currencyCode
621
+ }
622
+ product {
623
+ handle
624
+ id
625
+ productType
626
+ tags
627
+ title
628
+ vendor
629
+ collections(first: 10) {
630
+ nodes {
631
+ handle
632
+ }
633
+ }
634
+ options {
635
+ id
636
+ name
637
+ optionValues {
638
+ id
639
+ name
640
+ swatch {
641
+ color
642
+ image {
643
+ mediaContentType
644
+ previewImage {
645
+ height
646
+ id
647
+ url
648
+ width
649
+ altText
650
+ }
651
+ id
652
+ alt
653
+ }
654
+ }
655
+ }
656
+ }
657
+ images(first: 20) {
658
+ nodes {
659
+ altText
660
+ height
661
+ id
662
+ url
663
+ width
664
+ }
665
+ }
666
+ }
667
+ selectedOptions {
668
+ name
669
+ value
670
+ }
671
+ }
672
+ }
673
+ lineComponents {
674
+ id
675
+ quantity
676
+ cost {
677
+ amountPerQuantity {
678
+ amount
679
+ currencyCode
680
+ }
681
+ compareAtAmountPerQuantity {
682
+ amount
683
+ currencyCode
684
+ }
685
+ totalAmount {
686
+ amount
687
+ currencyCode
688
+ }
689
+ subtotalAmount {
690
+ amount
691
+ currencyCode
692
+ }
693
+ }
694
+ attributes {
695
+ key
696
+ value
697
+ }
698
+ discountAllocations {
699
+ discountedAmount {
700
+ amount
701
+ currencyCode
702
+ }
703
+ ... on CartAutomaticDiscountAllocation {
704
+ __typename
705
+ discountedAmount {
706
+ amount
707
+ currencyCode
708
+ }
709
+ title
710
+ }
711
+ ... on CartCodeDiscountAllocation {
712
+ __typename
713
+ code
714
+ discountedAmount {
715
+ amount
716
+ currencyCode
717
+ }
718
+ }
719
+ ... on CartCustomDiscountAllocation {
720
+ __typename
721
+ discountedAmount {
722
+ amount
723
+ currencyCode
724
+ }
725
+ title
726
+ }
727
+ }
728
+ merchandise {
729
+ ... on ProductVariant {
730
+ availableForSale
731
+ id
732
+ sku
733
+ title
734
+ compareAtPrice {
735
+ amount
736
+ currencyCode
737
+ }
738
+ image {
739
+ altText
740
+ height
741
+ id
742
+ url
743
+ width
744
+ }
745
+ price {
746
+ amount
747
+ currencyCode
748
+ }
749
+ product {
750
+ handle
751
+ id
752
+ productType
753
+ tags
754
+ title
755
+ vendor
756
+ collections(first: 10) {
757
+ nodes {
758
+ handle
759
+ }
760
+ }
761
+ options {
762
+ ...OptionFragment
763
+ }
764
+ images(first: 20) {
765
+ nodes {
766
+ altText
767
+ height
768
+ id
769
+ url
770
+ width
771
+ }
772
+ }
773
+ }
774
+ selectedOptions {
775
+ name
776
+ value
777
+ }
778
+ }
779
+ }
780
+ }
781
+ }
782
+ `;
783
+ var CART_FRAGMENT = `#graphql
784
+ fragment CartFragment on Cart {
785
+ id
786
+ checkoutUrl
787
+ createdAt
788
+ totalQuantity
789
+ note
790
+ updatedAt
791
+ __typename
792
+ buyerIdentity {
793
+ countryCode
794
+ customer {
795
+ id
796
+ email
797
+ firstName
798
+ lastName
799
+ displayName
800
+ }
801
+ email
802
+ phone
803
+ }
804
+ attributes {
805
+ key
806
+ value
807
+ }
808
+ cost {
809
+ subtotalAmount {
810
+ amount
811
+ currencyCode
812
+ }
813
+ totalAmount {
814
+ amount
815
+ currencyCode
816
+ }
817
+ }
818
+ discountAllocations {
819
+ discountedAmount {
820
+ amount
821
+ currencyCode
822
+ }
823
+ ... on CartAutomaticDiscountAllocation {
824
+ __typename
825
+ discountedAmount {
826
+ amount
827
+ currencyCode
828
+ }
829
+ title
830
+ }
831
+ ... on CartCodeDiscountAllocation {
832
+ __typename
833
+ code
834
+ discountedAmount {
835
+ amount
836
+ currencyCode
837
+ }
838
+ }
839
+ ... on CartCustomDiscountAllocation {
840
+ __typename
841
+ discountedAmount {
842
+ amount
843
+ currencyCode
844
+ }
845
+ title
846
+ }
847
+ }
848
+ discountCodes {
849
+ applicable
850
+ code
851
+ }
852
+ lines(first: $numCartLines) {
853
+ edges {
854
+ node {
855
+ ...CartLineComponentFragment
856
+ }
857
+ }
858
+ edges {
859
+ node {
860
+ ...CartLineFragment
861
+ }
862
+ }
863
+ }
864
+ }
865
+ ${CART_LINE_FRAGMENT}
866
+ ${CART_LINE_COMPONENT_FRAGMENT}
867
+ ${OPTION_FRAGMENT}
868
+ `;
869
+
870
+ // src/providers/RebuyHydrogenReactContextProvider.tsx
871
+ var import_jsx_runtime3 = require("react/jsx-runtime");
872
+ var RebuyHydrogenReactContext = ({ children, publicPrimaryDomian }) => {
873
+ const { loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
874
+ const location = (0, import_react5.useLocation)();
875
+ const queryObject = Utilities3.queryStringToObject(location.search);
876
+ const windowUrl = publicPrimaryDomian ? `${publicPrimaryDomian}${location.pathname}${location.search}` : "";
877
+ const {
878
+ cartAttributesUpdate,
879
+ cartCreate,
880
+ discountCodesUpdate,
881
+ error: hydrogenReactCartError,
882
+ linesAdd,
883
+ linesRemove,
884
+ linesUpdate,
885
+ noteUpdate,
886
+ status: hydrogenReactCartStatus,
887
+ ...hydrogenReactCartData
888
+ } = (0, import_hydrogen_react.useCart)();
889
+ const hydrogenReactCartActions = (0, import_react6.useMemo)(
890
+ () => ({
891
+ cartAttributesUpdate,
892
+ cartCreate,
893
+ discountCodesUpdate,
894
+ linesAdd,
895
+ linesRemove,
896
+ linesUpdate,
897
+ noteUpdate
898
+ }),
899
+ [cartAttributesUpdate, cartCreate, discountCodesUpdate, linesAdd, linesRemove, linesUpdate, noteUpdate]
900
+ );
901
+ const contextParameters = (0, import_react6.useMemo)(() => {
902
+ const propsForParamCreation = {
903
+ cacheKey: rebuyConfig?.shop?.cache_key,
904
+ hydrogenReactCartActions,
905
+ hydrogenReactCartError,
906
+ hydrogenReactCartStatus,
907
+ isHydrogenReact: true,
908
+ queryObject,
909
+ sourceHydrogenCart: hydrogenReactCartData,
910
+ // eslint-disable-line @typescript-eslint/no-explicit-any
911
+ windowUrl
912
+ };
913
+ return createContextParameters(propsForParamCreation);
914
+ }, [
915
+ rebuyConfig?.shop?.cache_key,
916
+ windowUrl,
917
+ queryObject,
918
+ hydrogenReactCartData,
919
+ hydrogenReactCartActions,
920
+ hydrogenReactCartStatus,
921
+ hydrogenReactCartError
922
+ ]);
923
+ const defaultContextValue = (0, import_react6.useMemo)(() => ({ contextParameters: {} }), []);
924
+ const rebuyContextValue = (0, import_react6.useMemo)(
925
+ () => configLoadingStatus === "success" && rebuyConfig ? { contextParameters } : defaultContextValue,
926
+ [configLoadingStatus, rebuyConfig, contextParameters, defaultContextValue]
927
+ );
928
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(RebuyContext.Provider, { value: rebuyContextValue, children: configLoadingStatus === "success" && rebuyConfig ? children : configLoadingStatus === "error" ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children }) : null });
929
+ };
930
+ var RebuyHydrogenReactContextProvider = ({
931
+ // --- Rebuy Specific Props ---
932
+ cartFragment = CART_FRAGMENT,
933
+ // --- ShopifyProvider Props ---
934
+ children,
935
+ countryIsoCode = "US",
936
+ customerAccessToken = "",
937
+ data,
938
+ languageIsoCode = "EN",
939
+ numCartLines,
940
+ onAttributesUpdate,
941
+ // --- CartProvider Props ---
942
+ onAttributesUpdateComplete,
943
+ onBuyerIdentityUpdate,
944
+ onBuyerIdentityUpdateComplete,
945
+ onCreate,
946
+ // --- CartProvider Callbacks (adapted) ---
947
+ onCreateComplete,
948
+ onDiscountCodesUpdate,
949
+ onDiscountCodesUpdateComplete,
950
+ onLineAdd,
951
+ onLineAddComplete,
952
+ onLineRemove,
953
+ onLineRemoveComplete,
954
+ onLineUpdate,
955
+ onLineUpdateComplete,
956
+ onNoteUpdate,
957
+ onNoteUpdateComplete,
958
+ overrideApiKey,
959
+ publicPrimaryDomian = "",
960
+ publicStoreDomain = "",
961
+ publicStorefrontApiToken = "",
962
+ publicStorefrontId = "",
963
+ storefrontApiVersion = "2024-07"
964
+ }) => {
965
+ const adaptedCallbacks = (0, import_react6.useMemo)(
966
+ () => ({
967
+ onAttributesUpdate: onAttributesUpdate ? () => onAttributesUpdate() : void 0,
968
+ onAttributesUpdateComplete: onAttributesUpdateComplete ? () => onAttributesUpdateComplete() : void 0,
969
+ onBuyerIdentityUpdate: onBuyerIdentityUpdate ? () => onBuyerIdentityUpdate() : void 0,
970
+ onBuyerIdentityUpdateComplete: onBuyerIdentityUpdateComplete ? () => onBuyerIdentityUpdateComplete() : void 0,
971
+ onCreate: onCreate ? () => onCreate() : void 0,
972
+ onCreateComplete: onCreateComplete ? () => onCreateComplete() : void 0,
973
+ onDiscountCodesUpdate: onDiscountCodesUpdate ? () => onDiscountCodesUpdate() : void 0,
974
+ onDiscountCodesUpdateComplete: onDiscountCodesUpdateComplete ? () => onDiscountCodesUpdateComplete() : void 0,
975
+ onLineAdd: onLineAdd ? () => onLineAdd() : void 0,
976
+ onLineAddComplete: onLineAddComplete ? () => onLineAddComplete() : void 0,
977
+ onLineRemove: onLineRemove ? () => onLineRemove() : void 0,
978
+ onLineRemoveComplete: onLineRemoveComplete ? () => onLineRemoveComplete() : void 0,
979
+ onLineUpdate: onLineUpdate ? () => onLineUpdate() : void 0,
980
+ onLineUpdateComplete: onLineUpdateComplete ? () => onLineUpdateComplete() : void 0,
981
+ onNoteUpdate: onNoteUpdate ? () => onNoteUpdate() : void 0,
982
+ onNoteUpdateComplete: onNoteUpdateComplete ? () => onNoteUpdateComplete() : void 0
983
+ }),
984
+ [
985
+ onAttributesUpdate,
986
+ onAttributesUpdateComplete,
987
+ onBuyerIdentityUpdate,
988
+ onBuyerIdentityUpdateComplete,
989
+ onCreate,
990
+ onCreateComplete,
991
+ onDiscountCodesUpdate,
992
+ onDiscountCodesUpdateComplete,
993
+ onLineAdd,
994
+ onLineAddComplete,
995
+ onLineRemove,
996
+ onLineRemoveComplete,
997
+ onLineUpdate,
998
+ onLineUpdateComplete,
999
+ onNoteUpdate,
1000
+ onNoteUpdateComplete
1001
+ ]
1002
+ );
1003
+ if (!publicStoreDomain || !publicStorefrontApiToken) {
1004
+ console.error(
1005
+ "[Rebuy React Provider] Critical environment variables publicStoreDomain or publicStorefrontApiToken are missing. ShopifyProvider and CartProvider may not function correctly."
1006
+ );
1007
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children });
1008
+ }
1009
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1010
+ import_hydrogen_react.ShopifyProvider,
1011
+ {
1012
+ countryIsoCode,
1013
+ languageIsoCode,
1014
+ storeDomain: publicStoreDomain,
1015
+ storefrontApiVersion,
1016
+ storefrontId: publicStorefrontId,
1017
+ storefrontToken: publicStorefrontApiToken,
1018
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1019
+ import_hydrogen_react.CartProvider,
1020
+ {
1021
+ cartFragment,
1022
+ countryCode: countryIsoCode,
1023
+ customerAccessToken,
1024
+ data,
1025
+ languageCode: languageIsoCode,
1026
+ numCartLines,
1027
+ ...adaptedCallbacks,
1028
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(RebuyConfigProvider, { initialShopDomain: publicStoreDomain, overrideApiKey, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(RebuyHydrogenReactContext, { publicPrimaryDomian, children }) })
1029
+ }
1030
+ )
1031
+ }
1032
+ );
1033
+ };
1034
+
1035
+ // src/widgetContainer/RebuyWidgetContainer.tsx
1036
+ var import_rebuy2 = require("@rebuy/rebuy");
1037
+ var Utilities4 = __toESM(require("@rebuy/rebuy/utilities"), 1);
1038
+ var import_hydrogen = require("@shopify/hydrogen");
1039
+ var import_react7 = __toESM(require("react"), 1);
1040
+ var RebuyWidgetContainerBase = ({ children, ...props }) => {
1041
+ const { apiKey, collection, collectionId, dataSource, limit, options, product, productId, variant, variantId } = props;
1042
+ const { apiKey: apiKeyFromContext, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
1043
+ const [rebuyApiClient, setRebuyApiClient] = (0, import_react7.useState)(null);
1044
+ const [initialized, setInitialized] = (0, import_react7.useState)(false);
1045
+ const shopifyProductId = product?.id ?? productId ?? null;
1046
+ const shopifyVariantId = variant?.id ?? variantId ?? null;
1047
+ const shopifyCollectionId = collection?.id ?? collectionId ?? null;
1048
+ const [products, setProducts] = (0, import_react7.useState)([]);
1049
+ const [metadata, setMetadata] = (0, import_react7.useState)();
1050
+ (0, import_react7.useEffect)(() => {
1051
+ if (!rebuyApiClient && apiKeyFromContext && configLoadingStatus === "success") {
1052
+ const client = new import_rebuy2.RebuyClient(apiKeyFromContext);
1053
+ if (options) {
1054
+ client.setDefaultParameters(options);
1055
+ }
1056
+ setRebuyApiClient(client);
1057
+ setInitialized(true);
1058
+ }
1059
+ }, [apiKeyFromContext, rebuyApiClient, configLoadingStatus, options]);
1060
+ const request = (0, import_react7.useMemo)(() => {
1061
+ const req = {
1062
+ endpoint: dataSource || "/api/v1/products/recommended",
1063
+ params: {}
1064
+ // Keeping this object generic to allow for custom endpoints
1065
+ };
1066
+ if (shopifyProductId) {
1067
+ req.params.shopify_product_ids = Utilities4.getIdFromGraphUrl(shopifyProductId, "Product") ?? "";
1068
+ }
1069
+ if (shopifyVariantId) {
1070
+ req.params.shopify_variant_ids = Utilities4.getIdFromGraphUrl(shopifyVariantId, "ProductVariant") ?? "";
1071
+ }
1072
+ if (shopifyCollectionId) {
1073
+ req.params.shopify_collection_ids = Utilities4.getIdFromGraphUrl(shopifyCollectionId, "Collection") ?? "";
1074
+ }
1075
+ if (limit) {
1076
+ req.params.limit = limit;
1077
+ }
1078
+ return req;
1079
+ }, [dataSource, shopifyProductId, shopifyVariantId, shopifyCollectionId, limit]);
1080
+ (0, import_react7.useEffect)(() => {
1081
+ let isMounted = true;
1082
+ if (!rebuyApiClient || !initialized || configLoadingStatus !== "success") return;
1083
+ const fetchData = async () => {
1084
+ const { data, metadata: metadata2 } = await rebuyApiClient.getStorefrontData(request.endpoint, request.params);
1085
+ if (isMounted) {
1086
+ setProducts(
1087
+ Array.isArray(data) ? data.map((product2) => ({
1088
+ ...product2,
1089
+ variants: {
1090
+ nodes: product2.variants ? (0, import_hydrogen.flattenConnection)(product2.variants) : []
1091
+ }
1092
+ })) : []
1093
+ );
1094
+ setMetadata(metadata2);
1095
+ }
1096
+ };
1097
+ fetchData();
1098
+ return () => {
1099
+ isMounted = false;
1100
+ };
1101
+ }, [rebuyApiClient, initialized, request, configLoadingStatus]);
1102
+ const childrenWithProps = (currentProps) => import_react7.default.Children.map(
1103
+ children,
1104
+ (child) => import_react7.default.isValidElement(child) ? import_react7.default.cloneElement(child, currentProps) : child
1105
+ );
1106
+ const childProps = {
1107
+ ...props,
1108
+ cacheKey: rebuyConfig?.shop?.cache_key,
1109
+ key: product?.id,
1110
+ metadata,
1111
+ products
1112
+ };
1113
+ if (configLoadingStatus !== "success" || !rebuyApiClient) {
1114
+ return null;
1115
+ }
1116
+ return childrenWithProps(childProps);
1117
+ };
1118
+ var RebuyWidgetContainer = RebuyWidgetContainerBase;
1119
+
1120
+ // src/components/ProductCard/defaultSettings.ts
1121
+ var defaultProductCardSettings = {
1122
+ layoutStyle: "grid",
1123
+ productOptions: {
1124
+ hide_out_of_stock_variants: false,
1125
+ match_variant: false,
1126
+ match_variant_out_of_stock: false,
1127
+ show_product_description: "hide",
1128
+ show_subscription_options: "always",
1129
+ show_variant_options: "always",
1130
+ show_variant_title: "show",
1131
+ show_variants_as_products: false,
1132
+ variant_display_limit: "product_limit"
1133
+ },
1134
+ quantityInput: {
1135
+ default_quantity: 1,
1136
+ enabled: true,
1137
+ max_value: 11,
1138
+ min_value: 1
1139
+ },
1140
+ settingsDiscount: {
1141
+ amount: 0,
1142
+ bundle_protection: {
1143
+ allowed_removals: 0,
1144
+ disable_atc_on_incomplete: false,
1145
+ enabled: false
1146
+ },
1147
+ discount_protection: {
1148
+ enabled: false,
1149
+ minimum_items_to_get_discount: 2
1150
+ },
1151
+ discounted_by: "other",
1152
+ discounted_from: "original_price",
1153
+ message: "",
1154
+ quantity: 1,
1155
+ show_saving_amount: false,
1156
+ type: "none"
1157
+ },
1158
+ variantSelector: "select"
1159
+ };
1160
+
1161
+ // src/components/ProductCard/ProductCard.tsx
1162
+ var import_react10 = require("@remix-run/react");
1163
+ var import_hydrogen4 = require("@shopify/hydrogen");
1164
+ var import_react11 = require("react");
1165
+
1166
+ // src/components/AddToCartBtn/HydrogenAddToCartBtn.tsx
1167
+ var import_hydrogen2 = require("@shopify/hydrogen");
1168
+
1169
+ // src/components/AddToCartBtn/AddToCartBtn.module.css
1170
+ var AddToCartBtn_default = {
1171
+ "rebuy-cart-button": "AddToCartBtn_rebuy-cart-button",
1172
+ "rebuy-cart-button__container": "AddToCartBtn_rebuy-cart-button__container"
1173
+ };
1174
+
1175
+ // src/components/AddToCartBtn/HydrogenAddToCartBtn.tsx
1176
+ var import_jsx_runtime4 = require("react/jsx-runtime");
1177
+ var HydrogenAddToCartBtn = ({
1178
+ addToCartBtnText,
1179
+ addToCartCallback,
1180
+ disabled,
1181
+ linesToAdd,
1182
+ moneyData
1183
+ }) => {
1184
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: AddToCartBtn_default["rebuy-cart-button__container"], children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1185
+ import_hydrogen2.CartForm,
1186
+ {
1187
+ action: import_hydrogen2.CartForm.ACTIONS.LinesAdd,
1188
+ inputs: {
1189
+ lines: linesToAdd
1190
+ },
1191
+ route: "/cart",
1192
+ children: (fetcher) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1193
+ "button",
1194
+ {
1195
+ className: AddToCartBtn_default["rebuy-cart-button"],
1196
+ disabled: disabled || fetcher.state !== "idle",
1197
+ onClick: addToCartCallback,
1198
+ type: "submit",
1199
+ children: [
1200
+ addToCartBtnText,
1201
+ moneyData && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1202
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: " | " }),
1203
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_hydrogen2.Money, { data: moneyData, withoutTrailingZeros: true })
1204
+ ] })
1205
+ ]
1206
+ }
1207
+ ) })
1208
+ }
1209
+ ) });
1210
+ };
1211
+
1212
+ // src/components/AddToCartBtn/HydrogenReactAddToCartBtn.tsx
1213
+ var import_hydrogen_react2 = require("@shopify/hydrogen-react");
1214
+ var import_jsx_runtime5 = require("react/jsx-runtime");
1215
+ var HydrogenReactAddToCartBtn = ({
1216
+ addToCartBtnText,
1217
+ addToCartCallback,
1218
+ disabled,
1219
+ linesToAdd,
1220
+ moneyData
1221
+ }) => {
1222
+ const { linesAdd } = (0, import_hydrogen_react2.useCart)();
1223
+ const handleAddToCart = () => {
1224
+ linesAdd(linesToAdd);
1225
+ addToCartCallback?.();
1226
+ };
1227
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("button", { className: AddToCartBtn_default["rebuy-cart-button"], disabled, onClick: handleAddToCart, type: "button", children: [
1228
+ addToCartBtnText,
1229
+ moneyData && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
1230
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: " | " }),
1231
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_hydrogen_react2.Money, { data: moneyData, withoutTrailingZeros: true })
1232
+ ] })
1233
+ ] });
1234
+ };
1235
+
1236
+ // src/components/AddToCartBtn/AddToCartBtn.tsx
1237
+ var import_jsx_runtime6 = require("react/jsx-runtime");
1238
+ var AddToCartBtn = ({
1239
+ addToCartBtnText,
1240
+ addToCartCallback,
1241
+ disabled,
1242
+ isHydrogenReact,
1243
+ moneyData,
1244
+ quantity,
1245
+ selectedVariants
1246
+ }) => {
1247
+ const linesToAdd = selectedVariants.map((variant) => ({
1248
+ attributes: [
1249
+ { key: "_source", value: "Rebuy" },
1250
+ { key: "_attribution", value: "Rebuy Product Recommendations" }
1251
+ ],
1252
+ merchandiseId: variant.id,
1253
+ quantity: quantity || 1,
1254
+ selectedVariant: variant
1255
+ }));
1256
+ if (isHydrogenReact) {
1257
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1258
+ HydrogenReactAddToCartBtn,
1259
+ {
1260
+ addToCartBtnText,
1261
+ addToCartCallback,
1262
+ disabled,
1263
+ linesToAdd,
1264
+ moneyData
1265
+ }
1266
+ );
1267
+ }
1268
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1269
+ HydrogenAddToCartBtn,
1270
+ {
1271
+ addToCartBtnText,
1272
+ addToCartCallback,
1273
+ disabled,
1274
+ linesToAdd,
1275
+ moneyData
1276
+ }
1277
+ );
1278
+ };
1279
+
1280
+ // src/components/ProductPrice/ProductPrice.tsx
1281
+ var import_hydrogen3 = require("@shopify/hydrogen");
1282
+
1283
+ // src/components/ProductPrice/ProductPrice.module.css
1284
+ var ProductPrice_default = {
1285
+ "rebuy-product-price": "ProductPrice_rebuy-product-price",
1286
+ "rebuy-product-price__current": "ProductPrice_rebuy-product-price__current",
1287
+ "rebuy-product-price__current--sale": "ProductPrice_rebuy-product-price__current--sale",
1288
+ "rebuy-product-price__compare-at": "ProductPrice_rebuy-product-price__compare-at"
1289
+ };
1290
+
1291
+ // src/components/ProductPrice/ProductPrice.tsx
1292
+ var import_jsx_runtime7 = require("react/jsx-runtime");
1293
+ var RebuyProductPrice = ({ selectedVariant, settingsDiscount }) => {
1294
+ if (!selectedVariant) return null;
1295
+ const { compareAtPriceV2: compareAtPrice, priceV2: price } = selectedVariant;
1296
+ const isDiscounted = (price2, compareAtPrice2) => Number(compareAtPrice2?.amount) > Number(price2?.amount);
1297
+ const currentPriceIsOnSale = compareAtPrice && isDiscounted(price, compareAtPrice);
1298
+ const CompareAtPrice = ({ data: compareAtPriceData }) => {
1299
+ return compareAtPriceData && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
1300
+ import_hydrogen3.Money,
1301
+ {
1302
+ as: "span",
1303
+ className: ProductPrice_default["rebuy-product-price__compare-at"],
1304
+ data: compareAtPriceData,
1305
+ withoutTrailingZeros: true
1306
+ }
1307
+ );
1308
+ };
1309
+ return price && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: ProductPrice_default["rebuy-product-price"], children: [
1310
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
1311
+ import_hydrogen3.Money,
1312
+ {
1313
+ as: "span",
1314
+ className: `${ProductPrice_default["rebuy-product-price__current"]} ${currentPriceIsOnSale ? ProductPrice_default["rebuy-product-price__current--sale"] : ""}`,
1315
+ data: price,
1316
+ withoutTrailingZeros: true
1317
+ }
1318
+ ),
1319
+ currentPriceIsOnSale && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(CompareAtPrice, { data: compareAtPrice })
1320
+ ] });
1321
+ };
1322
+
1323
+ // src/components/QuantityInput/QuantityInput.tsx
1324
+ var import_react8 = require("react");
1325
+
1326
+ // src/components/QuantityInput/QuantityInput.module.css
1327
+ var QuantityInput_default = {
1328
+ "rebuy-quantity__container": "QuantityInput_rebuy-quantity__container",
1329
+ "rebuy-quantity__select": "QuantityInput_rebuy-quantity__select"
1330
+ };
1331
+
1332
+ // src/components/QuantityInput/QuantityInput.tsx
1333
+ var import_jsx_runtime8 = require("react/jsx-runtime");
1334
+ var QuantityInput = ({
1335
+ defaultQuantity = 1,
1336
+ handleSelectedQuantity,
1337
+ maxValue = 10,
1338
+ minValue = 1
1339
+ }) => {
1340
+ const [quantity, setQuantity] = (0, import_react8.useState)(defaultQuantity);
1341
+ const handleChange = (event) => {
1342
+ const newValue = parseInt(event.target.value, 10);
1343
+ setQuantity(newValue);
1344
+ if (handleSelectedQuantity) {
1345
+ handleSelectedQuantity(newValue);
1346
+ }
1347
+ };
1348
+ const quantityOptions = Array.from({ length: maxValue - minValue + 1 }, (_, i) => minValue + i);
1349
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: QuantityInput_default["rebuy-quantity__container"], children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
1350
+ "select",
1351
+ {
1352
+ "aria-label": "Product quantity",
1353
+ className: QuantityInput_default["rebuy-quantity__select"],
1354
+ onChange: handleChange,
1355
+ value: quantity,
1356
+ children: quantityOptions.map((value) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value, children: value }, `quantity-${value}`))
1357
+ }
1358
+ ) });
1359
+ };
1360
+
1361
+ // src/components/Title/Title.tsx
1362
+ var import_clsx = __toESM(require("clsx"), 1);
1363
+
1364
+ // src/components/Title/Title.module.css
1365
+ var Title_default = {
1366
+ "rebuy-title": "Title_rebuy-title"
1367
+ };
1368
+
1369
+ // src/components/Title/Title.tsx
1370
+ var import_jsx_runtime9 = require("react/jsx-runtime");
1371
+ var Title = ({ className, level, style, text }) => {
1372
+ const combinedClassName = (0, import_clsx.default)(Title_default["rebuy-title"], className);
1373
+ switch (level) {
1374
+ case "h1":
1375
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h1", { className: combinedClassName, style, children: text });
1376
+ default:
1377
+ case "h2":
1378
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h2", { className: combinedClassName, style, children: text });
1379
+ case "h3":
1380
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h3", { className: combinedClassName, style, children: text });
1381
+ case "h4":
1382
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h4", { className: combinedClassName, style, children: text });
1383
+ case "h5":
1384
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h5", { className: combinedClassName, style, children: text });
1385
+ case "h6":
1386
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h6", { className: combinedClassName, style, children: text });
1387
+ }
1388
+ };
1389
+
1390
+ // src/components/VariantSelect/VariantSelect.tsx
1391
+ var import_clsx2 = __toESM(require("clsx"), 1);
1392
+ var import_react9 = require("react");
1393
+
1394
+ // src/components/VariantSelect/VariantSelect.module.css
1395
+ var VariantSelect_default = {
1396
+ "rebuy-variant__container": "VariantSelect_rebuy-variant__container",
1397
+ "rebuy-variant__select": "VariantSelect_rebuy-variant__select",
1398
+ "rebuy-variant__select-optgroup-label": "VariantSelect_rebuy-variant__select-optgroup-label",
1399
+ "rebuy-variant__select-option": "VariantSelect_rebuy-variant__select-option",
1400
+ "rebuy-variant__buttons": "VariantSelect_rebuy-variant__buttons",
1401
+ "rebuy-variant__button": "VariantSelect_rebuy-variant__button",
1402
+ "rebuy-variant__button--selected": "VariantSelect_rebuy-variant__button--selected"
1403
+ };
1404
+
1405
+ // src/components/VariantSelect/VariantSelect.tsx
1406
+ var import_jsx_runtime10 = require("react/jsx-runtime");
1407
+ var VariantSelect = ({ handleSelectedVariant, product, selectedId, style = "select" }) => {
1408
+ const [selectedVariantId, setSelectedVariantId] = (0, import_react9.useState)(selectedId || product.variants.nodes[0]?.id);
1409
+ (0, import_react9.useEffect)(() => {
1410
+ if (selectedId && selectedId !== selectedVariantId) {
1411
+ setSelectedVariantId(selectedId);
1412
+ }
1413
+ }, [selectedId, selectedVariantId]);
1414
+ const getOptionsLabel = (currentProduct) => {
1415
+ const firstVariantOptions = currentProduct.variants.nodes[0]?.selectedOptions;
1416
+ if (!firstVariantOptions || firstVariantOptions.length === 0) {
1417
+ return "Options";
1418
+ }
1419
+ return firstVariantOptions.map((option) => option.name).join(" / ");
1420
+ };
1421
+ const handleLocalVariantChange = (variantId) => {
1422
+ setSelectedVariantId(variantId);
1423
+ handleSelectedVariant(product, variantId);
1424
+ };
1425
+ if (!product?.variants?.nodes || product.variants.nodes.length <= 1) {
1426
+ return null;
1427
+ }
1428
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: VariantSelect_default["rebuy-variant__container"], children: style === "select" ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
1429
+ "select",
1430
+ {
1431
+ "aria-label": "Select variant",
1432
+ className: VariantSelect_default["rebuy-variant__select"],
1433
+ onChange: (e) => handleLocalVariantChange(e.target.value),
1434
+ value: selectedVariantId,
1435
+ children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
1436
+ "optgroup",
1437
+ {
1438
+ className: VariantSelect_default["rebuy-variant__select-optgroup-label"],
1439
+ label: getOptionsLabel(product),
1440
+ children: product.variants.nodes.map(({ id, title }) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
1441
+ "option",
1442
+ {
1443
+ className: VariantSelect_default["rebuy-variant__select-option"],
1444
+ value: id,
1445
+ children: title
1446
+ },
1447
+ `${id}-variant-option`
1448
+ ))
1449
+ }
1450
+ )
1451
+ }
1452
+ ) : /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: VariantSelect_default["rebuy-variant__buttons"], children: product.variants.nodes.map(({ id, title }) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
1453
+ "button",
1454
+ {
1455
+ "aria-pressed": id === selectedVariantId,
1456
+ className: (0, import_clsx2.default)(
1457
+ VariantSelect_default["rebuy-variant__button"],
1458
+ id === selectedVariantId && VariantSelect_default["rebuy-variant__button--selected"]
1459
+ ),
1460
+ onClick: () => handleLocalVariantChange(id),
1461
+ type: "button",
1462
+ children: title
1463
+ },
1464
+ `${id}-variant-button`
1465
+ )) }) });
1466
+ };
1467
+
1468
+ // src/components/ProductCard/ProductCard.module.css
1469
+ var ProductCard_default = {
1470
+ "rebuy-product-card__container": "ProductCard_rebuy-product-card__container",
1471
+ "rebuy-product-card": "ProductCard_rebuy-product-card",
1472
+ "rebuy-product-card__content": "ProductCard_rebuy-product-card__content",
1473
+ "rebuy-product-card__header": "ProductCard_rebuy-product-card__header",
1474
+ "rebuy-product-card__info": "ProductCard_rebuy-product-card__info",
1475
+ "rebuy-product-card__actions": "ProductCard_rebuy-product-card__actions",
1476
+ "rebuy-product-card__media-link": "ProductCard_rebuy-product-card__media-link",
1477
+ "rebuy-product-card__image": "ProductCard_rebuy-product-card__image",
1478
+ "rebuy-product-card__title": "ProductCard_rebuy-product-card__title",
1479
+ "rebuy-product-card__title-link": "ProductCard_rebuy-product-card__title-link",
1480
+ "rebuy-product-card__actions-variant-select": "ProductCard_rebuy-product-card__actions-variant-select",
1481
+ "rebuy-product-card__variant-select": "ProductCard_rebuy-product-card__variant-select",
1482
+ "rebuy-product-card__actions-quantity": "ProductCard_rebuy-product-card__actions-quantity",
1483
+ "rebuy-product-card__actions-button": "ProductCard_rebuy-product-card__actions-button",
1484
+ "rebuy-product-card__vendor": "ProductCard_rebuy-product-card__vendor",
1485
+ "rebuy-product-card__variant-title": "ProductCard_rebuy-product-card__variant-title",
1486
+ "rebuy-product-card__review": "ProductCard_rebuy-product-card__review",
1487
+ "rebuy-product-card__star-rating": "ProductCard_rebuy-product-card__star-rating",
1488
+ "rebuy-product-card__star-rating-value": "ProductCard_rebuy-product-card__star-rating-value",
1489
+ "rebuy-product-card__star-rating-background": "ProductCard_rebuy-product-card__star-rating-background",
1490
+ "rebuy-product-card__star-rating-foreground": "ProductCard_rebuy-product-card__star-rating-foreground",
1491
+ "rebuy-product-card__review-count": "ProductCard_rebuy-product-card__review-count",
1492
+ "rebuy-product-card__review-count-parenthesis": "ProductCard_rebuy-product-card__review-count-parenthesis",
1493
+ "rebuy-product-card__review-count-number": "ProductCard_rebuy-product-card__review-count-number",
1494
+ "rebuy-product-card__review-count-label": "ProductCard_rebuy-product-card__review-count-label",
1495
+ "rebuy-product-card__description": "ProductCard_rebuy-product-card__description"
1496
+ };
1497
+
1498
+ // src/components/ProductCard/ProductCard.tsx
1499
+ var import_jsx_runtime11 = require("react/jsx-runtime");
1500
+ var ProductCard = ({
1501
+ addToCartBtnText,
1502
+ addToCartCallback,
1503
+ isHydrogenReact,
1504
+ isInPopup,
1505
+ onPopupDismiss,
1506
+ product,
1507
+ productCardTitleLevel,
1508
+ settings = defaultProductCardSettings
1509
+ }) => {
1510
+ const [selectedVariant, setSelectedVariant] = (0, import_react11.useState)(product.variants.nodes[0]);
1511
+ const [selectedQuantity, setSelectedQuantity] = (0, import_react11.useState)(settings?.quantityInput?.default_quantity || 1);
1512
+ const displayImage = selectedVariant.image || product.featuredImage;
1513
+ const handleSelectedVariant = (product2, variant_id) => {
1514
+ const updatedVariant = product2.variants.nodes.find((variant) => variant.id === variant_id);
1515
+ if (updatedVariant) {
1516
+ setSelectedVariant(updatedVariant);
1517
+ }
1518
+ };
1519
+ const handleSelectedQuantity = (quantity) => {
1520
+ setSelectedQuantity(quantity);
1521
+ };
1522
+ const handleLinkClick = () => {
1523
+ if (isInPopup && onPopupDismiss) {
1524
+ onPopupDismiss();
1525
+ }
1526
+ };
1527
+ const showVariantTitle = settings?.productOptions?.show_variant_title && selectedVariant.title.toLowerCase() !== "default title";
1528
+ const showReviews = product.reviews && product?.reviews?.review_count && product?.reviews?.review_count > 0;
1529
+ const productReviewsRating = product.reviews?.star_rating;
1530
+ const showProductDescription = settings?.productOptions?.show_product_description === "show" && product.description !== "" && product.description !== null;
1531
+ const showVariantSelect = product?.variants.nodes.length > 1 && (settings?.productOptions?.show_variant_options === "default" || settings?.productOptions?.show_variant_options === "always");
1532
+ const showQuantityInput = settings?.quantityInput?.enabled && settings?.quantityInput?.max_value !== null && settings?.quantityInput?.min_value !== null;
1533
+ const cardLayout = settings?.layoutStyle || "grid";
1534
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card__container"], children: [
1535
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card"], "data-layout": cardLayout, children: [
1536
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1537
+ import_react10.Link,
1538
+ {
1539
+ "aria-label": `View ${product.title}`,
1540
+ className: ProductCard_default["rebuy-product-card__media-link"],
1541
+ onClick: handleLinkClick,
1542
+ rel: "nofollow",
1543
+ to: `/products/${product.handle}`,
1544
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1545
+ import_hydrogen4.Image,
1546
+ {
1547
+ alt: displayImage?.altText ?? `Picture of ${product.title}`,
1548
+ className: ProductCard_default["rebuy-product-card__image"],
1549
+ data: displayImage,
1550
+ sizes: "(max-width: 320px) 280px, (max-width: 768px) 720px, 1440px"
1551
+ }
1552
+ )
1553
+ }
1554
+ ) }),
1555
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card__info"], children: [
1556
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card__content"], children: [
1557
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card__header"], children: [
1558
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: ProductCard_default["rebuy-product-card__vendor"], children: product.vendor }),
1559
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1560
+ import_react10.Link,
1561
+ {
1562
+ "aria-label": `View ${product.title}`,
1563
+ className: ProductCard_default["rebuy-product-card__title-link"],
1564
+ onClick: handleLinkClick,
1565
+ rel: "nofollow",
1566
+ to: `/products/${product.handle}`,
1567
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1568
+ Title,
1569
+ {
1570
+ className: ProductCard_default["rebuy-product-card__title"],
1571
+ level: productCardTitleLevel,
1572
+ text: product.title
1573
+ }
1574
+ )
1575
+ }
1576
+ ),
1577
+ showVariantTitle && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: ProductCard_default["rebuy-product-card__variant-title"], children: selectedVariant.title })
1578
+ ] }),
1579
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1580
+ RebuyProductPrice,
1581
+ {
1582
+ selectedVariant,
1583
+ settingsDiscount: settings?.settingsDiscount
1584
+ }
1585
+ ),
1586
+ showReviews && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { "aria-label": "product star rating", className: ProductCard_default["rebuy-product-card__review"], children: [
1587
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("span", { className: ProductCard_default["rebuy-product-card__star-rating"], children: [
1588
+ productReviewsRating && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("span", { className: ProductCard_default["rebuy-product-card__star-rating-value"], children: [
1589
+ productReviewsRating,
1590
+ " stars out of 5 stars"
1591
+ ] }),
1592
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: ProductCard_default["rebuy-product-card__star-rating-background"] }),
1593
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1594
+ "span",
1595
+ {
1596
+ className: ProductCard_default["rebuy-product-card__star-rating-foreground"],
1597
+ style: productReviewsRating ? { width: productReviewsRating / 5 * 100 + "%" } : {},
1598
+ children: product.reviews && productReviewsRating && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
1599
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1600
+ "span",
1601
+ {
1602
+ className: ProductCard_default["rebuy-product-card__review-count-parenthesis"],
1603
+ children: "("
1604
+ }
1605
+ ),
1606
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: ProductCard_default["rebuy-product-card__review-count-number"], children: productReviewsRating.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") }),
1607
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: ProductCard_default["rebuy-product-card__review-count-label"], children: "Reviews" }),
1608
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1609
+ "span",
1610
+ {
1611
+ className: ProductCard_default["rebuy-product-card__review-count-parenthesis"],
1612
+ children: ")"
1613
+ }
1614
+ )
1615
+ ] })
1616
+ }
1617
+ )
1618
+ ] }),
1619
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: ProductCard_default["rebuy-product-card__review-count"], children: productReviewsRating })
1620
+ ] }),
1621
+ showProductDescription && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: ProductCard_default["rebuy-product-card__description"], children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { children: product.description }) })
1622
+ ] }),
1623
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: ProductCard_default["rebuy-product-card__actions"], children: [
1624
+ showVariantSelect && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1625
+ "div",
1626
+ {
1627
+ className: ProductCard_default["rebuy-product-card__actions-variant-select"],
1628
+ "data-layout": cardLayout,
1629
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1630
+ VariantSelect,
1631
+ {
1632
+ handleSelectedVariant,
1633
+ product,
1634
+ selectedId: selectedVariant.id,
1635
+ style: settings?.variantSelector
1636
+ }
1637
+ )
1638
+ }
1639
+ ),
1640
+ showQuantityInput && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: ProductCard_default["rebuy-product-card__actions-quantity"], children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1641
+ QuantityInput,
1642
+ {
1643
+ defaultQuantity: settings?.quantityInput?.default_quantity,
1644
+ handleSelectedQuantity,
1645
+ maxValue: settings?.quantityInput?.max_value,
1646
+ minValue: settings?.quantityInput?.min_value
1647
+ }
1648
+ ) }),
1649
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: ProductCard_default["rebuy-product-card__actions-button"], children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1650
+ AddToCartBtn,
1651
+ {
1652
+ addToCartBtnText,
1653
+ addToCartCallback,
1654
+ isHydrogenReact,
1655
+ quantity: selectedQuantity,
1656
+ selectedVariants: [selectedVariant]
1657
+ }
1658
+ ) })
1659
+ ] })
1660
+ ] })
1661
+ ] }),
1662
+ showVariantSelect && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: ProductCard_default["rebuy-product-card__variant-select"], "data-layout": cardLayout, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
1663
+ VariantSelect,
1664
+ {
1665
+ handleSelectedVariant,
1666
+ product,
1667
+ selectedId: selectedVariant.id,
1668
+ style: settings?.variantSelector
1669
+ }
1670
+ ) })
1671
+ ] });
1672
+ };
1673
+
1674
+ // src/hooks/titleLevel.tsx
1675
+ var getTitleLevel = (level, decreaseLevel = false) => {
1676
+ switch (level) {
1677
+ case "h1":
1678
+ if (decreaseLevel) {
1679
+ return "h2" /* H2 */;
1680
+ }
1681
+ return "h1" /* H1 */;
1682
+ case "h2":
1683
+ if (decreaseLevel) {
1684
+ return "h3" /* H3 */;
1685
+ }
1686
+ return "h2" /* H2 */;
1687
+ case "h3":
1688
+ if (decreaseLevel) {
1689
+ return "h4" /* H4 */;
1690
+ }
1691
+ return "h3" /* H3 */;
1692
+ case "h4":
1693
+ if (decreaseLevel) {
1694
+ return "h5" /* H5 */;
1695
+ }
1696
+ return "h4" /* H4 */;
1697
+ case "h5":
1698
+ if (decreaseLevel) {
1699
+ return "h6" /* H6 */;
1700
+ }
1701
+ return "h5" /* H5 */;
1702
+ case "h6":
1703
+ if (decreaseLevel) {
1704
+ return "h6" /* H6 */;
1705
+ }
1706
+ return "h6" /* H6 */;
1707
+ default:
1708
+ return "h2" /* H2 */;
1709
+ }
1710
+ };
1711
+
1712
+ // src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.module.css
1713
+ var RebuyCompleteTheLook_default = {
1714
+ container: "RebuyCompleteTheLook_container",
1715
+ productGrid: "RebuyCompleteTheLook_productGrid",
1716
+ productItem: "RebuyCompleteTheLook_productItem"
1717
+ };
1718
+
1719
+ // src/widgets/RebuyCompleteTheLook/RebuyCompleteTheLook.tsx
1720
+ var import_jsx_runtime12 = require("react/jsx-runtime");
1721
+ var RebuyCompleteTheLook = (props) => {
1722
+ const {
1723
+ addToCartBtnText = "Add to cart",
1724
+ addToCartCallback,
1725
+ customTitle = `These pair with ${props.product?.title}`,
1726
+ customTitleLevel = "h2",
1727
+ customTitleStyle,
1728
+ products = []
1729
+ } = props;
1730
+ if (products.length === 0) {
1731
+ console.log("RebuyCompleteTheLook: No products found");
1732
+ return null;
1733
+ }
1734
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("section", { className: RebuyCompleteTheLook_default.container, children: [
1735
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Title, { level: getTitleLevel(customTitleLevel), style: customTitleStyle, text: customTitle }),
1736
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("ul", { className: RebuyCompleteTheLook_default.productGrid, children: products.map((product) => /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("li", { className: RebuyCompleteTheLook_default.productItem, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1737
+ ProductCard,
1738
+ {
1739
+ addToCartBtnText,
1740
+ addToCartCallback,
1741
+ isHydrogenReact: props.isHydrogenReact,
1742
+ product,
1743
+ productCardTitleLevel: getTitleLevel(customTitleLevel, true)
1744
+ }
1745
+ ) }, product.id)) })
1746
+ ] });
1747
+ };
1748
+
1749
+ // src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.tsx
1750
+ var import_react14 = require("react");
1751
+
1752
+ // src/utils/convertToRebuyProduct.tsx
1753
+ var convertToRebuyProduct = (isHydrogenReact, product) => {
1754
+ const mainProductVariants = isHydrogenReact ? product?.variants?.nodes?.map((variant) => {
1755
+ return {
1756
+ ...variant
1757
+ };
1758
+ }) || [] : product?.adjacentVariants.map((variant) => {
1759
+ return {
1760
+ availableForSale: variant.availableForSale,
1761
+ compareAtPriceV2: {
1762
+ amount: variant.compareAtPrice?.amount || "",
1763
+ currencyCode: variant.compareAtPrice?.currencyCode || "USD"
1764
+ },
1765
+ id: variant.id,
1766
+ image: {
1767
+ altText: variant.image?.altText || "",
1768
+ height: variant.image?.height || 100,
1769
+ id: variant.image?.id || "",
1770
+ url: variant.image?.url || "",
1771
+ width: variant.image?.width || 100
1772
+ },
1773
+ priceV2: {
1774
+ amount: variant.price.amount || "",
1775
+ currencyCode: variant.price.currencyCode || "USD"
1776
+ },
1777
+ product: {
1778
+ handle: product.handle,
1779
+ id: product.id,
1780
+ title: product.title,
1781
+ vendor: product.vendor
1782
+ },
1783
+ selectedOptions: variant.selectedOptions,
1784
+ sku: variant.sku || "",
1785
+ title: variant.title || ""
1786
+ };
1787
+ }) || [];
1788
+ return isHydrogenReact ? {
1789
+ collections: {
1790
+ nodes: product?.collections.nodes.map((collection) => {
1791
+ return {
1792
+ handle: collection.handle
1793
+ };
1794
+ }) || []
1795
+ },
1796
+ compareAtPriceRange: {
1797
+ maxVariantCompareAtPrice: null,
1798
+ minVariantCompareAtPrice: null
1799
+ },
1800
+ description: product?.description || "",
1801
+ descriptionHtml: product?.descriptionHtml || "",
1802
+ featuredImage: {
1803
+ altText: product?.featuredImage?.altText || "",
1804
+ height: product?.featuredImage?.height || 100,
1805
+ id: product?.featuredImage?.id || "",
1806
+ url: product?.featuredImage?.url || "",
1807
+ width: product?.featuredImage?.width || 100
1808
+ },
1809
+ handle: product?.handle || "",
1810
+ id: product?.id || "",
1811
+ images: [{ altText: "", height: 100, id: "", url: "", width: 100 }],
1812
+ media: [],
1813
+ metafields: [],
1814
+ options: [],
1815
+ priceRange: product?.priceRange || {
1816
+ maxVariantPrice: { amount: "0", currencyCode: "USD" },
1817
+ minVariantPrice: { amount: "0", currencyCode: "USD" }
1818
+ },
1819
+ selected: true,
1820
+ selectedOptions: product?.selectedVariant?.selectedOptions?.reduce((acc, option) => {
1821
+ return { ...acc, [option.name]: option.value };
1822
+ }, {}) || {},
1823
+ selectedSellingPlan: {},
1824
+ selectedSellingPlanAllocation: {},
1825
+ selectedVariant: {
1826
+ availableForSale: product?.selectedVariant?.availableForSale || false,
1827
+ compareAtPriceV2: {
1828
+ amount: product?.selectedVariant?.compareAtPrice?.amount || "",
1829
+ currencyCode: product?.selectedVariant?.compareAtPrice?.currencyCode || "USD"
1830
+ },
1831
+ id: product?.selectedVariant?.id || "",
1832
+ image: {
1833
+ altText: product?.selectedVariant?.image?.altText || "",
1834
+ height: product?.selectedVariant?.image?.height || 100,
1835
+ id: product?.selectedVariant?.image?.id || "",
1836
+ url: product?.selectedVariant?.image?.url || "",
1837
+ width: product?.selectedVariant?.image?.width || 100
1838
+ },
1839
+ priceV2: {
1840
+ amount: product?.selectedVariant?.price.amount || "",
1841
+ currencyCode: product?.selectedVariant?.price.currencyCode || "USD"
1842
+ },
1843
+ product: {
1844
+ handle: product?.handle || "",
1845
+ id: product?.id || "",
1846
+ title: product?.title || "",
1847
+ vendor: product?.vendor || ""
1848
+ },
1849
+ selectedOptions: product?.selectedVariant?.selectedOptions || [],
1850
+ sku: product?.selectedVariant?.sku || "",
1851
+ title: product?.selectedVariant?.title || ""
1852
+ },
1853
+ sellingPlanGroups: [],
1854
+ seo: {
1855
+ description: product?.seo?.description || "",
1856
+ title: product?.seo?.title || ""
1857
+ },
1858
+ title: product?.title || "",
1859
+ variants: {
1860
+ nodes: mainProductVariants
1861
+ },
1862
+ vendor: product?.vendor || ""
1863
+ } : {
1864
+ collections: {
1865
+ nodes: []
1866
+ },
1867
+ compareAtPriceRange: {
1868
+ maxVariantCompareAtPrice: null,
1869
+ minVariantCompareAtPrice: null
1870
+ },
1871
+ description: product?.description || "",
1872
+ descriptionHtml: product?.descriptionHtml || "",
1873
+ featuredImage: {
1874
+ altText: product?.selectedOrFirstAvailableVariant?.image?.altText || "",
1875
+ height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,
1876
+ id: product?.selectedOrFirstAvailableVariant?.image?.id || "",
1877
+ url: product?.selectedOrFirstAvailableVariant?.image?.url || "",
1878
+ width: product?.selectedOrFirstAvailableVariant?.image?.width || 100
1879
+ },
1880
+ handle: product?.handle || "",
1881
+ id: product?.id || "",
1882
+ images: [
1883
+ {
1884
+ altText: product?.selectedOrFirstAvailableVariant?.image?.altText || "",
1885
+ height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,
1886
+ id: product?.selectedOrFirstAvailableVariant?.image?.id || "",
1887
+ url: product?.selectedOrFirstAvailableVariant?.image?.url || "",
1888
+ width: product?.selectedOrFirstAvailableVariant?.image?.width || 100
1889
+ }
1890
+ ],
1891
+ media: [],
1892
+ metafields: [],
1893
+ options: [],
1894
+ priceRange: product?.priceRange || {
1895
+ maxVariantPrice: { amount: "0", currencyCode: "USD" },
1896
+ minVariantPrice: { amount: "0", currencyCode: "USD" }
1897
+ },
1898
+ selected: true,
1899
+ selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions?.reduce((acc, option) => {
1900
+ return { ...acc, [option.name]: option.value };
1901
+ }, {}) || {},
1902
+ selectedSellingPlan: {},
1903
+ selectedSellingPlanAllocation: {},
1904
+ selectedVariant: {
1905
+ availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,
1906
+ compareAtPriceV2: {
1907
+ amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || "",
1908
+ currencyCode: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || "USD"
1909
+ },
1910
+ id: product?.selectedOrFirstAvailableVariant?.id || "",
1911
+ image: {
1912
+ altText: product?.selectedOrFirstAvailableVariant?.image?.altText || "",
1913
+ height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,
1914
+ id: product?.selectedOrFirstAvailableVariant?.image?.id || "",
1915
+ url: product?.selectedOrFirstAvailableVariant?.image?.url || "",
1916
+ width: product?.selectedOrFirstAvailableVariant?.image?.width || 100
1917
+ },
1918
+ priceV2: {
1919
+ amount: product?.selectedOrFirstAvailableVariant?.price.amount || "",
1920
+ currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || "USD"
1921
+ },
1922
+ product: {
1923
+ handle: product?.handle || "",
1924
+ id: product?.id || "",
1925
+ title: product?.title || "",
1926
+ vendor: product?.vendor || ""
1927
+ },
1928
+ selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],
1929
+ sku: product?.selectedOrFirstAvailableVariant?.sku || "",
1930
+ title: product?.selectedOrFirstAvailableVariant?.title || ""
1931
+ },
1932
+ sellingPlanGroups: [],
1933
+ seo: {
1934
+ description: null,
1935
+ title: null
1936
+ },
1937
+ title: product?.title || "",
1938
+ variants: {
1939
+ nodes: [
1940
+ {
1941
+ availableForSale: product?.selectedOrFirstAvailableVariant?.availableForSale || false,
1942
+ compareAtPriceV2: {
1943
+ amount: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.amount || "",
1944
+ currencyCode: product?.selectedOrFirstAvailableVariant?.compareAtPrice?.currencyCode || "USD"
1945
+ },
1946
+ id: product?.selectedOrFirstAvailableVariant?.id || "",
1947
+ image: {
1948
+ altText: product?.selectedOrFirstAvailableVariant?.image?.altText || "",
1949
+ height: product?.selectedOrFirstAvailableVariant?.image?.height || 100,
1950
+ id: product?.selectedOrFirstAvailableVariant?.image?.id || "",
1951
+ url: product?.selectedOrFirstAvailableVariant?.image?.url || "",
1952
+ width: product?.selectedOrFirstAvailableVariant?.image?.width || 100
1953
+ },
1954
+ priceV2: {
1955
+ amount: product?.selectedOrFirstAvailableVariant?.price.amount || "",
1956
+ currencyCode: product?.selectedOrFirstAvailableVariant?.price.currencyCode || "USD"
1957
+ },
1958
+ product: {
1959
+ handle: product?.handle || "",
1960
+ id: product?.id || "",
1961
+ title: product?.title || "",
1962
+ vendor: product?.vendor || ""
1963
+ },
1964
+ selectedOptions: product?.selectedOrFirstAvailableVariant?.selectedOptions || [],
1965
+ sku: product?.selectedOrFirstAvailableVariant?.sku || "",
1966
+ title: product?.selectedOrFirstAvailableVariant?.title || ""
1967
+ },
1968
+ ...mainProductVariants
1969
+ ]
1970
+ },
1971
+ vendor: product?.vendor || ""
1972
+ };
1973
+ };
1974
+
1975
+ // src/widgets/RebuyDynamicBundleProducts/BundleImages.tsx
1976
+ var import_react12 = require("@remix-run/react");
1977
+ var import_hydrogen5 = require("@shopify/hydrogen");
1978
+ var import_react13 = require("react");
1979
+
1980
+ // src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.module.css
1981
+ var RebuyDynamicBundleProducts_default = {
1982
+ container: "RebuyDynamicBundleProducts_container",
1983
+ addCartBtnContainer: "RebuyDynamicBundleProducts_addCartBtnContainer",
1984
+ bundleContainer: "RebuyDynamicBundleProducts_bundleContainer",
1985
+ select: "RebuyDynamicBundleProducts_select",
1986
+ bundleItemRowContainer: "RebuyDynamicBundleProducts_bundleItemRowContainer",
1987
+ unselected: "RebuyDynamicBundleProducts_unselected",
1988
+ bundleItemRow: "RebuyDynamicBundleProducts_bundleItemRow",
1989
+ bundleItemInput: "RebuyDynamicBundleProducts_bundleItemInput",
1990
+ bundleItemLabel: "RebuyDynamicBundleProducts_bundleItemLabel",
1991
+ bundleImages: "RebuyDynamicBundleProducts_bundleImages",
1992
+ bundleImage: "RebuyDynamicBundleProducts_bundleImage",
1993
+ "fade-in": "RebuyDynamicBundleProducts_fade-in",
1994
+ bundleImageDelimiter: "RebuyDynamicBundleProducts_bundleImageDelimiter",
1995
+ compareAtPrice: "RebuyDynamicBundleProducts_compareAtPrice"
1996
+ };
1997
+
1998
+ // src/widgets/RebuyDynamicBundleProducts/BundleImages.tsx
1999
+ var import_jsx_runtime13 = require("react/jsx-runtime");
2000
+ var BundleImages = ({ products }) => {
2001
+ const selected = products.filter((product) => product.selected);
2002
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("ul", { className: RebuyDynamicBundleProducts_default.bundleImages, children: products.map((product, index) => {
2003
+ const image = product.selectedVariant?.image;
2004
+ const productImage = image ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
2005
+ import_hydrogen5.Image,
2006
+ {
2007
+ alt: image.altText || `Picture of ${product.title}`,
2008
+ className: RebuyDynamicBundleProducts_default.bundleImage,
2009
+ data: image,
2010
+ height: 80,
2011
+ title: product.title,
2012
+ width: 80
2013
+ }
2014
+ ) : (
2015
+ // No image defined
2016
+ product.title
2017
+ );
2018
+ const showDelimiter = selected[0]?.id !== product.id;
2019
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react13.Fragment, { children: product.selected && /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_jsx_runtime13.Fragment, { children: [
2020
+ showDelimiter && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("li", { className: RebuyDynamicBundleProducts_default.bundleImageDelimiter, children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("span", { children: "+" }) }),
2021
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("li", { className: "flex items-center", children: product.default ? (
2022
+ // Already on product page
2023
+ productImage
2024
+ ) : (
2025
+ // Link to product
2026
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react12.Link, { title: product.title, to: `/products/${product.handle}`, children: productImage })
2027
+ ) })
2028
+ ] }) }, product.id + "-BundleImages-" + index);
2029
+ }) });
2030
+ };
2031
+
2032
+ // src/widgets/RebuyDynamicBundleProducts/Select.tsx
2033
+ var import_jsx_runtime14 = require("react/jsx-runtime");
2034
+ var Select = ({ onSelectVariant, product }) => {
2035
+ const getOptionsLabel = (product2) => {
2036
+ const options = product2.variants.nodes[0].selectedOptions;
2037
+ const optionsFromKeys = options ? Object.keys(options[0]) : [];
2038
+ const optionsFromValues = options ? options.map((option) => option.name) : [];
2039
+ const useValues = optionsFromKeys.every((key) => ["name", "value"].includes(key));
2040
+ return (useValues ? optionsFromValues : optionsFromKeys).join(" / ");
2041
+ };
2042
+ return product && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
2043
+ "select",
2044
+ {
2045
+ "aria-label": "select variant",
2046
+ className: RebuyDynamicBundleProducts_default.select,
2047
+ onChange: (e) => onSelectVariant(product, e.target.value),
2048
+ value: product.selectedVariant.id,
2049
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("optgroup", { label: getOptionsLabel(product), children: product.variants.nodes.map(({ id, title }) => /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("option", { value: id, children: title }, id + "-BundleVariant")) })
2050
+ }
2051
+ );
2052
+ };
2053
+
2054
+ // src/widgets/RebuyDynamicBundleProducts/BundleSelection.tsx
2055
+ var import_jsx_runtime15 = require("react/jsx-runtime");
2056
+ var BundleSelection = ({ onSelectVariant, onToggleBundleItem, products }) => {
2057
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("ul", { children: products.map((product, index) => {
2058
+ const { availableForSale } = product.selectedVariant;
2059
+ const isOutOfStock = !availableForSale;
2060
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
2061
+ "li",
2062
+ {
2063
+ className: `${RebuyDynamicBundleProducts_default.bundleItemRowContainer} ${!product.selected && RebuyDynamicBundleProducts_default.unselected}`,
2064
+ children: /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { className: RebuyDynamicBundleProducts_default.bundleItemRow, children: [
2065
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
2066
+ "input",
2067
+ {
2068
+ checked: product.selected && availableForSale,
2069
+ className: "mt-1 rounded-sm accent-black cursor-pointer",
2070
+ disabled: isOutOfStock,
2071
+ id: `${product.id}-toggle`,
2072
+ onChange: () => onToggleBundleItem(product),
2073
+ type: "checkbox",
2074
+ value: product.id
2075
+ }
2076
+ ),
2077
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { className: RebuyDynamicBundleProducts_default.bundleItemInput, children: [
2078
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("label", { className: RebuyDynamicBundleProducts_default.bundleItemLabel, htmlFor: `${product.id}-toggle`, children: [
2079
+ isOutOfStock && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("b", { children: "SOLD OUT" }),
2080
+ product.default && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("b", { children: "This item:" }),
2081
+ product.title,
2082
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(RebuyProductPrice, { selectedVariant: product.selectedVariant })
2083
+ ] }),
2084
+ product.variants.nodes.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Select, { onSelectVariant, product })
2085
+ ] })
2086
+ ] })
2087
+ },
2088
+ product.id + "-BundleSelection" + index
2089
+ );
2090
+ }) });
2091
+ };
2092
+
2093
+ // src/widgets/RebuyDynamicBundleProducts/BundlePrice.tsx
2094
+ var import_hydrogen6 = require("@shopify/hydrogen");
2095
+ var import_jsx_runtime16 = require("react/jsx-runtime");
2096
+ var BundlePrice = ({ products }) => {
2097
+ const isDisabled = products.filter((product) => product.selected).length < 1;
2098
+ const totalBundlePrice = () => {
2099
+ let total = 0;
2100
+ let currencyCode = "USD";
2101
+ for (const product of products) {
2102
+ if (product.selected && product.selectedVariant) {
2103
+ const { priceV2: price2 } = product.selectedVariant;
2104
+ total += Number(price2?.amount);
2105
+ currencyCode = price2?.currencyCode || "USD";
2106
+ }
2107
+ }
2108
+ return {
2109
+ amount: String(total),
2110
+ currencyCode
2111
+ };
2112
+ };
2113
+ const totalBundleCompareAtPrice = () => {
2114
+ let compareAtTotal = 0;
2115
+ let currencyCode = "USD";
2116
+ for (const product of products) {
2117
+ if (product.selected && product.selectedVariant) {
2118
+ const { compareAtPriceV2: compareAtPrice2, priceV2: price2 } = product.selectedVariant;
2119
+ currencyCode = price2?.currencyCode || "USD";
2120
+ compareAtTotal += Number((compareAtPrice2 || price2)?.amount);
2121
+ }
2122
+ }
2123
+ return {
2124
+ amount: String(compareAtTotal),
2125
+ currencyCode
2126
+ };
2127
+ };
2128
+ const isDiscounted = (price2, compareAtPrice2) => Number(compareAtPrice2?.amount) > Number(price2?.amount);
2129
+ const price = totalBundlePrice();
2130
+ const compareAtPrice = totalBundleCompareAtPrice();
2131
+ const CompareAtPrice = ({ data: compareAtPrice2 }) => {
2132
+ return compareAtPrice2 && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_hydrogen6.Money, { as: "span", className: RebuyDynamicBundleProducts_default.compareAtPrice, data: compareAtPrice2, withoutTrailingZeros: true });
2133
+ };
2134
+ return products.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("div", { className: "flex items-center flex-col", children: !isDisabled && /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("p", { className: "flex items-center gap-2 mb-2", children: [
2135
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("span", { children: "Total Price:" }),
2136
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_hydrogen6.Money, { as: "span", data: price, withoutTrailingZeros: true }),
2137
+ isDiscounted(price, compareAtPrice) && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(CompareAtPrice, { data: compareAtPrice })
2138
+ ] }) });
2139
+ };
2140
+
2141
+ // src/widgets/RebuyDynamicBundleProducts/RebuyDynamicBundleProducts.tsx
2142
+ var import_jsx_runtime17 = require("react/jsx-runtime");
2143
+ var RebuyDynamicBundleProducts = (props) => {
2144
+ const {
2145
+ addToCartBtnText = "Add to cart",
2146
+ addToCartCallback,
2147
+ customTitle = `These pair with ${props.product?.title}`,
2148
+ customTitleLevel = "h2",
2149
+ customTitleStyle,
2150
+ isHydrogenReact,
2151
+ product,
2152
+ products = []
2153
+ } = props;
2154
+ const [bundleProducts, setBundleProducts] = (0, import_react14.useState)([]);
2155
+ (0, import_react14.useEffect)(() => {
2156
+ const mainProduct = convertToRebuyProduct(isHydrogenReact || false, product);
2157
+ const formattedProducts = products.map((product2) => {
2158
+ return {
2159
+ ...product2,
2160
+ selected: true,
2161
+ selectedVariant: product2.variants.nodes[0]
2162
+ };
2163
+ });
2164
+ setBundleProducts([mainProduct, ...formattedProducts]);
2165
+ }, [product, products, isHydrogenReact]);
2166
+ const onToggleBundleItem = (0, import_react14.useCallback)(
2167
+ (product2) => {
2168
+ product2.selected = !product2.selected;
2169
+ setBundleProducts([...bundleProducts]);
2170
+ },
2171
+ [bundleProducts]
2172
+ );
2173
+ const onSelectVariant = (0, import_react14.useCallback)(
2174
+ (product2, variant_id) => {
2175
+ const variant = product2.variants.nodes.find(({ id }) => id === variant_id);
2176
+ if (variant) {
2177
+ product2.selectedVariant = variant;
2178
+ product2.selected = variant.availableForSale || false;
2179
+ setBundleProducts([...bundleProducts]);
2180
+ }
2181
+ },
2182
+ [bundleProducts]
2183
+ );
2184
+ if (products.length === 0) {
2185
+ console.log("RebuyDynamicBundleProducts: No products found");
2186
+ return null;
2187
+ }
2188
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("section", { className: RebuyDynamicBundleProducts_default.container, children: [
2189
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Title, { level: getTitleLevel(customTitleLevel), style: customTitleStyle, text: customTitle }),
2190
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("div", { className: RebuyDynamicBundleProducts_default.bundleContainer, children: [
2191
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(BundleImages, { products: bundleProducts }),
2192
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(BundlePrice, { products: bundleProducts }),
2193
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("div", { className: RebuyDynamicBundleProducts_default.addCartBtnContainer, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
2194
+ AddToCartBtn,
2195
+ {
2196
+ addToCartBtnText,
2197
+ addToCartCallback,
2198
+ disabled: bundleProducts.filter((product2) => product2.selected).length === 0,
2199
+ isHydrogenReact,
2200
+ selectedVariants: bundleProducts.filter((product2) => product2.selected).map((product2) => {
2201
+ return product2.selectedVariant;
2202
+ })
2203
+ }
2204
+ ) }),
2205
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
2206
+ BundleSelection,
2207
+ {
2208
+ onSelectVariant,
2209
+ onToggleBundleItem,
2210
+ products: bundleProducts
2211
+ }
2212
+ )
2213
+ ] })
2214
+ ] });
2215
+ };
2216
+
2217
+ // src/widgets/RebuyProductAddOns/RebuyProductAddOns.tsx
2218
+ var import_hydrogen_react3 = require("@shopify/hydrogen-react");
2219
+ var import_react16 = require("react");
2220
+
2221
+ // src/widgets/RebuyProductAddOns/RebuyProductAddOnCard.tsx
2222
+ var import_react15 = require("@remix-run/react");
2223
+ var import_hydrogen7 = require("@shopify/hydrogen");
2224
+
2225
+ // src/widgets/RebuyProductAddOns/RebuyProductAddOns.module.css
2226
+ var RebuyProductAddOns_default = {
2227
+ container: "RebuyProductAddOns_container",
2228
+ productAddOnsList: "RebuyProductAddOns_productAddOnsList",
2229
+ addOnCard: "RebuyProductAddOns_addOnCard",
2230
+ addOnCardContent: "RebuyProductAddOns_addOnCardContent",
2231
+ addOnCardInput: "RebuyProductAddOns_addOnCardInput",
2232
+ addOnCardContentImage: "RebuyProductAddOns_addOnCardContentImage",
2233
+ addOnCardOutOfStock: "RebuyProductAddOns_addOnCardOutOfStock",
2234
+ addOnCardTextContent: "RebuyProductAddOns_addOnCardTextContent",
2235
+ addOnCardLearnMore: "RebuyProductAddOns_addOnCardLearnMore",
2236
+ addCartBtnContainer: "RebuyProductAddOns_addCartBtnContainer",
2237
+ moneyContainer: "RebuyProductAddOns_moneyContainer"
2238
+ };
2239
+
2240
+ // src/widgets/RebuyProductAddOns/RebuyProductAddOnCard.tsx
2241
+ var import_jsx_runtime18 = require("react/jsx-runtime");
2242
+ var RebuyProductAddOnCard = ({
2243
+ handleChange,
2244
+ learnMoreText,
2245
+ outOfStockText,
2246
+ product,
2247
+ titleLevel
2248
+ }) => {
2249
+ const { availableForSale, image } = product.selectedVariant || {};
2250
+ return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("label", { className: RebuyProductAddOns_default.addOnCard, htmlFor: product.id, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("div", { className: RebuyProductAddOns_default.addOnCardContent, children: [
2251
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
2252
+ "input",
2253
+ {
2254
+ checked: Boolean(product.selected),
2255
+ className: RebuyProductAddOns_default.addOnCardInput,
2256
+ disabled: !product.variants.nodes[0].availableForSale,
2257
+ id: product.id,
2258
+ name: product.title,
2259
+ onChange: (event) => handleChange(event, product),
2260
+ type: "checkbox",
2261
+ value: ""
2262
+ }
2263
+ ),
2264
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("div", { className: RebuyProductAddOns_default.addOnCardContentImage, children: image && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
2265
+ import_hydrogen7.Image,
2266
+ {
2267
+ alt: image.altText || `Picture of ${product.title}`,
2268
+ data: image,
2269
+ height: 150,
2270
+ width: 300
2271
+ }
2272
+ ) }),
2273
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("div", { className: RebuyProductAddOns_default.addOnCardTextContent, children: [
2274
+ !availableForSale && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("p", { className: RebuyProductAddOns_default.addOnCardOutOfStock, children: outOfStockText }),
2275
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Title, { level: titleLevel, text: product.title }),
2276
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(RebuyProductPrice, { selectedVariant: product.selectedVariant }),
2277
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_react15.Link, { className: RebuyProductAddOns_default.addOnCardLearnMore, to: `/products/${product.handle}`, children: learnMoreText })
2278
+ ] })
2279
+ ] }) });
2280
+ };
2281
+
2282
+ // src/widgets/RebuyProductAddOns/RebuyProductAddOns.tsx
2283
+ var import_jsx_runtime19 = require("react/jsx-runtime");
2284
+ var RebuyProductAddOns = (props) => {
2285
+ const {
2286
+ addToCartCallback,
2287
+ customTitle = `These pair with ${props.product?.title}`,
2288
+ customTitleLevel = "h2",
2289
+ customTitleStyle,
2290
+ includeMainProduct = false,
2291
+ isHydrogenReact,
2292
+ learnMoreText = "Learn more",
2293
+ outOfStockText = "Out of stock",
2294
+ product,
2295
+ products = [],
2296
+ addToCartBtnText = "Add to cart",
2297
+ subtotalText = "Add-ons Subtotal: ",
2298
+ withProductText = `With ${product?.title}: `
2299
+ } = props;
2300
+ const [addedItems, setAddedItems] = (0, import_react16.useState)(products);
2301
+ const [subtotalWithProduct, setSubtotalWithProduct] = (0, import_react16.useState)();
2302
+ const [subtotalWithOutProduct, setSubtotalWithOutProduct] = (0, import_react16.useState)();
2303
+ (0, import_react16.useEffect)(() => {
2304
+ let initialTotal = 0;
2305
+ let currencyCode = "USD";
2306
+ products.map((product2) => {
2307
+ product2.selectedVariant = product2.variants.nodes[0];
2308
+ product2.selected = true;
2309
+ if (product2.selectedVariant?.priceV2) {
2310
+ initialTotal += Number(product2.selectedVariant.priceV2.amount);
2311
+ currencyCode = product2.selectedVariant.priceV2.currencyCode || "USD";
2312
+ }
2313
+ });
2314
+ setSubtotalWithProduct({
2315
+ amount: String(initialTotal),
2316
+ currencyCode
2317
+ });
2318
+ setSubtotalWithOutProduct({
2319
+ amount: String(
2320
+ initialTotal - Number(
2321
+ isHydrogenReact ? product?.selectedVariant?.price.amount : product?.selectedOrFirstAvailableVariant?.price.amount
2322
+ )
2323
+ ),
2324
+ currencyCode
2325
+ });
2326
+ setAddedItems(products);
2327
+ if (includeMainProduct) {
2328
+ setAddedItems([convertToRebuyProduct(isHydrogenReact || false, product), ...products]);
2329
+ } else {
2330
+ setAddedItems(products);
2331
+ }
2332
+ }, [products, product, isHydrogenReact, includeMainProduct]);
2333
+ const handleChange = (0, import_react16.useCallback)(
2334
+ (event, product2) => {
2335
+ const newProducts = [...products];
2336
+ const productIndex = newProducts.findIndex((p) => p.id === product2.id);
2337
+ if (productIndex !== -1) {
2338
+ newProducts[productIndex] = {
2339
+ ...newProducts[productIndex],
2340
+ selected: event.target.checked
2341
+ };
2342
+ product2.selected = event.target.checked;
2343
+ if (event.target.checked) {
2344
+ setAddedItems((prev) => [...prev, product2]);
2345
+ } else {
2346
+ setAddedItems((prev) => prev.filter((item) => item.id !== product2.id));
2347
+ }
2348
+ }
2349
+ },
2350
+ [products]
2351
+ );
2352
+ (0, import_react16.useEffect)(() => {
2353
+ let total = 0;
2354
+ let currencyCode = "USD";
2355
+ addedItems.forEach((item) => {
2356
+ if (item.selected && item.selectedVariant?.priceV2) {
2357
+ total += Number(item.selectedVariant.priceV2.amount);
2358
+ currencyCode = item.selectedVariant.priceV2.currencyCode || "USD";
2359
+ }
2360
+ });
2361
+ setSubtotalWithProduct({
2362
+ amount: String(total),
2363
+ currencyCode
2364
+ });
2365
+ setSubtotalWithOutProduct({
2366
+ amount: String(
2367
+ total - Number(
2368
+ isHydrogenReact ? product?.selectedVariant?.price.amount : product?.selectedOrFirstAvailableVariant?.price.amount
2369
+ )
2370
+ ),
2371
+ currencyCode
2372
+ });
2373
+ }, [addedItems, product, isHydrogenReact]);
2374
+ if (products.length === 0) {
2375
+ console.log("RebuyProductAddOns: No products found");
2376
+ return null;
2377
+ }
2378
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: RebuyProductAddOns_default.container, children: [
2379
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Title, { level: getTitleLevel(customTitleLevel), style: customTitleStyle, text: customTitle }),
2380
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("ul", { className: RebuyProductAddOns_default.productAddOnsList, children: products.map((product2) => /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
2381
+ RebuyProductAddOnCard,
2382
+ {
2383
+ handleChange,
2384
+ learnMoreText,
2385
+ outOfStockText,
2386
+ product: product2,
2387
+ titleLevel: getTitleLevel(customTitleLevel, true)
2388
+ }
2389
+ ) }, product2.id)) }),
2390
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: RebuyProductAddOns_default.productAddOnsFooter, children: [
2391
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: RebuyProductAddOns_default.moneyContainer, children: [
2392
+ subtotalText,
2393
+ subtotalWithOutProduct && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_hydrogen_react3.Money, { data: subtotalWithOutProduct, withoutTrailingZeros: true })
2394
+ ] }),
2395
+ includeMainProduct && /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)("div", { className: RebuyProductAddOns_default.moneyContainer, children: [
2396
+ withProductText,
2397
+ subtotalWithProduct && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_hydrogen_react3.Money, { data: subtotalWithProduct, withoutTrailingZeros: true })
2398
+ ] }),
2399
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("div", { className: RebuyProductAddOns_default.addCartBtnContainer, children: includeMainProduct ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
2400
+ AddToCartBtn,
2401
+ {
2402
+ addToCartBtnText,
2403
+ addToCartCallback,
2404
+ disabled: addedItems.length === 0,
2405
+ isHydrogenReact,
2406
+ moneyData: subtotalWithProduct,
2407
+ selectedVariants: addedItems.map((item) => item.selectedVariant)
2408
+ }
2409
+ ) : /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
2410
+ AddToCartBtn,
2411
+ {
2412
+ addToCartBtnText,
2413
+ addToCartCallback,
2414
+ disabled: addedItems.length === 0,
2415
+ isHydrogenReact,
2416
+ moneyData: subtotalWithOutProduct,
2417
+ selectedVariants: addedItems.map((item) => item.selectedVariant)
2418
+ }
2419
+ ) })
2420
+ ] })
2421
+ ] });
2422
+ };
2423
+
2424
+ // src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.module.css
2425
+ var RebuyProductRecommendations_default = {
2426
+ container: "RebuyProductRecommendations_container",
2427
+ productGrid: "RebuyProductRecommendations_productGrid"
2428
+ };
2429
+
2430
+ // src/widgets/RebuyProductRecommendations/RebuyProductRecommendations.tsx
2431
+ var import_jsx_runtime20 = require("react/jsx-runtime");
2432
+ var RebuyProductRecommendations = (props) => {
2433
+ const {
2434
+ addToCartBtnText = "Add to cart",
2435
+ addToCartCallback,
2436
+ customTitle = `These pair with ${props.product?.title}`,
2437
+ customTitleLevel = "h2",
2438
+ customTitleStyle,
2439
+ products = []
2440
+ } = props;
2441
+ if (products.length === 0) {
2442
+ console.log("RebuyProductRecommendations: No products found");
2443
+ return null;
2444
+ }
2445
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)("section", { className: RebuyProductRecommendations_default.container, children: [
2446
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Title, { level: getTitleLevel(customTitleLevel), style: customTitleStyle, text: customTitle }),
2447
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("ul", { className: RebuyProductRecommendations_default.productGrid, children: products.map((product) => /* @__PURE__ */ (0, import_jsx_runtime20.jsx)("li", { className: RebuyProductRecommendations_default.productItem, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
2448
+ ProductCard,
2449
+ {
2450
+ addToCartBtnText,
2451
+ addToCartCallback,
2452
+ isHydrogenReact: props.isHydrogenReact,
2453
+ product,
2454
+ productCardTitleLevel: getTitleLevel(customTitleLevel, true)
2455
+ }
2456
+ ) }, product.id)) })
2457
+ ] });
2458
+ };
2459
+
2460
+ // src/widgets/RebuyWidget/RebuyWidget.tsx
2461
+ var import_rebuy3 = require("@rebuy/rebuy");
2462
+ var Utilities5 = __toESM(require("@rebuy/rebuy/utilities"), 1);
2463
+ var import_hydrogen8 = require("@shopify/hydrogen");
2464
+ var import_react21 = require("react");
2465
+
2466
+ // src/assets/Close.tsx
2467
+ var import_jsx_runtime21 = require("react/jsx-runtime");
2468
+ var Close = () => {
2469
+ return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("svg", { height: "1em", viewBox: "0 0 352 512", width: "1em", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)("path", { d: "M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.19 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.19 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z" }) });
2470
+ };
2471
+
2472
+ // src/hooks/useBreakpoint.ts
2473
+ var import_react17 = require("react");
2474
+ var useBreakpoint = (settings) => {
2475
+ const [breakpoint, setBreakpoint] = (0, import_react17.useState)("medium");
2476
+ (0, import_react17.useEffect)(() => {
2477
+ if (!settings?.breakpoints) return;
2478
+ const handleResize = () => {
2479
+ const width = window.innerWidth;
2480
+ if (width <= settings.breakpoints.medium.max) {
2481
+ if (width >= settings.breakpoints.medium.min) {
2482
+ setBreakpoint("medium");
2483
+ } else {
2484
+ setBreakpoint("small");
2485
+ }
2486
+ } else {
2487
+ setBreakpoint("large");
2488
+ }
2489
+ };
2490
+ handleResize();
2491
+ const debounceDelay = 150;
2492
+ let timeoutId;
2493
+ const debouncedHandleResize = () => {
2494
+ clearTimeout(timeoutId);
2495
+ timeoutId = setTimeout(handleResize, debounceDelay);
2496
+ };
2497
+ window.addEventListener("resize", debouncedHandleResize);
2498
+ return () => {
2499
+ window.removeEventListener("resize", debouncedHandleResize);
2500
+ clearTimeout(timeoutId);
2501
+ };
2502
+ }, [settings]);
2503
+ return breakpoint;
2504
+ };
2505
+
2506
+ // src/hooks/usePopupTrigger.tsx
2507
+ var import_react18 = require("react");
2508
+ var usePopupTrigger = (settings, popupTriggerId, widgetId, popupShownOnce, showPopup, setShowPopup, setPopupShownOnce) => {
2509
+ const delayInMs = settings?.display_type === "popup" ? (settings?.popup_delay || 0) * 1e3 : 0;
2510
+ const popupTrigger = settings?.popup_trigger;
2511
+ const showPopupWithDelay = (0, import_react18.useCallback)(() => {
2512
+ if (!settings || settings.display_type !== "popup") return;
2513
+ setTimeout(() => {
2514
+ setShowPopup(true);
2515
+ setPopupShownOnce(true);
2516
+ }, delayInMs);
2517
+ }, [delayInMs, setShowPopup, setPopupShownOnce, settings]);
2518
+ (0, import_react18.useEffect)(() => {
2519
+ if (!settings || settings.display_type !== "popup" || popupTrigger !== "load" || popupShownOnce) return;
2520
+ const timer = setTimeout(() => {
2521
+ setShowPopup(true);
2522
+ setPopupShownOnce(true);
2523
+ }, delayInMs);
2524
+ return () => clearTimeout(timer);
2525
+ }, [popupTrigger, popupShownOnce, delayInMs, setShowPopup, setPopupShownOnce, settings]);
2526
+ (0, import_react18.useEffect)(() => {
2527
+ if (!settings || settings.display_type !== "popup" || popupTrigger !== "add_to_cart" || !popupTriggerId) return;
2528
+ const selector = `#${popupTriggerId}`;
2529
+ const handleCartAdd = () => {
2530
+ if (!showPopup) {
2531
+ showPopupWithDelay();
2532
+ }
2533
+ };
2534
+ const observer = new MutationObserver(() => {
2535
+ const elements2 = document.querySelectorAll(selector);
2536
+ if (elements2.length) {
2537
+ elements2.forEach((el) => {
2538
+ el.addEventListener("click", handleCartAdd);
2539
+ });
2540
+ observer.disconnect();
2541
+ }
2542
+ });
2543
+ const elements = document.querySelectorAll(selector);
2544
+ if (elements.length) {
2545
+ elements.forEach((el) => {
2546
+ el.addEventListener("click", handleCartAdd);
2547
+ });
2548
+ } else {
2549
+ observer.observe(document.body, { childList: true, subtree: true });
2550
+ }
2551
+ return () => {
2552
+ observer.disconnect();
2553
+ document.querySelectorAll(selector).forEach((el) => {
2554
+ el.removeEventListener("click", handleCartAdd);
2555
+ });
2556
+ };
2557
+ }, [popupTrigger, popupTriggerId, showPopup, showPopupWithDelay, settings]);
2558
+ (0, import_react18.useEffect)(() => {
2559
+ if (!settings || settings.display_type !== "popup" || popupTrigger !== "submit") return;
2560
+ const selector = "form";
2561
+ const handleSubmit = () => {
2562
+ showPopupWithDelay();
2563
+ };
2564
+ const forms = document.querySelectorAll(selector);
2565
+ forms.forEach((form) => {
2566
+ form.addEventListener("submit", handleSubmit);
2567
+ });
2568
+ return () => {
2569
+ forms.forEach((form) => {
2570
+ form.removeEventListener("submit", handleSubmit);
2571
+ });
2572
+ };
2573
+ }, [popupTrigger, showPopupWithDelay, settings]);
2574
+ (0, import_react18.useEffect)(() => {
2575
+ if (!settings || settings.display_type !== "popup" || popupTrigger !== "exit") return;
2576
+ const handleExitIntent = (e) => {
2577
+ if (e.clientY <= 0 && !popupShownOnce) {
2578
+ showPopupWithDelay();
2579
+ }
2580
+ };
2581
+ const handleVisibilityChange = () => {
2582
+ if (document.visibilityState === "hidden" && !popupShownOnce) {
2583
+ const shouldShowOnFocus = true;
2584
+ localStorage.setItem(`rebuy-popup-pending-${widgetId}`, shouldShowOnFocus.toString());
2585
+ } else if (document.visibilityState === "visible") {
2586
+ const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);
2587
+ if (pendingPopup === "true" && !popupShownOnce) {
2588
+ showPopupWithDelay();
2589
+ localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);
2590
+ }
2591
+ }
2592
+ };
2593
+ document.addEventListener("mouseleave", handleExitIntent);
2594
+ document.addEventListener("visibilitychange", handleVisibilityChange);
2595
+ if (document.visibilityState === "visible") {
2596
+ const pendingPopup = localStorage.getItem(`rebuy-popup-pending-${widgetId}`);
2597
+ if (pendingPopup === "true" && !popupShownOnce) {
2598
+ showPopupWithDelay();
2599
+ localStorage.removeItem(`rebuy-popup-pending-${widgetId}`);
2600
+ }
2601
+ }
2602
+ return () => {
2603
+ document.removeEventListener("mouseleave", handleExitIntent);
2604
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
2605
+ };
2606
+ }, [popupTrigger, popupShownOnce, showPopupWithDelay, widgetId, settings]);
2607
+ };
2608
+
2609
+ // src/components/ProductCarousel/ProductCarousel.tsx
2610
+ var import_react19 = require("react");
2611
+
2612
+ // src/components/ProductCarousel/ProductCarousel.module.css
2613
+ var ProductCarousel_default = {
2614
+ "rebuy-carousel": "ProductCarousel_rebuy-carousel",
2615
+ "rebuy-carousel__container": "ProductCarousel_rebuy-carousel__container",
2616
+ "rebuy-carousel__slide": "ProductCarousel_rebuy-carousel__slide",
2617
+ "rebuy-carousel__controls": "ProductCarousel_rebuy-carousel__controls",
2618
+ "rebuy-carousel__prev": "ProductCarousel_rebuy-carousel__prev",
2619
+ "rebuy-carousel__next": "ProductCarousel_rebuy-carousel__next",
2620
+ "rebuy-carousel__pagination": "ProductCarousel_rebuy-carousel__pagination",
2621
+ "rebuy-carousel__dot": "ProductCarousel_rebuy-carousel__dot",
2622
+ "rebuy-carousel__grid": "ProductCarousel_rebuy-carousel__grid"
2623
+ };
2624
+
2625
+ // src/components/ProductCarousel/ProductCarousel.tsx
2626
+ var import_jsx_runtime22 = require("react/jsx-runtime");
2627
+ var ProductCarousel = ({
2628
+ addToCartBtnText,
2629
+ addToCartCallback,
2630
+ columns,
2631
+ isHydrogenReact,
2632
+ productCardTitleLevel,
2633
+ products,
2634
+ settings,
2635
+ showPagination = true
2636
+ }) => {
2637
+ const [currentSlide, setCurrentSlide] = (0, import_react19.useState)(0);
2638
+ const [totalSlides, setTotalSlides] = (0, import_react19.useState)(0);
2639
+ const [repeatedProducts, setRepeatedProducts] = (0, import_react19.useState)([]);
2640
+ (0, import_react19.useEffect)(() => {
2641
+ if (products.length === 0) {
2642
+ setRepeatedProducts([]);
2643
+ return;
2644
+ }
2645
+ const productsNeeded = Math.ceil(products.length / columns) * columns;
2646
+ let repeated = [...products];
2647
+ while (repeated.length < productsNeeded) {
2648
+ const remaining = productsNeeded - repeated.length;
2649
+ repeated = [...repeated, ...products.slice(0, remaining)];
2650
+ }
2651
+ setRepeatedProducts(repeated);
2652
+ }, [products, columns]);
2653
+ (0, import_react19.useEffect)(() => {
2654
+ if (repeatedProducts.length && columns) {
2655
+ setTotalSlides(Math.ceil(repeatedProducts.length / columns));
2656
+ }
2657
+ }, [repeatedProducts.length, columns]);
2658
+ const nextSlide = () => {
2659
+ setCurrentSlide((prev) => (prev + 1) % totalSlides);
2660
+ };
2661
+ const prevSlide = () => {
2662
+ setCurrentSlide((prev) => (prev - 1 + totalSlides) % totalSlides);
2663
+ };
2664
+ const goToSlide = (slideIndex) => {
2665
+ setCurrentSlide(slideIndex);
2666
+ };
2667
+ const slides = [];
2668
+ for (let i = 0; i < repeatedProducts.length; i += columns) {
2669
+ slides.push(repeatedProducts.slice(i, i + columns));
2670
+ }
2671
+ return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)("div", { className: ProductCarousel_default["rebuy-carousel"], children: [
2672
+ /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
2673
+ "div",
2674
+ {
2675
+ className: ProductCarousel_default["rebuy-carousel__container"],
2676
+ style: { transform: `translateX(-${currentSlide * 100}%)` },
2677
+ children: slides.map((slideProducts, index) => /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("div", { className: ProductCarousel_default["rebuy-carousel__slide"], children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("div", { className: ProductCarousel_default["rebuy-carousel__grid"], "data-columns": columns, children: slideProducts.map((product, productIndex) => /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
2678
+ ProductCard,
2679
+ {
2680
+ addToCartBtnText,
2681
+ addToCartCallback,
2682
+ isHydrogenReact,
2683
+ product,
2684
+ productCardTitleLevel,
2685
+ settings
2686
+ },
2687
+ `${product.id}-${index}-${productIndex}`
2688
+ )) }) }, index))
2689
+ }
2690
+ ),
2691
+ totalSlides > 1 && /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)("div", { className: ProductCarousel_default["rebuy-carousel__controls"], children: [
2692
+ /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("button", { className: ProductCarousel_default["rebuy-carousel__prev"], onClick: prevSlide, type: "button", children: "\u2190" }),
2693
+ /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("button", { className: ProductCarousel_default["rebuy-carousel__next"], onClick: nextSlide, type: "button", children: "\u2192" })
2694
+ ] }),
2695
+ showPagination && totalSlides > 1 && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)("div", { className: ProductCarousel_default["rebuy-carousel__pagination"], children: Array.from({ length: totalSlides }).map((_, index) => /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
2696
+ "button",
2697
+ {
2698
+ className: ProductCarousel_default["rebuy-carousel__dot"],
2699
+ "data-active": index === currentSlide ? "true" : "false",
2700
+ onClick: () => goToSlide(index),
2701
+ type: "button"
2702
+ },
2703
+ index
2704
+ )) })
2705
+ ] });
2706
+ };
2707
+
2708
+ // src/components/Timer/Timer.tsx
2709
+ var import_react20 = require("react");
2710
+
2711
+ // src/components/Timer/Timer.module.css
2712
+ var Timer_default = {
2713
+ "rebuy-timer__container": "Timer_rebuy-timer__container",
2714
+ "rebuy-timer__text": "Timer_rebuy-timer__text",
2715
+ "rebuy-timer__title": "Timer_rebuy-timer__title",
2716
+ "rebuy-timer__display": "Timer_rebuy-timer__display",
2717
+ "rebuy-timer__display--urgent": "Timer_rebuy-timer__display--urgent",
2718
+ pulse: "Timer_pulse",
2719
+ "rebuy-timer__minutes": "Timer_rebuy-timer__minutes",
2720
+ "rebuy-timer__seconds": "Timer_rebuy-timer__seconds",
2721
+ "rebuy-timer__separator": "Timer_rebuy-timer__separator"
2722
+ };
2723
+
2724
+ // src/components/Timer/Timer.tsx
2725
+ var import_jsx_runtime23 = require("react/jsx-runtime");
2726
+ var Timer = ({ action, durationMinutes, durationSeconds, isPopup = false, onDismiss, title }) => {
2727
+ const initialTotalSeconds = (durationMinutes || 0) * 60 + (durationSeconds || 0);
2728
+ const [totalSeconds, setTotalSeconds] = (0, import_react20.useState)(initialTotalSeconds);
2729
+ const [timerActive, setTimerActive] = (0, import_react20.useState)(true);
2730
+ const minutes = Math.floor(totalSeconds / 60);
2731
+ const seconds = totalSeconds % 60;
2732
+ const formattedMinutes = String(minutes).padStart(2, "0");
2733
+ const formattedSeconds = String(seconds).padStart(2, "0");
2734
+ const handleTimerEnd = (0, import_react20.useCallback)(() => {
2735
+ setTimerActive(false);
2736
+ switch (action) {
2737
+ case "dismiss":
2738
+ if (isPopup && onDismiss) {
2739
+ onDismiss();
2740
+ }
2741
+ break;
2742
+ case "checkout":
2743
+ window.location.href = "/checkout";
2744
+ break;
2745
+ case "cart":
2746
+ window.location.href = "/cart";
2747
+ break;
2748
+ case "stop":
2749
+ default:
2750
+ break;
2751
+ }
2752
+ }, [action, isPopup, onDismiss]);
2753
+ (0, import_react20.useEffect)(() => {
2754
+ if (!timerActive) return;
2755
+ const interval = setInterval(() => {
2756
+ setTotalSeconds((prevSeconds) => {
2757
+ if (prevSeconds <= 0) {
2758
+ clearInterval(interval);
2759
+ handleTimerEnd();
2760
+ return 0;
2761
+ }
2762
+ return prevSeconds - 1;
2763
+ });
2764
+ }, 1e3);
2765
+ return () => clearInterval(interval);
2766
+ }, [timerActive, handleTimerEnd]);
2767
+ const isUrgent = totalSeconds < 10;
2768
+ return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { className: Timer_default["rebuy-timer__container"], children: /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("p", { className: Timer_default["rebuy-timer__text"], children: [
2769
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("span", { className: Timer_default["rebuy-timer__title"], children: title }),
2770
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(
2771
+ "span",
2772
+ {
2773
+ className: `${Timer_default["rebuy-timer__display"]} ${isUrgent ? Timer_default["rebuy-timer__display--urgent"] : ""}`,
2774
+ children: [
2775
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("span", { className: Timer_default["rebuy-timer__minutes"], children: formattedMinutes }),
2776
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("span", { className: Timer_default["rebuy-timer__separator"], children: ":" }),
2777
+ /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("span", { className: Timer_default["rebuy-timer__seconds"], children: formattedSeconds })
2778
+ ]
2779
+ }
2780
+ )
2781
+ ] }) });
2782
+ };
2783
+
2784
+ // src/widgets/RebuyWidget/RebuyWidget.module.css
2785
+ var RebuyWidget_default = {
2786
+ "rebuy-widget__container": "RebuyWidget_rebuy-widget__container",
2787
+ "rebuy-widget__popup-overlay": "RebuyWidget_rebuy-widget__popup-overlay",
2788
+ "rebuy-widget__popup-content": "RebuyWidget_rebuy-widget__popup-content",
2789
+ "rebuy-widget__content": "RebuyWidget_rebuy-widget__content",
2790
+ "rebuy-widget__inner-content": "RebuyWidget_rebuy-widget__inner-content",
2791
+ "rebuy-widget__description": "RebuyWidget_rebuy-widget__description",
2792
+ "rebuy-widget__modal-close": "RebuyWidget_rebuy-widget__modal-close",
2793
+ "rebuy-widget__product-grid": "RebuyWidget_rebuy-widget__product-grid"
2794
+ };
2795
+
2796
+ // src/widgets/RebuyWidget/WidgetContent.tsx
2797
+ var import_jsx_runtime24 = require("react/jsx-runtime");
2798
+ var WidgetContent = ({
2799
+ addToCartCallback,
2800
+ customTitleLevel,
2801
+ isHydrogenReact,
2802
+ isInPopup,
2803
+ onDismiss,
2804
+ products,
2805
+ settings
2806
+ }) => {
2807
+ const currentBreakpoint = useBreakpoint(settings);
2808
+ const hasTimer = settings && settings.timer.enabled && settings.language.timer_title !== "" && (settings.timer.duration_minutes !== null || settings.timer.duration_seconds !== null);
2809
+ const hasSuperTitle = settings?.language.super_title !== "";
2810
+ const hasPrimaryTitle = settings?.language.title !== "";
2811
+ const hasDescription = settings?.language.description !== "";
2812
+ const layoutSettings = settings?.layout?.[currentBreakpoint];
2813
+ const isCarousel = layoutSettings?.carousel || false;
2814
+ const columns = layoutSettings?.columns || 1;
2815
+ const showPagination = layoutSettings?.show_paginations || false;
2816
+ const productCardSettings = {
2817
+ layoutStyle: layoutSettings?.style,
2818
+ productOptions: settings?.product_options,
2819
+ quantityInput: settings?.quantity_inputs,
2820
+ settingsDiscount: settings?.discount,
2821
+ variantSelector: settings?.view_options.variant_selector
2822
+ };
2823
+ const productCardTitleLevel = hasSuperTitle ? getTitleLevel(getTitleLevel(customTitleLevel, true), true) : getTitleLevel(customTitleLevel, true);
2824
+ const renderProducts = () => {
2825
+ if (!products || products.length === 0) {
2826
+ return null;
2827
+ }
2828
+ if (isCarousel) {
2829
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
2830
+ ProductCarousel,
2831
+ {
2832
+ addToCartBtnText: settings?.language.add_to_cart,
2833
+ addToCartCallback,
2834
+ columns,
2835
+ isHydrogenReact,
2836
+ productCardTitleLevel,
2837
+ products,
2838
+ settings: productCardSettings,
2839
+ showPagination
2840
+ }
2841
+ );
2842
+ }
2843
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { className: RebuyWidget_default["rebuy-widget__product-grid"], "data-columns": columns, role: "list", tabIndex: 0, children: products.map((product) => /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
2844
+ ProductCard,
2845
+ {
2846
+ addToCartBtnText: settings?.language.add_to_cart,
2847
+ addToCartCallback,
2848
+ isHydrogenReact,
2849
+ isInPopup,
2850
+ onPopupDismiss: onDismiss,
2851
+ product,
2852
+ productCardTitleLevel,
2853
+ settings: productCardSettings
2854
+ }
2855
+ ) }, product.id)) });
2856
+ };
2857
+ return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { className: RebuyWidget_default["rebuy-widget__inner-content"], children: [
2858
+ hasTimer && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
2859
+ Timer,
2860
+ {
2861
+ action: settings?.timer.action,
2862
+ durationMinutes: settings?.timer.duration_minutes,
2863
+ durationSeconds: settings?.timer.duration_seconds,
2864
+ isPopup: settings?.display_type === "popup",
2865
+ onDismiss,
2866
+ title: settings?.language.timer_title
2867
+ }
2868
+ ),
2869
+ hasSuperTitle && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
2870
+ Title,
2871
+ {
2872
+ level: getTitleLevel(customTitleLevel),
2873
+ style: { marginBottom: "0", textAlign: "center" },
2874
+ text: settings.language.super_title
2875
+ }
2876
+ ),
2877
+ hasPrimaryTitle && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
2878
+ Title,
2879
+ {
2880
+ level: getTitleLevel(customTitleLevel, hasSuperTitle ? true : false),
2881
+ style: { textAlign: "center" },
2882
+ text: settings.language.title
2883
+ }
2884
+ ),
2885
+ hasDescription && /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("p", { className: RebuyWidget_default["rebuy-widget__description"], children: settings.language.description }),
2886
+ renderProducts()
2887
+ ] });
2888
+ };
2889
+
2890
+ // src/widgets/RebuyWidget/RebuyWidget.tsx
2891
+ var import_jsx_runtime25 = require("react/jsx-runtime");
2892
+ var RebuyWidget = (props) => {
2893
+ const {
2894
+ addToCartCallback,
2895
+ customTitleLevel = "h2",
2896
+ isHydrogenReact,
2897
+ popupTriggerId,
2898
+ product,
2899
+ productId,
2900
+ variant,
2901
+ variantId,
2902
+ widgetId
2903
+ } = props;
2904
+ const { apiKey: apiKeyFromConfig, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
2905
+ const [settings, setSettings] = (0, import_react21.useState)(null);
2906
+ const [loadingSettings, setLoadingSettings] = (0, import_react21.useState)(true);
2907
+ const [error, setError] = (0, import_react21.useState)(null);
2908
+ const [showPopup, setShowPopup] = (0, import_react21.useState)(false);
2909
+ const [popupShownOnce, setPopupShownOnce] = (0, import_react21.useState)(false);
2910
+ const popupRef = (0, import_react21.useRef)(null);
2911
+ const [Rebuy, setRebuy] = (0, import_react21.useState)(null);
2912
+ const rebuyGeneralContext = (0, import_react21.useContext)(RebuyContext);
2913
+ const generalContextParams = rebuyGeneralContext?.contextParameters;
2914
+ const mainCacheKey = rebuyConfig?.shop?.cache_key;
2915
+ const generalContextCacheKey = generalContextParams?.cacheKey;
2916
+ const cacheKeyToUse = mainCacheKey || generalContextCacheKey || "";
2917
+ const [initialized, setInitialized] = (0, import_react21.useState)(false);
2918
+ const shopifyProductId = product?.id ?? productId ?? null;
2919
+ const shopifyVariantId = variant?.id ?? variantId ?? null;
2920
+ const [products, setProducts] = (0, import_react21.useState)([]);
2921
+ const currentBreakpoint = useBreakpoint(settings);
2922
+ const shouldHideWidget = settings?.layout?.[currentBreakpoint]?.style === "none";
2923
+ usePopupTrigger(settings, popupTriggerId, widgetId, popupShownOnce, showPopup, setShowPopup, setPopupShownOnce);
2924
+ (0, import_react21.useEffect)(() => {
2925
+ if (!Rebuy && apiKeyFromConfig && configLoadingStatus === "success") {
2926
+ const client = new import_rebuy3.RebuyClient(apiKeyFromConfig);
2927
+ if (generalContextParams) {
2928
+ client.setContextParameters(generalContextParams);
2929
+ }
2930
+ setRebuy(client);
2931
+ setInitialized(true);
2932
+ }
2933
+ }, [Rebuy, apiKeyFromConfig, configLoadingStatus, generalContextParams]);
2934
+ (0, import_react21.useEffect)(() => {
2935
+ if (!Rebuy || !generalContextParams) return;
2936
+ Rebuy.setContextParameters(generalContextParams);
2937
+ }, [Rebuy, generalContextParams]);
2938
+ (0, import_react21.useEffect)(() => {
2939
+ if (configLoadingStatus === "loading") {
2940
+ return;
2941
+ }
2942
+ if (!widgetId || !Rebuy || configLoadingStatus !== "success") {
2943
+ if (!widgetId && !loadingSettings && configLoadingStatus === "idle") {
2944
+ setError("Widget ID is missing.");
2945
+ } else if (!loadingSettings && configLoadingStatus === "error") {
2946
+ setError("Rebuy configuration failed to load.");
2947
+ } else if (!loadingSettings && apiKeyFromConfig && !Rebuy) {
2948
+ setError("Rebuy client not initialized.");
2949
+ } else if (!apiKeyFromConfig && !loadingSettings && configLoadingStatus === "success") {
2950
+ setError("Rebuy API Key is missing.");
2951
+ }
2952
+ if (!loadingSettings) setLoadingSettings(false);
2953
+ return;
2954
+ }
2955
+ const fetchSettings = async () => {
2956
+ setLoadingSettings(true);
2957
+ setError(null);
2958
+ try {
2959
+ const settingsParams = { id: widgetId };
2960
+ if (cacheKeyToUse) {
2961
+ settingsParams.cache_key = cacheKeyToUse;
2962
+ }
2963
+ const settingsResponse = await Rebuy.getShieldedAsset("/api/v1/widgets/settings", settingsParams);
2964
+ const fetchedWidgetSettings = settingsResponse?.data;
2965
+ if (!fetchedWidgetSettings || typeof fetchedWidgetSettings.endpoint !== "string" || fetchedWidgetSettings.endpoint.trim() === "") {
2966
+ throw new Error("Received invalid settings data: endpoint is missing or invalid.");
2967
+ }
2968
+ setSettings({
2969
+ ...fetchedWidgetSettings,
2970
+ hide_quantity_selector: fetchedWidgetSettings.hide_quantity_selector ?? false
2971
+ });
2972
+ } catch (e) {
2973
+ console.error(`[RebuyCrossSell] Error fetching widget settings for ID ${widgetId}:`, e);
2974
+ setError(e instanceof Error ? e.message : "Failed to load widget configuration.");
2975
+ setSettings(null);
2976
+ } finally {
2977
+ setLoadingSettings(false);
2978
+ }
2979
+ };
2980
+ fetchSettings();
2981
+ }, [widgetId, Rebuy, configLoadingStatus, apiKeyFromConfig, cacheKeyToUse]);
2982
+ const request = (0, import_react21.useMemo)(() => {
2983
+ const request2 = {
2984
+ endpoint: settings?.endpoint || "/api/v1/products/recommended",
2985
+ params: {}
2986
+ // Keeping this object generic to allow for custom endpoints
2987
+ };
2988
+ if (shopifyProductId) {
2989
+ request2.params.shopify_product_ids = Utilities5.getIdFromGraphUrl(shopifyProductId, "Product");
2990
+ }
2991
+ if (shopifyVariantId) {
2992
+ request2.params.shopify_variant_ids = Utilities5.getIdFromGraphUrl(shopifyVariantId, "ProductVariant");
2993
+ }
2994
+ if (settings?.limit) {
2995
+ request2.params.limit = settings.limit;
2996
+ }
2997
+ return request2;
2998
+ }, [settings, shopifyProductId, shopifyVariantId]);
2999
+ (0, import_react21.useEffect)(() => {
3000
+ let isMounted = true;
3001
+ if (!Rebuy || !initialized || !settings || configLoadingStatus !== "success") return;
3002
+ const fetchData = async () => {
3003
+ try {
3004
+ const params = { ...request.params };
3005
+ if (cacheKeyToUse) {
3006
+ params.cache_key = cacheKeyToUse;
3007
+ }
3008
+ params.uuid = crypto.randomUUID?.() || Math.random().toString(36).substring(2);
3009
+ if (apiKeyFromConfig) {
3010
+ params.key = apiKeyFromConfig;
3011
+ }
3012
+ let endpointToUse = request.endpoint;
3013
+ if (endpointToUse && endpointToUse.startsWith("/") && !endpointToUse.startsWith("/api/v1/")) {
3014
+ if (endpointToUse.startsWith("/custom") || endpointToUse.startsWith("/rules")) {
3015
+ endpointToUse = `/api/v1${endpointToUse}`;
3016
+ }
3017
+ }
3018
+ const { data } = await Rebuy.getStorefrontData(endpointToUse, params);
3019
+ if (isMounted) {
3020
+ setProducts(
3021
+ Array.isArray(data) ? data.map((product2) => ({
3022
+ ...product2,
3023
+ variants: {
3024
+ nodes: product2.variants ? (0, import_hydrogen8.flattenConnection)(product2.variants) : []
3025
+ }
3026
+ })) : []
3027
+ );
3028
+ }
3029
+ } catch (e) {
3030
+ console.error(`Error fetching products for widget ID ${widgetId}`, e);
3031
+ if (isMounted) {
3032
+ setProducts([]);
3033
+ setError(e instanceof Error ? e.message : "Failed to load products.");
3034
+ }
3035
+ }
3036
+ };
3037
+ fetchData();
3038
+ return () => {
3039
+ isMounted = false;
3040
+ };
3041
+ }, [
3042
+ Rebuy,
3043
+ initialized,
3044
+ request,
3045
+ generalContextParams,
3046
+ widgetId,
3047
+ settings,
3048
+ configLoadingStatus,
3049
+ apiKeyFromConfig,
3050
+ cacheKeyToUse
3051
+ ]);
3052
+ (0, import_react21.useEffect)(() => {
3053
+ if (!showPopup) return;
3054
+ const handleClickOutside = (event) => {
3055
+ if (popupRef.current && !popupRef.current.contains(event.target)) {
3056
+ setShowPopup(false);
3057
+ }
3058
+ };
3059
+ document.addEventListener("mousedown", handleClickOutside);
3060
+ return () => {
3061
+ document.removeEventListener("mousedown", handleClickOutside);
3062
+ };
3063
+ }, [showPopup]);
3064
+ const closePopup = () => {
3065
+ setShowPopup(false);
3066
+ };
3067
+ if (configLoadingStatus === "loading") {
3068
+ return null;
3069
+ }
3070
+ if (configLoadingStatus === "error") {
3071
+ console.error("Rebuy configuration failed to load");
3072
+ return null;
3073
+ }
3074
+ if (products?.length === 0 && settings && !loadingSettings) {
3075
+ console.log("No products to render for widgetId:", widgetId);
3076
+ return null;
3077
+ }
3078
+ if (error) {
3079
+ console.error("Error:", error);
3080
+ return null;
3081
+ }
3082
+ if (settings && !loadingSettings && shouldHideWidget) {
3083
+ return null;
3084
+ }
3085
+ return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_jsx_runtime25.Fragment, { children: products && settings && !loadingSettings && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: `${RebuyWidget_default["rebuy-widget__container"]}`, id: `rebuy-widget-${widgetId}`, children: settings?.display_type === "popup" && (settings.popup_trigger !== "add_to_cart" || settings.popup_trigger === "add_to_cart" && popupTriggerId) ? /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { children: showPopup && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: RebuyWidget_default["rebuy-widget__popup-overlay"], children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: RebuyWidget_default["rebuy-widget__popup-content"], ref: popupRef, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)("div", { className: RebuyWidget_default["rebuy-widget__content"], children: [
3086
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
3087
+ "button",
3088
+ {
3089
+ "aria-label": "close modal",
3090
+ className: RebuyWidget_default["rebuy-widget__modal-close"],
3091
+ onClick: closePopup,
3092
+ children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Close, {})
3093
+ }
3094
+ ),
3095
+ /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
3096
+ WidgetContent,
3097
+ {
3098
+ addToCartCallback: () => {
3099
+ addToCartCallback?.();
3100
+ setTimeout(() => {
3101
+ closePopup();
3102
+ }, 0);
3103
+ },
3104
+ customTitleLevel,
3105
+ isHydrogenReact,
3106
+ isInPopup: settings?.display_type === "popup",
3107
+ onDismiss: closePopup,
3108
+ products,
3109
+ settings
3110
+ }
3111
+ )
3112
+ ] }) }) }) }) : /* @__PURE__ */ (0, import_jsx_runtime25.jsx)("div", { className: RebuyWidget_default["rebuy-widget__content"], children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
3113
+ WidgetContent,
3114
+ {
3115
+ addToCartCallback,
3116
+ customTitleLevel,
3117
+ isHydrogenReact,
3118
+ isInPopup: settings?.display_type === "popup",
3119
+ products,
3120
+ settings
3121
+ }
3122
+ ) }) }) });
3123
+ };
3124
+
3125
+ // src/hooks/useRebuyTheme.ts
3126
+ var import_react22 = require("react");
3127
+
3128
+ // src/constants/api.ts
3129
+ var REBUY_THEME_STYLES_BASE_URL = "https://rebuyengine.com/api/v1/theme-styles";
3130
+
3131
+ // src/hooks/useRebuyTheme.ts
3132
+ var useRebuyTheme = (options = {}) => {
3133
+ const { apiKey: contextApiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
3134
+ const linkObject = (0, import_react22.useMemo)(() => {
3135
+ if (configLoadingStatus === "loading" && !options.overrideApiKey) {
3136
+ return [];
3137
+ }
3138
+ if (configLoadingStatus === "error" && !options.overrideApiKey && !contextApiKey) {
3139
+ console.warn(
3140
+ "[useRebuyTheme] Rebuy config failed to load and no overrideApiKey provided. Cannot generate theme styles link."
3141
+ );
3142
+ return [];
3143
+ }
3144
+ const effectiveApiKey = options.overrideApiKey || contextApiKey;
3145
+ if (!effectiveApiKey) {
3146
+ if (configLoadingStatus === "success" || options.overrideApiKey) {
3147
+ console.warn(
3148
+ "[useRebuyTheme] API key is missing. Provide it via RebuyConfigProvider or options.overrideApiKey. Stylesheet will not be loaded."
3149
+ );
3150
+ }
3151
+ return [];
3152
+ }
3153
+ const stylesheetUrl = `${REBUY_THEME_STYLES_BASE_URL}?key=${effectiveApiKey}`;
3154
+ return [{ href: stylesheetUrl, rel: "stylesheet" }];
3155
+ }, [rebuyConfig, contextApiKey, configLoadingStatus, options.overrideApiKey]);
3156
+ return linkObject;
3157
+ };
3158
+
3159
+ // src/utils/csp.ts
3160
+ var REBUY_STYLE_SRC_DOMAIN = "https://rebuyengine.com";
3161
+ var updateRebuyCsp = (existing, options = {}) => {
3162
+ const {
3163
+ styleSrc = true
3164
+ /* , connectSrc = false */
3165
+ } = options;
3166
+ let currentCspString;
3167
+ const isHeadersObject = existing instanceof Headers;
3168
+ if (isHeadersObject) {
3169
+ currentCspString = existing.get("Content-Security-Policy") || "";
3170
+ } else {
3171
+ currentCspString = existing;
3172
+ }
3173
+ const cspParts = currentCspString.split(";").map((part) => part.trim()).filter((part) => part);
3174
+ const updateDirective = (directiveName, domainToAdd) => {
3175
+ const directiveIndex = cspParts.findIndex((part) => part.toLowerCase().startsWith(directiveName.toLowerCase()));
3176
+ if (directiveIndex !== -1) {
3177
+ const currentDirective = cspParts[directiveIndex];
3178
+ const values = currentDirective.substring(directiveName.length).trim().split(" ");
3179
+ if (!values.includes(domainToAdd)) {
3180
+ values.push(domainToAdd);
3181
+ }
3182
+ cspParts[directiveIndex] = `${directiveName} ${values.join(" ")}`;
3183
+ } else {
3184
+ cspParts.push(`${directiveName} ${domainToAdd}`);
3185
+ }
3186
+ };
3187
+ if (styleSrc) {
3188
+ updateDirective("style-src", REBUY_STYLE_SRC_DOMAIN);
3189
+ if (cspParts.some((part) => part.toLowerCase().startsWith("style-src-elem"))) {
3190
+ updateDirective("style-src-elem", REBUY_STYLE_SRC_DOMAIN);
3191
+ }
3192
+ }
3193
+ const newCspString = cspParts.join("; ");
3194
+ if (isHeadersObject) {
3195
+ existing.set("Content-Security-Policy", newCspString);
3196
+ return existing;
3197
+ }
3198
+ return newCspString;
3199
+ };
3200
+
3201
+ // src/utils/theme.ts
3202
+ var getRebuyThemeStylesLink = (options) => {
3203
+ const { apiKey } = options;
3204
+ if (!apiKey) {
3205
+ console.warn("[getRebuyThemeStylesLink] API key is missing. Stylesheet link will not be generated.");
3206
+ return [];
3207
+ }
3208
+ const stylesheetUrl = `${REBUY_THEME_STYLES_BASE_URL}?key=${apiKey}`;
3209
+ return [{ href: stylesheetUrl, rel: "stylesheet" }];
3210
+ };
3211
+ //# sourceMappingURL=index.js.map